[Bio] / FigKernelPackages / FIGMODELmodel.pm Repository:
ViewVC logotype

Annotation of /FigKernelPackages/FIGMODELmodel.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.14 - (view) (download) (as text)

1 : chenry 1.7 use strict;
2 : chenry 1.2 package FIGMODELmodel;
3 :    
4 :     =head1 FIGMODELmodel object
5 :     =head2 Introduction
6 :     Module for manipulating model objects.
7 :     =head2 Core Object Methods
8 :    
9 :     =head3 new
10 :     Definition:
11 :     FIGMODELmodel = FIGMODELmodel->new();
12 :     Description:
13 :     This is the constructor for the FIGMODELmodel object.
14 :     =cut
15 :     sub new {
16 :     my ($class,$figmodel,$id) = @_;
17 : chenry 1.6
18 : chenry 1.2 #Error checking first
19 :     if (!defined($figmodel)) {
20 :     print STDERR "FIGMODELmodel->new(undef,".$id."):figmodel must be defined to create a model object!\n";
21 :     return undef;
22 :     }
23 :     my $self = {_figmodel => $figmodel};
24 :     bless $self;
25 :     if (!defined($id)) {
26 :     $self->figmodel()->error_message("FIGMODELmodel->new(figmodel,undef):id must be defined to create a model object");
27 :     return undef;
28 :     }
29 :    
30 :     #Checking that the id exists
31 : chenry 1.14 my $modelHandle = $self->figmodel()->database()->get_object_manager("model");
32 :     if (!defined($modelHandle)) {
33 : chenry 1.2 $self->figmodel()->error_message("FIGMODELmodel->new(figmodel,".$id."):could not load MODELS table. Check database!");
34 :     return undef;
35 :     }
36 :    
37 :     #If the id is a number, we get the model row by index
38 :     if ($id =~ m/^\d+$/) {
39 : chenry 1.14 my $objects = $modelHandle->get_objects();
40 :     $self->{_data} = $objects->[$id];
41 :     $self->figmodel()->{_models}->{$id} = $self;
42 : chenry 1.2 } else {
43 : chenry 1.14 my $objects = $modelHandle->get_objects({id => $id});
44 :     if (!defined($objects->[0]) && $id =~ m/(.+)(V[^V]+)/) {
45 :     $objects = $modelHandle->get_objects({id => $1});
46 :     if (!defined($objects->[0])) {
47 : chenry 1.5 $self->figmodel()->error_message("FIGMODELmodel->new(figmodel,".$id."):could not find model ".$id." in database!");
48 :     return undef;
49 :     }
50 : chenry 1.14 $self->{_selectedversion} = $2;
51 :     } elsif (!defined($objects->[0])) {
52 :     $self->figmodel()->error_message("FIGMODELmodel->new(figmodel,".$id."):could not find model ".$id." in database!");
53 :     return undef;
54 : chenry 1.2 }
55 : chenry 1.14 $self->{_data} = $objects->[0];
56 : chenry 1.2 }
57 :     if (!defined($self->{_data})) {
58 :     $self->figmodel()->error_message("FIGMODELmodel->new(figmodel,".$id."):could not find specified id in database!");
59 :     return undef;
60 :     }
61 :     $self->figmodel()->{_models}->{$self->id()} = $self;
62 : chenry 1.14
63 : chenry 1.2 return $self;
64 :     }
65 :    
66 :     =head3 config
67 :     Definition:
68 :     ref::key value = FIGMODELmodel->config(string::key);
69 :     Description:
70 :     Trying to avoid using calls that assume configuration data is stored in a particular manner.
71 :     Call this function to get file paths etc.
72 :     =cut
73 :     sub config {
74 :     my ($self,$key) = @_;
75 :     return $self->figmodel()->config($key);
76 :     }
77 :    
78 :     =head3 fail
79 :     Definition:
80 :     -1 = FIGMODELmodel->fail();
81 :     Description:
82 :     Standard return for failed functions.
83 :     =cut
84 :     sub fail {
85 :     my ($self) = @_;
86 :     return $self->figmodel()->fail();
87 :     }
88 :    
89 :     =head3 success
90 :     Definition:
91 :     1 = FIGMODELmodel->success();
92 :     Description:
93 :     Standard return for successful functions.
94 :     =cut
95 :     sub success {
96 :     my ($self) = @_;
97 :     return $self->figmodel()->success();
98 :     }
99 :    
100 :     =head3 figmodel
101 :     Definition:
102 :     FIGMODEL = FIGMODELmodel->figmodel();
103 :     Description:
104 :     Returns a FIGMODEL object
105 :     =cut
106 :     sub figmodel {
107 :     my ($self) = @_;
108 :     return $self->{"_figmodel"};
109 :     }
110 :    
111 :     =head3 fig
112 :     Definition:
113 :     FIGMODEL = FIGMODELmodel->fig();
114 :     Description:
115 :     Returns a FIG object
116 :     =cut
117 :     sub fig {
118 :     my ($self) = @_;
119 :     if (!defined($self->{_fig}) && $self->source() !~ /^MGRAST/) {
120 :     if ($self->source() =~ /^RAST/) {
121 :     $self->{"_fig"} = $self->figmodel()->fig();#$self->genome());
122 :     } else {
123 :     $self->{"_fig"} = $self->figmodel()->fig();
124 :     }
125 :     }
126 :     return $self->{"_fig"};
127 :     }
128 :    
129 : chenry 1.10 =head3 aquireModelLock
130 :    
131 :     Definition:
132 :    
133 :     FIGMODELmodel->aquireModelLock();
134 :    
135 :     Description:
136 :    
137 :     Locks the database for alterations relating to the current model object
138 :    
139 :     =cut
140 :     sub aquireModelLock {
141 :     my ($self) = @_;
142 :     $self->figmodel()->database()->genericLock($self->id());
143 :     }
144 :    
145 :     =head3 releaseModelLock
146 :    
147 :     Definition:
148 :    
149 :     FIGMODELmodel->releaseModelLock();
150 :    
151 :     Description:
152 :    
153 :     Unlocks the database for alterations relating to the current model object
154 :    
155 :     =cut
156 :     sub releaseModelLock {
157 :     my ($self) = @_;
158 :     $self->figmodel()->database()->genericUnlock($self->id());
159 :     }
160 :    
161 : chenry 1.2 =head3 mgdata
162 :     Definition:
163 :     FIGMODEL = FIGMODELmodel->mgdata();
164 :     Description:
165 :     Returns a mgrast database object
166 :     =cut
167 :     sub mgdata {
168 :     my ($self) = @_;
169 :     if (!defined($self->{_mgdata}) && $self->source() =~ /^MGRAST/) {
170 :     require MGRAST;
171 :     $self->{_mgdata} = $self->figmodel()->mgrast()->Job->get_objects( { 'genome_id' => $self->genome() } )
172 :     }
173 :     return $self->{_mgdata};
174 :     }
175 :    
176 :     =head3 id
177 :     Definition:
178 :     string = FIGMODELmodel->id();
179 :     Description:
180 :     Returns model id
181 :     =cut
182 :     sub id {
183 :     my ($self) = @_;
184 : chenry 1.14 return $self->{_data}->id();
185 : chenry 1.2 }
186 :    
187 :     =head3 owner
188 :     Definition:
189 :     string = FIGMODELmodel->owner();
190 :     Description:
191 :     Returns the username for the model owner
192 :     =cut
193 :     sub owner {
194 :     my ($self) = @_;
195 : chenry 1.14 return $self->{_data}->owner();
196 : chenry 1.2 }
197 :    
198 :     =head3 name
199 :     Definition:
200 :     string = FIGMODELmodel->name();
201 :     Description:
202 :     Returns the name of the organism or metagenome sample being modeled
203 :     =cut
204 :     sub name {
205 :     my ($self) = @_;
206 :    
207 :     if (!defined($self->{_name})) {
208 :     my $source = $self->source();
209 :     if ($source =~ /^MGRAST/) {
210 :     $self->{_name} = "NA";
211 :     if (defined($self->mgdata())) {
212 :     $self->{_name} = $self->mgdata()->genome_name;
213 :     }
214 :     } elsif ($source !~ /^RAST/) {
215 :     $self->{_name} = $self->fig()->orgname_of_orgid($self->genome());
216 : chenry 1.14 } else {
217 :     $self->{_name} = $self->figmodel()->get_genome_stats($self->genome())->{NAME}->[0];
218 : chenry 1.2 }
219 :     }
220 :    
221 :     return $self->{_name};
222 :     }
223 :    
224 :     =head3 get_reaction_class
225 :     Definition:
226 :     string = FIGMODELmodel->get_reaction_class(string::reaction ID);
227 :     Description:
228 :     Returns reaction class
229 :     =cut
230 :     sub get_reaction_class {
231 :     my ($self,$reaction,$nohtml) = @_;
232 :    
233 :     if (!-e $self->directory()."ReactionClassification-".$self->id().".tbl") {
234 :     if (!defined($self->{_reaction_classes})) {
235 :     $self->{_reaction_classes} = $self->figmodel()->database()->load_table($self->directory()."ReactionClassification-".$self->id()."-Complete.tbl",";","|",0,["REACTION"]);
236 :     if (!defined($self->{_reaction_classes})) {
237 :     return undef;
238 :     }
239 :     }
240 :    
241 :     my $ClassRow = $self->{_reaction_classes}->get_row_by_key($reaction,"REACTION");
242 :     if (defined($ClassRow) && defined($ClassRow->{CLASS})) {
243 :     my $class;
244 : dejongh 1.9 my $min = $ClassRow->{MIN}->[0];
245 :     my $max = $ClassRow->{MAX}->[0];
246 : chenry 1.2 if ($ClassRow->{CLASS}->[0] eq "Positive") {
247 :     $class = "Essential =>";
248 : dejongh 1.11 $class.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
249 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[0] eq "Negative") {
250 :     $class = "Essential <=";
251 : dejongh 1.11 $class.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
252 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[0] eq "Positive variable") {
253 :     $class = "Active =>";
254 : dejongh 1.11 $class.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
255 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[0] eq "Negative variable") {
256 :     $class = "Active <=";
257 : dejongh 1.11 $class.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
258 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[0] eq "Variable") {
259 :     $class = "Active <=>";
260 : dejongh 1.11 $class.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
261 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[0] eq "Blocked") {
262 :     $class = "Inactive";
263 :     } elsif ($ClassRow->{CLASS}->[0] eq "Dead") {
264 :     $class = "Disconnected";
265 :     }
266 : dejongh 1.9
267 : chenry 1.2 if (!defined($nohtml) || $nohtml ne "1") {
268 : dejongh 1.9 $class = "<span title=\"Flux:".$min." to ".$max."\">".$class."</span>";
269 : chenry 1.2 }
270 : dejongh 1.9
271 : chenry 1.2 return $class;
272 :     }
273 :     return undef;
274 :     }
275 :    
276 :     if (!defined($self->{_reaction_classes})) {
277 :     $self->{_reaction_classes} = $self->figmodel()->database()->load_table($self->directory()."ReactionClassification-".$self->id().".tbl",";","|",0,["REACTION"]);
278 :     if (!defined($self->{_reaction_classes})) {
279 :     return undef;
280 :     }
281 :     }
282 :    
283 :     my $ClassRow = $self->{_reaction_classes}->get_row_by_key($reaction,"REACTION");
284 :     my $classstring = "";
285 :     if (defined($ClassRow) && defined($ClassRow->{CLASS})) {
286 :     for (my $i=0; $i < @{$ClassRow->{CLASS}};$i++) {
287 :     if (length($classstring) > 0) {
288 :     $classstring .= "<br>";
289 :     }
290 :     my $NewClass;
291 : dejongh 1.9 my $min = $ClassRow->{MIN}->[$i];
292 :     my $max = $ClassRow->{MAX}->[$i];
293 : chenry 1.2 if ($ClassRow->{CLASS}->[$i] eq "Positive") {
294 :     $NewClass = $ClassRow->{MEDIA}->[$i].":Essential =>";
295 : dejongh 1.11 $NewClass.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
296 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[$i] eq "Negative") {
297 :     $NewClass = $ClassRow->{MEDIA}->[$i].":Essential <=";
298 : dejongh 1.11 $NewClass.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
299 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[$i] eq "Positive variable") {
300 :     $NewClass = $ClassRow->{MEDIA}->[$i].":Active =>";
301 : dejongh 1.11 $NewClass.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
302 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[$i] eq "Negative variable") {
303 :     $NewClass = $ClassRow->{MEDIA}->[$i].":Active <=";
304 : dejongh 1.11 $NewClass.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
305 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[$i] eq "Variable") {
306 :     $NewClass = $ClassRow->{MEDIA}->[$i].":Active <=>";
307 : dejongh 1.11 $NewClass.="<br>[Flux: ".sprintf("%.3g",$min)." to ".sprintf("%.3g",$max)."]<br>";
308 : chenry 1.2 } elsif ($ClassRow->{CLASS}->[$i] eq "Blocked") {
309 :     $NewClass = $ClassRow->{MEDIA}->[$i].":Inactive";
310 :     } elsif ($ClassRow->{CLASS}->[$i] eq "Dead") {
311 :     $NewClass = $ClassRow->{MEDIA}->[$i].":Disconnected";
312 : dejongh 1.9 }
313 :    
314 :     if (!defined($nohtml) || $nohtml ne "1") {
315 :     $NewClass = "<span title=\"Flux:".$min." to ".$max."\">".$NewClass."</span>";
316 : chenry 1.2 }
317 :     $classstring .= $NewClass;
318 :     }
319 :     }
320 :     return $classstring;
321 :     }
322 :    
323 :     =head3 get_biomass
324 :     Definition:
325 :     string = FIGMODELmodel->get_biomass();
326 :     Description:
327 :     Returns data for the biomass reaction
328 :     =cut
329 :     sub get_biomass {
330 :     my ($self) = @_;
331 :    
332 :     if (!defined($self->{_biomass})) {
333 :     my $rxntbl = $self->reaction_table();
334 :     for (my $i=0; $i < $rxntbl->size(); $i++) {
335 :     if ($rxntbl->get_row($i)->{"LOAD"}->[0] =~ m/bio\d\d\d\d\d/) {
336 :     $self->{_biomass} = $rxntbl->get_row($i)->{"LOAD"}->[0];
337 :     last;
338 :     }
339 :     }
340 :     }
341 :    
342 :     return $self->get_reaction_data($self->{_biomass});
343 :     }
344 :    
345 :     =head3 get_reaction_data
346 :     Definition:
347 :     string = FIGMODELmodel->get_reaction_data(string::reaction ID);
348 :     Description:
349 :     Returns model reaction data
350 :     =cut
351 :     sub get_reaction_data {
352 :     my ($self,$reaction) = @_;
353 :    
354 :     if (!defined($self->reaction_table())) {
355 :     return undef;
356 :     }
357 :     if ($reaction =~ m/^\d+$/) {
358 :     $self->reaction_table()->get_row($reaction);
359 :     }
360 :     return $self->reaction_table()->get_row_by_key($reaction,"LOAD");
361 :     }
362 :    
363 :     =head3 get_reaction_id
364 :     Definition:
365 :     string = FIGMODELmodel->get_reaction_id(string::reaction ID);
366 :     Description:
367 :     Returns model reaction id
368 :     =cut
369 :     sub get_reaction_id {
370 :     my ($self,$reaction) = @_;
371 :    
372 :     my $Data = $self->get_reaction_data($reaction);
373 :     if (!defined($Data) || !defined($Data->{LOAD}->[0])) {
374 :     return undef;
375 :     }
376 :     return $Data->{LOAD}->[0];
377 :     }
378 :    
379 : chenry 1.10 =head3 load_model_table
380 :    
381 :     Definition: FIGMODELTable = FIGMODELmodel->load_model_table(string:table name,0/1:refresh the table));
382 :    
383 :     Description: Returns the table specified by the input filename. Table will be stored in a file in the model directory.
384 :    
385 :     =cut
386 :     sub load_model_table {
387 :     my ($self,$name,$refresh) = @_;
388 :     if (!defined($refresh)) {
389 :     $refresh = 1;
390 :     }
391 :     if ($refresh == 1) {
392 :     delete $self->{"_".$name};
393 :     }
394 :     if (!defined($self->{"_".$name})) {
395 :     my $tbldef = $self->figmodel()->config("$name");
396 :     if (!defined($tbldef)) {
397 :     return undef;
398 :     }
399 :     my $filename = $self->directory().$name."-".$self->id().$self->selected_version().".tbl";
400 :     $self->{"_".$name} = $self->figmodel()->database()->load_table($filename,"\t","|",$tbldef->{headingline}->[0],$tbldef->{hashcolumns});
401 :     if (!defined($self->{"_".$name})) {
402 :     if (defined($tbldef->{prefix})) {
403 :     $self->{"_".$name} = FIGMODELTable->new($tbldef->{columns},$filename,$tbldef->{hashcolumns},"\t","|",join(@{$tbldef->{prefix}},"\n"));
404 :     } else {
405 :     $self->{"_".$name} = FIGMODELTable->new($tbldef->{columns},$filename,$tbldef->{hashcolumns},"\t","|");
406 :     }
407 :     }
408 :     }
409 :     return $self->{"_".$name};
410 :     }
411 :    
412 : chenry 1.2 =head3 get_reaction_number
413 :     Definition:
414 :     int = FIGMODELmodel->get_reaction_number();
415 :     Description:
416 :     Returns the number of reactions in the model
417 :     =cut
418 :     sub get_reaction_number {
419 :     my ($self) = @_;
420 :     if (!defined($self->reaction_table())) {
421 :     return 0;
422 :     }
423 :     return $self->reaction_table()->size();
424 :     }
425 :    
426 :     =head3 reaction_table
427 :     Definition:
428 :     FIGMODELTable = FIGMODELmodel->reaction_table();
429 :     Description:
430 :     Returns FIGMODELTable with the reaction list for the model
431 :     =cut
432 :     sub reaction_table {
433 :     my ($self) = @_;
434 :    
435 :     if (!defined($self->{_reaction_data})) {
436 :     $self->{_reaction_data} = $self->figmodel()->database()->GetDBModel($self->id());
437 : chenry 1.10 my $classTbl = $self->reaction_class_table();
438 :     for (my $i=0; $i < $classTbl->size(); $i++) {
439 :     my $row = $classTbl->get_row($i);
440 :     my $rxnRow = $self->{_reaction_data}->get_row_by_key($row->{"REACTION"}->[0],"LOAD");
441 :     for (my $j=0; $j < @{$row->{MEDIA}};$j++) {
442 :     my $class = "Active <=>";
443 :     if ($row->{CLASS}->[$j] eq "Positive") {
444 :     $class = "Essential =>";
445 :     } elsif ($row->{CLASS}->[$j] eq "Negative") {
446 :     $class = "Essential <=";
447 :     } elsif ($row->{CLASS}->[$j] eq "Blocked") {
448 :     $class = "Inactive";
449 :     } elsif ($row->{CLASS}->[$j] eq "Positive variable") {
450 :     $class = "Active =>";
451 :     } elsif ($row->{CLASS}->[$j] eq "Negative variable") {
452 :     $class = "Active <=";
453 :     } elsif ($row->{CLASS}->[$j] eq "Variable") {
454 :     $class = "Active <=>";
455 :     } elsif ($row->{CLASS}->[$j] eq "Dead") {
456 :     $class = "Dead";
457 :     }
458 :     push(@{$rxnRow->{PREDICTIONS}},$row->{MEDIA}->[$j].":".$class);
459 :     }
460 :     }
461 : chenry 1.2 }
462 :    
463 :     return $self->{_reaction_data};
464 :     }
465 :    
466 : chenry 1.10 =head3 feature_table
467 :     Definition:
468 :     FIGMODELTable = FIGMODELmodel->feature_table();
469 :     Description:
470 :     Returns FIGMODELTable with the feature list for the model
471 :     =cut
472 :     sub feature_table {
473 :     my ($self) = @_;
474 :    
475 :     if (!defined($self->{_feature_data})) {
476 :     #Getting the genome feature list
477 :     my $FeatureTable = $self->figmodel()->GetGenomeFeatureTable($self->genome());
478 :     if (!defined($FeatureTable)) {
479 :     print STDERR "FIGMODELmodel:feature_table:Could not get features for genome ".$self->genome()." in database!";
480 :     return undef;
481 :     }
482 :     #Getting the reaction table for the model
483 :     my $rxnTable = $self->reaction_table();
484 :     if (!defined($rxnTable)) {
485 :     print STDERR "FIGMODELmodel:feature_table:Could not get reaction table for model ".$self->id()." in database!";
486 :     return undef;
487 :     }
488 :     #Cloning the feature table
489 :     $self->{_feature_data} = $FeatureTable->clone_table_def();
490 :     $self->{_feature_data}->add_headings(($self->id()."REACTIONS",$self->id()."PREDICTIONS"));
491 :     for (my $i=0; $i < $rxnTable->size(); $i++) {
492 :     my $Row = $rxnTable->get_row($i);
493 :     if (defined($Row) && defined($Row->{"ASSOCIATED PEG"})) {
494 :     foreach my $GeneSet (@{$Row->{"ASSOCIATED PEG"}}) {
495 : chenry 1.13 my $temp = $GeneSet;
496 :     $temp =~ s/\+/|/g;
497 :     $temp =~ s/\sAND\s/|/gi;
498 :     $temp =~ s/\sOR\s/|/gi;
499 :     $temp =~ s/[\(\)\s]//g;
500 :     my @GeneList = split(/\|/,$temp);
501 : chenry 1.10 foreach my $Gene (@GeneList) {
502 :     my $FeatureRow = $self->{_feature_data}->get_row_by_key("fig|".$self->genome().".".$Gene,"ID");
503 :     if (!defined($FeatureRow)) {
504 :     $FeatureRow = $FeatureTable->get_row_by_key("fig|".$self->genome().".".$Gene,"ID");
505 :     if (defined($FeatureRow)) {
506 :     $self->{_feature_data}->add_row($FeatureRow);
507 :     }
508 :     }
509 :     if (defined($FeatureRow)) {
510 :     $self->{_feature_data}->add_data($FeatureRow,$self->id()."REACTIONS",$Row->{"LOAD"}->[0],1);
511 :     }
512 :     }
513 :     }
514 :     }
515 :     }
516 :     #Loading predictions
517 :     my @files = glob($self->directory()."EssentialGenes-".$self->id()."-*");
518 :     foreach my $file (@files) {
519 :     if ($file =~ m/\-([^\-]+)\.tbl/) {
520 :     my $media = $1;
521 :     my $list = $self->figmodel()->database()->load_single_column_file($file,"");
522 :     my $hash;
523 :     foreach my $gene (@{$list}) {
524 :     $hash->{$gene} = 1;
525 :     }
526 :     for (my $i=0; $i < $self->{_feature_data}->size(); $i++) {
527 :     my $Row = $self->{_feature_data}->get_row($i);
528 :     if ($Row->{ID}->[0] =~ m/(peg\.\d+)/) {
529 :     my $gene = $1;
530 :     if (defined($hash->{$gene})) {
531 :     push(@{$Row->{$self->id()."PREDICTIONS"}},$media.":essential");
532 :     } else {
533 :     push(@{$Row->{$self->id()."PREDICTIONS"}},$media.":nonessential");
534 :     }
535 :     }
536 :     }
537 :     }
538 :     }
539 :     }
540 :     return $self->{_feature_data};
541 :     }
542 :    
543 : chenry 1.2 =head3 reaction_class_table
544 :     Definition:
545 :     FIGMODELTable = FIGMODELmodel->reaction_class_table();
546 :     Description:
547 :     Returns FIGMODELTable with the reaction class data, and creates the table file if it does not exist
548 :     =cut
549 :     sub reaction_class_table {
550 :     my ($self) = @_;
551 :    
552 :     if (!defined($self->{_reaction_class_table})) {
553 :     if (-e $self->directory()."ReactionClassification-".$self->id().$self->selected_version().".tbl") {
554 :     $self->{_reaction_class_table} = $self->figmodel()->database()->load_table($self->directory()."ReactionClassification-".$self->id().$self->selected_version().".tbl",";","|",0,["REACTION","CLASS","MEDIA"]);
555 :     } else {
556 :     $self->{_reaction_class_table} = FIGMODELTable->new(["REACTION","MEDIA","CLASS","MIN","MAX"],$self->directory()."ReactionClassification-".$self->id().$self->selected_version().".tbl",["REACTION","CLASS","MEDIA"],";","|",undef);
557 :     }
558 :     }
559 :    
560 :     return $self->{_reaction_class_table};
561 :     }
562 :    
563 :     =head3 compound_class_table
564 :     Definition:
565 :     FIGMODELTable = FIGMODELmodel->compound_class_table();
566 :     Description:
567 :     Returns FIGMODELTable with the compound class data, and creates the table file if it does not exist
568 :     =cut
569 :     sub compound_class_table {
570 :     my ($self) = @_;
571 :    
572 :     if (!defined($self->{_compound_class_table})) {
573 :     if (-e $self->directory()."CompoundClassification-".$self->id().$self->selected_version().".tbl") {
574 :     $self->{_compound_class_table} = $self->figmodel()->database()->load_table($self->directory()."CompoundClassification-".$self->id().$self->selected_version().".tbl",";","|",0,["COMPOUND","CLASS","MEDIA"]);
575 :     } else {
576 :     $self->{_compound_class_table} = FIGMODELTable->new(["COMPOUND","MEDIA","CLASS","MIN","MAX"],$self->directory()."CompoundClassification-".$self->id().$self->selected_version().".tbl",["COMPOUND","CLASS","MEDIA"],";","|",undef);
577 :     }
578 :     }
579 :    
580 :     return $self->{_compound_class_table};
581 :     }
582 :    
583 : chenry 1.3 =head3 get_essential_genes
584 :     Definition:
585 :     [string::peg ID] = FIGMODELmodel->get_essential_genes(string::media condition);
586 :     Description:
587 :     Returns an reference to an array of the predicted essential genes during growth in the input media condition
588 :     =cut
589 :     sub get_essential_genes {
590 :     my ($self,$media) = @_;
591 :    
592 :     if (!defined($media)) {
593 :     $media = "Complete";
594 :     }
595 :     if (!defined($self->{_essential_genes}->{$media})) {
596 :     $self->{_essential_genes}->{$media} = undef;
597 :     if (-e $self->directory()."EssentialGenes-".$self->id().$self->selected_version()."-".$media.".tbl") {
598 :     $self->{_essential_genes}->{$media} = $self->figmodel()->database()->load_single_column_file($self->directory()."EssentialGenes-".$self->id().$self->selected_version()."-".$media.".tbl","");
599 :     }
600 :     }
601 :    
602 :     return $self->{_essential_genes}->{$media};
603 :     }
604 :    
605 : chenry 1.2 =head3 compound_table
606 :     Definition:
607 :     FIGMODELTable = FIGMODELmodel->compound_table();
608 :     Description:
609 :     Returns FIGMODELTable with the compound list for the model
610 :     =cut
611 :     sub compound_table {
612 :     my ($self) = @_;
613 :    
614 :     if (!defined($self->{_compound_table})) {
615 :     $self->{_compound_table} = $self->figmodel()->database()->GetDBModelCompounds($self->id());
616 :     }
617 :    
618 :     return $self->{_compound_table};
619 :     }
620 :    
621 :     =head3 get_compound_data
622 :     Definition:
623 : chenry 1.10 {string:key=>[string]:values} = FIGMODELmodel->get_compound_data(string::compound ID);
624 : chenry 1.2 Description:
625 :     Returns model compound data
626 :     =cut
627 :     sub get_compound_data {
628 :     my ($self,$compound) = @_;
629 :    
630 :     if (!defined($self->compound_table())) {
631 :     return undef;
632 :     }
633 :     if ($compound =~ m/^\d+$/) {
634 : chenry 1.10 return $self->compound_table()->get_row($compound);
635 : chenry 1.2 }
636 :     return $self->compound_table()->get_row_by_key($compound,"DATABASE");
637 :     }
638 :    
639 : chenry 1.10 =head3 get_feature_data
640 :     Definition:
641 :     {string:key=>[string]:values} = FIGMODELmodel->get_feature_data(string::feature ID);
642 :     Description:
643 :     Returns model feature data
644 :     =cut
645 :     sub get_feature_data {
646 :     my ($self,$feature) = @_;
647 :     if (!defined($self->feature_table())) {
648 :     return undef;
649 :     }
650 :     if ($feature =~ m/^\d+$/) {
651 :     return $self->feature_table()->get_row($feature);
652 :     }
653 :     if ($feature =~ m/(peg\.\d+)/) {
654 :     $feature = $1;
655 :     }
656 :     return $self->feature_table()->get_row_by_key("fig|".$self->genome().".".$feature,"ID");
657 :     }
658 :    
659 : chenry 1.2 =head3 genome
660 :     Definition:
661 :     string = FIGMODELmodel->genome();
662 :     Description:
663 :     Returns model genome
664 :     =cut
665 :     sub genome {
666 :     my ($self) = @_;
667 : chenry 1.14 return $self->{_data}->genome();
668 : chenry 1.2 }
669 :    
670 :     =head3 source
671 :     Definition:
672 :     string = FIGMODELmodel->source();
673 :     Description:
674 :     Returns model source
675 :     =cut
676 :     sub source {
677 :     my ($self) = @_;
678 : chenry 1.14 return $self->{_data}->source();
679 : chenry 1.2 }
680 :    
681 :     =head3 rights
682 :     Definition:
683 :     1/0 = FIGMODELmodel->rights(string::username);
684 :     Description:
685 :     Returns 1 if the input user can view the model, and zero otherwise
686 :     =cut
687 :     sub rights {
688 :     my ($self,$username) = @_;
689 :     if ($self->public()) {
690 :     return 1;
691 :     }
692 :     if (!defined($username) || $username eq "NONE") {
693 :     return 0;
694 :     }
695 :     if (!defined($self->{_userrights}->{$username})) {
696 : chenry 1.14 $self->{_userrights}->{$self->{_data}->owner()} = 1;
697 :     my @users = split(/\|/,$self->{_data}->users());
698 :     for (my $i=0; $i < @users;$i++) {
699 :     $self->{_userrights}->{$users[$i]} = 1;
700 : chenry 1.2 }
701 :     }
702 :     return $self->{_userrights}->{$username};
703 :     }
704 :    
705 :     =head3 public
706 :     Definition:
707 :     1/0 = FIGMODELmodel->public();
708 :     Description:
709 :     Returns 1 if the model is public, and zero otherwise
710 :     =cut
711 :     sub public {
712 :     my ($self) = @_;
713 : chenry 1.14 if ($self->{_data}->users() eq "all") {
714 :     return 1;
715 : chenry 1.2 }
716 : chenry 1.14 return 0;
717 : chenry 1.2 }
718 :    
719 :     =head3 directory
720 :     Definition:
721 :     string = FIGMODELmodel->directory();
722 :     Description:
723 :     Returns model directory
724 :     =cut
725 :     sub directory {
726 :     my ($self) = @_;
727 :    
728 :     if (!defined($self->{_directory})) {
729 :     my $userdirectory = "";
730 :     if ($self->owner() ne "master") {
731 :     $userdirectory = $self->owner()."/";
732 :     }
733 :     my $source = $self->source();
734 :     if ($source =~ /^MGRAST/) {
735 :     $self->{_directory} = $self->figmodel()->config("organism directory")->[0].$userdirectory.$self->genome()."/";
736 :     } elsif ($source =~ /^RAST/) {
737 :     $self->{_directory} = $self->figmodel()->config("organism directory")->[0].$userdirectory.$self->genome()."/";
738 :     } elsif ($source =~ /^SEED/) {
739 :     $self->{_directory} = $self->figmodel()->config("organism directory")->[0].$userdirectory.$self->genome()."/";
740 :     } elsif ($source =~ /^PM/) {
741 :     if (length($userdirectory) == 0) {
742 :     $self->{_directory} = $self->figmodel()->config("imported model directory")->[0].$self->id()."/";
743 :     } else {
744 :     $self->{_directory} = $self->figmodel()->config("organism directory")->[0].$userdirectory.$self->id()."/";
745 :     }
746 :     }
747 :     }
748 :    
749 :     return $self->{_directory};
750 :     }
751 :    
752 :     =head3 filename
753 :     Definition:
754 :     string = FIGMODELmodel->filename();
755 :     Description:
756 :     Returns model filename
757 :     =cut
758 :     sub filename {
759 :     my ($self) = @_;
760 :    
761 :     return $self->directory().$self->id().$self->selected_version().".txt";
762 :     }
763 :    
764 :     =head3 version
765 :     Definition:
766 :     string = FIGMODELmodel->version();
767 :     Description:
768 :     Returns the version of the model
769 :     =cut
770 :     sub version {
771 :     my ($self) = @_;
772 :    
773 :     if (!defined($self->{_version})) {
774 :     if (!defined($self->{_selectedversion})) {
775 : chenry 1.14 $self->{_version} = "V".$self->{_data}->version().".".$self->{_data}->autocompleteVersion();
776 : chenry 1.2 } else {
777 :     $self->{_version} = $self->{_selectedversion};
778 :     }
779 :     }
780 :     return $self->{_version};
781 :     }
782 :    
783 :     =head3 selected_version
784 :     Definition:
785 :     string = FIGMODELmodel->selected_version();
786 :     Description:
787 :     Returns the selected version of the model
788 :     =cut
789 :     sub selected_version {
790 :     my ($self) = @_;
791 :    
792 :     if (!defined($self->{_selectedversion})) {
793 :     return "";
794 :     }
795 :     return $self->{_selectedversion};
796 :     }
797 :    
798 :     =head3 modification_time
799 :     Definition:
800 :     string = FIGMODELmodel->modification_time();
801 :     Description:
802 :     Returns the selected version of the model
803 :     =cut
804 :     sub modification_time {
805 :     my ($self) = @_;
806 : chenry 1.14 return $self->{_data}->modificationDate();
807 : chenry 1.2 }
808 :    
809 :     =head3 gene_reactions
810 :     Definition:
811 :     string = FIGMODELmodel->gene_reactions();
812 :     Description:
813 :     Returns the number of reactions added by the gap filling
814 :     =cut
815 :     sub gene_reactions {
816 :     my ($self) = @_;
817 : chenry 1.14 return ($self->{_data}->reactions() - $self->{_data}->autoCompleteReactions() - $self->{_data}->spontaneousReactions() - $self->{_data}->gapFillReactions());
818 : chenry 1.2 }
819 :    
820 :     =head3 total_compounds
821 :     Definition:
822 :     string = FIGMODELmodel->total_compounds();
823 :     Description:
824 :     Returns the number of compounds in the model
825 :     =cut
826 :     sub total_compounds {
827 :     my ($self) = @_;
828 : chenry 1.14 return $self->{_data}->compounds();
829 : chenry 1.2 }
830 :    
831 :     =head3 gapfilling_reactions
832 :     Definition:
833 :     string = FIGMODELmodel->gapfilling_reactions();
834 :     Description:
835 :     Returns the number of reactions added by the gap filling
836 :     =cut
837 :     sub gapfilling_reactions {
838 :     my ($self) = @_;
839 : chenry 1.14 return ($self->{_data}->autoCompleteReactions()+$self->{_data}->gapFillReactions());
840 : chenry 1.2 }
841 :    
842 :     =head3 total_reactions
843 :     Definition:
844 :     string = FIGMODELmodel->total_reactions();
845 :     Description:
846 :     Returns the total number of reactions in the model
847 :     =cut
848 :     sub total_reactions {
849 :     my ($self) = @_;
850 : chenry 1.14 return $self->{_data}->reactions();
851 : chenry 1.2 }
852 :    
853 :     =head3 model_genes
854 :     Definition:
855 :     string = FIGMODELmodel->model_genes();
856 :     Description:
857 :     Returns the number of genes mapped to one or more reactions in the model
858 :     =cut
859 :     sub model_genes {
860 :     my ($self) = @_;
861 : chenry 1.14 return $self->{_data}->associatedGenes();
862 : chenry 1.2 }
863 :    
864 :     =head3 class
865 :     Definition:
866 :     string = FIGMODELmodel->class();
867 :     Description:
868 :     Returns the class of the model: gram positive, gram negative, other
869 :     =cut
870 :     sub class {
871 :     my ($self) = @_;
872 : chenry 1.14 return $self->{_data}->cellwalltype();
873 : chenry 1.2 }
874 :    
875 :     =head3 taxonomy
876 :     Definition:
877 :     string = FIGMODELmodel->taxonomy();
878 :     Description:
879 :     Returns model taxonomy or biome if this is an metagenome model
880 :     =cut
881 :     sub taxonomy {
882 :     my ($self) = @_;
883 :    
884 :     if (!defined($self->{_taxonomy})) {
885 :     my $source = $self->source();
886 :     if ($source =~ /^MGRAST/) {
887 :     $self->{_taxonomy} = "NA";
888 :     my $mgmodeldata = $self->figmodel()->database()->mg_model_data($self->genome());
889 :     if (defined($mgmodeldata)) {
890 :     $self->{_taxonomy} = $mgmodeldata->biome();
891 :     }
892 :     } else {
893 :     $self->{_taxonomy} = $self->fig()->taxonomy_of($self->genome());
894 :     }
895 :     }
896 :    
897 :     return $self->{_taxonomy};
898 :     }
899 :    
900 :     =head3 genome_size
901 :     Definition:
902 :     string = FIGMODELmodel->genome_size();
903 :     Description:
904 :     Returns size of the modeled genome in KB
905 :     =cut
906 :     sub genome_size {
907 :     my ($self) = @_;
908 :    
909 :     if (!defined($self->{_genome_size})) {
910 :     my $source = $self->source();
911 :     if ($source =~ /^MGRAST/) {
912 :     $self->{_genome_size} = "NA";
913 :     if (defined($self->mgdata())) {
914 :     $self->{_genome_size} = $self->mgdata()->size;
915 :     }
916 :     } else {
917 :     $self->{_genome_size} = $self->fig()->genome_szdna($self->genome());
918 :     }
919 :     }
920 :    
921 :     return $self->{_genome_size};
922 :     }
923 :    
924 :     =head3 genome_genes
925 :     Definition:
926 :     string = FIGMODELmodel->genome_genes();
927 :     Description:
928 :     Returns the number of genes in the modeled genome
929 :     =cut
930 :     sub genome_genes {
931 :     my ($self) = @_;
932 :    
933 :     if (!defined($self->{_genome_genes})) {
934 :     my $source = $self->source();
935 :     if ($source =~ /^MGRAST/) {
936 :     $self->{_genome_genes} = "NA";
937 :     if (defined($self->mgdata())) {
938 :     $self->{_genome_genes} = $self->mgdata()->genome_contig_count;
939 :     }
940 : chenry 1.14 } else {
941 :     $self->{_genome_genes} = $self->figmodel()->get_genome_stats($self->genome())->{"TOTAL GENES"}->[0];
942 : chenry 1.2 }
943 :     }
944 :    
945 :     return $self->{_genome_genes};
946 :     }
947 :    
948 :     =head3 run_default_model_predictions
949 :     Definition:
950 :     0/1::status = FIGMODELmodel->run_default_model_predictions(string::media ID);
951 :     Description:
952 :     =cut
953 :     sub run_default_model_predictions {
954 :     my ($self,$Media) = @_;
955 :    
956 :     #Assuming complete media if none is provided
957 :     if (!defined($Media)) {
958 :     $Media = "Complete";
959 :     }
960 :    
961 :     #Predicting essentiality
962 :     my $result = $self->figmodel()->RunFBASimulation($self->id(),"SINGLEKO",undef,undef,[$self->id()],[$Media]);
963 :     #Checking that the table is defined and the output file exists
964 :     if (defined($result) && defined($result->get_row(0)->{"ESSENTIALGENES"})) {
965 :     $self->figmodel()->database()->print_array_to_file($self->directory()."EssentialGenes-".$self->id()."-".$Media.".tbl",[join("\n",@{$result->get_row(0)->{"ESSENTIALGENES"}})]);
966 : chenry 1.3 } else {
967 :     $self->figmodel()->error_message("FIGMODELmodel:run_default_model_predictions:could not identify essential reactions for model ".$self->id().$self->selected_version().".");
968 :     return $self->figmodel()->fail();
969 : chenry 1.2 }
970 :    
971 :     #Classifying reactions and compounds
972 :     my $tbl = $self->classify_model_reactions($Media);
973 : chenry 1.3 if (!defined($tbl)) {
974 :     $self->figmodel()->error_message("FIGMODELmodel:run_default_model_predictions:could not classify reactions for model ".$self->id().$self->selected_version().".");
975 :     return $self->figmodel()->fail();
976 :     }
977 : chenry 1.2 $tbl->save();
978 :    
979 :     return $self->figmodel()->success();
980 :     }
981 :    
982 :     =head3 update_stats_for_gap_filling
983 :     Definition:
984 :     {string => [string]} = FIGMODELmodel->update_stats_for_gap_filling(int::gapfill time);
985 :     Description:
986 :     =cut
987 :     sub update_stats_for_gap_filling {
988 :     my ($self,$gapfilltime) = @_;
989 : chenry 1.14 $self->{_data}->autoCompleteTime($gapfilltime);
990 :     $self->{_data}->autocompleteDate(time());
991 :     $self->{_data}->modificationDate(time());
992 :     my $version = $self->{_data}->autocompleteVersion();
993 :     $self->{_data}->autocompleteVersion($version+1);
994 : chenry 1.2 }
995 :    
996 :     =head3 update_stats_for_build
997 :     Definition:
998 :     {string => [string]} = FIGMODELmodel->update_stats_for_build();
999 :     Description:
1000 :     =cut
1001 :     sub update_stats_for_build {
1002 :     my ($self) = @_;
1003 : chenry 1.14 $self->{_data}->builtDate(time());
1004 :     $self->{_data}->modificationDate(time());
1005 :     my $version = $self->{_data}->version();
1006 :     $self->{_data}->version($version+1);
1007 : chenry 1.2 }
1008 :    
1009 :     =head3 update_model_stats
1010 :     Definition:
1011 :     FIGMODELmodel->update_model_stats();
1012 :     Description:
1013 :     =cut
1014 :     sub update_model_stats {
1015 :     my ($self) = @_;
1016 :    
1017 :     #Getting reaction table
1018 :     my $rxntbl = $self->reaction_table();
1019 :     if (!defined($rxntbl)) {
1020 :     $self->figmodel()->error_message("FIGMODELmodel:update_model_stats:Could not load reaction list for ".$self->id());
1021 :     return undef;
1022 :     }
1023 :     my $cpdtbl = $self->compound_table();
1024 :    
1025 : chenry 1.14 #Calculating all necessary stats
1026 : chenry 1.2 my %GeneHash;
1027 :     my %NonpegHash;
1028 :     my %CompoundHash;
1029 : chenry 1.14 my $spontaneousReactions = 0;
1030 :     my $gapFillReactions = 0;
1031 :     my $biologReactions = 0;
1032 :     my $transporters = 0;
1033 :     my $autoCompleteReactions = 0;
1034 :     my $associatedSubsystemGenes = 0;
1035 : chenry 1.2 for (my $i=0; $i < $rxntbl->size(); $i++) {
1036 :     my $Row = $rxntbl->get_row($i);
1037 :     if (defined($Row) && defined($Row->{"ASSOCIATED PEG"})) {
1038 :     my $ReactionRow = $self->figmodel()->get_reaction($Row->{"LOAD"}->[0]);
1039 :     if (defined($ReactionRow->{"EQUATION"}->[0])) {
1040 :     #Checking for extracellular metabolites which indicate that this is a transporter
1041 :     if ($ReactionRow->{"EQUATION"}->[0] =~ m/\[e\]/) {
1042 : chenry 1.14 $transporters++;
1043 : chenry 1.2 }
1044 :     }
1045 :     #Identifying spontaneous/biolog/gapfilling/gene associated reactions
1046 :     if ($Row->{"ASSOCIATED PEG"}->[0] =~ m/BIOLOG/i) {
1047 : chenry 1.14 $biologReactions++;
1048 :     } elsif ($Row->{"ASSOCIATED PEG"}->[0] =~ m/GROW/i) {
1049 :     $gapFillReactions++;
1050 : chenry 1.2 } elsif ($Row->{"ASSOCIATED PEG"}->[0] =~ m/SPONTANEOUS/i) {
1051 : chenry 1.14 $spontaneousReactions++;
1052 : chenry 1.2 } elsif ($Row->{"ASSOCIATED PEG"}->[0] =~ m/GAP/ || $Row->{"ASSOCIATED PEG"}->[0] =~ m/UNIVERSAL/i || $Row->{"ASSOCIATED PEG"}->[0] =~ m/UNKNOWN/i) {
1053 : chenry 1.14 $autoCompleteReactions++;
1054 : chenry 1.2 } else {
1055 :     foreach my $GeneSet (@{$Row->{"ASSOCIATED PEG"}}) {
1056 : chenry 1.5 $_ = $GeneSet;
1057 :     my @GeneList = /(peg\.\d+)/g;
1058 : chenry 1.2 foreach my $Gene (@GeneList) {
1059 :     if ($Gene =~ m/(peg\.\d+)/) {
1060 :     $GeneHash{$1} = 1;
1061 :     } else {
1062 :     $NonpegHash{$Gene} = 1;
1063 :     }
1064 :     }
1065 :     }
1066 :     }
1067 :     }
1068 :     }
1069 :     my @genes = keys(%GeneHash);
1070 :     my @othergenes = keys(%NonpegHash);
1071 : chenry 1.14
1072 :     #Setting the reaction count
1073 :     $self->{_data}->reactions($rxntbl->size());
1074 :     #Setting the metabolite count
1075 :     $self->{_data}->compounds($rxntbl->size());
1076 :     #Setting the gene count
1077 :     my $geneCount = @genes + @othergenes;
1078 :     $self->{_data}->associatedGenes($geneCount);
1079 :     #Setting remaining stats
1080 :     $self->{_data}->spontaneousReactions($spontaneousReactions);
1081 :     $self->{_data}->gapFillReactions($gapFillReactions);
1082 :     $self->{_data}->biologReactions($biologReactions);
1083 :     $self->{_data}->transporters($transporters);
1084 :     $self->{_data}->autoCompleteReactions($autoCompleteReactions);
1085 :     $self->{_data}->associatedSubsystemGenes($associatedSubsystemGenes);
1086 :     #Setting the model class
1087 :     my $class = "";
1088 :     for (my $i=0; $i < @{$self->figmodel()->config("class list")}; $i++) {
1089 :     if (defined($self->figmodel()->config($self->figmodel()->config("class list")->[$i]))) {
1090 :     if (defined($self->figmodel()->config($self->figmodel()->config("class list")->[$i])->{$self->id()})) {
1091 :     $class = $self->figmodel()->config("class list")->[$i];
1092 :     last;
1093 :     }
1094 :     if ($class eq "" && defined($self->figmodel()->config($self->figmodel()->config("class list")->[$i])->{$self->genome()})) {
1095 :     $class = $self->figmodel()->config("class list")->[$i];
1096 :     }
1097 :     }
1098 :     }
1099 :     if ($class eq "") {
1100 :     $class = $self->figmodel()->get_genome_stats($self->genome())->{CLASS}->[0];
1101 :     }
1102 :     if ($class eq "") {
1103 :     $class = "unknown";
1104 :     }
1105 :     $self->{_data}->cellwalltype($class);
1106 : chenry 1.2 }
1107 :    
1108 :     =head3 GapFillModel
1109 :     Definition:
1110 :     (success/fail) = FIGMODELmodel->GapFillModel();
1111 :     Description:
1112 :     This function performs an optimization to identify the minimal set of reactions that must be added to a model in order for biomass to be produced by the biomass reaction in the model.
1113 :     Before running the gap filling, the existing model is backup in the same directory with the current version numbers appended.
1114 :     If the model has been gap filled previously, the previous gap filling reactions are removed prior to running the gap filling again.
1115 :     =cut
1116 :     sub GapFillModel {
1117 :     my ($self,$donotclear) = @_;
1118 :    
1119 :     #Setting status of model to gap filling
1120 :     my $OrganismID = $self->genome();
1121 :     $self->set_status(1,"Auto completion running");
1122 :     my $UniqueFilename = $self->figmodel()->filename();
1123 :     my $StartTime = time();
1124 :    
1125 :     #Archiving the existing model
1126 :     $self->ArchiveModel();
1127 :    
1128 :     #Removing any gapfilling reactions that may be currently present in the model
1129 :     if (!defined($donotclear) || $donotclear != 1) {
1130 :     my $ModelTable = $self->reaction_table();
1131 :     for (my $i=0; $i < $ModelTable->size(); $i++) {
1132 :     if (!defined($ModelTable->get_row($i)->{"ASSOCIATED PEG"}->[0]) || $ModelTable->get_row($i)->{"ASSOCIATED PEG"}->[0] eq "GAP FILLING" || $ModelTable->get_row($i)->{"ASSOCIATED PEG"}->[0] =~ m/BIOLOG/ || $ModelTable->get_row($i)->{"ASSOCIATED PEG"}->[0] =~ m/GROWMATCH/) {
1133 :     $ModelTable->delete_row($i);
1134 :     $i--;
1135 :     }
1136 :     }
1137 :     $ModelTable->save();
1138 :     }
1139 :    
1140 :     #Calling the MFAToolkit to run the gap filling optimization
1141 :     my $MinimalMediaTable = $self->figmodel()->database()->GetDBTable("MINIMAL MEDIA TABLE");
1142 :     my $Media = "Complete";
1143 :     if (defined($MinimalMediaTable->get_row_by_key($self->genome(),"Organism"))) {
1144 :     $Media = $MinimalMediaTable->get_row_by_key($self->genome(),"Organism")->{"Minimal media"}->[0];
1145 :     #Loading media, changing bounds, saving media as a test media
1146 :     my $MediaTable = FIGMODELTable::load_table($self->config("Media directory")->[0].$Media.".txt",";","",0,["VarName"]);
1147 :     for (my $i=0; $i < $MediaTable->size(); $i++) {
1148 :     if ($MediaTable->get_row($i)->{"Min"}->[0] < 0) {
1149 :     $MediaTable->get_row($i)->{"Min"}->[0] = -10000;
1150 :     }
1151 :     if ($MediaTable->get_row($i)->{"Max"}->[0] > 0) {
1152 :     $MediaTable->get_row($i)->{"Max"}->[0] = 10000;
1153 :     }
1154 :     }
1155 :     $MediaTable->save($self->config("Media directory")->[0].$UniqueFilename."TestMedia.txt");
1156 : dejongh 1.11 system($self->figmodel()->GenerateMFAToolkitCommandLineCall($UniqueFilename,$self->id(),$UniqueFilename."TestMedia",["GapFilling"],{"Default max drain flux" => 0,"Reactions to knockout" => $self->config("permanently knocked out reactions")->[0]},"GapFill".$self->id().".log",undef));
1157 : chenry 1.2 unlink($self->config("Media directory")->[0].$UniqueFilename."TestMedia.txt");
1158 :     } else {
1159 : dejongh 1.11 system($self->figmodel()->GenerateMFAToolkitCommandLineCall($UniqueFilename,$self->id(),undef,["GapFilling"],{"Reactions to knockout" => $self->config("permanently knocked out reactions")->[0]},"GapFill".$self->id().".log",undef));
1160 : chenry 1.2 }
1161 :    
1162 :     #Parse the solutions file for the model and get the reaction list from it
1163 :     my $SolutionData = $self->figmodel()->LoadProblemReport($UniqueFilename);
1164 :     #Clearing the mfatoolkit output and log file
1165 :     $self->figmodel()->clearing_output($UniqueFilename,"GapFill".$self->id().".log");
1166 :     if (!defined($SolutionData) || $SolutionData->size() == 0) {
1167 :     $self->set_status(1,"Auto completion failed: auto completion solution not found");
1168 :     $self->figmodel()->error_message("FIGMODEL:GapFillModel: Gap filling report not found!");
1169 :     return $self->fail();
1170 :     }
1171 :     $SolutionData->save("/home/chenry/Solution.txt");
1172 :    
1173 :     #Looking for the last printed recursive MILP solution
1174 :     for (my $i=($SolutionData->size()-1); $i >=0; $i--) {
1175 :     if (defined($SolutionData->get_row($i)->{"Notes"}) && $SolutionData->get_row($i)->{"Notes"}->[0] =~ m/^Recursive/) {
1176 :     my $AllSolutions = substr($SolutionData->get_row($i)->{"Notes"}->[0],15);
1177 :     my @TempThree = split(/\|/,$AllSolutions);
1178 :     if (@TempThree > 0 && $TempThree[0] =~ m/.+:(.+)/) {
1179 :     my @TempFour = split(/,/,$1);
1180 :     my $DirectionList;
1181 :     my $ReactionList;
1182 :     for (my $j=0; $j < @TempFour; $j++) {
1183 :     my $ID = "";
1184 :     my $Sign = "=>";
1185 :     if ($TempFour[$j] =~ m/\-(rxn\d\d\d\d\d)/) {
1186 :     $ID = $1;
1187 :     $Sign = "<=";
1188 :     } elsif ($TempFour[$j] =~ m/\+(rxn\d\d\d\d\d)/) {
1189 :     $ID = $1;
1190 :     }
1191 :     if ($ID ne "") {
1192 :     if ($self->figmodel()->reversibility_of_reaction($ID) ne $Sign) {
1193 :     $Sign = "<=>";
1194 :     }
1195 :     push(@{$DirectionList},$Sign);
1196 :     push(@{$ReactionList},$ID);
1197 :     }
1198 :     }
1199 :     $self->figmodel()->IntegrateGrowMatchSolution($self->id(),undef,$ReactionList,$DirectionList,"GAP FILLING",0,1);
1200 :     }
1201 :     last;
1202 :     }
1203 :     }
1204 :     #Updating model stats with gap filling results
1205 :     my $ElapsedTime = time() - $StartTime;
1206 : chenry 1.7 $self->figmodel()->database()->ClearDBModel($self->id(),1);
1207 : chenry 1.2 #Determining why each gap filling reaction was added
1208 :     $self->figmodel()->IdentifyDependancyOfGapFillingReactions($self->id(),$Media);
1209 :     if (!defined($donotclear) || $donotclear != 1) {
1210 :     $self->figmodel()->AddBiologTransporters($self->id());
1211 :     if ($self->id() !~ m/MGRast/) {
1212 :     $self->update_stats_for_gap_filling($ElapsedTime);
1213 :     }
1214 :     } else {
1215 :     $self->update_model_stats();
1216 :     }
1217 :     #Printing the updated SBML file
1218 :     $self->PrintSBMLFile();
1219 :     $self->PrintModelLPFile($self->id());
1220 :     $self->set_status(1,"Auto completion successfully finished");
1221 :     $self->run_default_model_predictions();
1222 :    
1223 :     return $self->success();
1224 :     }
1225 :    
1226 : chenry 1.10 =head3 GapGenModel
1227 :     Definition:
1228 :     FIGMODELmodel->GapGenModel();
1229 :     Description:
1230 :     Runs the gap generation algorithm to correct a single false positive prediction. Results are loaded into a table.
1231 :     =cut
1232 :    
1233 :     sub GapGenModel {
1234 :     my ($self,$Media,$KOList,$NoKOList,$Experiment,$SolutionLimit) = @_;
1235 :    
1236 :     #Enforcing nonoptional arguments
1237 :     if (!defined($Media)) {
1238 :     return undef;
1239 :     }
1240 :     if (!defined($KOList)) {
1241 :     $KOList->[0] = "none";
1242 :     }
1243 :     if (!defined($NoKOList)) {
1244 :     $NoKOList->[0] = "none";
1245 :     }
1246 :     if (!defined($Experiment)) {
1247 :     $Experiment= "ReactionKO";
1248 :     }
1249 :     if (!defined($SolutionLimit)) {
1250 :     $SolutionLimit = "10";
1251 :     }
1252 :    
1253 :     #Translating the KO lists into arrays
1254 :     if (ref($KOList) ne "ARRAY") {
1255 :     my $temp = $KOList;
1256 :     $KOList = ();
1257 :     push(@{$KOList},split(/[,;]/,$temp));
1258 :     }
1259 :     my $noKOHash;
1260 :     if (defined($NoKOList) && ref($NoKOList) ne "ARRAY") {
1261 :     my $temp = $NoKOList;
1262 :     $NoKOList = ();
1263 :     push(@{$NoKOList},split(/[,;]/,$temp));
1264 :     foreach my $rxn (@{$NoKOList}) {
1265 :     $noKOHash->{$rxn} = 1;
1266 :     }
1267 :     }
1268 :    
1269 :     #Checking if solutions exist for the input parameters
1270 :     $self->aquireModelLock();
1271 :     my $tbl = $self->load_model_table("GapGenSolutions");
1272 :     my $solutionRow = $tbl->get_table_by_key($Experiment,"Experiment")->get_table_by_key($Media,"Media")->get_row_by_key(join(",",@{$KOList}),"KOlist");
1273 :     my $solutions;
1274 :     if (defined($solutionRow)) {
1275 :     #Checking if any solutions conform to the no KO list
1276 :     foreach my $solution (@{$solutionRow->{Solutions}}) {
1277 :     my @reactions = split(/,/,$solution);
1278 :     my $include = 1;
1279 :     foreach my $rxn (@reactions) {
1280 :     if ($rxn =~ m/(rxn\d\d\d\d\d)/) {
1281 :     if (defined($noKOHash->{$1})) {
1282 :     $include = 0;
1283 :     }
1284 :     }
1285 :     }
1286 :     if ($include == 1) {
1287 :     push(@{$solutions},$solution);
1288 :     }
1289 :     }
1290 :     } else {
1291 :     $solutionRow = {Media => [$Media],Experiment => [$Experiment],KOlist => [join(",",@{$KOList})]};
1292 :     $tbl->add_row($solutionRow);
1293 :     $self->figmodel()->database()->save_table($tbl);
1294 :     }
1295 :     $self->releaseModelLock();
1296 :    
1297 :     #Returning solution list of solutions were found
1298 :     if (defined($solutions) && @{$solutions} > 0) {
1299 :     return $solutions;
1300 :     }
1301 :    
1302 :     #Getting unique filename
1303 :     my $Filename = $self->figmodel()->filename();
1304 :    
1305 :     #Running the gap generation
1306 :     system($self->figmodel()->GenerateMFAToolkitCommandLineCall($Filename,$self->id().$self->selected_version(),$Media,["GapGeneration"],{"Recursive MILP solution limit" => $SolutionLimit ,"Reactions that should always be active" => join(";",@{$NoKOList}),"Reactions to knockout" => join(";",@{$KOList}),"Reactions that are always blocked" => "none"},"Gapgeneration-".$self->id().$self->selected_version()."-".$Filename.".log",undef,undef));
1307 :     my $ProblemReport = $self->figmodel()->LoadProblemReport($Filename);
1308 :     if (!defined($ProblemReport)) {
1309 :     $self->figmodel()->error_message("FIGMODEL:GapGenerationAlgorithm;No problem report;".$Filename.";".$self->id().$self->selected_version().";".$Media.";".$KOList.";".$NoKOList);
1310 :     return undef;
1311 :     }
1312 :    
1313 :     #Clearing the output folder and log file
1314 :     $self->figmodel()->clearing_output($Filename,"Gapgeneration-".$self->id().$self->selected_version()."-".$Filename.".log");
1315 :    
1316 :     #Saving the solution
1317 :     $self->aquireModelLock();
1318 :     $tbl = $self->load_model_table("GapGenSolutions");
1319 :     $solutionRow = $tbl->get_table_by_key($Experiment,"Experiment")->get_table_by_key($Media,"Media")->get_row_by_key(join(",",@{$KOList}),"KOlist");
1320 :     for (my $j=0; $j < $ProblemReport->size(); $j++) {
1321 :     if ($ProblemReport->get_row($j)->{"Notes"}->[0] =~ m/^Recursive\sMILP\s([^)]+)/) {
1322 :     my @SolutionList = split(/\|/,$1);
1323 :     for (my $k=0; $k < @SolutionList; $k++) {
1324 :     if ($SolutionList[$k] =~ m/(\d+):(.+)/) {
1325 :     push(@{$solutionRow->{Solutions}},$2);
1326 :     push(@{$solutions},$2);
1327 :     }
1328 :     }
1329 :     }
1330 :     }
1331 :     $self->figmodel()->database()->save_table($tbl);
1332 :     $self->releaseModelLock();
1333 :    
1334 :     return $solutions;
1335 :     }
1336 :    
1337 : chenry 1.2 =head3 datagapfill
1338 :     Definition:
1339 :     success()/fail() = FIGMODELmodel->datagapfill();
1340 :     Description:
1341 :     Run gapfilling on the input run specifications
1342 :     =cut
1343 :     sub datagapfill {
1344 :     my ($self,$GapFillingRunSpecs,$TansferFileSuffix) = @_;
1345 :     my $UniqueFilename = $self->figmodel()->filename();
1346 :     if (defined($GapFillingRunSpecs) && @{$GapFillingRunSpecs} > 0) {
1347 :     system($self->figmodel()->GenerateMFAToolkitCommandLineCall($UniqueFilename,$self->id().$self->selected_version(),"NoBounds",["DataGapFilling"],{"Reactions to knockout" => $self->config("permanently knocked out reactions")->[0],"Gap filling runs" => join(";",@{$GapFillingRunSpecs})},"GapFilling-".$self->id().$self->selected_version()."-".$UniqueFilename.".log",undef,undef));
1348 :     #Checking that the solution exists
1349 :     if (!-e $self->config("MFAToolkit output directory")->[0].$UniqueFilename."/GapFillingSolutionTable.txt") {
1350 :     $self->figmodel()->error_message("FIGMODEL:GapFillingAlgorithm: Could not find MFA output file!");
1351 :     $self->figmodel()->database()->print_array_to_file($self->directory().$self->id().$self->selected_version()."-GFS.txt",["Experiment;Solution index;Solution cost;Solution reactions"]);
1352 :     return undef;
1353 :     }
1354 :     my $GapFillResultTable = $self->figmodel()->database()->load_table($self->config("MFAToolkit output directory")->[0].$UniqueFilename."/GapFillingSolutionTable.txt",";","",0,undef);
1355 :     if (defined($TansferFileSuffix)) {
1356 :     system("cp ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/GapFillingSolutionTable.txt ".$self->directory().$self->id().$self->selected_version()."-".$TansferFileSuffix.".txt");
1357 :     }
1358 :     #If the system is not configured to preserve all logfiles, then the mfatoolkit output folder is deleted
1359 :     $self->figmodel()->clearing_output($UniqueFilename,"GapFilling-".$self->id().$self->selected_version()."-".$UniqueFilename.".log");
1360 : chenry 1.5 return $GapFillResultTable;
1361 : chenry 1.2 }
1362 :     if (defined($TansferFileSuffix)) {
1363 :     $self->figmodel()->database()->print_array_to_file($self->directory().$self->id().$self->selected_version()."-".$TansferFileSuffix.".txt",["Experiment;Solution index;Solution cost;Solution reactions"]);
1364 :     }
1365 :     return undef;
1366 :     }
1367 :    
1368 :     =head3 TestSolutions
1369 :     Definition:
1370 :     $model->TestSolutions($ModelID,$NumProcessors,$ProcessorIndex,$GapFill);
1371 :     Description:
1372 :     Example:
1373 :     =cut
1374 :    
1375 :     sub TestSolutions {
1376 :     my ($self,$OriginalErrorFilename,$GapFillResultTable) = @_;
1377 :     #Getting the filename
1378 :     my $UniqueFilename = $self->figmodel()->filename();
1379 :     #Reading in the original error matrix which has the headings for the original model simulation
1380 :     my $OriginalErrorData;
1381 :     if (!defined($OriginalErrorFilename) || !-e $self->directory().$OriginalErrorFilename) {
1382 :     my ($FalsePostives,$FalseNegatives,$CorrectNegatives,$CorrectPositives,$Errorvector,$HeadingVector) = $self->RunAllStudiesWithDataFast("All");
1383 :     $OriginalErrorData = [$HeadingVector,$Errorvector];
1384 :     } else {
1385 :     $OriginalErrorData = $self->figmodel()->database()->load_single_column_file($self->directory().$OriginalErrorFilename,"");
1386 :     }
1387 :     my $HeadingHash;
1388 :     my @HeadingArray = split(/;/,$OriginalErrorData->[0]);
1389 :     my @OrigErrorArray = split(/;/,$OriginalErrorData->[1]);
1390 :     for (my $i=0; $i < @HeadingArray; $i++) {
1391 :     my @SubArray = split(/:/,$HeadingArray[$i]);
1392 :     $HeadingHash->{$SubArray[0].":".$SubArray[1].":".$SubArray[2]} = $i;
1393 :     }
1394 :     #Scanning through the gap filling solutions
1395 :     my $TempVersion = "V".$UniqueFilename;
1396 :     my $ErrorMatrixLines;
1397 :     for (my $i=0; $i < $GapFillResultTable->size(); $i++) {
1398 :     print "Starting problem solving ".$i."\n";
1399 :     my $ErrorLine = $GapFillResultTable->get_row($i)->{"Experiment"}->[0].";".$GapFillResultTable->get_row($i)->{"Solution index"}->[0].";".$GapFillResultTable->get_row($i)->{"Solution cost"}->[0].";".$GapFillResultTable->get_row($i)->{"Solution reactions"}->[0];
1400 :     #Integrating solution into test model
1401 :     my $ReactionArray;
1402 :     my $DirectionArray;
1403 :     my @ReactionList = split(/,/,$GapFillResultTable->get_row($i)->{"Solution reactions"}->[0]);
1404 :     my %SolutionHash;
1405 :     for (my $k=0; $k < @ReactionList; $k++) {
1406 :     if ($ReactionList[$k] =~ m/(.+)(rxn\d\d\d\d\d)/) {
1407 :     my $Reaction = $2;
1408 :     my $Sign = $1;
1409 :     if (defined($SolutionHash{$Reaction})) {
1410 :     $SolutionHash{$Reaction} = "<=>";
1411 :     } elsif ($Sign eq "-") {
1412 :     $SolutionHash{$Reaction} = "<=";
1413 :     } elsif ($Sign eq "+") {
1414 :     $SolutionHash{$Reaction} = "=>";
1415 :     } else {
1416 :     $SolutionHash{$Reaction} = $Sign;
1417 :     }
1418 :     }
1419 :     }
1420 :     @ReactionList = keys(%SolutionHash);
1421 :     for (my $k=0; $k < @ReactionList; $k++) {
1422 :     push(@{$ReactionArray},$ReactionList[$k]);
1423 :     push(@{$DirectionArray},$SolutionHash{$ReactionList[$k]});
1424 :     }
1425 :     print "Integrating solution!\n";
1426 : chenry 1.5 $self->figmodel()->IntegrateGrowMatchSolution($self->id().$self->selected_version(),$self->directory().$self->id().$TempVersion.".txt",$ReactionArray,$DirectionArray,"Gapfilling ".$GapFillResultTable->get_row($i)->{"Experiment"}->[0],1,1);
1427 :     $self->PrintModelLPFile();
1428 : chenry 1.2 #Running the model against all available experimental data
1429 :     print "Running test model!\n";
1430 :     my ($FalsePostives,$FalseNegatives,$CorrectNegatives,$CorrectPositives,$Errorvector,$HeadingVector) = $self->RunAllStudiesWithDataFast("All");
1431 :    
1432 :     @HeadingArray = split(/;/,$HeadingVector);
1433 :     my @ErrorArray = @OrigErrorArray;
1434 :     my @TempArray = split(/;/,$Errorvector);
1435 :     for (my $j=0; $j < @HeadingArray; $j++) {
1436 :     my @SubArray = split(/:/,$HeadingArray[$j]);
1437 :     $ErrorArray[$HeadingHash->{$SubArray[0].":".$SubArray[1].":".$SubArray[2]}] = $TempArray[$j];
1438 :     }
1439 :     $ErrorLine .= ";".$FalsePostives."/".$FalseNegatives.";".join(";",@ErrorArray);
1440 :     push(@{$ErrorMatrixLines},$ErrorLine);
1441 :     print "Finishing problem solving ".$i."\n";
1442 :     }
1443 :     #Clearing out the test model
1444 :     if (-e $self->directory().$self->id().$TempVersion.".txt") {
1445 :     unlink($self->directory().$self->id().$TempVersion.".txt");
1446 :     unlink($self->directory()."SimulationOutput".$self->id().$TempVersion.".txt");
1447 :     }
1448 :     return $ErrorMatrixLines;
1449 :     }
1450 :    
1451 :     =head3 status
1452 :     Definition:
1453 :     int::model status = FIGMODELmodel->status();
1454 :     Description:
1455 :     Returns the current status of the SEED model associated with the input genome ID.
1456 :     model status = 1: model exists
1457 :     model status = 0: model is being built
1458 :     model status = -1: model does not exist
1459 :     model status = -2: model build failed
1460 :     =cut
1461 :     sub status {
1462 :     my ($self) = @_;
1463 :     return $self->{_data}->{status}->[0];
1464 :     }
1465 :    
1466 :     =head3 message
1467 :     Definition:
1468 :     string::model message = FIGMODELmodel->message();
1469 :     Description:
1470 :     Returns a message associated with the models current status
1471 :     =cut
1472 :     sub message {
1473 :     my ($self) = @_;
1474 :     return $self->{_data}->{message}->[0];
1475 :     }
1476 :    
1477 :     =head3 set_status
1478 :     Definition:
1479 :     (success/fail) = FIGMODELmodel->set_status(int::new status,string::status message);
1480 :     Description:
1481 :     Changes the current status of the SEED model
1482 :     new status = 1: model exists
1483 :     new status = 0: model is being built
1484 :     new status = -1: model does not exist
1485 :     new status = -2: model build failed
1486 :     =cut
1487 :     sub set_status {
1488 :     my ($self,$NewStatus,$Message) = @_;
1489 :    
1490 :     #Getting the model row from the MODELS table
1491 :     $self->{_data}->{status}->[0] = $NewStatus;
1492 :     $self->{_data}->{message}->[0] = $Message;
1493 :     $self->figmodel()->database()->update_row("MODELS",$self->{_data},"id");
1494 :     return $self->config("SUCCESS")->[0];
1495 :     }
1496 :    
1497 :     =head3 CreateSingleGenomeReactionList
1498 :     Definition:
1499 :     FIGMODEL->CreateSingleGenomeReactionList();
1500 :     Description:
1501 :     This function uses fig calls to obtain a list of genes and functions for a genome, and it uses a file mapping reactions and functional roles to produce a reaction list.
1502 :     Example:
1503 :     =cut
1504 :    
1505 :     sub CreateSingleGenomeReactionList {
1506 :     my ($self,$RunGapFilling) = @_;
1507 :    
1508 : chenry 1.5 #Creating directory
1509 :     if ($self->owner() ne "master" && !-d $self->figmodel()->config("organism directory")->[0].$self->owner()."/") {
1510 :     system("mkdir ".$self->figmodel()->config("organism directory")->[0].$self->owner()."/");
1511 :     } elsif ($self->owner() eq "master" && !-d $self->figmodel()->config("organism directory")->[0].$self->genome()."/") {
1512 :     system("mkdir ".$self->figmodel()->config("organism directory")->[0].$self->genome()."/");
1513 :     }
1514 :     if ($self->owner() ne "master" && !-d $self->figmodel()->config("organism directory")->[0].$self->owner()."/".$self->genome()."/") {
1515 :     system("mkdir ".$self->figmodel()->config("organism directory")->[0].$self->owner()."/".$self->genome()."/");
1516 :     }
1517 :    
1518 : chenry 1.2 #Getting genome stats
1519 :     my $genomestats = $self->figmodel()->get_genome_stats($self->genome());
1520 :     my $FeatureTable = $self->figmodel()->GetGenomeFeatureTable($self->genome());
1521 :     if (!defined($FeatureTable)) {
1522 :     $self->figmodel()->error_message("FIGMODEL:CreateSingleGenomeReactionList: ".$self->id()." genome features could not be accessed!");
1523 :     return $self->fail();
1524 :     }
1525 :     #Checking that the number of genes exceeds the minimum size
1526 :     if ($FeatureTable->size() < $self->config("minimum genome size for modeling")->[0]) {
1527 :     $self->figmodel()->error_message("FIGMODEL:CreateSingleGenomeReactionList: ".$self->id()." genome rejected as too small for modeling!");
1528 :     return $self->fail();
1529 :     }
1530 :     #Setting up needed variables
1531 :     my $OriginalModelTable = undef;
1532 :     #Locking model status table
1533 :     my $ModelTable = $self->figmodel()->database()->LockDBTable("MODELS");
1534 :     my $Row = $ModelTable->get_row_by_key($self->id(),"id");
1535 :     if (!defined($Row) || !defined($Row->{status}->[0])) {
1536 :     $self->figmodel()->database()->UnlockDBTable("MODELS");
1537 :     $self->figmodel()->error_message("FIGMODEL:CreateSingleGenomeReactionList: ".$self->id()." has no row in models table!");
1538 :     return $self->fail();
1539 :     } elsif ($Row->{status}->[0] == 0) {
1540 :     $self->figmodel()->error_message("FIGMODEL:CreateSingleGenomeReactionList:Model is already being built. Canceling current build.");
1541 :     $self->figmodel()->database()->UnlockDBTable("MODELS");
1542 :     return $self->fail();
1543 :     }elsif ($Row->{status}->[0] == 1) {
1544 :     $OriginalModelTable = $self->reaction_table();
1545 :     $self->ArchiveModel();
1546 :     $Row->{status}->[0] = 0;
1547 :     $Row->{message}->[0] = "Rebuilding preliminary reconstruction";
1548 :     } else {
1549 :     $Row->{status}->[0] = 0;
1550 :     $Row->{message}->[0] = "Preliminary reconstruction";
1551 :     }
1552 :     #Updating the status table
1553 :     $self->figmodel()->database()->save_table($ModelTable);
1554 :     $self->figmodel()->database()->UnlockDBTable("MODELS");
1555 :     #Sorting GenomeData by gene location on the chromosome
1556 :     $FeatureTable->sort_rows("MIN LOCATION");
1557 :     my ($ComplexHash,$SuggestedMappings,$UnrecognizedReactions,$ReactionHash);
1558 :     my %LastGenePosition;
1559 :     my $GeneRoles;
1560 :     for (my $j=0; $j < $FeatureTable->size(); $j++) {
1561 :     my $CurrentRow = $FeatureTable->get_row($j);
1562 :     #"ID","ALIASES","MIN LOCATION","MAX LOCATION","ROLES","SUBSYSTEMS","SUBSYSTEM CLASS"
1563 :     if (defined($CurrentRow)) {
1564 :     my $GeneID = $CurrentRow->{"ID"}->[0];
1565 :     if ($GeneID =~ m/(peg\.\d+)/) {
1566 :     $GeneID = $1;
1567 :     }
1568 :     foreach my $Role (@{$CurrentRow->{"ROLES"}}) {
1569 :     if ($self->figmodel()->role_is_valid($Role) != 0) {
1570 :     push(@{$GeneRoles->{$GeneID}},$Role);
1571 :     my $ReactionHashArrayRef = $self->figmodel()->reactions_of_role($Role);
1572 :     if ($ReactionHashArrayRef != 0) {
1573 :     foreach my $Mapping (@{$ReactionHashArrayRef}) {
1574 :     if (defined($Mapping->{"REACTION"}) && defined($Mapping->{"MASTER"}) && defined($Mapping->{"SUBSYSTEM"}) && defined($Mapping->{"SOURCE"})) {
1575 :     if ($Mapping->{"REACTION"}->[0] =~ m/rxn\d\d\d\d\d/) {
1576 :     if ($Mapping->{"MASTER"}->[0] eq 1) {
1577 :     #Creating a complex if consecutive genes have been assigned to the same reaction
1578 :     $ComplexHash->{$Mapping->{"REACTION"}->[0]}->{$Mapping->{"COMPLEX"}->[0]}->{$Role}->{$GeneID} = 1;
1579 :     if (!defined($LastGenePosition{$Mapping->{"REACTION"}->[0]})) {
1580 :     $LastGenePosition{$Mapping->{"REACTION"}->[0]} = $j;
1581 :     push(@{$ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"GENES"}},$GeneID);
1582 :     } elsif (($j-$LastGenePosition{$Mapping->{"REACTION"}->[0]}) < 3 && $LastGenePosition{$Mapping->{"REACTION"}->[0]} != $j) {
1583 :     my $CurrentComplex = pop(@{$ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"GENES"}});
1584 :     push(@{$ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"GENES"}},$CurrentComplex."+".$GeneID);
1585 :     } elsif ($LastGenePosition{$Mapping->{"REACTION"}->[0]} != $j) {
1586 :     push(@{$ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"GENES"}},$GeneID);
1587 :     }
1588 :     $LastGenePosition{$Mapping->{"REACTION"}->[0]} = $j;
1589 :     #Adding a subsystem for the reaction
1590 :     if ($self->figmodel()->subsystem_is_valid($Mapping->{"SUBSYSTEM"}->[0]) == 1) {
1591 :     ($ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"SUBSYSTEMS"},my $NumMatches) = $self->figmodel()->add_elements_unique($ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"SUBSYSTEMS"},$Mapping->{"SUBSYSTEM"}->[0]);
1592 :     if (!defined($ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}) || $ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}->[0] > 1) {
1593 :     if ($Mapping->{"SOURCE"}->[0] =~ m/Hope\sFiles/) {
1594 :     $ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}->[0] = 1;
1595 :     } elsif ($Mapping->{"SOURCE"}->[0] =~ m/SEED/) {
1596 :     $ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}->[0] = 2;
1597 :     } elsif (!defined($ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}) || $ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}->[0] > 2) {
1598 :     $ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}->[0] = 3;
1599 :     }
1600 :     }
1601 :     }
1602 :     #Handling confidence
1603 :     if (!defined($ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}) || $ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}->[0] > 2) {
1604 :     if ($Mapping->{"SOURCE"}->[0] =~ m/MATT/) {
1605 :     $ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}->[0] = 3;
1606 :     } elsif ($Mapping->{"SOURCE"}->[0] =~ m/CHRIS/) {
1607 :     $ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}->[0] = 4;
1608 :     } else {
1609 :     $ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"CONFIDENCE"}->[0] = 5;
1610 :     }
1611 :     }
1612 :     #Parsing sources
1613 :     ($ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"SOURCE"},my $NumMatches) = $self->figmodel()->add_elements_unique($ReactionHash->{$Mapping->{"REACTION"}->[0]}->{"SOURCE"},split(/\|/,$Mapping->{"SOURCE"}->[0]));
1614 :     } else {
1615 :     push(@{$SuggestedMappings},$GeneID."\t".$Mapping->{"REACTION"}->[0]."\t".$Role);
1616 :     }
1617 :     } else {
1618 :     push(@{$UnrecognizedReactions},$GeneID."\t".$Mapping->{"REACTION"}->[0]."\t".$Role);
1619 :     }
1620 :     }
1621 :     }
1622 :     }
1623 :     }
1624 :     }
1625 :     }
1626 :     }
1627 :    
1628 :     #Creating nonadjacent complexes
1629 :     my @ReactionList = keys(%{$ReactionHash});
1630 :     foreach my $Reaction (@ReactionList) {
1631 :     #If multiple genes are assigned to the reaction, we check if they should should be in a complex
1632 :     if (@{$ReactionHash->{$Reaction}->{"GENES"}} > 0 && defined($ComplexHash->{$Reaction})) {
1633 :     my $GeneArray;
1634 :     foreach my $Complex (keys(%{$ComplexHash->{$Reaction}})) {
1635 :     my %ComplexComponents;
1636 :     foreach my $CurrentGeneSet (@{$ReactionHash->{$Reaction}->{"GENES"}}) {
1637 :     my @GeneList = split(/\+/,$CurrentGeneSet);
1638 :     my %RoleHash;
1639 :     foreach my $Gene (@GeneList) {
1640 :     foreach my $Role (@{$GeneRoles->{$Gene}}) {
1641 :     if (defined($ComplexHash->{$Reaction}->{$Complex}->{$Role})) {
1642 :     $RoleHash{$Role} = 1;
1643 :     }
1644 :     }
1645 :     }
1646 :     if (keys(%RoleHash) > 0) {
1647 :     if (!defined($ComplexComponents{join("|",sort(keys(%RoleHash)))})) {
1648 :     my @RoleList = keys(%RoleHash);
1649 :     my @ComplexList = keys(%ComplexComponents);
1650 :     foreach my $ComplexSet (@ComplexList) {
1651 :     my @RoleList = split(/\|/,$ComplexSet);
1652 :     my $Match = 0;
1653 :     foreach my $SingleRole (@RoleList) {
1654 :     if (defined($RoleHash{$SingleRole})) {
1655 :     $Match = 1;
1656 :     last;
1657 :     }
1658 :     }
1659 :     if ($Match == 1) {
1660 :     foreach my $SingleRole (@RoleList) {
1661 :     $RoleHash{$SingleRole} = 1
1662 :     }
1663 :     push(@{$ComplexComponents{join("|",sort(keys(%RoleHash)))}},@{$ComplexComponents{$ComplexSet}});
1664 :     delete $ComplexComponents{$ComplexSet};
1665 :     }
1666 :     }
1667 :     }
1668 :     push(@{$ComplexComponents{join("|",sort(keys(%RoleHash)))}},$CurrentGeneSet);
1669 :     }
1670 :     }
1671 :     my @Position;
1672 :     my @Options;
1673 :     my $Count = 0;
1674 :     foreach my $RoleSet (keys(%ComplexComponents)) {
1675 :     push(@Position,0);
1676 :     push(@{$Options[$Count]},@{$ComplexComponents{$RoleSet}});
1677 :     $Count++;
1678 :     }
1679 :     my $Done = 0;
1680 :     $Count = 0;
1681 :     my $NewRelationship;
1682 :     while($Done == 0) {
1683 :     #Creating complex with current indecies
1684 :     $NewRelationship->[$Count] = $Options[0]->[$Position[0]];
1685 :     for (my $i=1; $i < @Position; $i++) {
1686 :     $NewRelationship->[$Count] .= "+".$Options[$i]->[$Position[$i]];
1687 :     }
1688 :     $NewRelationship->[$Count] = join("+",$self->figmodel()->remove_duplicates(split(/\+/,$NewRelationship->[$Count])));
1689 :     $Count++;
1690 :     #Iterating indecies
1691 :     my $CurrentIndex = 0;
1692 :     while($CurrentIndex >= 0) {
1693 :     if ($CurrentIndex >= @Position) {
1694 :     $CurrentIndex = -1000;
1695 :     } elsif ($Position[$CurrentIndex]+1 == @{$Options[$CurrentIndex]}) {
1696 :     $Position[$CurrentIndex] = -1;
1697 :     $CurrentIndex++;
1698 :     } else {
1699 :     $Position[$CurrentIndex]++;
1700 :     $CurrentIndex--;
1701 :     }
1702 :     }
1703 :     if ($CurrentIndex == -1000) {
1704 :     $Done = 1;
1705 :     }
1706 :     }
1707 :     push(@{$GeneArray},@{$NewRelationship});
1708 :     }
1709 :     @{$ReactionHash->{$Reaction}->{"GENES"}} = $self->figmodel()->remove_duplicates(@{$GeneArray});
1710 :     }
1711 :     }
1712 :    
1713 :     #Getting the reaction table
1714 :     my $ReactionTable = $self->figmodel()->database()->GetDBTable("REACTIONS");
1715 :    
1716 :     #Creating the model reaction table
1717 :     my $NewModelTable = FIGMODELTable->new(["LOAD","DIRECTIONALITY","COMPARTMENT","ASSOCIATED PEG","SUBSYSTEM","CONFIDENCE","REFERENCE","NOTES"],$self->directory().$self->id().".txt",["LOAD"],";","|","REACTIONS\n");
1718 :     @ReactionList = keys(%{$ReactionHash});
1719 :     foreach my $ReactionID (@ReactionList) {
1720 :     #Getting the thermodynamic reversibility from the database
1721 :     my $Directionality = $self->figmodel()->reversibility_of_reaction($ReactionID);
1722 :     my $Subsystem = "NONE";
1723 :     if (defined($ReactionHash->{$ReactionID}->{"SUBSYSTEMS"})) {
1724 :     $Subsystem = join("|",@{$ReactionHash->{$ReactionID}->{"SUBSYSTEMS"}});
1725 :     }
1726 :     my $Source = "NONE";
1727 :     if (defined($ReactionHash->{$ReactionID}->{"SOURCE"})) {
1728 :     $Source = join("|",@{$ReactionHash->{$ReactionID}->{"SOURCE"}});
1729 :     }
1730 :     $NewModelTable->add_row({"LOAD" => [$ReactionID],"DIRECTIONALITY" => [$Directionality],"COMPARTMENT" => ["c"],"ASSOCIATED PEG" => [join("|",@{$ReactionHash->{$ReactionID}->{"GENES"}})],"SUBSYSTEM" => [$Subsystem],"CONFIDENCE" => [$ReactionHash->{$ReactionID}->{"CONFIDENCE"}->[0]],"REFERENCE" => [$Source],"NOTES" => ["NONE"]});
1731 :     }
1732 :    
1733 :     #Adding the spontaneous and universal reactions
1734 :     foreach my $ReactionID (@{$self->config("spontaneous reactions")}) {
1735 :     #Getting the thermodynamic reversibility from the database
1736 :     my $Directionality = $self->figmodel()->reversibility_of_reaction($ReactionID);
1737 :     #Checking if the reaction is already in the model
1738 :     if (!defined($NewModelTable->get_row_by_key($ReactionID,"LOAD"))) {
1739 :     $NewModelTable->add_row({"LOAD" => [$ReactionID],"DIRECTIONALITY" => [$Directionality],"COMPARTMENT" => ["c"],"ASSOCIATED PEG" => ["SPONTANEOUS"],"SUBSYSTEM" => ["NONE"],"CONFIDENCE" => [4],"REFERENCE" => ["SPONTANEOUS"],"NOTES" => ["NONE"]});
1740 :     }
1741 :     }
1742 :     foreach my $ReactionID (@{$self->config("universal reactions")}) {
1743 :     #Getting the thermodynamic reversibility from the database
1744 :     my $Directionality = $self->figmodel()->reversibility_of_reaction($ReactionID);
1745 :     #Checking if the reaction is already in the model
1746 :     if (!defined($NewModelTable->get_row_by_key($ReactionID,"LOAD"))) {
1747 :     $NewModelTable->add_row({"LOAD" => [$ReactionID],"DIRECTIONALITY" => [$Directionality],"COMPARTMENT" => ["c"],"ASSOCIATED PEG" => ["UNIVERSAL"],"SUBSYSTEM" => ["NONE"],"CONFIDENCE" => [4],"REFERENCE" => ["UNIVERSAL"],"NOTES" => ["NONE"]});
1748 :     }
1749 :     }
1750 :    
1751 :     #Checking if a biomass reaction already exists
1752 : chenry 1.13 my $BiomassReactionRow = $self->BuildSpecificBiomassReaction();
1753 : chenry 1.2 if (!defined($BiomassReactionRow)) {
1754 : chenry 1.13 $self->set_status(-2,"Preliminary reconstruction failed: could not generate biomass reaction");
1755 :     $self->figmodel()->error_message("FIGMODEL:CreateModelReactionList: Could not generate biomass function for ".$self->id()."!");
1756 :     return $self->fail();
1757 : chenry 1.2 }
1758 :     my $ReactionList = $BiomassReactionRow->{"ESSENTIAL REACTIONS"};
1759 :     push(@{$ReactionList},$BiomassReactionRow->{DATABASE}->[0]);
1760 :    
1761 :     #Adding biomass reactions to the model table
1762 :     foreach my $BOFReaction (@{$ReactionList}) {
1763 :     #Getting the thermodynamic reversibility from the database
1764 :     my $Directionality = $self->figmodel()->reversibility_of_reaction($BOFReaction);
1765 :     #Checking if the reaction is already in the model
1766 :     if (!defined($NewModelTable->get_row_by_key($BOFReaction,"LOAD"))) {
1767 :     if ($BOFReaction =~ m/bio/) {
1768 :     $NewModelTable->add_row({"LOAD" => [$BOFReaction],"DIRECTIONALITY" => [$Directionality],"COMPARTMENT" => ["c"],"ASSOCIATED PEG" => ["BOF"],"SUBSYSTEM" => ["NONE"],"CONFIDENCE" => [1],"REFERENCE" => ["Biomass objective function"],"NOTES" => ["NONE"]});
1769 :     } else {
1770 :     $NewModelTable->add_row({"LOAD" => [$BOFReaction],"DIRECTIONALITY" => [$Directionality],"COMPARTMENT" => ["c"],"ASSOCIATED PEG" => ["INITIAL GAP FILLING"],"SUBSYSTEM" => ["NONE"],"CONFIDENCE" => [5],"REFERENCE" => ["Initial gap filling"],"NOTES" => ["NONE"]});
1771 :     }
1772 :     }
1773 :     }
1774 :    
1775 :     #Completing any incomplete reactions sets
1776 :     my $ReactionSetTable = $self->figmodel()->database()->GetDBTable("REACTION SETS");
1777 :     for (my $i=0; $i < $ReactionSetTable->size(); $i++) {
1778 :     if (defined($NewModelTable->get_row_by_key($ReactionSetTable->get_row($i)->{"Trigger reaction"}->[0],"LOAD"))) {
1779 :     foreach my $Reaction (@{$ReactionSetTable->get_row($i)->{"Dependant reactions"}}) {
1780 :     if (!defined($NewModelTable->get_row_by_key($ReactionSetTable->get_row($i)->{"Trigger reaction"}->[0],"LOAD"))) {
1781 :     #Getting the thermodynamic reversibility from the database
1782 :     my $Directionality = $self->figmodel()->reversibility_of_reaction($Reaction);
1783 :     $NewModelTable->add_row({"LOAD" => [$Reaction],"DIRECTIONALITY" => [$Directionality],"COMPARTMENT" => ["c"],"ASSOCIATED PEG" => ["REACTION SET GAP FILLING"],"SUBSYSTEM" => ["NONE"],"CONFIDENCE" => [5],"REFERENCE" => ["Added due to presence of ".$ReactionSetTable->get_row($i)->{"Trigger reaction"}->[0]],"NOTES" => ["NONE"]});
1784 :     }
1785 :     }
1786 :     }
1787 :     }
1788 :    
1789 :     #Now we compare the model to the previous model to determine if any differences exist that aren't gap filling reactions
1790 :     if (defined($OriginalModelTable)) {
1791 :     my $PerfectMatch = 1;
1792 :     my $ReactionCount = 0;
1793 :     for (my $i=0; $i < $OriginalModelTable->size(); $i++) {
1794 :     #We only check that nongapfilling reactions exist in the new model
1795 :     if ($OriginalModelTable->get_row($i)->{"ASSOCIATED PEG"}->[0] !~ m/GAP/ || $OriginalModelTable->get_row($i)->{"ASSOCIATED PEG"}->[0] eq "INITIAL GAP FILLING") {
1796 :     $ReactionCount++;
1797 :     my $Row = $NewModelTable->get_row_by_key($OriginalModelTable->get_row($i)->{"LOAD"}->[0],"LOAD");
1798 :     if (defined($Row)) {
1799 :     #We check that the reaction directionality is identical
1800 :     if ($Row->{"DIRECTIONALITY"}->[0] ne $OriginalModelTable->get_row($i)->{"DIRECTIONALITY"}->[0]) {
1801 :     if (defined($OriginalModelTable->get_row($i)->{"NOTES"}->[0]) && $OriginalModelTable->get_row($i)->{"NOTES"}->[0] =~ m/Directionality\sswitched\sfrom\s([^\s])/) {
1802 :     if ($1 ne $Row->{"DIRECTIONALITY"}->[0]) {
1803 :     print "Directionality mismatch for reaction ".$OriginalModelTable->get_row($i)->{"LOAD"}->[0].": ".$1." vs ".$Row->{"DIRECTIONALITY"}->[0]."\n";
1804 :     $PerfectMatch = 0;
1805 :     last;
1806 :     }
1807 :     } else {
1808 :     print "Directionality mismatch for reaction ".$OriginalModelTable->get_row($i)->{"LOAD"}->[0].": ".$OriginalModelTable->get_row($i)->{"DIRECTIONALITY"}->[0]." vs ".$Row->{"DIRECTIONALITY"}->[0]."\n";
1809 :     $PerfectMatch = 0;
1810 :     last;
1811 :     }
1812 :     }
1813 :     #We check that the genes assigned to the reaction are identical
1814 :     if ($PerfectMatch == 1 && @{$OriginalModelTable->get_row($i)->{"ASSOCIATED PEG"}} != @{$Row->{"ASSOCIATED PEG"}}) {
1815 :     print "Gene associatation mismatch for reaction ".$OriginalModelTable->get_row($i)->{"LOAD"}->[0].": ".@{$OriginalModelTable->get_row($i)->{"ASSOCIATED PEG"}}." vs ".@{$Row->{"ASSOCIATED PEG"}}."\n";
1816 :     $PerfectMatch = 0;
1817 :     last;
1818 :     }
1819 :     if ($PerfectMatch == 1) {
1820 :     my @GeneSetOne = sort(@{$OriginalModelTable->get_row($i)->{"ASSOCIATED PEG"}});
1821 :     my @GeneSetTwo = sort(@{$Row->{"ASSOCIATED PEG"}});
1822 :     for (my $j=0; $j < @GeneSetOne; $j++) {
1823 :     if ($GeneSetOne[$j] ne $GeneSetTwo[$j]) {
1824 :     print "Gene mismatch for reaction ".$OriginalModelTable->get_row($i)->{"LOAD"}->[0].": ".$GeneSetOne[$j]." vs ".$GeneSetTwo[$j]."\n";
1825 :     $PerfectMatch = 0;
1826 :     $i = $OriginalModelTable->size();
1827 :     last;
1828 :     }
1829 :     }
1830 :     }
1831 :     } else {
1832 :     print "Original model contains an extra reaction:".$OriginalModelTable->get_row($i)->{"LOAD"}->[0]."\n";
1833 :     $PerfectMatch = 0;
1834 :     last;
1835 :     }
1836 :     }
1837 :     }
1838 :     if ($PerfectMatch == 1 && $ReactionCount == $NewModelTable->size()) {
1839 :     #Bailing out of function as the model has not changed
1840 :     $self->set_status(1,"rebuild canceled because model has not changed");
1841 :     return $self->success();
1842 :     }
1843 :     }
1844 :    
1845 :     #Saving the new model to file
1846 :     $self->set_status(1,"Preliminary reconstruction complete");
1847 :     $self->figmodel()->database()->save_table($NewModelTable);
1848 :     $self->{_reaction_data} = $NewModelTable;
1849 :     #Clearing the previous model from the cache
1850 : chenry 1.7 $self->figmodel()->database()->ClearDBModel($self->id(),1);
1851 : chenry 1.2 #Updating the model stats table
1852 :     $self->update_stats_for_build();
1853 :     $self->PrintSBMLFile();
1854 :    
1855 :     #Adding model to gapfilling queue
1856 :     if (defined($RunGapFilling) && $RunGapFilling == 1) {
1857 :     $self->set_status(1,"Autocompletion queued");
1858 :     $self->figmodel()->add_job_to_queue("gapfillmodel?".$self->id(),"QSUB","cplex",$self->owner(),"BACK");
1859 :     }
1860 :     return $self->success();
1861 :     }
1862 :    
1863 :     =head3 CreateMetaGenomeReactionList
1864 :     Definition:
1865 :     (success/fail) = FIGMODELmodel->CreateMetaGenomeReactionList();
1866 :     Description:
1867 :     This is the code called to create or update the reaction list for a metgenome model
1868 :     =cut
1869 :    
1870 :     sub CreateMetaGenomeReactionList {
1871 :     my ($self) = @_;
1872 :    
1873 :     #Checking if the metagenome file exists
1874 :     if (!-e $self->config("raw MGRAST directory")->[0].$self->genome().".summary") {
1875 :     $self->error_message("FIGMODEL:CreateMetaGenomeReactionList: could not find raw data file for metagenome ".$self->genome());
1876 :     }
1877 :     #Loading metagenome data
1878 :     my $MGRASTData = $self->figmodel()->database()->load_multiple_column_file($self->config("raw MGRAST directory")->[0].$self->genome().".summary","\t");
1879 :     if (!defined($MGRASTData)) {
1880 :     $self->error_message("FIGMODEL:CreateMetaGenomeReactionList: could not find raw data file for metagenome ".$self->genome());
1881 :     }
1882 :    
1883 :     #Setting up needed variables
1884 :     my $OriginalModelTable = undef;
1885 :    
1886 :     #Checking status
1887 :     if ($self->status() < 0) {
1888 :     $self->set_status(0,"Preliminary reconstruction");
1889 :     } elsif ($self->status() == 0) {
1890 :     $self->error_message("FIGMODEL->CreateModelReactionList:Model is already being built. Canceling current build.");
1891 :     return $self->fail();
1892 :     } else {
1893 :     $OriginalModelTable = $self->reaction_table();
1894 :     $self->ArchiveModel();
1895 :     $self->set_status(0,"Rebuilding preliminary reconstruction");
1896 :     }
1897 :    
1898 :     #Getting the reaction table
1899 :     my $ReactionTable = $self->figmodel()->database()->GetDBTable("REACTIONS");
1900 :     #Creating model table
1901 :     my $ModelTable = FIGMODELTable->new(["LOAD","DIRECTIONALITY","COMPARTMENT","ASSOCIATED PEG","SUBSYSTEM","CONFIDENCE","REFERENCE","NOTES"],$self->directory().$self->id().".txt",["LOAD"],";","|","REACTIONS\n");
1902 :     for (my $i=0; $i < @{$MGRASTData};$i++) {
1903 :     #MD5,PEG,number of sims,role,sim e-scores
1904 :     my $Role = $MGRASTData->[$i]->[3];
1905 :     my $MD5 = $MGRASTData->[$i]->[0];
1906 :     my $peg = $MGRASTData->[$i]->[1];
1907 :     my $sims = $MGRASTData->[$i]->[4];
1908 :     $sims =~ s/;/,/g;
1909 :    
1910 :     #Checking for subsystems
1911 :     my $GeneSubsystems = $self->figmodel()->subsystems_of_role($Role);
1912 :     #Checking if there are reactions associated with this role
1913 :     my $ReactionHashArrayRef = $self->figmodel()->reactions_of_role($Role);
1914 :     if ($ReactionHashArrayRef != 0) {
1915 :     foreach my $Mapping (@{$ReactionHashArrayRef}) {
1916 :     if (defined($Mapping->{"REACTION"}) && defined($Mapping->{"MASTER"}) && defined($Mapping->{"SUBSYSTEM"}) && defined($Mapping->{"SOURCE"})) {
1917 :     if ($Mapping->{"REACTION"}->[0] =~ m/rxn\d\d\d\d\d/) {
1918 :     if ($Mapping->{"MASTER"}->[0] eq 1) {
1919 :     #Checking if the reaction is already in the model
1920 :     my $ReactionRow = $ModelTable->get_row_by_key($Mapping->{"REACTION"}->[0],"LOAD");
1921 :     if (!defined($ReactionRow)) {
1922 :     $ReactionRow = {"LOAD" => [$Mapping->{"REACTION"}->[0]],"DIRECTIONALITY" => [$self->figmodel()->reversibility_of_reaction($Mapping->{"REACTION"}->[0])],"COMPARTMENT" => ["c"]};
1923 :     $ModelTable->add_row($ReactionRow);
1924 :     }
1925 :     push(@{$ReactionRow->{"ASSOCIATED PEG"}},substr($peg,4));
1926 :     push(@{$ReactionRow->{"REFERENCE"}},$MD5.":".$Role);
1927 :     push(@{$ReactionRow->{"CONFIDENCE"}},$sims);
1928 :     if (defined($GeneSubsystems)) {
1929 :     push(@{$ReactionRow->{"SUBSYSTEM"}},@{$GeneSubsystems});
1930 :     }
1931 :     }
1932 :     }
1933 :     }
1934 :     }
1935 :     }
1936 :     }
1937 :    
1938 :     #Adding the spontaneous and universal reactions
1939 :     foreach my $ReactionID (@{$self->config("spontaneous reactions")}) {
1940 :     #Getting the thermodynamic reversibility from the database
1941 :     my $Directionality = $self->figmodel()->reversibility_of_reaction($ReactionID);
1942 :     #Checking if the reaction is already in the model
1943 :     if (!defined($ModelTable->get_row_by_key($ReactionID,"LOAD"))) {
1944 :     $ModelTable->add_row({"LOAD" => [$ReactionID],"DIRECTIONALITY" => [$Directionality],"COMPARTMENT" => ["c"],"ASSOCIATED PEG" => ["SPONTANEOUS"],"SUBSYSTEM" => ["NONE"],"CONFIDENCE" => [4],"REFERENCE" => ["SPONTANEOUS"],"NOTES" => ["NONE"]});
1945 :     }
1946 :     }
1947 :     foreach my $ReactionID (@{$self->config("universal reactions")}) {
1948 :     #Getting the thermodynamic reversibility from the database
1949 :     my $Directionality = $self->figmodel()->reversibility_of_reaction($ReactionID);
1950 :     #Checking if the reaction is already in the model
1951 :     if (!defined($ModelTable->get_row_by_key($ReactionID,"LOAD"))) {
1952 :     $ModelTable->add_row({"LOAD" => [$ReactionID],"DIRECTIONALITY" => [$Directionality],"COMPARTMENT" => ["c"],"ASSOCIATED PEG" => ["UNIVERSAL"],"SUBSYSTEM" => ["NONE"],"CONFIDENCE" => [4],"REFERENCE" => ["UNIVERSAL"],"NOTES" => ["NONE"]});
1953 :     }
1954 :     }
1955 :    
1956 :     #Completing any incomplete reactions sets
1957 :     my $ReactionSetTable = $self->figmodel()->database()->GetDBTable("REACTION SETS");
1958 :     for (my $i=0; $i < $ReactionSetTable->size(); $i++) {
1959 :     if (defined($ModelTable->get_row_by_key($ReactionSetTable->get_row($i)->{"Trigger reaction"}->[0],"LOAD"))) {
1960 :     foreach my $Reaction (@{$ReactionSetTable->get_row($i)->{"Dependant reactions"}}) {
1961 :     if (!defined($ModelTable->get_row_by_key($ReactionSetTable->get_row($i)->{"Trigger reaction"}->[0],"LOAD"))) {
1962 :     #Getting the thermodynamic reversibility from the database
1963 :     my $Directionality = $self->figmodel()->reversibility_of_reaction($Reaction);
1964 :     $ModelTable->add_row({"LOAD" => [$Reaction],"DIRECTIONALITY" => [$Directionality],"COMPARTMENT" => ["c"],"ASSOCIATED PEG" => ["REACTION SET GAP FILLING"],"SUBSYSTEM" => ["NONE"],"CONFIDENCE" => [5],"REFERENCE" => ["Added due to presence of ".$ReactionSetTable->get_row($i)->{"Trigger reaction"}->[0]],"NOTES" => ["NONE"]});
1965 :     }
1966 :     }
1967 :     }
1968 :     }
1969 :    
1970 :     #Clearing the previous model from the cache
1971 : chenry 1.7 $self->figmodel()->database()->ClearDBModel($self->id(),1);
1972 : chenry 1.2 $ModelTable->save();
1973 :    
1974 :     return $self->success();
1975 :     }
1976 :    
1977 :     =head3 ArchiveModel
1978 :     Definition:
1979 :     (success/fail) = FIGMODELmodel->ArchiveModel();
1980 :     Description:
1981 :     This function archives the specified model in the model directory with the current version numbers appended.
1982 :     This function is used to preserve old versions of models prior to overwriting so new versions may be compared with old versions.
1983 :     =cut
1984 :     sub ArchiveModel {
1985 :     my ($self) = @_;
1986 :    
1987 :     #Checking that the model file exists
1988 :     if (!(-e $self->filename())) {
1989 :     $self->figmodel()->error_message("FIGMODEL:ArchiveModel: Model file ".$self->filename()." not found!");
1990 :     return $self->fail();
1991 :     }
1992 :    
1993 :     #Copying the model file
1994 :     system("cp ".$self->filename()." ".$self->directory().$self->id().$self->version().".txt");
1995 :     }
1996 :    
1997 :     =head3 PrintModelDataToFile
1998 :     Definition:
1999 :     (success/fail) = FIGMODELmodel->PrintModelDataToFile();
2000 :     Description:
2001 :     This function uses the MFAToolkit to print out all of the compound and reaction data for the input model.
2002 :     Some of the data printed by the toolkit is calculated internally in the toolkit and not stored in any files, so this data can only be retrieved through this
2003 :     function. The LoadModel function for example would not give you this data.
2004 :     =cut
2005 :     sub PrintModelDataToFile {
2006 :     my($self) = @_;
2007 :    
2008 :     #Running the MFAToolkit on the model file
2009 :     my $OutputIndex = $self->figmodel()->filename();
2010 :     my $Command = $self->config("MFAToolkit executable")->[0]." parameterfile ../Parameters/Printing.txt resetparameter output_folder ".$OutputIndex.'/ LoadCentralSystem "'.$self->filename().'"';
2011 :     system($Command);
2012 :    
2013 :     #Copying the model file printed by the toolkit out of the output directory and into the model directory
2014 :     if (!-e $self->config("MFAToolkit output directory")->[0].$OutputIndex."/".$self->id().$self->selected_version().".txt") {
2015 :     $self->figmodel()->error_message("New model file not created due to an error. Check that the input modelfile exists.");
2016 :     $self->figmodel()->cleardirectory($OutputIndex);
2017 :     return $self->fail();
2018 :     }
2019 :    
2020 :     $Command = 'cp "'.$self->config("MFAToolkit output directory")->[0].$OutputIndex."/".$self->id().$self->selected_version().'.txt" "'.$self->directory().$self->id().$self->selected_version().'Data.txt"';
2021 :     system($Command);
2022 :     $Command = 'cp "'.$self->config("MFAToolkit output directory")->[0].$OutputIndex.'/ErrorLog0.txt" "'.$self->directory().'ModelErrors.txt"';
2023 :     system($Command);
2024 :     $self->figmodel()->cleardirectory($OutputIndex);
2025 :     return $self->success();
2026 :     }
2027 :    
2028 :     =head2 Analysis Functions
2029 :    
2030 :     =head3 run_microarray_analysis
2031 :     Definition:
2032 :     int::status = FIGMODEL->run_microarray_analysis(string::media,string::job id,string::gene calls);
2033 :     Description:
2034 :     Runs microarray analysis attempting to turn off genes that are inactive in the microarray
2035 :     =cut
2036 :     sub run_microarray_analysis {
2037 : chenry 1.5 my ($self,$media,$label,$index,$genecall) = @_;
2038 : chenry 1.2 $genecall =~ s/_/:/g;
2039 :     $genecall =~ s/\//;/g;
2040 : chenry 1.5 my $uniqueFilename = $self->figmodel()->filename();
2041 :     my $command = $self->figmodel()->GenerateMFAToolkitCommandLineCall($uniqueFilename,$self->id(),$media,["ProductionMFA","ShewenellaExperiment"],{"Microarray assertions" => $label.";".$index.";".$genecall,"MFASolver" => "CPLEX","Network output location" => "/scratch/"},"MicroarrayAnalysis-".$uniqueFilename.".txt",undef,$self->selected_version());
2042 : chenry 1.2 system($command);
2043 : chenry 1.5 my $filename = $self->figmodel()->config("MFAToolkit output directory")->[0].$uniqueFilename."/MicroarrayOutput-".$index.".txt";
2044 :     if (-e $filename) {
2045 :     my $output = $self->figmodel()->database()->load_single_column_file($filename);
2046 :     if (defined($output->[0])) {
2047 :     my @array = split(/;/,$output->[0]);
2048 :     $self->figmodel()->clearing_output($uniqueFilename,"MicroarrayAnalysis-".$uniqueFilename.".txt");
2049 :     return ($array[0],$array[1],$array[8].":".$array[2],$array[9].":".$array[3],$array[10].":".$array[4],$array[11].":".$array[5],$array[12].":".$array[6],$array[13].":".$array[7]);
2050 :     }
2051 :     print STDERR $filename." is empty!";
2052 :     }
2053 :     print STDERR $filename." not found!";
2054 :     $self->figmodel()->clearing_output($uniqueFilename,"MicroarrayAnalysis-".$uniqueFilename.".txt");
2055 :    
2056 :     return undef;
2057 : chenry 1.2 }
2058 :    
2059 :     =head3 find_minimal_pathways
2060 :     Definition:
2061 :     int::status = FIGMODEL->find_minimal_pathways(string::media,string::objective);
2062 :     Description:
2063 :     Runs microarray analysis attempting to turn off genes that are inactive in the microarray
2064 :     =cut
2065 :     sub find_minimal_pathways {
2066 : chenry 1.5 my ($self,$media,$objective,$solutionnum,$AllReversible,$additionalexchange) = @_;
2067 : chenry 1.2
2068 :     #Setting default media
2069 :     if (!defined($media)) {
2070 :     $media = "Complete";
2071 :     }
2072 :    
2073 :     #Setting default solution number
2074 :     if (!defined($solutionnum)) {
2075 :     $solutionnum = "5";
2076 :     }
2077 :    
2078 : chenry 1.5 #Setting additional exchange fluxes
2079 :     if (!defined($additionalexchange) || length($additionalexchange) == 0) {
2080 :     if ($self->id() eq "iAF1260") {
2081 :     $additionalexchange = "cpd03422[c]:-100:100;cpd01997[c]:-100:100;cpd11416[c]:-100:0;cpd15378[c]:-100:0;cpd15486[c]:-100:0";
2082 :     } else {
2083 :     $additionalexchange = $self->figmodel()->config("default exchange fluxes")->[0];
2084 :     }
2085 :     }
2086 :    
2087 : chenry 1.2 #Translating objective
2088 :     my $objectivestring;
2089 :     if ($objective eq "ALL") {
2090 :     #Getting the list of universal building blocks
2091 :     my $buildingblocks = $self->config("universal building blocks");
2092 :     my @objectives = keys(%{$buildingblocks});
2093 :     #Getting the nonuniversal building blocks
2094 :     my $otherbuildingblocks = $self->config("nonuniversal building blocks");
2095 :     my @array = keys(%{$otherbuildingblocks});
2096 :     if (defined($self->get_biomass()) && defined($self->figmodel()->get_reaction($self->get_biomass()->{"LOAD"}->[0]))) {
2097 :     my $equation = $self->figmodel()->get_reaction($self->get_biomass()->{"LOAD"}->[0])->{"EQUATION"}->[0];
2098 :     if (defined($equation)) {
2099 :     for (my $i=0; $i < @array; $i++) {
2100 :     if (CORE::index($equation,$array[$i]) > 0) {
2101 :     push(@objectives,$array[$i]);
2102 :     }
2103 :     }
2104 :     }
2105 :     }
2106 :     for (my $i=0; $i < @objectives; $i++) {
2107 : chenry 1.5 $self->find_minimal_pathways($media,$objectives[$i]);
2108 : chenry 1.2 }
2109 : chenry 1.5 return;
2110 : chenry 1.2 } elsif ($objective eq "ENERGY") {
2111 :     $objectivestring = "MAX;FLUX;rxn00062;c;1";
2112 :     } elsif ($objective =~ m/cpd\d\d\d\d\d/) {
2113 : chenry 1.5 if ($objective =~ m/\[(\w)\]/) {
2114 :     $objectivestring = "MIN;DRAIN_FLUX;".$objective.";".$1.";1";
2115 :     $additionalexchange .= ";".$objective."[".$1."]:-100:0";
2116 :     } else {
2117 :     $objectivestring = "MIN;DRAIN_FLUX;".$objective.";c;1";
2118 :     $additionalexchange .= ";".$objective."[c]:-100:0";
2119 :     }
2120 :     } elsif ($objective =~ m/(rxn\d\d\d\d\d)/) {
2121 :     my ($Reactants,$Products) = $self->figmodel()->GetReactionSubstrateData($objective);
2122 :     for (my $i=0; $i < @{$Products};$i++) {
2123 :     my $temp = $Products->[$i]->{"DATABASE"}->[0];
2124 :     if ($additionalexchange !~ m/$temp/) {
2125 :     #$additionalexchange .= ";".$temp."[c]:-100:0";
2126 :     }
2127 :     }
2128 :     for (my $i=0; $i < @{$Reactants};$i++) {
2129 :     print $Reactants->[$i]->{"DATABASE"}->[0]." started\n";
2130 :     $self->find_minimal_pathways($media,$Reactants->[$i]->{"DATABASE"}->[0],$additionalexchange);
2131 :     print $Reactants->[$i]->{"DATABASE"}->[0]." done\n";
2132 :     }
2133 :     return;
2134 :     }
2135 :    
2136 :     #Adding additional drains
2137 :     if (($objective eq "cpd15665" || $objective eq "cpd15667" || $objective eq "cpd15668" || $objective eq "cpd15669") && $additionalexchange !~ m/cpd15666/) {
2138 :     $additionalexchange .= ";cpd15666[c]:0:100";
2139 :     } elsif ($objective eq "cpd11493" && $additionalexchange !~ m/cpd12370/) {
2140 :     $additionalexchange .= ";cpd12370[c]:0:100";
2141 :     } elsif ($objective eq "cpd00166" && $additionalexchange !~ m/cpd01997/) {
2142 :     $additionalexchange .= ";cpd01997[c]:0:100;cpd03422[c]:0:100";
2143 :     }
2144 :    
2145 :     #Running MFAToolkit
2146 :     my $filename = $self->figmodel()->filename();
2147 :     my $command;
2148 :     if (defined($AllReversible) && $AllReversible == 1) {
2149 :     $command = $self->figmodel()->GenerateMFAToolkitCommandLineCall($filename,$self->id(),$media,["ProductionMFA"],{"Make all reactions reversible in MFA"=>1, "Recursive MILP solution limit" => $solutionnum,"Generate pathways to objective" => 1,"MFASolver" => "CPLEX","objective" => $objectivestring,"exchange species" => $additionalexchange},"MinimalPathways-".$media."-".$self->id().$self->selected_version().".txt",undef,$self->selected_version());
2150 :     } else {
2151 :     $command = $self->figmodel()->GenerateMFAToolkitCommandLineCall($filename,$self->id(),$media,["ProductionMFA"],{"Make all reactions reversible in MFA"=>0, "Recursive MILP solution limit" => $solutionnum,"Generate pathways to objective" => 1,"MFASolver" => "CPLEX","objective" => $objectivestring,"exchange species" => $additionalexchange},"MinimalPathways-".$media."-".$self->id().$self->selected_version().".txt",undef,$self->selected_version());
2152 :     }
2153 :     system($command);
2154 :    
2155 :     #Loading problem report
2156 :     my $results = $self->figmodel()->LoadProblemReport($filename);
2157 :     #Clearing output
2158 :     $self->figmodel()->clearing_output($filename,"MinimalPathways-".$media."-".$self->id()."-".$objective.".txt");
2159 :     if (!defined($results)) {
2160 :     print STDERR $objective." pathway results not found!\n";
2161 :     return;
2162 :     }
2163 :    
2164 :     #Parsing output
2165 :     my @Array;
2166 :     my $row = $results->get_row(1);
2167 :     if (defined($row->{"Notes"}->[0])) {
2168 :     $_ = $row->{"Notes"}->[0];
2169 :     @Array = /\d+:([^\|]+)\|/g;
2170 :     }
2171 :    
2172 :     #Writing output to file
2173 : dejongh 1.8 $self->figmodel()->database()->print_array_to_file($self->directory()."MinimalPathways-".$media."-".$objective."-".$self->id()."-".$AllReversible."-".$self->selected_version().".txt",[join("|",@Array)]);
2174 : chenry 1.5 }
2175 :    
2176 :     =head3 find_minimal_pathways
2177 :     Definition:
2178 :     int::status = FIGMODEL->find_minimal_pathways(string::media,string::objective);
2179 :     Description:
2180 :     Runs microarray analysis attempting to turn off genes that are inactive in the microarray
2181 :     =cut
2182 :     sub find_minimal_pathways_two {
2183 :     my ($self,$media,$objective,$solutionnum,$AllReversible,$additionalexchange) = @_;
2184 :    
2185 :     #Setting default media
2186 :     if (!defined($media)) {
2187 :     $media = "Complete";
2188 :     }
2189 :    
2190 :     #Setting default solution number
2191 :     if (!defined($solutionnum)) {
2192 :     $solutionnum = "5";
2193 : chenry 1.2 }
2194 :    
2195 :     #Setting additional exchange fluxes
2196 : chenry 1.5 if (!defined($additionalexchange) || length($additionalexchange) == 0) {
2197 :     if ($self->id() eq "iAF1260") {
2198 :     $additionalexchange = "cpd03422[c]:-100:100;cpd01997[c]:-100:100;cpd11416[c]:-100:0;cpd15378[c]:-100:0;cpd15486[c]:-100:0";
2199 :     } else {
2200 :     $additionalexchange = $self->figmodel()->config("default exchange fluxes")->[0];
2201 :     }
2202 :     }
2203 :    
2204 :     #Translating objective
2205 :     my $objectivestring;
2206 :     if ($objective eq "ALL") {
2207 :     #Getting the list of universal building blocks
2208 :     my $buildingblocks = $self->config("universal building blocks");
2209 :     my @objectives = keys(%{$buildingblocks});
2210 :     #Getting the nonuniversal building blocks
2211 :     my $otherbuildingblocks = $self->config("nonuniversal building blocks");
2212 :     my @array = keys(%{$otherbuildingblocks});
2213 :     if (defined($self->get_biomass()) && defined($self->figmodel()->get_reaction($self->get_biomass()->{"LOAD"}->[0]))) {
2214 :     my $equation = $self->figmodel()->get_reaction($self->get_biomass()->{"LOAD"}->[0])->{"EQUATION"}->[0];
2215 :     if (defined($equation)) {
2216 :     for (my $i=0; $i < @array; $i++) {
2217 :     if (CORE::index($equation,$array[$i]) > 0) {
2218 :     push(@objectives,$array[$i]);
2219 :     }
2220 :     }
2221 :     }
2222 :     }
2223 :     for (my $i=0; $i < @objectives; $i++) {
2224 :     $self->find_minimal_pathways($media,$objectives[$i]);
2225 :     }
2226 :     return;
2227 :     } elsif ($objective eq "ENERGY") {
2228 :     $objectivestring = "MAX;FLUX;rxn00062;c;1";
2229 :     } elsif ($objective =~ m/cpd\d\d\d\d\d/) {
2230 :     if ($objective =~ m/\[(\w)\]/) {
2231 :     $objectivestring = "MIN;DRAIN_FLUX;".$objective.";".$1.";1";
2232 :     $additionalexchange .= ";".$objective."[".$1."]:-100:0";
2233 :     } else {
2234 :     $objectivestring = "MIN;DRAIN_FLUX;".$objective.";c;1";
2235 :     $additionalexchange .= ";".$objective."[c]:-100:0";
2236 :     }
2237 :     } elsif ($objective =~ m/(rxn\d\d\d\d\d)/) {
2238 :     my ($Reactants,$Products) = $self->figmodel()->GetReactionSubstrateData($objective);
2239 :     for (my $i=0; $i < @{$Products};$i++) {
2240 :     my $temp = $Products->[$i]->{"DATABASE"}->[0];
2241 :     if ($additionalexchange !~ m/$temp/) {
2242 :     #$additionalexchange .= ";".$temp."[c]:-100:0";
2243 :     }
2244 :     }
2245 :     for (my $i=0; $i < @{$Reactants};$i++) {
2246 :     print $Reactants->[$i]->{"DATABASE"}->[0]." started\n";
2247 :     $self->find_minimal_pathways($media,$Reactants->[$i]->{"DATABASE"}->[0],$additionalexchange);
2248 :     print $Reactants->[$i]->{"DATABASE"}->[0]." done\n";
2249 :     }
2250 :     return;
2251 :     }
2252 :    
2253 :     #Adding additional drains
2254 :     if (($objective eq "cpd15665" || $objective eq "cpd15667" || $objective eq "cpd15668" || $objective eq "cpd15669") && $additionalexchange !~ m/cpd15666/) {
2255 : chenry 1.2 $additionalexchange .= ";cpd15666[c]:0:100";
2256 : chenry 1.5 } elsif ($objective eq "cpd11493" && $additionalexchange !~ m/cpd12370/) {
2257 : chenry 1.2 $additionalexchange .= ";cpd12370[c]:0:100";
2258 : chenry 1.5 } elsif ($objective eq "cpd00166" && $additionalexchange !~ m/cpd01997/) {
2259 : chenry 1.2 $additionalexchange .= ";cpd01997[c]:0:100;cpd03422[c]:0:100";
2260 :     }
2261 :    
2262 :     #Running MFAToolkit
2263 :     my $filename = $self->figmodel()->filename();
2264 : chenry 1.5 my $command;
2265 :     if (defined($AllReversible) && $AllReversible == 1) {
2266 :     $command = $self->figmodel()->GenerateMFAToolkitCommandLineCall($filename,$self->id(),$media,["ProductionMFA"],{"use simple variable and constraint names"=>1,"Make all reactions reversible in MFA"=>1, "Recursive MILP solution limit" => $solutionnum,"Generate pathways to objective" => 1,"MFASolver" => "SCIP","objective" => $objectivestring,"exchange species" => $additionalexchange},"MinimalPathways-".$media."-".$self->id().$self->selected_version().".txt",undef,$self->selected_version());
2267 :     } else {
2268 :     $command = $self->figmodel()->GenerateMFAToolkitCommandLineCall($filename,$self->id(),$media,["ProductionMFA"],{"use simple variable and constraint names"=>1,"Make all reactions reversible in MFA"=>0, "Recursive MILP solution limit" => $solutionnum,"Generate pathways to objective" => 1,"MFASolver" => "SCIP","objective" => $objectivestring,"exchange species" => $additionalexchange},"MinimalPathways-".$media."-".$self->id().$self->selected_version().".txt",undef,$self->selected_version());
2269 :     }
2270 :     print $command."\n";
2271 : chenry 1.2 system($command);
2272 :    
2273 :     #Loading problem report
2274 :     my $results = $self->figmodel()->LoadProblemReport($filename);
2275 :     #Clearing output
2276 :     $self->figmodel()->clearing_output($filename,"MinimalPathways-".$media."-".$self->id()."-".$objective.".txt");
2277 :     if (!defined($results)) {
2278 : chenry 1.5 print STDERR $objective." pathway results not found!\n";
2279 : chenry 1.2 return;
2280 :     }
2281 :    
2282 :     #Parsing output
2283 :     my @Array;
2284 :     my $row = $results->get_row(1);
2285 :     if (defined($row->{"Notes"}->[0])) {
2286 :     $_ = $row->{"Notes"}->[0];
2287 :     @Array = /\d+:([^\|]+)\|/g;
2288 :     }
2289 : chenry 1.5
2290 :     #Writing output to file
2291 : dejongh 1.8 $self->figmodel()->database()->print_array_to_file($self->directory()."MinimalPathways-".$media."-".$objective."-".$self->id()."-".$AllReversible."-".$self->selected_version().".txt",[join("|",@Array)]);
2292 : chenry 1.5 }
2293 : chenry 1.2
2294 : chenry 1.5 sub combine_minimal_pathways {
2295 :     my ($self) = @_;
2296 :    
2297 :     my $tbl;
2298 :     if (-e $self->directory()."MinimalPathwayTable-".$self->id().$self->selected_version().".tbl") {
2299 :     $tbl = FIGMODELTable::load_table($self->directory()."MinimalPathwayTable-".$self->id().$self->selected_version().".tbl",";","|",0,["Objective","Media","Reversible"]);
2300 : chenry 1.2 } else {
2301 : chenry 1.5 $tbl = FIGMODELTable->new(["Objective","Media","Reactions","Reversible","Shortest path","Number of essentials","Essentials","Length"],$self->directory()."MinimalPathwayTable-".$self->id().$self->selected_version().".tbl",["Objective","Media","Reversible"],";","|");
2302 : chenry 1.2 }
2303 : chenry 1.5 my @files = glob($self->directory()."MinimalPathways-*");
2304 :     for (my $i=0; $i < @files;$i++) {
2305 :     if ($files[$i] =~ m/MinimalPathways\-(\S+)\-(cpd\d\d\d\d\d)\-(\w+)\-(\d)\-/ || $files[$i] =~ m/MinimalPathways\-(\S+)\-(ENERGY)\-(\w+)\-(\d)\-/) {
2306 :     my $reactions = $self->figmodel()->database()->load_single_column_file($files[$i],"");
2307 :     if (defined($reactions) && @{$reactions} > 0 && length($reactions->[0]) > 0) {
2308 :     my $newrow = {"Objective"=>[$2],"Media"=>[$1],"Reversible"=>[$4]};
2309 :     my $row = $tbl->get_table_by_key($newrow->{"Objective"}->[0],"Objective")->get_table_by_key($newrow->{"Media"}->[0],"Media")->get_row_by_key($newrow->{"Reversible"}->[0],"Reversible");
2310 :     if (!defined($row)) {
2311 :     $row = $tbl->add_row($newrow);
2312 :     }
2313 :     $row->{Reactions} = $self->figmodel()->database()->load_single_column_file($files[$i],"");
2314 :     delete($row->{"Shortest path"});
2315 :     delete($row->{"Number of essentials"});
2316 :     delete($row->{"Essentials"});
2317 :     delete($row->{"Length"});
2318 :     for (my $j=0; $j < @{$row->{Reactions}}; $j++) {
2319 :     my @array = split(/,/,$row->{Reactions}->[$j]);
2320 :     $row->{"Length"}->[$j] = @array;
2321 :     if (!defined($row->{"Shortest path"}->[0]) || $row->{"Length"}->[$j] < $row->{"Shortest path"}->[0]) {
2322 :     $row->{"Shortest path"}->[0] = $row->{"Length"}->[$j];
2323 :     }
2324 :     $row->{"Number of essentials"}->[0] = 0;
2325 :     for (my $k=0; $k < @array;$k++) {
2326 :     if ($array[$k] =~ m/(rxn\d\d\d\d\d)/) {
2327 :     my $class = $self->get_reaction_class($1,1);
2328 :     my $temp = $row->{Media}->[0].":Essential";
2329 :     if ($class =~ m/$temp/) {
2330 :     $row->{"Number of essentials"}->[$j]++;
2331 :     if (!defined($row->{"Essentials"}->[$j]) && length($row->{"Essentials"}->[$j]) > 0) {
2332 :     $row->{"Essentials"}->[$j] = $array[$k];
2333 :     } else {
2334 :     $row->{"Essentials"}->[$j] .= ",".$array[$k];
2335 :     }
2336 :     }
2337 :     }
2338 :     }
2339 :     }
2340 :     }
2341 :     }
2342 :     }
2343 :     $tbl->save();
2344 : chenry 1.2 }
2345 :    
2346 :     =head3 calculate_growth
2347 :     Definition:
2348 :     string::growth = FIGMODELmodel->calculate_growth(string:media);
2349 :     Description:
2350 :     Calculating growth in the input media
2351 :     =cut
2352 :     sub calculate_growth {
2353 :     my ($self,$Media) = @_;
2354 :     my $UniqueFilename = $self->figmodel()->filename();
2355 :     system($self->figmodel()->GenerateMFAToolkitCommandLineCall($UniqueFilename,$self->id(),$Media,["ProductionMFA"],{"optimize metabolite production if objective is zero" => 1},$self->id()."-".$Media."-GrowthTest.txt",undef,$self->selected_version()));
2356 :     my $ProblemReport = $self->figmodel()->LoadProblemReport($UniqueFilename);
2357 :     my $Result;
2358 :     if (defined($ProblemReport)) {
2359 :     my $Row = $ProblemReport->get_row(0);
2360 :     if (defined($Row) && defined($Row->{"Objective"}->[0])) {
2361 :     if ($Row->{"Objective"}->[0] < 0.00000001) {
2362 :     $Result = "NOGROWTH:".$Row->{"Individual metabolites with zero production"}->[0];
2363 :     } else {
2364 :     $Result = $Row->{"Objective"}->[0];
2365 :     }
2366 :     }
2367 :     }
2368 :     return $Result;
2369 :     }
2370 :    
2371 :     =head3 classify_model_reactions
2372 :     Definition:
2373 :     (FIGMODELTable:Reaction classes,FIGMODELTable:Compound classes) = FIGMODELmodel->classify_model_reactions(string:media);
2374 :     Description:
2375 :     This function uses the MFAToolkit to minimize and maximize the flux through every reaction in the input model during minimal growth on the input media.
2376 :     The results are returned in a hash of strings where the keys are the reaction IDs and the strings are structured as follows: "Class;Min flux;Max flux".
2377 :     Possible values for "Class" include:
2378 :     1.) Positive: these reactions are essential in the forward direction.
2379 :     2.) Negative: these reactions are essential in the reverse direction.
2380 :     3.) Positive variable: these reactions are nonessential, but they only ever proceed in the forward direction.
2381 :     4.) Negative variable: these reactions are nonessential, but they only ever proceed in the reverse direction.
2382 :     5.) Variable: these reactions are nonessential and proceed in the forward or reverse direction.
2383 :     6.) Blocked: these reactions never carry any flux at all in the media condition tested.
2384 :     7.) Dead: these reactions are disconnected from the network.
2385 :     =cut
2386 :     sub classify_model_reactions {
2387 : chenry 1.3 my ($self,$Media,$SaveChanges) = @_;
2388 : chenry 1.2
2389 :     #Getting unique file for printing model output
2390 :     my $UniqueFilename = $self->figmodel()->filename();
2391 :     #Running the MFAToolkit
2392 :     system($self->figmodel()->GenerateMFAToolkitCommandLineCall($UniqueFilename,$self->id(),$Media,["ProductionMFA"],{"identify dead ends" => 1,"find tight bounds" => 1,"MFASolver" => "GLPK"},"Classify-".$self->id().$self->selected_version()."-".$UniqueFilename.".log",undef,$self->selected_version()));
2393 :     #Reading in the output bounds file
2394 :     my ($ReactionTB,$CompoundTB,$DeadCompounds,$DeadEndCompounds,$DeadReactions);
2395 :     if (-e $self->config("MFAToolkit output directory")->[0].$UniqueFilename."/MFAOutput/TightBoundsReactionData0.txt") {
2396 :     $ReactionTB = $self->figmodel()->database()->load_table($self->config("MFAToolkit output directory")->[0].$UniqueFilename."/MFAOutput/TightBoundsReactionData0.txt",";","|",1,["DATABASE ID"]);
2397 :     }
2398 :     if (-e $self->config("MFAToolkit output directory")->[0].$UniqueFilename."/MFAOutput/TightBoundsCompoundData0.txt") {
2399 :     $CompoundTB = $self->figmodel()->database()->load_table($self->config("MFAToolkit output directory")->[0].$UniqueFilename."/MFAOutput/TightBoundsCompoundData0.txt",";","|",1,["DATABASE ID"]);
2400 :     }
2401 :     if (-e $self->config("MFAToolkit output directory")->[0].$UniqueFilename."/DeadReactions.txt") {
2402 :     $DeadReactions = $self->figmodel()->put_array_in_hash($self->figmodel()->database()->load_single_column_file($self->config("MFAToolkit output directory")->[0].$UniqueFilename."/DeadReactions.txt",""));
2403 :     }
2404 :     if (-e $self->config("MFAToolkit output directory")->[0].$UniqueFilename."/DeadMetabolites.txt") {
2405 :     $DeadCompounds = $self->figmodel()->put_array_in_hash($self->figmodel()->database()->load_single_column_file($self->config("MFAToolkit output directory")->[0].$UniqueFilename."/DeadMetabolites.txt",""));
2406 :     }
2407 :     if (-e $self->config("MFAToolkit output directory")->[0].$UniqueFilename."/DeadEndMetabolites.txt") {
2408 :     $DeadEndCompounds = $self->figmodel()->put_array_in_hash($self->figmodel()->database()->load_single_column_file($self->config("MFAToolkit output directory")->[0].$UniqueFilename."/DeadEndMetabolites.txt",""));
2409 :     }
2410 :     if (!defined($ReactionTB) && !defined($CompoundTB)) {
2411 :     print STDERR "FIGMODEL:ClassifyModelReactions: Classification file not found when classifying reactions in ".$self->id().$self->selected_version()." with ".$Media." media. Most likely the model did not grow.\n";
2412 :     return (undef,undef);
2413 :     }
2414 :    
2415 :     #Clearing output
2416 :     $self->figmodel()->clearing_output($UniqueFilename,"Classify-".$self->id().$self->selected_version()."-".$UniqueFilename.".log");
2417 :     #Creating the table objects that will hold the results of the reaction classification
2418 :     my $rxnclasstable = $self->reaction_class_table();
2419 :     my $cpdclasstable = $self->compound_class_table();
2420 :     #Loading the compound table
2421 :     if (defined($CompoundTB)) {
2422 :     for (my $i=0; $i < $CompoundTB->size(); $i++) {
2423 :     my $Row = $CompoundTB->get_row($i);
2424 :     if (defined($Row->{"DATABASE ID"})) {
2425 :     #Getting the compound row
2426 :     my $CpdRow = $cpdclasstable->get_row_by_key($Row->{"DATABASE ID"}->[0].$Row->{COMPARTMENT}->[0],"COMPOUND",1);
2427 :     #Setting row values
2428 :     my $Max = 0;
2429 :     my $Min = 0;
2430 :     my $Class = "Unknown";
2431 :     if (defined($DeadCompounds) && defined($DeadCompounds->{$Row->{"DATABASE ID"}->[0]})) {
2432 :     $Class = "Dead";
2433 :     } elsif (defined($DeadEndCompounds) && defined($DeadEndCompounds->{$Row->{"DATABASE ID"}->[0]})) {
2434 :     $Class = "Deadend";
2435 :     } elsif (defined($Row->{"Min DRAIN_FLUX"}) && defined($Row->{"Max DRAIN_FLUX"}) && $Row->{"Min DRAIN_FLUX"}->[0] ne "1e+07") {
2436 :     $Max = $Row->{"Max DRAIN_FLUX"}->[0];
2437 :     $Min = $Row->{"Min DRAIN_FLUX"}->[0];
2438 :     if ($Row->{"Min DRAIN_FLUX"}->[0] > 0.00000001) {
2439 :     $Class = "Positive";
2440 :     } elsif ($Row->{"Max DRAIN_FLUX"}->[0] < -0.00000001) {
2441 :     $Class = "Negative";
2442 :     } elsif ($Row->{"Min DRAIN_FLUX"}->[0] < -0.00000001) {
2443 :     if ($Row->{"Max DRAIN_FLUX"}->[0] > 0.00000001) {
2444 :     $Class = "Variable";
2445 :     } else {
2446 :     $Max = 0;
2447 :     $Class = "Negative variable";
2448 :     }
2449 :     } elsif ($Row->{"Max DRAIN_FLUX"}->[0] > 0.00000001) {
2450 :     $Min = 0;
2451 :     $Class = "Positive variable";
2452 :     } else {
2453 :     $Min = 0;
2454 :     $Max = 0;
2455 :     $Class = "Blocked";
2456 :     }
2457 :     }
2458 :     my $index = 0;
2459 :     if (defined($CpdRow->{MEDIA})) {
2460 :     for (my $i=0; $i < @{$CpdRow->{MEDIA}};$i++) {
2461 :     $index++;
2462 :     if ($CpdRow->{MEDIA}->[$i] eq $Media) {
2463 :     $index = $i;
2464 :     last;
2465 :     }
2466 :     }
2467 :     }
2468 :     $CpdRow->{MIN}->[$index] = $Min;
2469 :     $CpdRow->{MAX}->[$index] = $Max;
2470 :     $CpdRow->{CLASS}->[$index] = $Class;
2471 :     $CpdRow->{MEDIA}->[$index] = $Media;
2472 :     }
2473 :     }
2474 : chenry 1.3 if (!defined($SaveChanges) || $SaveChanges == 1) {
2475 :     $cpdclasstable->save();
2476 :     }
2477 : chenry 1.2 }
2478 :     if (defined($ReactionTB)) {
2479 :     for (my $i=0; $i < $ReactionTB->size(); $i++) {
2480 :     my $Row = $ReactionTB->get_row($i);
2481 :     if (defined($Row->{"DATABASE ID"})) {
2482 :     #Getting the compound row
2483 :     my $Compartment = "c";
2484 :     if (defined($Row->{COMPARTMENT}->[0])) {
2485 :     $Compartment = $Row->{COMPARTMENT}->[0];
2486 :     }
2487 :     my $RxnRow = $rxnclasstable->get_row_by_key($Row->{"DATABASE ID"}->[0],"REACTION",1);
2488 :     my $Max = 0;
2489 :     my $Min = 0;
2490 :     my $Class = "Unknown";
2491 :     if (defined($DeadReactions) && defined($DeadReactions->{$Row->{"DATABASE ID"}->[0]})) {
2492 :     $Class = "Dead";
2493 :     } elsif (defined($Row->{"Min FLUX"}) && defined($Row->{"Max FLUX"})) {
2494 :     $Max = $Row->{"Max FLUX"}->[0];
2495 :     $Min = $Row->{"Min FLUX"}->[0];
2496 :     if ($Row->{"Min FLUX"}->[0] > 0.00000001) {
2497 :     $Class = "Positive";
2498 :     } elsif ($Row->{"Max FLUX"}->[0] < -0.00000001) {
2499 :     $Class = "Negative";
2500 :     } elsif ($Row->{"Min FLUX"}->[0] < -0.00000001) {
2501 :     if ($Row->{"Max FLUX"}->[0] > 0.00000001) {
2502 :     $Class = "Variable";
2503 :     } else {
2504 :     $Max = 0;
2505 :     $Class = "Negative variable";
2506 :     }
2507 :     } elsif ($Row->{"Max FLUX"}->[0] > 0.00000001) {
2508 :     $Min = 0;
2509 :     $Class = "Positive variable";
2510 :     } else {
2511 :     $Min = 0;
2512 :     $Max = 0;
2513 :     $Class = "Blocked";
2514 :     }
2515 :     }
2516 :     my $index = 0;
2517 :     if (defined($RxnRow->{MEDIA})) {
2518 :     for (my $i=0; $i < @{$RxnRow->{MEDIA}};$i++) {
2519 :     $index++;
2520 :     if ($RxnRow->{MEDIA}->[$i] eq $Media) {
2521 :     $index = $i;
2522 :     last;
2523 :     }
2524 :     }
2525 :     }
2526 :     $RxnRow->{MIN}->[$index] = $Min;
2527 :     $RxnRow->{MAX}->[$index] = $Max;
2528 :     $RxnRow->{CLASS}->[$index] = $Class;
2529 :     $RxnRow->{MEDIA}->[$index] = $Media;
2530 :     }
2531 :     }
2532 : chenry 1.3 if (!defined($SaveChanges) || $SaveChanges == 1) {
2533 :     $rxnclasstable->save();
2534 :     }
2535 : chenry 1.2 }
2536 :     return ($rxnclasstable,$cpdclasstable);
2537 :     }
2538 :    
2539 :     =head3 RunAllStudiesWithDataFast
2540 :     Definition:
2541 :     (integer::false positives,integer::false negatives,integer::correct negatives,integer::correct positives,string::error vector,string heading vector) = FIGMODELmodel->RunAllStudiesWithDataFast(string::experiment,0/1::print result);
2542 :     Description:
2543 :     Simulates every experimental condition currently available for the model.
2544 :     =cut
2545 :    
2546 :     sub RunAllStudiesWithDataFast {
2547 :     my ($self,$Experiment,$PrintResults) = @_;
2548 :    
2549 :     #Printing lp and key file for model
2550 :     if (!-e $self->directory()."FBA-".$self->id().$self->selected_version().".lp") {
2551 :     $self->PrintModelLPFile();
2552 :     }
2553 :     my $UniqueFilename = $self->figmodel()->filename();
2554 :    
2555 :     #Determing the simulations that need to be run
2556 :     my $ExperimentalDataTable = $self->figmodel()->GetExperimentalDataTable($self->genome(),$Experiment);
2557 :     #Creating the table of jobs to submit
2558 :     my $JobArray = $self->GetSimulationJobTable($ExperimentalDataTable,$Experiment,$UniqueFilename);
2559 :     #Printing the job file
2560 :     if (!-d $self->config("MFAToolkit output directory")->[0].$UniqueFilename."/") {
2561 :     system("mkdir ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/");
2562 :     }
2563 :     $JobArray->save();
2564 :    
2565 :     #Running simulations
2566 :     system($self->config("mfalite executable")->[0]." ".$self->config("Reaction database directory")->[0]."masterfiles/MediaTable.txt ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/Jobfile.txt ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/Output.txt");
2567 :     #Parsing the results
2568 :     my $Results = $self->figmodel()->database()->load_table($self->config("MFAToolkit output directory")->[0].$UniqueFilename."/Output.txt",";","\\|",0,undef);
2569 :     if (!defined($Results)) {
2570 :     $self->figmodel()->error_message("FIGMODELmodel:RunAllStudiesWithDataFast:Could not find simulation results: ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/Output.txt");
2571 :     return undef;
2572 :     }
2573 :     my ($FalsePostives,$FalseNegatives,$CorrectNegatives,$CorrectPositives,$Errorvector,$HeadingVector,$SimulationResults) = $self->EvaluateSimulationResults($Results,$ExperimentalDataTable);
2574 :     #Printing results to file
2575 :     $self->figmodel()->database()->save_table($SimulationResults,undef,undef,undef,"False negatives\tFalse positives\tCorrect negatives\tCorrect positives\n".$FalseNegatives."\t".$FalsePostives."\t".$CorrectNegatives."\t".$CorrectPositives."\n");
2576 :     $self->figmodel()->clearing_output($UniqueFilename);
2577 :    
2578 :     return ($FalsePostives,$FalseNegatives,$CorrectNegatives,$CorrectPositives,$Errorvector,$HeadingVector);
2579 :     }
2580 :    
2581 :     =head3 GetSimulationJobTable
2582 :     Definition:
2583 :     my $JobTable = $model->GetSimulationJobTable($Experiment,$PrintResults,$Version);
2584 :     Description:
2585 :     =cut
2586 :    
2587 :     sub GetSimulationJobTable {
2588 :     my ($self,$SimulationTable,$Experiment,$Folder) = @_;
2589 :    
2590 :     #Determing the simulations that need to be run
2591 :     if (!defined($SimulationTable)) {
2592 :     $SimulationTable = $self->figmodel()->GetExperimentalDataTable($self->genome(),$Experiment);
2593 :     if (!defined($SimulationTable)) {
2594 :     return undef;
2595 :     }
2596 :     }
2597 :    
2598 :     #Creating the job table
2599 :     my $JobTable = $self->figmodel()->CreateJobTable($Folder);
2600 :     for (my $i=0; $i < $SimulationTable->size(); $i++) {
2601 :     if ($SimulationTable->get_row($i)->{"Heading"}->[0] =~ m/Gene\sKO/) {
2602 :     my $Row = $JobTable->get_row_by_key("Gene KO","LABEL",1);
2603 :     $JobTable->add_data($Row,"MEDIA",$SimulationTable->get_row($i)->{"Media"}->[0],1);
2604 :     } elsif ($SimulationTable->get_row($i)->{"Heading"}->[0] =~ m/Media\sgrowth/) {
2605 :     my $Row = $JobTable->get_row_by_key("Growth phenotype","LABEL",1);
2606 :     $JobTable->add_data($Row,"MEDIA",$SimulationTable->get_row($i)->{"Media"}->[0],1);
2607 :     } elsif ($SimulationTable->get_row($i)->{"Heading"}->[0] =~ m/Interval\sKO/) {
2608 :     my $Row = $JobTable->get_row_by_key($SimulationTable->get_row($i)->{"Heading"}->[0],"LABEL",1);
2609 :     $JobTable->add_data($Row,"MEDIA",$SimulationTable->get_row($i)->{"Media"}->[0],1);
2610 :     $JobTable->add_data($Row,"GENE KO",$SimulationTable->get_row($i)->{"Experiment type"}->[0],1);
2611 :     }
2612 :     }
2613 :    
2614 :     #Filling in model specific elements of the job table
2615 :     for (my $i=0; $i < $JobTable->size(); $i++) {
2616 :     if ($JobTable->get_row($i)->{"LABEL"}->[0] =~ m/Gene\sKO/) {
2617 :     $JobTable->get_row($i)->{"RUNTYPE"}->[0] = "SINGLEKO";
2618 :     $JobTable->get_row($i)->{"SAVE NONESSENTIALS"}->[0] = 1;
2619 :     } else {
2620 :     $JobTable->get_row($i)->{"RUNTYPE"}->[0] = "GROWTH";
2621 :     $JobTable->get_row($i)->{"SAVE NONESSENTIALS"}->[0] = 0;
2622 :     }
2623 :     $JobTable->get_row($i)->{"LP FILE"}->[0] = $self->directory()."FBA-".$self->id().$self->selected_version();
2624 :     $JobTable->get_row($i)->{"MODEL"}->[0] = $self->directory().$self->id().$self->selected_version().".txt";
2625 :     $JobTable->get_row($i)->{"SAVE FLUXES"}->[0] = 0;
2626 :     }
2627 :    
2628 :     return $JobTable;
2629 :     }
2630 :    
2631 :     =head3 EvaluateSimulationResults
2632 :     Definition:
2633 :     (integer::false positives,integer::false negatives,integer::correct negatives,integer::correct positives,string::error vector,string heading vector,FIGMODELtable::simulation results) = FIGMODELmodel->EvaluateSimulationResults(FIGMODELtable::raw simulation results,FIGMODELtable::experimental data);
2634 :     Description:
2635 :     Compares simulation results with experimental data to produce a table indicating where predictions are incorrect.
2636 :     =cut
2637 :    
2638 :     sub EvaluateSimulationResults {
2639 :     my ($self,$Results,$ExperimentalDataTable) = @_;
2640 :    
2641 :     #Comparing experimental results with simulation results
2642 :     my $SimulationResults = FIGMODELTable->new(["Run result","Experiment type","Media","Experiment ID","Reactions knocked out"],$self->directory()."SimulationOutput".$self->id().$self->selected_version().".txt",["Experiment ID","Media"],"\t",",",undef);
2643 :     my $FalsePostives = 0;
2644 :     my $FalseNegatives = 0;
2645 :     my $CorrectNegatives = 0;
2646 :     my $CorrectPositives = 0;
2647 :     my @Errorvector;
2648 :     my @HeadingVector;
2649 :     my $ReactionKOWithGeneHash;
2650 :     for (my $i=0; $i < $Results->size(); $i++) {
2651 :     if ($Results->get_row($i)->{"LABEL"}->[0] eq "Gene KO") {
2652 :     if (defined($Results->get_row($i)->{"REACTION KO WITH GENES"})) {
2653 :     for (my $j=0; $j < @{$Results->get_row($i)->{"REACTION KO WITH GENES"}}; $j++) {
2654 :     my @Temp = split(/:/,$Results->get_row($i)->{"REACTION KO WITH GENES"}->[$j]);
2655 :     if (defined($Temp[1]) && length($Temp[1]) > 0) {
2656 :     $ReactionKOWithGeneHash->{$Temp[0]} = $Temp[1];
2657 :     }
2658 :     }
2659 :     }
2660 :     if ($Results->get_row($i)->{"OBJECTIVE"}->[0] == 0) {
2661 :     for (my $j=0; $j < @{$Results->get_row($i)->{"NONESSENTIALGENES"}}; $j++) {
2662 :     my $Row = $ExperimentalDataTable->get_row_by_key("Gene KO:".$Results->get_row($i)->{"MEDIA"}->[0].":".$Results->get_row($i)->{"NONESSENTIALGENES"}->[$j],"Heading");
2663 :     if (defined($Row)) {
2664 :     my $KOReactions = "none";
2665 :     if (defined($ReactionKOWithGeneHash->{$Results->get_row($i)->{"NONESSENTIALGENES"}->[$j]})) {
2666 :     $KOReactions = $ReactionKOWithGeneHash->{$Results->get_row($i)->{"NONESSENTIALGENES"}->[$j]};
2667 :     }
2668 :     push(@HeadingVector,$Row->{"Heading"}->[0].":".$KOReactions);
2669 :     my $Status = "Unknown";
2670 :     if ($Row->{"Growth"}->[0] > 0) {
2671 :     $Status = "False negative";
2672 :     $FalseNegatives++;
2673 :     push(@Errorvector,3);
2674 :     } else {
2675 :     $Status = "False positive";
2676 :     $FalsePostives++;
2677 :     push(@Errorvector,2);
2678 :     }
2679 :     $SimulationResults->add_row({"Run result" => [$Status],"Experiment type" => ["Gene KO"],"Media" => [$Row->{"Media"}->[0]],"Experiment ID" => [$Row->{"Experiment ID"}->[0]],"Reactions knocked out" => [$KOReactions]});
2680 :     }
2681 :     }
2682 :     } else {
2683 :     for (my $j=0; $j < @{$Results->get_row($i)->{"ESSENTIALGENES"}}; $j++) {
2684 :     #print $j."\t".$Results->get_row($i)->{"ESSENTIALGENES"}->[$j]."\n";
2685 :     my $Row = $ExperimentalDataTable->get_row_by_key("Gene KO:".$Results->get_row($i)->{"MEDIA"}->[0].":".$Results->get_row($i)->{"ESSENTIALGENES"}->[$j],"Heading");
2686 :     if (defined($Row)) {
2687 :     my $KOReactions = "none";
2688 :     if (defined($ReactionKOWithGeneHash->{$Results->get_row($i)->{"ESSENTIALGENES"}->[$j]})) {
2689 :     $KOReactions = $ReactionKOWithGeneHash->{$Results->get_row($i)->{"ESSENTIALGENES"}->[$j]};
2690 :     }
2691 :     push(@HeadingVector,$Row->{"Heading"}->[0].":".$KOReactions);
2692 :     my $Status = "Unknown";
2693 :     if ($Row->{"Growth"}->[0] > 0) {
2694 :     $Status = "False negative";
2695 :     $FalseNegatives++;
2696 :     push(@Errorvector,3);
2697 :     } else {
2698 :     $Status = "Correct negative";
2699 :     $CorrectNegatives++;
2700 :     push(@Errorvector,1);
2701 :     }
2702 :     $SimulationResults->add_row({"Run result" => [$Status],"Experiment type" => ["Gene KO"],"Media" => [$Row->{"Media"}->[0]],"Experiment ID" => [$Row->{"Experiment ID"}->[0]],"Reactions knocked out" => [$KOReactions]});
2703 :     }
2704 :     }
2705 :     for (my $j=0; $j < @{$Results->get_row($i)->{"NONESSENTIALGENES"}}; $j++) {
2706 :     my $Row = $ExperimentalDataTable->get_row_by_key("Gene KO:".$Results->get_row($i)->{"MEDIA"}->[0].":".$Results->get_row($i)->{"NONESSENTIALGENES"}->[$j],"Heading");
2707 :     if (defined($Row)) {
2708 :     my $KOReactions = "none";
2709 :     if (defined($ReactionKOWithGeneHash->{$Results->get_row($i)->{"NONESSENTIALGENES"}->[$j]})) {
2710 :     $KOReactions = $ReactionKOWithGeneHash->{$Results->get_row($i)->{"NONESSENTIALGENES"}->[$j]};
2711 :     }
2712 :     push(@HeadingVector,$Row->{"Heading"}->[0].":".$KOReactions);
2713 :     my $Status = "Unknown";
2714 :     if ($Row->{"Growth"}->[0] > 0) {
2715 :     $Status = "Correct positive";
2716 :     $CorrectPositives++;
2717 :     push(@Errorvector,0);
2718 :     } else {
2719 :     $Status = "False positive";
2720 :     $FalsePostives++;
2721 :     push(@Errorvector,2);
2722 :     }
2723 :     $SimulationResults->add_row({"Run result" => [$Status],"Experiment type" => ["Gene KO"],"Media" => [$Row->{"Media"}->[0]],"Experiment ID" => [$Row->{"Experiment ID"}->[0]],"Reactions knocked out" => [$KOReactions]});
2724 :     }
2725 :     }
2726 :     }
2727 :     } elsif ($Results->get_row($i)->{"LABEL"}->[0] eq "Growth phenotype") {
2728 :     my $Row = $ExperimentalDataTable->get_row_by_key("Media growth:".$Results->get_row($i)->{"MEDIA"}->[0].":".$Results->get_row($i)->{"MEDIA"}->[0],"Heading");
2729 :     if (defined($Row)) {
2730 :     push(@HeadingVector,$Row->{"Heading"}->[0].":none");
2731 :     my $Status = "Unknown";
2732 :     if ($Row->{"Growth"}->[0] > 0) {
2733 :     if ($Results->get_row($i)->{"OBJECTIVE"}->[0] > 0) {
2734 :     $Status = "Correct positive";
2735 :     $CorrectPositives++;
2736 :     push(@Errorvector,0);
2737 :     } else {
2738 :     $Status = "False negative";
2739 :     $FalseNegatives++;
2740 :     push(@Errorvector,3);
2741 :     }
2742 :     } else {
2743 :     if ($Results->get_row($i)->{"OBJECTIVE"}->[0] > 0) {
2744 :     $Status = "False positive";
2745 :     $FalsePostives++;
2746 :     push(@Errorvector,2);
2747 :     } else {
2748 :     $Status = "Correct negative";
2749 :     $CorrectNegatives++;
2750 :     push(@Errorvector,1);
2751 :     }
2752 :     }
2753 :     $SimulationResults->add_row({"Run result" => [$Status],"Experiment type" => ["Media growth"],"Media" => [$Row->{"Media"}->[0]],"Experiment ID" => [$Row->{"Media"}->[0]],"Reactions knocked out" => ["none"]});
2754 :     }
2755 :     } elsif ($Results->get_row($i)->{"LABEL"}->[0] =~ m/Interval\sKO/ && defined($Results->get_row($i)->{"KOGENES"}->[0])) {
2756 :     my $Row = $ExperimentalDataTable->get_row_by_key($Results->get_row($i)->{"LABEL"}->[0],"Heading");
2757 :     if (defined($Row)) {
2758 :     my $Status = "Unknown";
2759 :     if ($Row->{"Growth"}->[0] > 0) {
2760 :     if ($Results->get_row($i)->{"OBJECTIVE"}->[0] > 0) {
2761 :     $Status = "Correct positive";
2762 :     $CorrectPositives++;
2763 :     push(@Errorvector,0);
2764 :     } else {
2765 :     $Status = "False negative";
2766 :     $FalseNegatives++;
2767 :     push(@Errorvector,3);
2768 :     }
2769 :     } else {
2770 :     if ($Results->get_row($i)->{"OBJECTIVE"}->[0] > 0) {
2771 :     $Status = "False positive";
2772 :     $FalsePostives++;
2773 :     push(@Errorvector,2);
2774 :     } else {
2775 :     $Status = "Correct negative";
2776 :     $CorrectNegatives++;
2777 :     push(@Errorvector,1);
2778 :     }
2779 :     }
2780 :     $SimulationResults->add_row({"Run result" => [$Status],"Experiment type" => ["Interval KO"],"Media" => [$Row->{"Media"}->[0]],"Experiment ID" => [$Row->{"Experiment ID"}->[0]],"Reactions knocked out" => ["none"]});
2781 :     }
2782 :     }
2783 :     }
2784 :    
2785 :     return ($FalsePostives,$FalseNegatives,$CorrectNegatives,$CorrectPositives,join(";",@Errorvector),join(";",@HeadingVector),$SimulationResults);
2786 :     }
2787 :    
2788 :     =head3 InspectSolution
2789 :     Definition:
2790 :     $model->InspectSolution(string::gene knocked out,string::media condition,[string]::list of reactions);
2791 :     Description:
2792 :     =cut
2793 :    
2794 :     sub InspectSolution {
2795 :     my ($self,$GeneKO,$Media,$ReactionList) = @_;
2796 :    
2797 :     #Getting a directory for the results
2798 :     my $UniqueFilename = $self->figmodel()->filename();
2799 :     system("mkdir ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/");
2800 :     my $TempVersion = "V".$UniqueFilename;
2801 :    
2802 :     #Setting gene ko to none if no genes are to be knocked out
2803 :     if ($GeneKO !~ m/^peg\./) {
2804 :     $GeneKO = "none";
2805 :     }
2806 :    
2807 :     #Implementing the input solution in the test model
2808 :     my $ReactionArray;
2809 :     my $DirectionArray;
2810 :     my %SolutionHash;
2811 :     for (my $k=0; $k < @{$ReactionList}; $k++) {
2812 :     if ($ReactionList->[$k] =~ m/(.+)(rxn\d\d\d\d\d)/) {
2813 :     my $Reaction = $2;
2814 :     my $Sign = $1;
2815 :     if (defined($SolutionHash{$Reaction})) {
2816 :     $SolutionHash{$Reaction} = "<=>";
2817 :     } elsif ($Sign eq "-") {
2818 :     $SolutionHash{$Reaction} = "<=";
2819 :     } elsif ($Sign eq "+") {
2820 :     $SolutionHash{$Reaction} = "=>";
2821 :     } else {
2822 :     $SolutionHash{$Reaction} = $Sign;
2823 :     }
2824 :     }
2825 :     }
2826 :     my @TempList = keys(%SolutionHash);
2827 :     for (my $k=0; $k < @TempList; $k++) {
2828 :     push(@{$ReactionArray},$TempList[$k]);
2829 :     push(@{$DirectionArray},$SolutionHash{$TempList[$k]});
2830 :     }
2831 :    
2832 :     print "Integrating solution!\n";
2833 :     $self->figmodel()->IntegrateGrowMatchSolution($self->id().$self->selected_version(),$self->directory().$self->id().$TempVersion.".txt",$ReactionArray,$DirectionArray,"SolutionInspection",1,1);
2834 :    
2835 :     #Printing lp and key file for model
2836 :     $self->PrintModelLPFile();
2837 :    
2838 :     #Running FBA on the test model
2839 :     my $JobTable = $self->figmodel()->CreateJobTable($UniqueFilename);
2840 :     $JobTable->add_row({"LABEL" => ["TEST"],"RUNTYPE" => ["GROWTH"],"LP FILE" => [$self->directory()."FBA-".$self->id().$TempVersion],"MODEL" => [$self->directory().$self->id().$TempVersion.".txt"],"MEDIA" => [$Media],"REACTION KO" => ["none|".join("|",@{$ReactionList})],"GENE KO" => [$GeneKO],"SAVE FLUXES" => [0],"SAVE NONESSENTIALS" => [0]});
2841 :     $JobTable->save();
2842 :    
2843 :     #Running simulations
2844 :     system($self->config("mfalite executable")->[0]." ".$self->config("Reaction database directory")->[0]."masterfiles/MediaTable.txt ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/Jobfile.txt ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/Output.txt");
2845 :    
2846 :     #Parsing the results
2847 :     my $Results = $self->figmodel()->database()->load_table($self->config("MFAToolkit output directory")->[0].$UniqueFilename."/Output.txt",";","\\|",0,undef);
2848 :     if (!defined($Results)) {
2849 :     $self->figmodel()->error_message("FIGMODELmodel:InspectSolution:Could not load problem report ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/Output.txt");
2850 :     return undef;
2851 :     }
2852 :    
2853 :     #Making sure that the model grew with all reactions present
2854 :     my $Found = 0;
2855 :     for (my $i=0; $i < $Results->size(); $i++) {
2856 :     if (defined($Results->get_row($i)->{"KOGENES"}->[0]) && defined($Results->get_row($i)->{"KOREACTIONS"}->[0]) && $Results->get_row($i)->{"KOREACTIONS"}->[0] eq "none" && $Results->get_row($i)->{"KOGENES"}->[0] eq $GeneKO && $Results->get_row($i)->{"OBJECTIVE"}->[0] > 0.00001) {
2857 :     $Found = 1;
2858 :     }
2859 :     }
2860 :     if ($Found == 0) {
2861 :     print "Solution no longer valid\n";
2862 :     return undef;
2863 :     }
2864 :    
2865 :     #Making sure all of the reactions added are still necessary
2866 :     my $FinalReactionList;
2867 :     for (my $k=0; $k < $Results->size(); $k++) {
2868 :     if (defined($Results->get_row($k)->{"KOGENES"}->[0]) && $Results->get_row($k)->{"KOGENES"}->[0] eq $GeneKO) {
2869 :     if (defined($Results->get_row($k)->{"KOREACTIONS"}->[0]) && $Results->get_row($k)->{"KOREACTIONS"}->[0] =~ m/rxn\d\d\d\d\d/ && $Results->get_row($k)->{"OBJECTIVE"}->[0] < 0.000001) {
2870 :     push(@{$FinalReactionList},$Results->get_row($k)->{"KOREACTIONS"}->[0]);
2871 :     }
2872 :     }
2873 :     }
2874 :    
2875 :     #Deleting extra files created
2876 :     unlink($self->directory()."FBA-".$self->id().$TempVersion.".lp");
2877 :     unlink($self->directory()."FBA-".$self->id().$TempVersion.".key");
2878 :     unlink($self->directory().$self->id().$TempVersion.".txt");
2879 :    
2880 :     #Deleting the test model and the MFA folder
2881 :     $self->figmodel()->clearing_output($UniqueFilename);
2882 :    
2883 :     return $FinalReactionList;
2884 :     }
2885 :    
2886 :     =head3 GapFillingAlgorithm
2887 :    
2888 :     Definition:
2889 :     FIGMODELmodel->GapFillingAlgorithm();
2890 :    
2891 :     Description:
2892 :     This is a wrapper for running the gap filling algorithm on any model in the database.
2893 :     The algorithm performs a gap filling for any false negative prediction of the avialable experimental data.
2894 :     This function is threaded to improve efficiency: one thread does nothing but using the MFAToolkit to fill gaps for every false negative prediction.
2895 :     The other thread reads in the gap filling solutions, builds a test model for each solution, and runs the test model against all available experimental data.
2896 :     This function prints two important output files in the Model directory:
2897 :     1.) GapFillingOutput.txt: this is a summary of the results of the gap filling analysis
2898 :     2.) GapFillingErrorMatrix.txt: this lists the correct and incorrect predictions for each gapfilling solution implemented in a test model.
2899 :     =cut
2900 :    
2901 :     sub GapFillingAlgorithm {
2902 :     my ($self) = @_;
2903 :    
2904 :     #First the input model version and model filename should be simulated and the false negatives identified
2905 :     my ($FalsePostives,$FalseNegatives,$CorrectNegatives,$CorrectPositives,$Errorvector,$HeadingVector) = $self->RunAllStudiesWithDataFast("All");
2906 :    
2907 :     #Getting the filename
2908 :     my $UniqueFilename = $self->figmodel()->filename();
2909 :    
2910 :     #Printing the original performance vector
2911 :     $self->figmodel()->database()->print_array_to_file($self->directory().$self->id().$self->selected_version()."-OPEM".".txt",[$HeadingVector,$Errorvector]);
2912 :    
2913 :     my $PreviousGapFilling;
2914 :     if (-e $self->directory().$self->id().$self->selected_version()."-GFS.txt") {
2915 :     #Backing up the old solution file
2916 :     system("cp ".$self->directory().$self->id().$self->selected_version()."-GFS.txt ".$self->directory().$self->id().$self->selected_version()."-OldGFS.txt");
2917 :     unlink($self->directory().$self->id().$self->selected_version()."-GFS.txt");
2918 :     }
2919 :     if (-e $self->directory().$self->id().$self->selected_version()."-OldGFS.txt") {
2920 :     #Reading in the solution file from the previous gap filling if it exists
2921 :     $PreviousGapFilling = $self->figmodel()->database()->load_table($self->directory().$self->id().$self->selected_version()."-OldGFS.txt",";",",",0,["Experiment"]);
2922 :     }
2923 :    
2924 :     #Now we use the simulation output to make the gap filling run data
2925 :     my @Errors = split(/;/,$Errorvector);
2926 :     my @Headings = split(/;/,$HeadingVector);
2927 :     my $GapFillingRunSpecs = "";
2928 :     my $Count = 0;
2929 :     my $RescuedPreviousResults;
2930 :     my $RunCount = 0;
2931 :     my $SolutionExistedCount = 0;
2932 :     my $AcceptedSolutions = 0;
2933 :     my $RejectedSolutions = 0;
2934 :     my $NoExistingSolutions = 0;
2935 :     for (my $i=0; $i < @Errors; $i++) {
2936 :     if ($Errors[$i] == 3) {
2937 :     my @HeadingDataArray = split(/:/,$Headings[$i]);
2938 :     if ($HeadingDataArray[2] !~ m/^peg\./ || $HeadingDataArray[3] ne "none") {
2939 :     my $SolutionFound = 0;
2940 :     if (defined($PreviousGapFilling) && defined($PreviousGapFilling->get_row_by_key($HeadingDataArray[2],"Experiment"))) {
2941 :     my @Rows = $PreviousGapFilling->get_rows_by_key($HeadingDataArray[2],"Experiment");
2942 :     for (my $j=0; $j < @Rows; $j++) {
2943 :     if ($HeadingDataArray[2] =~ m/^peg\./) {
2944 :     my $ReactionList = $self->InspectSolution($HeadingDataArray[2],$HeadingDataArray[1],$Rows[$j]->{"Solution reactions"});
2945 :     if (defined($ReactionList)) {
2946 :     print join(",",@{$Rows[$j]->{"Solution reactions"}})."\t".join(",",@{$ReactionList})."\n";
2947 :     $SolutionFound++;
2948 :     push(@{$RescuedPreviousResults},$Rows[$j]->{"Experiment"}->[0].";".$Rows[$j]->{"Solution index"}->[0].";".$Rows[$j]->{"Solution cost"}->[0].";".join(",",@{$ReactionList}));
2949 :     $AcceptedSolutions++;
2950 :     } else {
2951 :     $RejectedSolutions++;
2952 :     }
2953 :     } else {
2954 :     my $ReactionList = $self->InspectSolution($HeadingDataArray[2],$HeadingDataArray[1],$Rows[$j]->{"Solution reactions"});
2955 :     if (defined($ReactionList)) {
2956 :     print join(",",@{$Rows[$j]->{"Solution reactions"}})."\t".join(",",@{$ReactionList})."\n";
2957 :     $SolutionFound++;
2958 :     push(@{$RescuedPreviousResults},$Rows[$j]->{"Experiment"}->[0].";".$Rows[$j]->{"Solution index"}->[0].";".$Rows[$j]->{"Solution cost"}->[0].";".join(",",@{$ReactionList}));
2959 :     $AcceptedSolutions++;
2960 :     } else {
2961 :     $RejectedSolutions++;
2962 :     }
2963 :     }
2964 :     }
2965 :     } else {
2966 :     $NoExistingSolutions++;
2967 :     }
2968 :     if ($SolutionFound == 0) {
2969 :     $RunCount++;
2970 :     if (length($GapFillingRunSpecs) > 0) {
2971 :     $GapFillingRunSpecs .= ";";
2972 :     }
2973 : chenry 1.5 $GapFillingRunSpecs .= $HeadingDataArray[2].":".$HeadingDataArray[1].":".$HeadingDataArray[3];
2974 : chenry 1.2 } else {
2975 :     $SolutionExistedCount++;
2976 :     }
2977 :     }
2978 :     $Count++;
2979 :     }
2980 :     }
2981 :    
2982 :     #Updating the growmatch progress table
2983 :     my $Row = $self->figmodel()->database()->get_row_by_key("GROWMATCH TABLE",$self->genome(),"ORGANISM",1);
2984 :     $Row->{"INITIAL FP"}->[0] = $FalsePostives;
2985 :     $Row->{"INITIAL FN"}->[0] = $FalseNegatives;
2986 :     $Row->{"GF TIMING"}->[0] = time()."-";
2987 :     $Row->{"FN WITH SOL"}->[0] = $FalseNegatives-$NoExistingSolutions;
2988 :     $Row->{"FN WITH ACCEPTED SOL"}->[0] = $SolutionExistedCount;
2989 :     $Row->{"TOTAL ACCEPTED GF SOL"}->[0] = $AcceptedSolutions;
2990 :     $Row->{"TOTAL REJECTED GF SOL"}->[0] = $RejectedSolutions;
2991 :     $Row->{"FN WITH NO SOL"}->[0] = $NoExistingSolutions+$RejectedSolutions;
2992 :     $self->figmodel()->database()->update_row("GROWMATCH TABLE",$Row,"ORGANISM");
2993 :    
2994 :     #Running the gap filling once to correct all false negative errors
2995 :     my $SolutionsFound = 0;
2996 :     my $GapFillingArray;
2997 :     push(@{$GapFillingArray},split(/;/,$GapFillingRunSpecs));
2998 : chenry 1.5 my $GapFillingResults = $self->datagapfill($GapFillingArray,"GFS");
2999 :     if (defined($GapFillingResults)) {
3000 :     $SolutionsFound = 1;
3001 :     }
3002 : chenry 1.2
3003 :     if (defined($RescuedPreviousResults) && @{$RescuedPreviousResults} > 0) {
3004 :     #Printing previous solutions to GFS file
3005 :     $self->figmodel()->database()->print_array_to_file($self->directory().$self->id().$self->selected_version()."-GFS.txt",$RescuedPreviousResults,1);
3006 :     $SolutionsFound = 1;
3007 :     }
3008 :    
3009 :     #Recording the finishing of the gapfilling
3010 :     $Row = $self->figmodel()->database()->get_row_by_key("GROWMATCH TABLE",$self->genome(),"ORGANISM",1);
3011 :     $Row->{"GF TIMING"}->[0] .= time();
3012 :     $self->figmodel()->database()->update_row("GROWMATCH TABLE",$Row,"ORGANISM");
3013 :    
3014 :     if ($SolutionsFound == 1) {
3015 :     #Scheduling solution testing
3016 :     $self->figmodel()->add_job_to_queue("testsolutions?".$self->id().$self->selected_version()."?-1?GF","QSUB","fast","master","BACK");
3017 :     } else {
3018 :     $self->figmodel()->error_message("No false negative predictions found. Data gap filling not necessary!");
3019 :     }
3020 :    
3021 :     return $self->success();
3022 :     }
3023 :    
3024 : chenry 1.5 =head3 SolutionReconciliation
3025 :     Definition:
3026 :     FIGMODELmodel->SolutionReconciliation();
3027 :     Description:
3028 :     This is a wrapper for running the solution reconciliation algorithm on any model in the database.
3029 :     The algorithm performs a reconciliation of any gap filling solutions to identify the combination of solutions that results in the optimal model.
3030 :     This function prints out one output file in the Model directory: ReconciliationOutput.txt: this is a summary of the results of the reconciliation analysis
3031 :     =cut
3032 :    
3033 :     sub SolutionReconciliation {
3034 :     my ($self,$GapFill,$Stage) = @_;
3035 :    
3036 :     #Setting the output filenames
3037 :     my $OutputFilename;
3038 :     my $OutputFilenameTwo;
3039 :     if ($GapFill == 1) {
3040 :     $OutputFilename = $self->directory().$self->id().$self->selected_version()."-GFReconciliation.txt";
3041 :     $OutputFilenameTwo = $self->directory().$self->id().$self->selected_version()."-GFSRS.txt";
3042 :     } else {
3043 :     $OutputFilename = $self->directory().$self->id().$self->selected_version()."-GGReconciliation.txt";
3044 :     $OutputFilenameTwo = $self->directory().$self->id().$self->selected_version()."-GGSRS.txt";
3045 :     }
3046 :    
3047 :     #In stage one, we run the reconciliation and create a test file to check combined solution performance
3048 :     if (!defined($Stage) || $Stage == 1) {
3049 :     my $GrowMatchTable = $self->figmodel()->database()->LockDBTable("GROWMATCH TABLE");
3050 :     my $Row = $GrowMatchTable->get_row_by_key($self->genome(),"ORGANISM",1);
3051 :     $Row->{"GF RECONCILATION TIMING"}->[0] = time()."-";
3052 :     $GrowMatchTable->save();
3053 :     $self->figmodel()->database()->UnlockDBTable("GROWMATCH TABLE");
3054 :    
3055 :     #Getting a unique filename
3056 :     my $UniqueFilename = $self->figmodel()->filename();
3057 :    
3058 :     #Copying over the necessary files
3059 :     if ($GapFill == 1) {
3060 :     if (!-e $self->directory().$self->id().$self->selected_version()."-GFEM.txt") {
3061 :     print STDERR "FIGMODEL:SolutionReconciliation:".$self->directory().$self->id().$self->selected_version()."-GFEM.txt file not found. Could not reconcile!";
3062 :     return 0;
3063 :     }
3064 :     if (!-e $self->directory().$self->id().$self->selected_version()."-OPEM.txt") {
3065 :     print STDERR "FIGMODEL:SolutionReconciliation:".$self->directory().$self->id().$self->selected_version()."-OPEM.txt file not found. Could not reconcile!";
3066 :     return 0;
3067 :     }
3068 :     system("cp ".$self->directory().$self->id().$self->selected_version()."-GFEM.txt ".$self->figmodel()->config("MFAToolkit input files")->[0].$UniqueFilename."-GFEM.txt");
3069 :     system("cp ".$self->directory().$self->id().$self->selected_version()."-OPEM.txt ".$self->figmodel()->config("MFAToolkit input files")->[0].$UniqueFilename."-OPEM.txt");
3070 :     #Backing up and deleting the existing reconciliation file
3071 :     if (-e $OutputFilename) {
3072 :     system("cp ".$OutputFilename." ".$self->directory().$self->id().$self->selected_version()."-OldGFReconciliation.txt");
3073 :     unlink($OutputFilename);
3074 :     }
3075 :     } else {
3076 :     if (!-e $self->directory().$self->id().$self->selected_version()."-GGEM.txt") {
3077 :     print STDERR "FIGMODEL:SolutionReconciliation:".$self->directory().$self->id().$self->selected_version()."-GGEM.txt file not found. Could not reconcile!";
3078 :     return 0;
3079 :     }
3080 :     if (!-e $self->directory().$self->id().$self->selected_version()."-GGOPEM.txt") {
3081 :     print STDERR "FIGMODEL:SolutionReconciliation:".$self->directory().$self->id().$self->selected_version()."-GGOPEM.txt file not found. Could not reconcile!";
3082 :     return 0;
3083 :     }
3084 :     system("cp ".$self->directory().$self->id().$self->selected_version()."-GGEM.txt ".$self->figmodel()->config("MFAToolkit input files")->[0].$UniqueFilename."-GGEM.txt");
3085 :     system("cp ".$self->directory().$self->id().$self->selected_version()."-GGOPEM.txt ".$self->figmodel()->config("MFAToolkit input files")->[0].$UniqueFilename."-OPEM.txt");
3086 :     #Backing up and deleting the existing reconciliation file
3087 :     if (-e $OutputFilename) {
3088 :     system("cp ".$OutputFilename." ".$self->directory().$self->id().$self->selected_version()."-OldGGReconciliation.txt");
3089 :     unlink($OutputFilename);
3090 :     }
3091 :     }
3092 :    
3093 :     #Running the reconciliation
3094 :     system($self->figmodel()->GenerateMFAToolkitCommandLineCall($UniqueFilename,$self->id(),"NONE",["SolutionReconciliation"],{"Solution data for model optimization" => $UniqueFilename},"Reconciliation".$UniqueFilename.".log",undef,$self->selected_version()));
3095 :     $GrowMatchTable = $self->figmodel()->database()->LockDBTable("GROWMATCH TABLE");
3096 :     $Row = $GrowMatchTable->get_row_by_key($self->genome(),"ORGANISM",1);
3097 :     $Row->{"GF RECONCILATION TIMING"}->[0] .= time();
3098 :     $GrowMatchTable->save();
3099 :     $self->figmodel()->database()->UnlockDBTable("GROWMATCH TABLE");
3100 :    
3101 :     #Loading the problem report from the reconciliation run
3102 :     my $ReconciliatonOutput = $self->figmodel()->LoadProblemReport($UniqueFilename);
3103 :     print $UniqueFilename."\n";
3104 :     #Clearing output files
3105 :     $self->figmodel()->clearing_output($UniqueFilename,"Reconciliation".$UniqueFilename.".log");
3106 :     $ReconciliatonOutput->save("/home/chenry/Test.txt");
3107 :    
3108 :     #Checking the a problem report was found and was loaded
3109 :     if (!defined($ReconciliatonOutput) || $ReconciliatonOutput->size() < 1 || !defined($ReconciliatonOutput->get_row(0)->{"Notes"}->[0])) {
3110 :     print STDERR "FIGMODEL:SolutionReconciliation: MFAToolkit output from SolutionReconciliation of ".$self->id()." not found!\n\n";
3111 :     return 0;
3112 :     }
3113 :    
3114 :     #Processing the solutions
3115 :     my $SolutionCount = 0;
3116 :     my $ReactionSetHash;
3117 :     my $SingleReactionHash;
3118 :     my $ReactionDataHash;
3119 :     for (my $n=0; $n < $ReconciliatonOutput->size(); $n++) {
3120 :     if (defined($ReconciliatonOutput->get_row($n)->{"Notes"}->[0]) && $ReconciliatonOutput->get_row($n)->{"Notes"}->[0] =~ m/^Recursive\sMILP\s([^;]+)/) {
3121 :     #Breaking up the solution into reaction sets
3122 :     my @ReactionSets = split(/\|/,$1);
3123 :     #Creating reaction lists for each set
3124 :     my $SolutionHash;
3125 :     for (my $i=0; $i < @ReactionSets; $i++) {
3126 :     if (length($ReactionSets[$i]) > 0) {
3127 :     my @Alternatives = split(/:/,$ReactionSets[$i]);
3128 :     for (my $j=1; $j < @Alternatives; $j++) {
3129 :     if (length($Alternatives[$j]) > 0) {
3130 :     push(@{$SolutionHash->{$Alternatives[$j]}},$Alternatives[0]);
3131 :     }
3132 :     }
3133 :     if (@Alternatives == 1) {
3134 :     $SingleReactionHash->{$Alternatives[0]}->{$SolutionCount} = 1;
3135 :     if (!defined($SingleReactionHash->{$Alternatives[0]}->{"COUNT"})) {
3136 :     $SingleReactionHash->{$Alternatives[0]}->{"COUNT"} = 0;
3137 :     }
3138 :     $SingleReactionHash->{$Alternatives[0]}->{"COUNT"}++;
3139 :     }
3140 :     }
3141 :     }
3142 :     #Identifying reactions sets and storing the sets in the reactions set hash
3143 :     foreach my $Solution (keys(%{$SolutionHash})) {
3144 :     my $SetKey = join(",",sort(@{$SolutionHash->{$Solution}}));
3145 :     if (!defined($ReactionSetHash->{$SetKey}->{$SetKey}->{$SolutionCount})) {
3146 :     $ReactionSetHash->{$SetKey}->{$SetKey}->{$SolutionCount} = 1;
3147 :     if (!defined($ReactionSetHash->{$SetKey}->{$SetKey}->{"COUNT"})) {
3148 :     $ReactionSetHash->{$SetKey}->{$SetKey}->{"COUNT"} = 0;
3149 :     }
3150 :     $ReactionSetHash->{$SetKey}->{$SetKey}->{"COUNT"}++;
3151 :     }
3152 :     $ReactionSetHash->{$SetKey}->{$Solution}->{$SolutionCount} = 1;
3153 :     if (!defined($ReactionSetHash->{$SetKey}->{$Solution}->{"COUNT"})) {
3154 :     $ReactionSetHash->{$SetKey}->{$Solution}->{"COUNT"} = 0;
3155 :     }
3156 :     $ReactionSetHash->{$SetKey}->{$Solution}->{"COUNT"}++;
3157 :     }
3158 :     $SolutionCount++;
3159 :     }
3160 :     }
3161 :    
3162 :     #Handling the scenario where no solutions were found
3163 :     if ($SolutionCount == 0) {
3164 :     print STDERR "FIGMODEL:SolutionReconciliation: Reconciliation unsuccessful. No solution found.\n\n";
3165 :     return 0;
3166 :     }
3167 :    
3168 :     #Printing results without solution performance figures. Also printing solution test file
3169 :     open (RECONCILIATION, ">$OutputFilename");
3170 :     #Printing the file heading
3171 :     print RECONCILIATION "DATABASE;DEFINITION;REVERSIBLITY;DELTAG;DIRECTION;NUMBER OF SOLUTIONS";
3172 :     for (my $i=0; $i < $SolutionCount; $i++) {
3173 :     print RECONCILIATION ";Solution ".$i;
3174 :     }
3175 :     print RECONCILIATION "\n";
3176 :     #Printing the singlet reactions first
3177 :     my $Solutions;
3178 :     print RECONCILIATION "SINGLET REACTIONS\n";
3179 :     my @SingletReactions = keys(%{$SingleReactionHash});
3180 :     for (my $j=0; $j < $SolutionCount; $j++) {
3181 :     $Solutions->[$j]->{"BASE"} = $j;
3182 :     }
3183 :     for (my $i=0; $i < @SingletReactions; $i++) {
3184 :     my $ReactionData;
3185 :     if (defined($ReactionDataHash->{$SingletReactions[$i]})) {
3186 :     $ReactionData = $ReactionDataHash->{$SingletReactions[$i]};
3187 :     } else {
3188 :     my $Direction = substr($SingletReactions[$i],0,1);
3189 :     if ($Direction eq "+") {
3190 :     $Direction = "=>";
3191 :     } else {
3192 :     $Direction = "<=";
3193 :     }
3194 :     my $Reaction = substr($SingletReactions[$i],1);
3195 :     $ReactionData = FIGMODELObject->load($self->figmodel()->config("reaction directory")->[0].$Reaction,"\t");
3196 :     $ReactionData->{"DIRECTIONS"}->[0] = $Direction;
3197 :     $ReactionData->{"REACTIONS"}->[0] = $Reaction;
3198 :     if (!defined($ReactionData->{"DEFINITION"}->[0])) {
3199 :     $ReactionData->{"DEFINITION"}->[0] = "UNKNOWN";
3200 :     }
3201 :     if (!defined($ReactionData->{"THERMODYNAMIC REVERSIBILITY"}->[0])) {
3202 :     $ReactionData->{"THERMODYNAMIC REVERSIBILITY"}->[0] = "UNKNOWN";
3203 :     }
3204 :     if (!defined($ReactionData->{"DELTAG"}->[0])) {
3205 :     $ReactionData->{"DELTAG"}->[0] = "UNKNOWN";
3206 :     }
3207 :     $ReactionDataHash->{$SingletReactions[$i]} = $ReactionData;
3208 :     }
3209 :     print RECONCILIATION $ReactionData->{"REACTIONS"}->[0].";".$ReactionData->{"DEFINITION"}->[0].";".$ReactionData->{"THERMODYNAMIC REVERSIBILITY"}->[0].";".$ReactionData->{"DELTAG"}->[0].";".$ReactionData->{"DIRECTIONS"}->[0].";".$SingleReactionHash->{$SingletReactions[$i]}->{"COUNT"};
3210 :     for (my $j=0; $j < $SolutionCount; $j++) {
3211 :     print RECONCILIATION ";";
3212 :     if (defined($SingleReactionHash->{$SingletReactions[$i]}->{$j})) {
3213 :     $Solutions->[$j]->{$SingletReactions[$i]} = 1;
3214 :     $Solutions->[$j]->{"BASE"} = $j;
3215 :     print RECONCILIATION "|".$j."|";
3216 :     }
3217 :     }
3218 :     print RECONCILIATION "\n";
3219 :     }
3220 :     #Printing the reaction sets with alternatives
3221 :     print RECONCILIATION "Reaction sets with alternatives\n";
3222 :     my @ReactionSets = keys(%{$ReactionSetHash});
3223 :     foreach my $ReactionSet (@ReactionSets) {
3224 :     my $NewSolutions;
3225 :     my $BaseReactions;
3226 :     my $AltList = [$ReactionSet];
3227 :     push(@{$AltList},keys(%{$ReactionSetHash->{$ReactionSet}}));
3228 :     for (my $j=0; $j < @{$AltList}; $j++) {
3229 :     my $CurrentNewSolutions;
3230 :     my $Index;
3231 :     if ($j == 0) {
3232 :     print RECONCILIATION "NEW SET\n";
3233 :     } elsif ($AltList->[$j] ne $ReactionSet) {
3234 :     print RECONCILIATION "ALTERNATIVE SET\n";
3235 :     #For each base solution in which this set is represented, we copy the base solution to the new solution
3236 :     my $NewSolutionCount = 0;
3237 :     for (my $k=0; $k < $SolutionCount; $k++) {
3238 :     if (defined($ReactionSetHash->{$ReactionSet}->{$AltList->[$j]}->{$k})) {
3239 :     if (defined($Solutions)) {
3240 :     $Index->{$k} = @{$Solutions} + $NewSolutionCount;
3241 :     } else {
3242 :     $Index->{$k} = $NewSolutionCount;
3243 :     }
3244 :     if (defined($NewSolutions) && @{$NewSolutions} > 0) {
3245 :     $Index->{$k} += @{$NewSolutions};
3246 :     }
3247 :     $CurrentNewSolutions->[$NewSolutionCount] = {};
3248 :     foreach my $Reaction (keys(%{$Solutions->[$k]})) {
3249 :     $CurrentNewSolutions->[$NewSolutionCount]->{$Reaction} = $Solutions->[$k]->{$Reaction};
3250 :     }
3251 :     $NewSolutionCount++;
3252 :     }
3253 :     }
3254 :     }
3255 :     if ($j == 0 || $AltList->[$j] ne $ReactionSet) {
3256 :     my @SingletReactions = split(/,/,$AltList->[$j]);
3257 :     for (my $i=0; $i < @SingletReactions; $i++) {
3258 :     #Adding base reactions to base solutions and set reactions the new solutions
3259 :     if ($j == 0) {
3260 :     push(@{$BaseReactions},$SingletReactions[$i]);
3261 :     } else {
3262 :     for (my $k=0; $k < @{$CurrentNewSolutions}; $k++) {
3263 :     $CurrentNewSolutions->[$k]->{$SingletReactions[$i]} = 1;
3264 :     }
3265 :     }
3266 :     #Getting reaction data and printing reaction in output file
3267 :     my $ReactionData;
3268 :     if (defined($ReactionDataHash->{$SingletReactions[$i]})) {
3269 :     $ReactionData = $ReactionDataHash->{$SingletReactions[$i]};
3270 :     } else {
3271 :     my $Direction = substr($SingletReactions[$i],0,1);
3272 :     if ($Direction eq "+") {
3273 :     $Direction = "=>";
3274 :     } else {
3275 :     $Direction = "<=";
3276 :     }
3277 :     my $Reaction = substr($SingletReactions[$i],1);
3278 :     $ReactionData = FIGMODELObject->load($self->figmodel()->config("reaction directory")->[0].$Reaction,"\t");
3279 :     $ReactionData->{"DIRECTIONS"}->[0] = $Direction;
3280 :     $ReactionData->{"REACTIONS"}->[0] = $Reaction;
3281 :     if (!defined($ReactionData->{"DEFINITION"}->[0])) {
3282 :     $ReactionData->{"DEFINITION"}->[0] = "UNKNOWN";
3283 :     }
3284 :     if (!defined($ReactionData->{"THERMODYNAMIC REVERSIBILITY"}->[0])) {
3285 :     $ReactionData->{"THERMODYNAMIC REVERSIBILITY"}->[0] = "UNKNOWN";
3286 :     }
3287 :     if (!defined($ReactionData->{"DELTAG"}->[0])) {
3288 :     $ReactionData->{"DELTAG"}->[0] = "UNKNOWN";
3289 :     }
3290 :     $ReactionDataHash->{$SingletReactions[$i]} = $ReactionData;
3291 :     }
3292 :     print RECONCILIATION $ReactionData->{"REACTIONS"}->[0].";".$ReactionData->{"DEFINITION"}->[0].";".$ReactionData->{"THERMODYNAMIC REVERSIBILITY"}->[0].";".$ReactionData->{"DELTAG"}->[0].";".$ReactionData->{"DIRECTIONS"}->[0].";".$ReactionSetHash->{$ReactionSet}->{$AltList->[$j]}->{"COUNT"};
3293 :     for (my $k=0; $k < $SolutionCount; $k++) {
3294 :     print RECONCILIATION ";";
3295 :     if (defined($ReactionSetHash->{$ReactionSet}->{$AltList->[$j]}->{$k})) {
3296 :     if ($j == 0) {
3297 :     print RECONCILIATION "|".$k."|";
3298 :     } else {
3299 :     print RECONCILIATION "|".$Index->{$k}."|";
3300 :     }
3301 :     }
3302 :     }
3303 :     print RECONCILIATION "\n";
3304 :     }
3305 :     #Adding the current new solutions to the new solutions array
3306 :     if (defined($CurrentNewSolutions) && @{$CurrentNewSolutions} > 0) {
3307 :     push(@{$NewSolutions},@{$CurrentNewSolutions});
3308 :     }
3309 :     }
3310 :     }
3311 :     #Adding the base reactions to all existing solutions
3312 :     for (my $j=0; $j < @{$Solutions}; $j++) {
3313 :     if (defined($ReactionSetHash->{$ReactionSet}->{$ReactionSet}->{$Solutions->[$j]->{"BASE"}})) {
3314 :     foreach my $SingleReaction (@{$BaseReactions}) {
3315 :     $Solutions->[$j]->{$SingleReaction} = 1;
3316 :     }
3317 :     }
3318 :     }
3319 :     #Adding the new solutions to the set of existing solutions
3320 :     push(@{$Solutions},@{$NewSolutions});
3321 :     }
3322 :     close(RECONCILIATION);
3323 :     #Now printing a file that defines all of the solutions in a format the testsolutions function understands
3324 :     open (RECONCILIATION, ">$OutputFilenameTwo");
3325 :     print RECONCILIATION "Experiment;Solution index;Solution cost;Solution reactions\n";
3326 :     for (my $i=0; $i < @{$Solutions}; $i++) {
3327 :     delete($Solutions->[$i]->{"BASE"});
3328 :     print RECONCILIATION "SR".$i.";".$i.";10;".join(",",keys(%{$Solutions->[$i]}))."\n";
3329 :     }
3330 :     close(RECONCILIATION);
3331 :    
3332 :     $GrowMatchTable = $self->figmodel()->database()->LockDBTable("GROWMATCH TABLE");
3333 :     $Row = $GrowMatchTable->get_row_by_key($self->genome(),"ORGANISM",1);
3334 :     $Row->{"GF RECON TESTING TIMING"}->[0] = time()."-";
3335 :     $Row->{"GF RECON SOLUTIONS"}->[0] = @{$Solutions};
3336 :     $GrowMatchTable->save();
3337 :     $self->figmodel()->database()->UnlockDBTable("GROWMATCH TABLE");
3338 :    
3339 :     #Scheduling the solution testing
3340 :     if ($GapFill == 1) {
3341 :     system($self->figmodel()->config("scheduler executable")->[0]." \"add:testsolutions?".$self->id().$self->selected_version()."?-1?GFSR:BACK:fast:QSUB\"");
3342 :     } else {
3343 :     system($self->figmodel()->config("scheduler executable")->[0]." \"add:testsolutions?".$self->id().$self->selected_version()."?-1?GGSR:BACK:fast:QSUB\"");
3344 :     }
3345 :     } else {
3346 :     #Reading in the solution testing results
3347 :     my $Data;
3348 :     if ($GapFill == 1) {
3349 :     $Data = $self->figmodel()->database()->load_single_column_file($self->directory().$self->id().$self->selected_version()."-GFSREM.txt","");
3350 :     } else {
3351 :     $Data = $self->figmodel()->database()->load_single_column_file($self->directory().$self->id().$self->selected_version()."-GGSREM.txt","");
3352 :     }
3353 :    
3354 :     #Reading in the preliminate reconciliation report
3355 :     my $OutputData = $self->figmodel()->database()->load_single_column_file($OutputFilename,"");
3356 :     #Replacing the file tags with actual performance data
3357 :     my $Count = 0;
3358 :     for (my $i=0; $i < @{$Data}; $i++) {
3359 :     if ($Data->[$i] =~ m/^SR(\d+);.+;(\d+\/\d+);/) {
3360 :     my $Index = $1;
3361 :     my $Performance = $Index."/".$2;
3362 :     for (my $j=0; $j < @{$OutputData}; $j++) {
3363 :     $OutputData->[$j] =~ s/\|$Index\|/$Performance/g;
3364 :     }
3365 :     }
3366 :     }
3367 :     $self->figmodel()->database()->print_array_to_file($OutputFilename,$OutputData);
3368 :    
3369 :     my $GrowMatchTable = $self->figmodel()->database()->LockDBTable("GROWMATCH TABLE");
3370 :     my $Row = $GrowMatchTable->get_row_by_key($self->genome(),"ORGANISM",1);
3371 :     $Row->{"GF RECON TESTING TIMING"}->[0] .= time();
3372 :     $GrowMatchTable->save();
3373 :     $self->figmodel()->database()->UnlockDBTable("GROWMATCH TABLE");
3374 :     }
3375 :    
3376 :     return 1;
3377 :     }
3378 :    
3379 : chenry 1.2 =head3 BuildSpecificBiomassReaction
3380 :     Definition:
3381 :     FIGMODELmodel->BuildSpecificBiomassReaction();
3382 :     Description:
3383 :     =cut
3384 :     sub BuildSpecificBiomassReaction {
3385 :     my ($self) = @_;
3386 :    
3387 :     my $biomassrxn;
3388 :     my $OrganismID = $self->genome();
3389 :     #Checking for a biomass override
3390 :     if (defined($self->config("biomass reaction override")->{$OrganismID})) {
3391 : chenry 1.13 my $biomassID = $self->config("biomass reaction override")->{$OrganismID};
3392 :     my $tbl = $self->database()->get_table("BIOMASS",1);
3393 :     $biomassrxn = $tbl->get_row_by_key($biomassID,"DATABASE");
3394 :     print "Overriding biomass template and selecting ".$biomassID." for ".$OrganismID.".\n";
3395 : chenry 1.2 } else {#Creating biomass reaction from the template
3396 :     #Getting the genome stats
3397 :     my $genomestats = $self->figmodel()->get_genome_stats($self->genome());
3398 :     my $Class = $genomestats->{CLASS}->[0];
3399 :     my $Name = $genomestats->{NAME}->[0];
3400 :    
3401 :     #Checking for phoenix variants
3402 :     my $PhoenixVariantTable = $self->figmodel()->database()->GetDBTable("Phoenix variants table");
3403 :     my $Phoenix = 0;
3404 :     my @Rows = $PhoenixVariantTable->get_rows_by_key($OrganismID,"GENOME");
3405 :     my $VariantHash;
3406 :     for (my $i=0; $i < @Rows; $i++) {
3407 :     $Phoenix = 1;
3408 :     if (defined($Rows[$i]->{"SUBSYSTEM"}) && defined($Rows[$i]->{"VARIANT"})) {
3409 :     $VariantHash->{$Rows[$i]->{"SUBSYSTEM"}->[0]} = $Rows[$i]->{"VARIANT"}->[0];
3410 :     }
3411 :     }
3412 :    
3413 :     #Collecting genome data
3414 :     my $RoleHash;
3415 :     my $FeatureTable = $self->figmodel()->GetGenomeFeatureTable($self->genome());
3416 :     for (my $i=0; $i < $FeatureTable->size(); $i++) {
3417 :     for (my $j=0; $j < @{$FeatureTable->get_row($i)->{"ROLES"}}; $j++) {
3418 :     $RoleHash->{$FeatureTable->get_row($i)->{"ROLES"}->[$j]} = 1;
3419 :     my $Subsystems = $self->figmodel()->subsystems_of_role($FeatureTable->get_row($i)->{"ROLES"}->[$j]);
3420 :     if (defined($Subsystems)) {
3421 :     for (my $k=0; $k < @{$Subsystems}; $k++) {
3422 :     if ($Phoenix == 0) {
3423 :     $VariantHash->{$Subsystems->[$k]} = 1;
3424 :     }
3425 :     }
3426 :     }
3427 :     }
3428 :     }
3429 :    
3430 :     #Scanning through the template item by item and determinine which biomass components should be added
3431 :     my $ComponentTypes;
3432 :     my $EquationData;
3433 :     my $BiomassReactionTemplateTable = $self->figmodel()->database()->GetDBTable("BIOMASS TEMPLATE");
3434 :     for (my $i=0; $i < $BiomassReactionTemplateTable->size(); $i++) {
3435 :     my $Row = $BiomassReactionTemplateTable->get_row($i);
3436 :     if (defined($Row->{"INCLUSION CRITERIA"}->[0]) && $Row->{"INCLUSION CRITERIA"}->[0] eq "UNIVERSAL") {
3437 :     push(@{$EquationData},$Row);
3438 :     $ComponentTypes->{$Row->{"CLASS"}->[0]}->{$Row->{"ID"}->[0]} = 1;
3439 :     } else {
3440 :     my $Criteria = $Row->{"INCLUSION CRITERIA"}->[0];
3441 :     my $End = 0;
3442 :     while ($End == 0) {
3443 :     if ($Criteria =~ m/^(.+)(AND)\{([^{^}]+)\}(.+)$/ || $Criteria =~ m/^(AND)\{([^{^}]+)\}$/ || $Criteria =~ m/^(.+)(OR)\{([^{^}]+)\}(.+)$/ || $Criteria =~ m/^(OR)\{([^{^}]+)\}$/) {
3444 :     print $Criteria."\n";
3445 :     my $Start = "";
3446 :     my $End = "";
3447 :     my $Condition = $1;
3448 :     my $Data = $2;
3449 :     if ($1 ne "AND" && $1 ne "OR") {
3450 :     $Start = $1;
3451 :     $End = $4;
3452 :     $Condition = $2;
3453 :     $Data = $3;
3454 :     }
3455 :     my $Result = "YES";
3456 :     if ($Condition eq "OR") {
3457 :     $Result = "NO";
3458 :     }
3459 :     my @Array = split(/\|/,$Data);
3460 :     for (my $j=0; $j < @Array; $j++) {
3461 :     if ($Array[$j] eq "YES" && $Condition eq "OR") {
3462 :     $Result = "YES";
3463 :     last;
3464 :     } elsif ($Array[$j] eq "NO" && $Condition eq "AND") {
3465 :     $Result = "NO";
3466 :     last;
3467 :     } elsif ($Array[$j] =~ m/^COMPOUND:(.+)/) {
3468 :     my $Match = 0;
3469 :     for (my $k=0; $k < @{$EquationData}; $k++) {
3470 :     if ($EquationData->[$k]->{"ID"}->[0] eq $1) {
3471 :     $Match = 1;
3472 :     last;
3473 :     }
3474 :     }
3475 :     if ($Match == 1 && $Condition eq "OR") {
3476 :     $Result = "YES";
3477 :     last;
3478 :     } elsif ($Match != 1 && $Condition eq "AND") {
3479 :     $Result = "NO";
3480 :     last;
3481 :     }
3482 :     } elsif ($Array[$j] =~ m/^!COMPOUND:(.+)/) {
3483 :     my $Match = 0;
3484 :     for (my $k=0; $k < @{$EquationData}; $k++) {
3485 :     if ($EquationData->[$k]->{"ID"}->[0] eq $1) {
3486 :     $Match = 1;
3487 :     last;
3488 :     }
3489 :     }
3490 :     if ($Match != 1 && $Condition eq "OR") {
3491 :     $Result = "YES";
3492 :     last;
3493 :     } elsif ($Match == 1 && $Condition eq "AND") {
3494 :     $Result = "NO";
3495 :     last;
3496 :     }
3497 :     } elsif ($Array[$j] =~ m/^NAME:(.+)/) {
3498 :     my $Comparison = $1;
3499 :     if ((!defined($Comparison) || !defined($Name) || $Name =~ m/$Comparison/) && $Condition eq "OR") {
3500 :     $Result = "YES";
3501 :     last;
3502 :     } elsif (defined($Comparison) && defined($Name) && $Name !~ m/$Comparison/ && $Condition eq "AND") {
3503 :     $Result = "NO";
3504 :     last;
3505 :     }
3506 :     } elsif ($Array[$j] =~ m/^!NAME:(.+)/) {
3507 :     my $Comparison = $1;
3508 :     if ((!defined($Comparison) || !defined($Name) || $Name !~ m/$Comparison/) && $Condition eq "OR") {
3509 :     $Result = "YES";
3510 :     last;
3511 :     } elsif (defined($Comparison) && defined($Name) && $Name =~ m/$Comparison/ && $Condition eq "AND") {
3512 :     $Result = "NO";
3513 :     last;
3514 :     }
3515 :     } elsif ($Array[$j] =~ m/^SUBSYSTEM:(.+)/) {
3516 :     my @SubsystemArray = split(/`/,$1);
3517 :     if (@SubsystemArray == 1) {
3518 :     if (defined($VariantHash->{$SubsystemArray[0]}) && $VariantHash->{$SubsystemArray[0]} ne -1 && $Condition eq "OR") {
3519 :     $Result = "YES";
3520 :     last;
3521 :     } elsif ((!defined($VariantHash->{$SubsystemArray[0]}) || $VariantHash->{$SubsystemArray[0]} eq -1) && $Condition eq "AND") {
3522 :     $Result = "NO";
3523 :     last;
3524 :     }
3525 :     } else {
3526 :     my $Match = 0;
3527 :     for (my $k=1; $k < @SubsystemArray; $k++) {
3528 :     if (defined($VariantHash->{$SubsystemArray[0]}) && $VariantHash->{$SubsystemArray[0]} eq $SubsystemArray[$k]) {
3529 :     $Match = 1;
3530 :     last;
3531 :     }
3532 :     }
3533 :     if ($Match == 1 && $Condition eq "OR") {
3534 :     $Result = "YES";
3535 :     last;
3536 :     } elsif ($Match != 1 && $Condition eq "AND") {
3537 :     $Result = "NO";
3538 :     last;
3539 :     }
3540 :     }
3541 :     } elsif ($Array[$j] =~ m/^!SUBSYSTEM:(.+)/) {
3542 :     my @SubsystemArray = split(/`/,$1);
3543 :     if (@SubsystemArray == 1) {
3544 :     if ((!defined($VariantHash->{$SubsystemArray[0]}) || $VariantHash->{$SubsystemArray[0]} eq -1) && $Condition eq "OR") {
3545 :     $Result = "YES";
3546 :     last;
3547 :     } elsif (defined($VariantHash->{$SubsystemArray[0]}) && $VariantHash->{$SubsystemArray[0]} ne -1 && $Condition eq "AND") {
3548 :     $Result = "NO";
3549 :     last;
3550 :     }
3551 :     } else {
3552 :     my $Match = 0;
3553 :     for (my $k=1; $k < @SubsystemArray; $k++) {
3554 :     if (defined($VariantHash->{$SubsystemArray[0]}) && $VariantHash->{$SubsystemArray[0]} eq $SubsystemArray[$k]) {
3555 :     $Match = 1;
3556 :     last;
3557 :     }
3558 :     }
3559 :     if ($Match != 1 && $Condition eq "OR") {
3560 :     $Result = "YES";
3561 :     last;
3562 :     } elsif ($Match == 1 && $Condition eq "AND") {
3563 :     $Result = "NO";
3564 :     last;
3565 :     }
3566 :     }
3567 :     } elsif ($Array[$j] =~ m/^ROLE:(.+)/) {
3568 :     if (defined($RoleHash->{$1}) && $Condition eq "OR") {
3569 :     $Result = "YES";
3570 :     last;
3571 :     } elsif (!defined($RoleHash->{$1}) && $Condition eq "AND") {
3572 :     $Result = "NO";
3573 :     last;
3574 :     }
3575 :     } elsif ($Array[$j] =~ m/^!ROLE:(.+)/) {
3576 :     if (!defined($RoleHash->{$1}) && $Condition eq "OR") {
3577 :     $Result = "YES";
3578 :     last;
3579 :     } elsif (defined($RoleHash->{$1}) && $Condition eq "AND") {
3580 :     $Result = "NO";
3581 :     last;
3582 :     }
3583 :     } elsif ($Array[$j] =~ m/^CLASS:(.+)/) {
3584 :     if ($Class eq $1 && $Condition eq "OR") {
3585 :     $Result = "YES";
3586 :     last;
3587 :     } elsif ($Class ne $1 && $Condition eq "AND") {
3588 :     $Result = "NO";
3589 :     last;
3590 :     }
3591 :     } elsif ($Array[$j] =~ m/^!CLASS:(.+)/) {
3592 :     if ($Class ne $1 && $Condition eq "OR") {
3593 :     $Result = "YES";
3594 :     last;
3595 :     } elsif ($Class eq $1 && $Condition eq "AND") {
3596 :     $Result = "NO";
3597 :     last;
3598 :     }
3599 :     }
3600 :     }
3601 :     $Criteria = $Start.$Result.$End;
3602 :     print $Criteria."\n";
3603 :     } else {
3604 :     $End = 1;
3605 :     last;
3606 :     }
3607 :     }
3608 :     if ($Criteria eq "YES") {
3609 :     push(@{$EquationData},$Row);
3610 :     $ComponentTypes->{$Row->{"CLASS"}->[0]}->{$Row->{"ID"}->[0]} = 1;
3611 :     }
3612 :     }
3613 :     }
3614 :    
3615 :     #Building biomass equation
3616 :     my %Reactants;
3617 :     my %Products;
3618 :     foreach my $EquationRow (@{$EquationData}) {
3619 :     #First determine what the coefficient should be
3620 :     my $Coefficient;
3621 :     if (defined($EquationRow->{"COEFFICIENT"}) && $EquationRow->{"COEFFICIENT"}->[0] =~ m/^[0-9\.]+$/) {
3622 :     $Coefficient = $EquationRow->{"COEFFICIENT"}->[0];
3623 :     } elsif (defined($EquationRow->{"COEFFICIENT"}) && $EquationRow->{"COEFFICIENT"}->[0] =~ m/cpd\d\d\d\d\d/) {
3624 :     $Coefficient = 0;
3625 :     my @CompoundList = split(/,/,$EquationRow->{"COEFFICIENT"}->[0]);
3626 :     foreach my $Compound (@CompoundList) {
3627 :     if (defined($Reactants{$Compound})) {
3628 :     $Coefficient += $Reactants{$Compound};
3629 :     }
3630 :     }
3631 :     } elsif (defined($EquationRow->{"COEFFICIENT"}) && $EquationRow->{"COEFFICIENT"}->[0] =~ m/^([0-9\.]+)\/(.+)$/) {
3632 :     my @Keys = keys(%{$ComponentTypes->{$2}});
3633 :     my $MW = 1;
3634 :     my $CompoundData = $self->figmodel()->LoadObject($EquationRow->{"ID"}->[0]);
3635 :     if (defined($CompoundData->{"MASS"})) {
3636 :     $MW = $CompoundData->{"MASS"}->[0];
3637 :     }
3638 :     $Coefficient = $1/@Keys/$MW;
3639 :     }
3640 :     if (defined($EquationRow->{"REACTANT"}) && $EquationRow->{"REACTANT"}->[0] eq "YES") {
3641 :     if (defined($Reactants{$EquationRow->{"ID"}->[0]})) {
3642 :     $Reactants{$EquationRow->{"ID"}->[0]} += $Coefficient;
3643 :     } elsif (defined($Products{$EquationRow->{"ID"}->[0]}) && $Products{$EquationRow->{"ID"}->[0]} > $Coefficient) {
3644 :     $Products{$EquationRow->{"ID"}->[0]} -= $Coefficient;
3645 :     } elsif (defined($Products{$EquationRow->{"ID"}->[0]}) && $Products{$EquationRow->{"ID"}->[0]} < $Coefficient) {
3646 :     $Reactants{$EquationRow->{"ID"}->[0]} = $Coefficient - $Products{$EquationRow->{"ID"}->[0]};
3647 :     delete $Products{$EquationRow->{"ID"}->[0]};
3648 :     } else {
3649 :     $Reactants{$EquationRow->{"ID"}->[0]} = $Coefficient;
3650 :     }
3651 :     } else {
3652 :     if (defined($Products{$EquationRow->{"ID"}->[0]})) {
3653 :     $Products{$EquationRow->{"ID"}->[0]} += $Coefficient;
3654 :     } elsif (defined($Reactants{$EquationRow->{"ID"}->[0]}) && $Reactants{$EquationRow->{"ID"}->[0]} > $Coefficient) {
3655 :     $Reactants{$EquationRow->{"ID"}->[0]} -= $Coefficient;
3656 :     } elsif (defined($Reactants{$EquationRow->{"ID"}->[0]}) && $Reactants{$EquationRow->{"ID"}->[0]} < $Coefficient) {
3657 :     $Products{$EquationRow->{"ID"}->[0]} = $Coefficient - $Reactants{$EquationRow->{"ID"}->[0]};
3658 :     delete $Reactants{$EquationRow->{"ID"}->[0]};
3659 :     } else {
3660 :     $Products{$EquationRow->{"ID"}->[0]} = $Coefficient;
3661 :     }
3662 :     }
3663 :     }
3664 :     my $Equation = "";
3665 :     my @ReactantList = sort(keys(%Reactants));
3666 :     for (my $i=0; $i < @ReactantList; $i++) {
3667 :     if (length($Equation) > 0) {
3668 :     $Equation .= " + ";
3669 :     }
3670 :     $Equation .= $self->figmodel()->format_coefficient($Reactants{$ReactantList[$i]})." ".$ReactantList[$i];
3671 :     }
3672 :     $Equation .= " => ";
3673 :     my $First = 1;
3674 :     @ReactantList = sort(keys(%Products));
3675 :     for (my $i=0; $i < @ReactantList; $i++) {
3676 :     if ($First == 0) {
3677 :     $Equation .= " + ";
3678 :     }
3679 :     $First = 0;
3680 :     $Equation .= $self->figmodel()->format_coefficient($Products{$ReactantList[$i]})." ".$ReactantList[$i];
3681 :     }
3682 :    
3683 :     #Adding the biomass equation to the biomass table
3684 :     my $NewRow = $self->figmodel()->add_biomass_reaction($Equation,$self->id(),"Template:".$self->genome());
3685 : chenry 1.13 $biomassrxn = $NewRow;
3686 : chenry 1.2 }
3687 : chenry 1.13 return $biomassrxn;
3688 : chenry 1.2 }
3689 :    
3690 :     =head3 PrintSBMLFile
3691 :     Definition:
3692 :     FIGMODELmodel->PrintSBMLFile();
3693 :     Description:
3694 :     Printing file with model data in SBML format
3695 :     =cut
3696 :     sub PrintSBMLFile {
3697 :     my($self) = @_;
3698 :    
3699 :     #Opening the SBML file for printing
3700 :     my $Filename = $self->config("SBML files")->[0].$self->id().".xml";
3701 :     if ($self->owner() ne "master") {
3702 :     if (!-d $self->config("SBML files")->[0].$self->owner()."/") {
3703 :     system("mkdir ".$self->config("SBML files")->[0].$self->owner()."/");
3704 :     }
3705 :     $Filename = $self->config("SBML files")->[0].$self->owner()."/".$self->id().".xml";
3706 :     }
3707 :     if (!open (SBMLOUTPUT, ">$Filename")) {
3708 :     return;
3709 :     }
3710 :    
3711 :     #Loading and parsing the model data
3712 :     my $ModelTable = $self->reaction_table();
3713 :     if (!defined($ModelTable) || !defined($ModelTable->{"array"})) {
3714 :     print "Failed to load ".$self->id()."\n";
3715 :     return;
3716 :     }
3717 :    
3718 :     #Adding intracellular metabolites that also need exchange fluxes to the exchange hash
3719 :     my $ExchangeHash = {"cpd11416" => "c"};
3720 :    
3721 :     my %CompartmentsPresent;
3722 :     $CompartmentsPresent{"c"} = 1;
3723 :     my %CompoundList;
3724 :     my @ReactionList;
3725 :     my $ReactionTable = $self->figmodel()->database()->GetDBTable("REACTIONS");
3726 :     for (my $i=0; $i < $ModelTable->size(); $i++) {
3727 :     my $Reaction = $ModelTable->get_row($i)->{"LOAD"}->[0];
3728 :     if (defined($ReactionTable->get_row_by_key($Reaction,"DATABASE")) && defined($ReactionTable->get_row_by_key($Reaction,"DATABASE")->{"EQUATION"}->[0])) {
3729 :     push(@ReactionList,$Reaction);
3730 :     $_ = $ReactionTable->get_row_by_key($Reaction,"DATABASE")->{"EQUATION"}->[0];
3731 :     my @MatchArray = /(cpd\d\d\d\d\d)/g;
3732 :     for (my $j=0; $j < @MatchArray; $j++) {
3733 :     $CompoundList{$MatchArray[$j]}->{"c"} = 1;
3734 :     }
3735 :     $_ = $ReactionTable->get_row_by_key($Reaction,"DATABASE")->{"EQUATION"}->[0];
3736 :     @MatchArray = /(cpd\d\d\d\d\d\[\D\])/g;
3737 :     for (my $j=0; $j < @MatchArray; $j++) {
3738 :     if ($MatchArray[$j] =~ m/(cpd\d\d\d\d\d)\[(\D)\]/) {
3739 :     $CompartmentsPresent{lc($2)} = 1;
3740 :     $CompoundList{$1}->{lc($2)} = 1;
3741 :     }
3742 :     }
3743 :     }
3744 :     }
3745 :    
3746 :     #Printing header to SBML file
3747 :     my $ModelName = $self->id();
3748 :     $ModelName =~ s/\./_/;
3749 :     print SBMLOUTPUT '<?xml version="1.0" encoding="UTF-8"?>'."\n";
3750 :     print SBMLOUTPUT '<sbml xmlns="http://www.sbml.org/sbml/level2" level="2" version="1" xmlns:html="http://www.w3.org/1999/xhtml">' . "\n";
3751 :     if (defined($self->figmodel()->database()->GetDBTable("MODEL STATS")->{$self->id()}->[0]->{"Organism name"}->[0])) {
3752 :     print SBMLOUTPUT '<model id="'.$ModelName.'" name="'.$self->figmodel()->database()->GetDBTable("MODEL STATS")->{$self->id()}->[0]->{"Organism name"}->[0].' SEED model">'."\n";
3753 :     } else {
3754 :     print SBMLOUTPUT '<model id="'.$ModelName.'" name="'.$self->id().' SEED model">'."\n";
3755 :     }
3756 :    
3757 :     #Printing the unit data
3758 :     print SBMLOUTPUT "<listOfUnitDefinitions>\n";
3759 :     print SBMLOUTPUT "\t<unitDefinition id=\"mmol_per_gDW_per_hr\">\n";
3760 :     print SBMLOUTPUT "\t\t<listOfUnits>\n";
3761 :     print SBMLOUTPUT "\t\t\t<unit kind=\"mole\" scale=\"-3\"/>\n";
3762 :     print SBMLOUTPUT "\t\t\t<unit kind=\"gram\" exponent=\"-1\"/>\n";
3763 :     print SBMLOUTPUT "\t\t\t<unit kind=\"second\" multiplier=\".00027777\" exponent=\"-1\"/>\n";
3764 :     print SBMLOUTPUT "\t\t</listOfUnits>\n";
3765 :     print SBMLOUTPUT "\t</unitDefinition>\n";
3766 :     print SBMLOUTPUT "</listOfUnitDefinitions>\n";
3767 :    
3768 :     #Printing compartments for SBML file
3769 :     print SBMLOUTPUT '<listOfCompartments>'."\n";
3770 :     foreach my $Compartment (keys(%CompartmentsPresent)) {
3771 :     if (defined($self->figmodel()->database()->GetDBTable("COMPARTMENTS")->{$Compartment}->[0]->{"Name"}->[0])) {
3772 :     my @OutsideList = split(/\//,$self->figmodel()->database()->GetDBTable("COMPARTMENTS")->{$Compartment}->[0]->{"Outside"}->[0]);
3773 :     my $Printed = 0;
3774 :     foreach my $Outside (@OutsideList) {
3775 :     if (defined($CompartmentsPresent{$Outside}) && defined($self->figmodel()->database()->GetDBTable("COMPARTMENTS")->{$Outside}->[0]->{"Name"}->[0])) {
3776 :     print SBMLOUTPUT '<compartment id="'.$self->figmodel()->database()->GetDBTable("COMPARTMENTS")->{$Compartment}->[0]->{"Name"}->[0].'" outside="'.$self->figmodel()->database()->GetDBTable("COMPARTMENTS")->{$Outside}->[0]->{"Name"}->[0].'"/>'."\n";
3777 :     $Printed = 1;
3778 :     last;
3779 :     }
3780 :     }
3781 :     if ($Printed eq 0) {
3782 :     print SBMLOUTPUT '<compartment id="'.$self->figmodel()->database()->GetDBTable("COMPARTMENTS")->{$Compartment}->[0]->{"Name"}->[0].'"/>'."\n";
3783 :     }
3784 :     }
3785 :     }
3786 :     print SBMLOUTPUT '</listOfCompartments>'."\n";
3787 :    
3788 :     #Printing the list of metabolites involved in the model
3789 :     print SBMLOUTPUT '<listOfSpecies>'."\n";
3790 :     foreach my $Compound (keys(%CompoundList)) {
3791 :     my $Name = $Compound;
3792 :     my $Formula = "";
3793 :     if (defined($self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"FORMULA"}->[0])) {
3794 :     $Formula = $self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"FORMULA"}->[0];
3795 :     }
3796 :     if (defined($self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"NAME"}->[0])) {
3797 :     $Name = $self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"NAME"}->[0];
3798 :     $Name =~ s/\s/_/;
3799 :     $Name .= "_".$Formula;
3800 :     }
3801 :     $Name =~ s/[<>;&\*]//;
3802 :     my $Charge = 0;
3803 :     if (defined($self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"CHARGE"}->[0])) {
3804 :     $Charge = $self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"CHARGE"}->[0];
3805 :     }
3806 :     foreach my $Compartment (keys(%{$CompoundList{$Compound}})) {
3807 :     if ($Compartment eq "e") {
3808 :     $ExchangeHash->{$Compound} = "e";
3809 :     }
3810 :     print SBMLOUTPUT '<species id="'.$Compound.'_'.$Compartment.'" name="'.$Name.'" compartment="'.$self->figmodel()->database()->GetDBTable("COMPARTMENTS")->{$Compartment}->[0]->{"Name"}->[0].'" charge="'.$Charge.'" boundaryCondition="false"/>'."\n";
3811 :     }
3812 :     }
3813 :     #Printing the boundary species
3814 :     foreach my $Compound (keys(%{$ExchangeHash})) {
3815 :     my $Name = $Compound;
3816 :     my $Formula = "";
3817 :     if (defined($self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"FORMULA"}->[0])) {
3818 :     $Formula = $self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"FORMULA"}->[0];
3819 :     }
3820 :     if (defined($self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"NAME"}->[0])) {
3821 :     $Name = $self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"NAME"}->[0];
3822 :     $Name =~ s/\s/_/;
3823 :     $Name .= "_".$Formula;
3824 :     }
3825 :     $Name =~ s/[<>;&\*]//;
3826 :     my $Charge = 0;
3827 :     if (defined($self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"CHARGE"}->[0])) {
3828 :     $Charge = $self->figmodel()->database()->GetDBTable("COMPOUNDS")->{$Compound}->[0]->{"CHARGE"}->[0];
3829 :     }
3830 :     print SBMLOUTPUT '<species id="'.$Compound.'_b" name="'.$Name.'" compartment="Extracellular" charge="'.$Charge.'" boundaryCondition="true"/>'."\n";
3831 :     }
3832 :     print SBMLOUTPUT '</listOfSpecies>'."\n";
3833 :    
3834 :     #Printing the list of reactions involved in the model
3835 :     my $ObjectiveCoef;
3836 :     print SBMLOUTPUT '<listOfReactions>'."\n";
3837 :     foreach my $Reaction (@ReactionList) {
3838 :     $ObjectiveCoef = "0.0";
3839 :     if (defined($self->figmodel()->database()->GetDBTable("REACTIONS")->{$Reaction}->[0]->{"EQUATION"}->[0])) {
3840 :     if ($Reaction =~ m/^bio/) {
3841 :     $ObjectiveCoef = "1.0";
3842 :     }
3843 :     my $LowerBound = -10000;
3844 :     my $UpperBound = 10000;
3845 :     my ($Reactants,$Products) = $self->figmodel()->GetReactionSubstrateData($Reaction);
3846 :     my $Name = $Reaction;
3847 :     if (defined($self->figmodel()->database()->GetDBTable("REACTIONS")->{$Reaction}->[0]->{"NAME"}->[0])) {
3848 :     $Name = $self->figmodel()->database()->GetDBTable("REACTIONS")->{$Reaction}->[0]->{"NAME"}->[0];
3849 :     $Name =~ s/[<>;&]//g;
3850 :     }
3851 :     my $Reversibility = "true";
3852 :     if (defined($ModelTable->{$Reaction}->[0]->{"DIRECTIONALITY"}->[0])) {
3853 :     if ($ModelTable->{$Reaction}->[0]->{"DIRECTIONALITY"}->[0] ne "<=>") {
3854 :     $LowerBound = 0;
3855 :     $Reversibility = "false";
3856 :     }
3857 :     if ($ModelTable->{$Reaction}->[0]->{"DIRECTIONALITY"}->[0] eq "<=") {
3858 :     my $Temp = $Products;
3859 :     $Products = $Reactants;
3860 :     $Reactants = $Temp;
3861 :     }
3862 :     }
3863 :     print SBMLOUTPUT '<reaction id="'.$Reaction.'" name="'.$Name.'" reversible="'.$Reversibility.'">'."\n";
3864 :     print SBMLOUTPUT "<notes>\n";
3865 :     my $ECData = "";
3866 :     if (defined($self->figmodel()->database()->GetDBTable("REACTIONS")->{$Reaction}->[0]->{"ENZYME"}->[0])) {
3867 :     $ECData = $self->figmodel()->database()->GetDBTable("REACTIONS")->{$Reaction}->[0]->{"ENZYME"}->[0];
3868 :     }
3869 :     my $SubsystemData = "";
3870 :     if (defined($ModelTable->{$Reaction}->[0]->{"SUBSYSTEM"}->[0])) {
3871 :     $SubsystemData = $ModelTable->{$Reaction}->[0]->{"SUBSYSTEM"}->[0];
3872 :     }
3873 :     my $GeneAssociation = "";
3874 :     my $ProteinAssociation = "";
3875 :     if (defined($ModelTable->{$Reaction}->[0]->{"ASSOCIATED PEG"}->[0])) {
3876 :     if (@{$ModelTable->{$Reaction}->[0]->{"ASSOCIATED PEG"}} == 1 && $ModelTable->{$Reaction}->[0]->{"ASSOCIATED PEG"}->[0] !~ m/\+/) {
3877 :     $GeneAssociation = $ModelTable->{$Reaction}->[0]->{"ASSOCIATED PEG"}->[0];
3878 :     } else {
3879 :     if (@{$ModelTable->{$Reaction}->[0]->{"ASSOCIATED PEG"}} > 1) {
3880 :     $GeneAssociation = "( ";
3881 :     }
3882 :     for (my $i=0; $i < @{$ModelTable->{$Reaction}->[0]->{"ASSOCIATED PEG"}}; $i++) {
3883 :     if ($i > 0) {
3884 :     $GeneAssociation .= " ) or ( ";
3885 :     }
3886 :     $GeneAssociation .= $ModelTable->{$Reaction}->[0]->{"ASSOCIATED PEG"}->[$i];
3887 :     }
3888 :     if (@{$ModelTable->{$Reaction}->[0]->{"ASSOCIATED PEG"}} > 1) {
3889 :     $GeneAssociation .= " )";
3890 :     }
3891 :     }
3892 :     $GeneAssociation =~ s/\+/ and /g;
3893 :     if ($GeneAssociation =~ m/\sor\s/ || $GeneAssociation =~ m/\sand\s/) {
3894 :     $GeneAssociation = "( ".$GeneAssociation." )";
3895 :     }
3896 :     $ProteinAssociation = $GeneAssociation;
3897 :     if (defined($self->figmodel()->database()->GetDBTable("MODEL STATS")->{$self->id()}->[0]->{"Genome ID"}->[0])) {
3898 :     $ProteinAssociation = $self->figmodel()->translate_gene_to_protein($ModelTable->{$Reaction}->[0]->{"ASSOCIATED PEG"}->[0],$self->figmodel()->database()->GetDBTable("MODEL STATS")->{$self->id()}->[0]->{"Genome ID"}->[0]);
3899 :     }
3900 :     }
3901 :     print SBMLOUTPUT "<html:p>GENE_ASSOCIATION:".$GeneAssociation."</html:p>\n";
3902 :     print SBMLOUTPUT "<html:p>PROTEIN_ASSOCIATION:".$ProteinAssociation."</html:p>\n";
3903 :     print SBMLOUTPUT "<html:p>SUBSYSTEM: ".$SubsystemData."</html:p>\n";
3904 :     print SBMLOUTPUT "<html:p>PROTEIN_CLASS: ".$ECData."</html:p>\n";
3905 :     print SBMLOUTPUT "</notes>\n";
3906 :     print SBMLOUTPUT "<listOfReactants>\n";
3907 :     foreach my $Reactant (@{$Reactants}) {
3908 :     print SBMLOUTPUT '<speciesReference species="'.$Reactant->{"DATABASE"}->[0]."_".$Reactant->{"COMPARTMENT"}->[0].'" stoichiometry="'.$Reactant->{"COEFFICIENT"}->[0].'"/>'."\n";
3909 :     }
3910 :     print SBMLOUTPUT "</listOfReactants>\n";
3911 :     print SBMLOUTPUT "<listOfProducts>\n";
3912 :     foreach my $Product (@{$Products}) {
3913 :     print SBMLOUTPUT '<speciesReference species="'.$Product->{"DATABASE"}->[0]."_".$Product->{"COMPARTMENT"}->[0].'" stoichiometry="'.$Product->{"COEFFICIENT"}->[0].'"/>'."\n";
3914 :     }
3915 :     print SBMLOUTPUT "</listOfProducts>\n";
3916 :     print SBMLOUTPUT "<kineticLaw>\n";
3917 :     print SBMLOUTPUT "\t<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n";
3918 :     print SBMLOUTPUT "\t\t\t<ci> FLUX_VALUE </ci>\n";
3919 :     print SBMLOUTPUT "\t</math>\n";
3920 :     print SBMLOUTPUT "\t<listOfParameters>\n";
3921 :     print SBMLOUTPUT "\t\t<parameter id=\"LOWER_BOUND\" value=\"".$LowerBound."\" units=\"mmol_per_gDW_per_hr\"/>\n";
3922 :     print SBMLOUTPUT "\t\t<parameter id=\"UPPER_BOUND\" value=\"".$UpperBound."\" units=\"mmol_per_gDW_per_hr\"/>\n";
3923 :     print SBMLOUTPUT "\t\t<parameter id=\"OBJECTIVE_COEFFICIENT\" value=\"".$ObjectiveCoef."\"/>\n";
3924 :     print SBMLOUTPUT "\t\t<parameter id=\"FLUX_VALUE\" value=\"0.0\" units=\"mmol_per_gDW_per_hr\"/>\n";
3925 :     print SBMLOUTPUT "\t</listOfParameters>\n";
3926 :     print SBMLOUTPUT "</kineticLaw>\n";
3927 :     print SBMLOUTPUT '</reaction>'."\n";
3928 :     }
3929 :     }
3930 :    
3931 :     my @ExchangeList = keys(%{$ExchangeHash});
3932 :     foreach my $ExCompound (@ExchangeList) {
3933 :     my $ExCompoundName = $ExCompound;
3934 :     my $Row = $self->figmodel()->database()->GetDBTable("COMPOUNDS")->get_row_by_key($ExCompound,"DATABASE");
3935 :     if (defined($Row) && defined($Row->{"NAME"}->[0])) {
3936 :     $ExCompoundName = $Row->{"NAME"}->[0];
3937 :     $ExCompoundName =~ s/[<>;&]//g;
3938 :     }
3939 :     $ObjectiveCoef = "0.0";
3940 :     print SBMLOUTPUT '<reaction id="EX_'.$ExCompound.'_'.$ExchangeHash->{$ExCompound}.'" name="EX_'.$ExCompoundName.'_'.$ExchangeHash->{$ExCompound}.'" reversible="true">'."\n";
3941 :     print SBMLOUTPUT "\t".'<notes>'."\n";
3942 :     print SBMLOUTPUT "\t\t".'<html:p>GENE_ASSOCIATION: </html:p>'."\n";
3943 :     print SBMLOUTPUT "\t\t".'<html:p>PROTEIN_ASSOCIATION: </html:p>'."\n";
3944 :     print SBMLOUTPUT "\t\t".'<html:p>SUBSYSTEM: S_</html:p>'."\n";
3945 :     print SBMLOUTPUT "\t\t".'<html:p>PROTEIN_CLASS: </html:p>'."\n";
3946 :     print SBMLOUTPUT "\t".'</notes>'."\n";
3947 :     print SBMLOUTPUT "\t".'<listOfReactants>'."\n";
3948 :     print SBMLOUTPUT "\t\t".'<speciesReference species="'.$ExCompound.'_'.$ExchangeHash->{$ExCompound}.'" stoichiometry="1.000000"/>'."\n";
3949 :     print SBMLOUTPUT "\t".'</listOfReactants>'."\n";
3950 :     print SBMLOUTPUT "\t".'<listOfProducts>'."\n";
3951 :     print SBMLOUTPUT "\t\t".'<speciesReference species="'.$ExCompound.'_b" stoichiometry="1.000000"/>'."\n";
3952 :     print SBMLOUTPUT "\t".'</listOfProducts>'."\n";
3953 :     print SBMLOUTPUT "\t".'<kineticLaw>'."\n";
3954 :     print SBMLOUTPUT "\t\t".'<math xmlns="http://www.w3.org/1998/Math/MathML">'."\n";
3955 :     print SBMLOUTPUT "\t\t\t\t".'<ci> FLUX_VALUE </ci>'."\n";
3956 :     print SBMLOUTPUT "\t\t".'</math>'."\n";
3957 :     print SBMLOUTPUT "\t\t".'<listOfParameters>'."\n";
3958 :     print SBMLOUTPUT "\t\t\t".'<parameter id="LOWER_BOUND" value="-10000.000000" units="mmol_per_gDW_per_hr"/>'."\n";
3959 :     print SBMLOUTPUT "\t\t\t".'<parameter id="UPPER_BOUND" value="10000.000000" units="mmol_per_gDW_per_hr"/>'."\n";
3960 :     print SBMLOUTPUT "\t\t\t".'<parameter id="OBJECTIVE_COEFFICIENT" value="'.$ObjectiveCoef.'"/>'."\n";
3961 :     print SBMLOUTPUT "\t\t\t".'<parameter id="FLUX_VALUE" value="0.000000" units="mmol_per_gDW_per_hr"/>'."\n";
3962 :     print SBMLOUTPUT "\t\t".'</listOfParameters>'."\n";
3963 :     print SBMLOUTPUT "\t".'</kineticLaw>'."\n";
3964 :     print SBMLOUTPUT '</reaction>'."\n";
3965 :     }
3966 :    
3967 :     #Closing out the file
3968 :     print SBMLOUTPUT '</listOfReactions>'."\n";
3969 :     print SBMLOUTPUT '</model>'."\n";
3970 :     print SBMLOUTPUT "</sbml>\n";
3971 :     close(SBMLOUTPUT);
3972 :     }
3973 :    
3974 :     =head3 PrintModelLPFile
3975 :     Definition:
3976 :     success()/fail() FIGMODELmodel->PrintModelLPFile();
3977 :     Description:
3978 :     Prints the lp file needed to run the model using the mpifba program
3979 :     =cut
3980 :     sub PrintModelLPFile {
3981 :     my ($self) = @_;
3982 :     #Printing lp and key file for model
3983 :     my $UniqueFilename = $self->figmodel()->filename();
3984 :     #Printing the standard FBA file
3985 :     system($self->figmodel()->GenerateMFAToolkitCommandLineCall($UniqueFilename,$self->id(),"NoBounds",["ProdFullFBALP"],undef,$self->id().$self->selected_version()."-LPPrint.log",undef,$self->selected_version()));
3986 :     system("cp ".$self->config("MFAToolkit output directory")->[0].$UniqueFilename."/CurrentProblem.lp ".$self->directory()."FBA-".$self->id().$self->selected_version().".lp");
3987 :     my $KeyTable = FIGMODELTable::load_table($self->config("MFAToolkit output directory")->[0].$UniqueFilename."/VariableKey.txt",";","|",0,undef);
3988 :     if (!defined($KeyTable)) {
3989 :     print STDERR "FIGMODEL:RunAllStudiesWithDataFast: ".$self->id()." LP file could not be printed.\n";
3990 :     return 0;
3991 :     }
3992 :     $KeyTable->headings(["Variable type","Variable ID"]);
3993 :     $KeyTable->save($self->directory()."FBA-".$self->id().$self->selected_version().".key");
3994 :     unlink($self->config("database message file directory")->[0].$self->id().$self->selected_version()."-LPPrint.log");
3995 :     $self->figmodel()->clearing_output($UniqueFilename,"FBA-".$self->id().$self->selected_version().".lp");
3996 :     }
3997 :    
3998 : chenry 1.5 =head3 patch_model
3999 :     Definition:
4000 :     FIGMODELTable:patch results = FIGMODELmodel->patch_model(FIGMODELTable:patch table);
4001 :     Description:
4002 :     =cut
4003 :     sub patch_model {
4004 :     my ($self,$tbl) = @_;
4005 :    
4006 :     #Instantiating table
4007 :     my $results = FIGMODELTable->new(["Reactions","New genes","Old genes","Genes","Roles","Status"],$self->directory()."PatchResults-".$self->id().$self->selected_version().".tbl",["Reaction"],"\t",";",undef);
4008 :     #Getting genome annotations
4009 :     my $features = $self->figmodel()->database()->get_genome_feature_table($self->genome());
4010 :     #Gettubg reaction table
4011 :     my $reactions = $self->reaction_table();
4012 :     #Checking for patched roles
4013 :     for (my $i=0; $i < $tbl->size(); $i++) {
4014 :     my $row = $tbl->get_row($i);
4015 :     my @genes = $features->get_rows_by_key($row->{ROLE}->[0],"ROLES");
4016 :     if (@genes > 0) {
4017 :     for (my $j=0; $j < @{$row->{REACTIONS}};$j++) {
4018 :     my $resultrxn = $results->get_row_by_key($row->{REACTIONS}->[$j],"Reactions");
4019 :     if (!defined($resultrxn)) {
4020 :     $resultrxn = $results->add_row({"Reactions"=>[$row->{REACTIONS}->[$j]],"Roles"=>[$row->{ROLE}->[0]]});
4021 :     }
4022 :     my $rxnrow = $reactions->get_row_by_key($row->{REACTIONS}->[$j],"LOAD");
4023 :     if (defined($rxnrow) && !defined($resultrxn->{"Old genes"})) {
4024 :     $resultrxn->{"Old genes"} = $rxnrow->{"ASSOCIATED PEG"};
4025 :     if ($resultrxn->{"Old genes"}->[0] !~ m/GAP|BOF|UNIVERSAL|SPONTANEOUS/) {
4026 :     push(@{$resultrxn->{"Genes"}},@{$resultrxn->{"Old genes"}});
4027 :     }
4028 :     }
4029 :     delete $resultrxn->{"Current gene set"};
4030 :     if (defined($resultrxn->{"Genes"})) {
4031 :     push(@{$resultrxn->{"Current gene set"}},@{$resultrxn->{"Genes"}});
4032 :     }
4033 :     for (my $k=0; $k < @genes; $k++) {
4034 :     if ($genes[$k]->{ID}->[0] =~ m/(peg\.\d+)/) {
4035 :     my $gene = $1;
4036 :     my $addgene = 1;
4037 :     if (defined($resultrxn->{"Old genes"})) {
4038 :     for (my $m=0; $m < @{$resultrxn->{"Old genes"}}; $m++) {
4039 :     if ($resultrxn->{"Old genes"}->[$m] =~ m/$gene/) {
4040 :     $addgene = 0;
4041 :     }
4042 :     }
4043 :     }
4044 :     if ($addgene == 1) {
4045 :     push(@{$resultrxn->{"New genes"}},$gene);
4046 :     if ($row->{COMPLEX}->[0] ne "0" && defined($resultrxn->{"Current gene set"})) {
4047 :     my $added = 0;
4048 :     for (my $m=0; $m < @{$resultrxn->{"Current gene set"}}; $m++) {
4049 :     if ($row->{COMPLEX}->[0] eq "1") {
4050 :     $resultrxn->{"Current gene set"}->[$m] = $resultrxn->{"Current gene set"}->[$m]."+".$gene;
4051 :     $added = 1;
4052 :     } else {
4053 :     my @geneset = split(/\+/,$resultrxn->{"Current gene set"}->[$m]);
4054 :     for (my $n=0; $n < @geneset;$n++) {
4055 :     if ($self->figmodel()->colocalized_genes($geneset[$n],$gene,$self->genome()) == 1) {
4056 :     $resultrxn->{"Current gene set"}->[$m] = $resultrxn->{"Current gene set"}->[$m]."+".$gene;
4057 :     $added = 1;
4058 :     last;
4059 :     }
4060 :     }
4061 :     }
4062 :     }
4063 :     if ($added == 0) {
4064 :     push(@{$resultrxn->{"Current gene set"}},$gene);
4065 :     }
4066 :     } else {
4067 :     push(@{$resultrxn->{"Current gene set"}},$gene);
4068 :     }
4069 :     }
4070 :     }
4071 :     }
4072 :     delete $resultrxn->{"Genes"};
4073 :     push(@{$resultrxn->{"Genes"}},@{$resultrxn->{"Current gene set"}});
4074 :     }
4075 :     }
4076 :     }
4077 :    
4078 :     #Ensuring that the old model is preserved
4079 :     $self->ArchiveModel();
4080 :     #Modifing the reaction list
4081 :     for (my $i=0; $i < $results->size();$i++) {
4082 :     my $row = $results->get_row($i);
4083 :     my $rxnrow = $reactions->get_row_by_key($row->{"Reactions"}->[0],"LOAD");
4084 :     if (defined($rxnrow)) {
4085 :     $rxnrow->{"ASSOCIATED PEG"} = $row->{"Genes"};
4086 :     } else {
4087 :     $reactions->add_row({LOAD=>[$row->{"Reactions"}->[0]],DIRECTIONALITY=>[$self->figmodel()->reversibility_of_reaction($row->{"Reactions"}->[0])],COMPARTMENT=>["c"],"ASSOCIATED PEG"=>$row->{"Genes"},SUBSYSTEM=>["NONE"],CONFIDENCE=>[2],REFERENCE=>["NONE"],NOTES=>["PATCH"]});
4088 :     }
4089 :     }
4090 :     $reactions->save();
4091 :     $results->save();
4092 :     $self->update_model_stats();
4093 :     $self->PrintModelLPFile();
4094 :     $self->run_default_model_predictions();
4095 :     #Returning results
4096 :     return $results;
4097 :     }
4098 :    
4099 :     =head3 translate_genes
4100 :     Definition:
4101 :     FIGMODELmodel->translate_genes();
4102 :     Description:
4103 :     =cut
4104 :     sub translate_genes {
4105 :     my ($self) = @_;
4106 :    
4107 :     #Loading gene translations
4108 :     if (!defined($self->{_gene_aliases})) {
4109 :     #Loading gene aliases from feature table
4110 :     my $tbl = $self->figmodel()->GetGenomeFeatureTable($self->genome());
4111 :     if (defined($tbl)) {
4112 :     for (my $i=0; $i < $tbl->size(); $i++) {
4113 :     my $row = $tbl->get_row($i);
4114 :     if ($row->{ID}->[0] =~ m/(peg\.\d+)/) {
4115 :     my $geneID = $1;
4116 :     for (my $j=0; $j < @{$row->{ALIASES}}; $j++) {
4117 :     $self->{_gene_aliases}->{$row->{ALIASES}->[$j]} = $geneID;
4118 :     }
4119 :     }
4120 :     }
4121 :     }
4122 :     #Loading additional gene aliases from the database
4123 :     if (-e $self->figmodel()->config("Translation directory")->[0]."AdditionalAliases/".$self->genome().".txt") {
4124 :     my $AdditionalAliases = $self->figmodel()->database()->load_multiple_column_file($self->figmodel()->config("Translation directory")->[0]."AdditionalAliases/".$self->genome().".txt","\t");
4125 :     for (my $i=0; $i < @{$AdditionalAliases}; $i++) {
4126 :     $self->{_gene_aliases}->{$AdditionalAliases->[$i]->[1]} = $AdditionalAliases->[$i]->[0];
4127 :     }
4128 :     }
4129 :     }
4130 :    
4131 :     #Cycling through reactions and translating genes
4132 :     for (my $i=0; $i < $self->reaction_table()->size(); $i++) {
4133 :     my $row = $self->reaction_table()->get_row($i);
4134 :     if (defined($row->{"ASSOCIATED PEG"})) {
4135 :     for (my $j=0; $j < @{$row->{"ASSOCIATED PEG"}}; $j++) {
4136 :     my $Original = $row->{"ASSOCIATED PEG"}->[$j];
4137 :     $Original =~ s/\sand\s/:/g;
4138 :     $Original =~ s/\sor\s/;/g;
4139 :     my @GeneNames = split(/[,\+\s\(\):;]/,$Original);
4140 :     foreach my $Gene (@GeneNames) {
4141 :     if (length($Gene) > 0 && defined($self->{_gene_aliases}->{$Gene})) {
4142 :     my $Replace = $self->{_gene_aliases}->{$Gene};
4143 :     $Original =~ s/([^\w])$Gene([^\w])/$1$Replace$2/g;
4144 :     $Original =~ s/^$Gene([^\w])/$Replace$1/g;
4145 :     $Original =~ s/([^\w])$Gene$/$1$Replace/g;
4146 :     $Original =~ s/^$Gene$/$Replace/g;
4147 :     }
4148 :     }
4149 :     $Original =~ s/:/ and /g;
4150 :     $Original =~ s/;/ or /g;
4151 :     $row->{"ASSOCIATED PEG"}->[$j] = $Original;
4152 :     }
4153 :     }
4154 :     }
4155 :    
4156 :     #Archiving model and saving reaction table
4157 :     $self->ArchiveModel();
4158 :     $self->reaction_table()->save();
4159 :     }
4160 : chenry 1.12
4161 : chenry 1.10 =head3 feature_web_data
4162 :     Definition:
4163 :     string:web output for feature/model connection = FIGMODELmodel->feature_web_data(FIGMODELfeature:feature);
4164 :     Description:
4165 :     =cut
4166 :     sub feature_web_data {
4167 :     my ($self,$feature) = @_;
4168 :    
4169 :     #First checking if the feature is in the model
4170 :     my $data = $self->get_feature_data($feature->{ID}->[0]);
4171 :     if (!defined($data)) {
4172 :     return "Not in model";
4173 :     }
4174 :    
4175 :     my $output;
4176 :     #Printing predictions
4177 :     if (defined($data->{$self->id()."PREDICTIONS"})) {
4178 :     #Parsing essentiality data
4179 :     my $essentialityData;
4180 :     if (defined($feature->{ESSENTIALITY})) {
4181 :     for (my $i=0; $i < @{$feature->{ESSENTIALITY}};$i++) {
4182 :     my @temp = split(/:/,$feature->{ESSENTIALITY}->[$i]);
4183 :     $essentialityData->{$temp[0]} = $temp[1];
4184 :     }
4185 :     }
4186 :     my $predictionHash;
4187 :     for (my $i=0; $i < @{$data->{$self->id()."PREDICTIONS"}};$i++) {
4188 :     my @temp = split(/:/,$data->{$self->id()."PREDICTIONS"}->[$i]);
4189 :     if (defined($essentialityData->{$temp[0]})) {
4190 :     if ($temp[1] eq "essential" && $essentialityData->{$temp[0]} eq "essential") {
4191 :     push(@{$predictionHash->{"Correct negative"}},$temp[0]);
4192 :     } elsif ($temp[1] eq "nonessential" && $essentialityData->{$temp[0]} eq "essential") {
4193 :     push(@{$predictionHash->{"False positive"}},$temp[0]);
4194 :     } elsif ($temp[1] eq "essential" && $essentialityData->{$temp[0]} eq "nonessential") {
4195 :     push(@{$predictionHash->{"False negative"}},$temp[0]);
4196 :     } elsif ($temp[1] eq "nonessential" && $essentialityData->{$temp[0]} eq "nonessential") {
4197 :     push(@{$predictionHash->{"Correct positive"}},$temp[0]);
4198 :     }
4199 :     } else {
4200 :     push(@{$predictionHash->{$temp[1]}},$temp[0]);
4201 :     }
4202 :     }
4203 :     foreach my $key (keys(%{$predictionHash})) {
4204 :     my $string = $key;
4205 :     $string = ucfirst($string);
4206 :     push(@{$output},'<span title="'.join(", ",@{$predictionHash->{$key}}).'">'.$string.'</span>');
4207 :     }
4208 :     }
4209 :    
4210 :     #Printing reactions
4211 :     if (defined($data->{$self->id()."REACTIONS"})) {
4212 :     for (my $i=0; $i < @{$data->{$self->id()."REACTIONS"}};$i++) {
4213 :     my $rxnData = $self->get_reaction_data($data->{$self->id()."REACTIONS"}->[$i]);
4214 :     my $reactionString = $self->figmodel()->web()->create_reaction_link($data->{$self->id()."REACTIONS"}->[$i],join(" or ",@{$rxnData->{"ASSOCIATED PEG"}}),$self->id());
4215 :     if (defined($rxnData->{PREDICTIONS})) {
4216 :     my $predictionHash;
4217 :     for (my $i=0; $i < @{$rxnData->{PREDICTIONS}};$i++) {
4218 :     my @temp = split(/:/,$rxnData->{PREDICTIONS}->[$i]);
4219 :     push(@{$predictionHash->{$temp[1]}},$temp[0]);
4220 :     }
4221 :     $reactionString .= "(";
4222 :     foreach my $key (keys(%{$predictionHash})) {
4223 :     if ($key eq "Essential =>") {
4224 :     $reactionString .= '<span title="Essential in '.join(",",@{$predictionHash->{$key}}).'">E=></span>,';
4225 :     } elsif ($key eq "Essential <=") {
4226 :     $reactionString .= '<span title="Essential in '.join(",",@{$predictionHash->{$key}}).'">E<=</span>,';
4227 :     } elsif ($key eq "Active =>") {
4228 :     $reactionString .= '<span title="Active in '.join(",",@{$predictionHash->{$key}}).'">A=></span>,';
4229 :     } elsif ($key eq "Active <=") {
4230 :     $reactionString .= '<span title="Active in '.join(",",@{$predictionHash->{$key}}).'">A<=</span>,';
4231 :     } elsif ($key eq "Active <=>") {
4232 :     $reactionString .= '<span title="Active in '.join(",",@{$predictionHash->{$key}}).'">A</span>,';
4233 :     } elsif ($key eq "Inactive") {
4234 :     $reactionString .= '<span title="Inactive in '.join(",",@{$predictionHash->{$key}}).'">I</span>,';
4235 :     } elsif ($key eq "Dead") {
4236 :     $reactionString .= '<span title="Dead">D</span>,';
4237 :     }
4238 :     }
4239 :     $reactionString =~ s/,$/)/;
4240 :     }
4241 :     push(@{$output},$reactionString);
4242 :     }
4243 :     }
4244 :    
4245 :     #Returning output
4246 :     return join("<br>",@{$output});
4247 :     }
4248 :    
4249 : chenry 1.12 =head3 remove_obsolete_reactions
4250 :     Definition:
4251 :     void FIGMODELmodel->remove_obsolete_reactions();
4252 :     Description:
4253 :     =cut
4254 :     sub remove_obsolete_reactions {
4255 :     my ($self) = @_;
4256 :    
4257 : chenry 1.13 (my $dummy,my $translation) = $self->figmodel()->put_two_column_array_in_hash($self->figmodel()->database()->load_multiple_column_file($self->figmodel()->config("Translation directory")->[0]."ObsoleteRxnIDs.txt","\t"));
4258 : chenry 1.12 my $rxnTbl = $self->reaction_table();
4259 : chenry 1.13 if (defined($rxnTbl)) {
4260 :     for (my $i=0; $i < $rxnTbl->size(); $i++) {
4261 :     my $row = $rxnTbl->get_row($i);
4262 :     if (defined($translation->{$row->{LOAD}->[0]}) || defined($translation->{$row->{LOAD}->[0]."r"})) {
4263 :     my $direction = $row->{DIRECTION}->[0];
4264 :     my $newRxn;
4265 :     if (defined($translation->{$row->{LOAD}->[0]."r"})) {
4266 :     $newRxn = $translation->{$row->{LOAD}->[0]."r"};
4267 :     if ($direction eq "<=") {
4268 :     $direction = "=>";
4269 :     } elsif ($direction eq "=>") {
4270 :     $direction = "<=";
4271 :     }
4272 :     } else {
4273 :     $newRxn = $translation->{$row->{LOAD}->[0]};
4274 : chenry 1.12 }
4275 : chenry 1.13 #Checking if the new reaction is already in the model
4276 :     my $newRow = $rxnTbl->get_row_by_key($newRxn,"LOAD");
4277 :     if (defined($newRow)) {
4278 :     #Handling direction
4279 :     if ($newRow->{DIRECTION}->[0] ne $direction) {
4280 :     $newRow->{DIRECTION}->[0] = "<=>";
4281 :     }
4282 :     push(@{$row->{"ASSOCIATED PEG"}},@{$rxnTbl->get_row($i)->{"ASSOCIATED PEG"}});
4283 :     } else {
4284 :     $rxnTbl->get_row($i)->{LOAD}->[0] = $newRxn;
4285 :     $rxnTbl->get_row($i)->{DIRECTION}->[0] = $direction;
4286 : chenry 1.12 }
4287 :     }
4288 :     }
4289 : chenry 1.13 $rxnTbl->save();
4290 : chenry 1.12 }
4291 :     }
4292 :    
4293 : chenry 1.2 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3