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

Annotation of /FigKernelPackages/FIGMODELmodel.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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