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

Annotation of /FigKernelPackages/FIGMODELmodel.pm

Parent Directory Parent Directory | Revision Log Revision Log


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