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

Annotation of /FigKernelPackages/FIGMODELmodel.pm

Parent Directory Parent Directory | Revision Log Revision Log


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