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

Annotation of /FigKernelPackages/FIGMODELmodel.pm

Parent Directory Parent Directory | Revision Log Revision Log


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