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

Annotation of /FigKernelPackages/model.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

1 : olson 1.1
2 :     ## _*_ Perl _*_ ##
3 :     #
4 :     # model.pm
5 :     #
6 :     # Kevin Formsma
7 :     # Hope College
8 :     # Created: 6/1/2006
9 :     #
10 :     ##################
11 :    
12 :     ### BrainStorm/Planning ###
13 :     #
14 :     # Functions
15 :     # -Scenario access methods for subsystem
16 :     # -Access current genome models
17 :     # -Interface to/Integration of find_reaction_paths.cgi
18 :     # -Scenario Relationships:
19 :     # 1. Automanaged - map togather based on starting/ending compounds
20 :     # 2. User Defined - through some type of map or XML
21 :     # -Generate files for Scenarios on a organism
22 :     # 1. Path Picking - All or Select?
23 :     # -Filter written Scenarios based on Relationships
24 :     # -Report valid Scenarios for a genome
25 :     #
26 :     #
27 :     # Basic Process for a Control Script
28 :     # 1. Input Genomes for model creation and Subsystems
29 :     # 2. Define selected Scenario relationships
30 :     # 3. Create Scenario Paths for each genome and subsystem
31 :     # 4. Filter invalid Scenarios based on relationships
32 :     # 5. Combine Subsystem models for each genome into genome models
33 :     # 6. Report on the model results for each genome
34 :     #
35 :    
36 :     package model;
37 :    
38 :     use strict;
39 : formsma 1.14 use Scenario;
40 : olson 1.1 use FIG;
41 :     use Subsystem;
42 :     use File::Path;
43 :    
44 :     our $fig= new FIG;
45 :    
46 :    
47 :     #global variables that make process_paths work
48 :     #These need to be cleared and reloaded frequently for process path and flux writing
49 :     my (%reactions_to_substrate_arrays, %reactions_to_product_arrays, %all_compounds_to_main);
50 :     my %all_reactions;
51 :     my %scenario_cycles;
52 :     my @all_outputs_lists;
53 :     my %all_inputs;
54 :     my %all_outputs;
55 :    
56 : dejongh 1.12 #this variable is used to set the loop count for single scenario and then assembly runs, 100/25 by default.
57 : olson 1.1 my $loop_max = 100;
58 :     my $loop_max_assembly = 25;
59 :    
60 :     #These store what supersets/Subsystems we are using
61 :     my %superset_to_ss;
62 :     my %ss_to_superset;
63 :    
64 :     #Flip this bit to enable debugging
65 : olson 1.11 my $debug = int($ENV{HOPE_DEBUG});
66 :    
67 :     sub set_fig
68 :     {
69 :     my($newfig) = @_;
70 :     $fig = $newfig;
71 :     }
72 : olson 1.1
73 :     sub new {
74 :     my $type = shift;
75 :     my $self = {};
76 :     return bless $self, $type;
77 :     }
78 :    
79 :    
80 :    
81 :     sub get_ss_scenarios
82 :     {
83 :     my ($ss_name) = @_;
84 :     # This is the scenario data structure storage
85 :     # %scenario_data{scenario_name}
86 :     #
87 :     my %scenario_data;
88 :    
89 :     my $subsystem = $fig->get_subsystem($ss_name);
90 : olson 1.11 if (!$subsystem)
91 :     {
92 :     warn "Cannot open subsystem $subsystem\n";
93 :     return;
94 :     }
95 :    
96 : olson 1.1 my @scenario_names = $subsystem->get_hope_scenario_names;
97 :     foreach my $name (@scenario_names)
98 :     {
99 :     $scenario_data{$name} = &get_scenario($subsystem,$name);
100 :     }
101 :    
102 :     return \%scenario_data;
103 :     }
104 :    
105 :    
106 :     sub get_scenario
107 :     {
108 :     my($subsystem,$name) = @_;
109 :    
110 :     my %data;
111 :    
112 :     my @inputs = @{$subsystem->get_hope_input_compounds($name)};
113 :     my @outputs = @{$subsystem->get_hope_output_compounds($name)};
114 :     my @map_ids = @{$subsystem->get_hope_map_ids($name)};
115 :     my @additional_reactions = @{$subsystem->get_hope_additional_reactions($name)};
116 :     my @ignore_reactions = @{$subsystem->get_hope_ignore_reactions($name)};
117 :    
118 :     $data{inputs} = \@inputs;
119 :     $data{outputs} = \@outputs;
120 :     $data{map_ids} = \@map_ids;
121 :     $data{additional_reactions} = \@additional_reactions;
122 :     $data{ignore_reactions} = \@ignore_reactions;
123 :    
124 :     return \%data;
125 :    
126 :     }
127 :    
128 :     sub process_init
129 :     {
130 :     my ($ss_name,$scenario_name,$genome,$assembly) = @_;
131 :     my (%sc_inputs, %sc_outputs);
132 :    
133 :     if ($genome eq "")
134 :     {
135 :     $genome = "All";
136 :     }
137 :     print STDERR "\nSubsystem : ".$ss_name." Scenario: $scenario_name \n" if $debug;
138 :     my $subsystem = $fig->get_subsystem($ss_name);
139 :     my $scenario_data = &get_scenario($subsystem,$scenario_name);
140 : dejongh 1.4
141 : olson 1.1 #load the other arrays
142 :     my %ss_reactions;
143 :    
144 : dejongh 1.4 if ($genome eq "All")
145 : olson 1.1 {
146 : dejongh 1.4 my %all_reactions = %{$subsystem->get_hope_reactions};
147 :     foreach my $role (keys %all_reactions)
148 : olson 1.1 {
149 : dejongh 1.4 map { $ss_reactions{$_} = 1 } @{$all_reactions{$role}};
150 : olson 1.1 }
151 :     }
152 : dejongh 1.4 else
153 : olson 1.1 {
154 : dejongh 1.4 my $reactions_for_genome = $subsystem->get_hope_reactions_for_genome($genome);
155 : dejongh 1.7 map { $ss_reactions{$_} = 1 } keys %{$reactions_for_genome} if defined $reactions_for_genome;
156 : olson 1.1 }
157 : dejongh 1.4
158 : olson 1.1 map { $sc_inputs{$_} = 1 } @{$scenario_data->{inputs}};
159 :    
160 :     foreach my $list (@{$scenario_data->{outputs}})
161 :     {
162 :     map { $sc_outputs{$_} = 1 } @$list;
163 :     push @all_outputs_lists, $list;
164 :     }
165 :    
166 :     map { $scenario_cycles{$_} = 1 if defined $sc_outputs{$_} } keys %sc_inputs;
167 :     map { $all_inputs{$_} = 1 } keys %sc_inputs;
168 :     map { $all_outputs{$_} = 1 } keys %sc_outputs;
169 :    
170 :     my @hope_additional_reactions = @{$scenario_data->{additional_reactions}};
171 :     my @hope_ignore_reactions = @{$scenario_data->{ignore_reactions}};
172 :     my %sc_reactions;
173 :     map { $sc_reactions{$_} = 1 } keys %ss_reactions;
174 :    
175 :     # flag additional reactions so we won't check if they are in a map
176 :     foreach my $rid (@hope_additional_reactions)
177 :     {
178 :     $sc_reactions{$rid} = 2;
179 :     }
180 :    
181 :     foreach my $rid (@hope_ignore_reactions)
182 :     {
183 :     delete $sc_reactions{$rid};
184 :     }
185 :    
186 :     #for now we do this outside of the if statment, but that might need to change
187 :     &load_substrate_and_product_arrays(\%sc_reactions,$scenario_data->{map_ids});
188 :    
189 :    
190 :    
191 :    
192 :     }
193 :    
194 :     sub execute_paths
195 :     {
196 :     my ($assembly_paths,$find_first,$input_path, $output_path) = @_;
197 :    
198 :     my $num_paths = scalar @{$assembly_paths};
199 :    
200 :     my (%substrates_to_reactions, %products_to_reactions,
201 :     %reactions_to_substrates, %reactions_to_products);
202 :    
203 :     if($num_paths ==0 ) #Load the reactions normally if we are creating scenarios
204 :     {
205 :     create_reactions(\%substrates_to_reactions,\%products_to_reactions,
206 :     \%reactions_to_substrates,
207 :     \%reactions_to_products);
208 :     }
209 :     #create assembly reactions that are closed 'paths' from scenarios or assemblies
210 :     if($num_paths > 0)
211 :     {
212 :     create_assembly_reactions(\%substrates_to_reactions,\%products_to_reactions,
213 :     \%reactions_to_substrates,
214 :     \%reactions_to_products,$assembly_paths);
215 :     }
216 :    
217 :     #This deals with user specifed input/output paths, and uses these to generate
218 :     #what our input and output compounds should be for an assembly.
219 :     #This is only used for creating assemblies, has no effect on scenario creation
220 :    
221 :     if(scalar @{$input_path} && scalar @{$output_path})
222 :     {
223 :    
224 :     %all_inputs = ();
225 :     %all_outputs = ();
226 :     #we should have loaded these paths above, so lets just pull out the information we need
227 :     foreach my $path (@$input_path)
228 :     {
229 :     my $input_rxn = "$path->[-3]/$path->[-2]/$path->[-1]_R";
230 :     my @user_in = @{$reactions_to_substrates{$input_rxn}};
231 :     map{ $all_inputs{$_} = 1 } @user_in;
232 :     }
233 :     foreach my $path (@$output_path)
234 :     {
235 :     my $output_rxn = "$path->[-3]/$path->[-2]/$path->[-1]_R";
236 :     my @user_out = @{$reactions_to_products{$output_rxn}};
237 :     map{ $all_outputs{$_} = 1 } @user_out;
238 :     }
239 :     #map { $scenario_cycles{$_} = 1 if defined $all_outputs{$_} } keys %all_inputs;
240 :     }
241 :    
242 :     print STDERR "Inputs :\n" if $debug;
243 : olson 1.2 print STDERR map { $_."\n" } keys %all_inputs if $debug;
244 : olson 1.1 print STDERR "Outputs:\n" if $debug;
245 : olson 1.2 print STDERR map { $_."\n" } keys %all_outputs if $debug;
246 : olson 1.1
247 :     #filter the input/outputs lists, removing the intersection unless something
248 :     # is a known cycle
249 :     foreach my $input (keys %all_inputs)
250 :     {
251 :     if(defined $all_outputs{$input} && ! defined $scenario_cycles{$input})
252 :     {
253 :     print STDERR "Deleting $input from input and output lists\n" if $debug;
254 :     delete $all_inputs{$input};
255 :     delete $all_outputs{$input};
256 :     }
257 :     }
258 :    
259 :     my $create_assembly = 0;
260 :     $create_assembly = 1 if(scalar @{$assembly_paths} !=0);
261 :     return process_paths(\%all_inputs, \%all_outputs, \@all_outputs_lists,
262 :     \%reactions_to_substrates, \%reactions_to_products,
263 :     \%substrates_to_reactions,\%products_to_reactions,$create_assembly,$find_first);
264 :     }
265 :    
266 :    
267 :     sub create_reactions
268 :     {
269 :     my ($substrates_to_reactions, $products_to_reactions,
270 :     $reactions_to_substrates, $reactions_to_products) = @_;
271 : olson 1.2 print STDERR "building SS reactions\n" if $debug;
272 : olson 1.1 # use subsystem reactions
273 :     foreach my $drxn (map { ($_."_L", $_."_R") } keys %all_reactions)
274 :     {
275 :     foreach my $substrArr ($reactions_to_substrate_arrays{$drxn})
276 :     {
277 :     foreach my $cinfo (@$substrArr)
278 :     {
279 :     my $cpd = $cinfo->[0];
280 :     my $main = $cinfo->[2] || defined $all_inputs{$cpd}; # main in this reaction
281 :    
282 :     if ($main)
283 :     {
284 :     push(@{$reactions_to_substrates->{$drxn}}, $cpd);
285 :     push(@{$substrates_to_reactions->{$cpd}}, $drxn);
286 :     }
287 :     }
288 :     }
289 :    
290 :     foreach my $prodArr ($reactions_to_product_arrays{$drxn})
291 :     {
292 :     foreach my $cinfo (@$prodArr)
293 :     {
294 :     my $cpd = $cinfo->[0];
295 :     my $main = $cinfo->[2] || defined $all_outputs{$cpd}; # main in this reaction
296 :    
297 :     if ($main)
298 :     {
299 :     push(@{$reactions_to_products->{$drxn}}, $cpd);
300 :     push(@{$products_to_reactions->{$cpd}}, $drxn);
301 :     }
302 :     }
303 :     }
304 :     }
305 :     }
306 :    
307 :     sub create_assembly_reactions
308 :     {
309 :     my ($substrates_to_reactions, $products_to_reactions,
310 :     $reactions_to_substrates, $reactions_to_products,$assembly_paths) = @_;
311 :     my %intersection;
312 :    
313 :     foreach my $path (@$assembly_paths)
314 :     {
315 : olson 1.13 my $paths_dir = $fig->model_directory() . "/" . join "/" , @$path;
316 : olson 1.1
317 :     my $drxn = "$path->[-3]/$path->[-2]/$path->[-1]_R";
318 :    
319 :     $all_reactions{"$path->[-3]/$path->[-2]/$path->[-1]"} = "R";
320 :    
321 :     print STDERR "Making reaction: $drxn\n" if $debug;
322 :    
323 :     open (M_INPUTS , $paths_dir."/inputs") or die ("Failed to open $paths_dir"."/inputs");
324 :     my @substrArr;
325 :    
326 :     print STDERR "Gathering Inputs:\n" if $debug;
327 :    
328 :     while (<M_INPUTS>)
329 :     {
330 :     my ($cpd, $stoich) = split "\t" , $_;
331 :    
332 :     #We are going to assume everything is a main...
333 :     if(!defined $all_compounds_to_main{$cpd})
334 :     {
335 :     $all_compounds_to_main{$cpd} = 1;
336 :     }
337 :    
338 :     if ($all_compounds_to_main{$cpd})
339 :     {
340 :     push(@{$reactions_to_substrates->{$drxn}}, $cpd);
341 :     push(@{$substrates_to_reactions->{$cpd}}, $drxn);
342 :     }
343 :    
344 :     if($all_compounds_to_main{$cpd} !=0 || !defined $all_compounds_to_main{$cpd})
345 :     {
346 :     $all_inputs{$cpd} = 1;
347 :     }
348 :     push @substrArr, [$cpd, $stoich, $all_compounds_to_main{$cpd}];
349 :    
350 :     my @names = $fig->names_of_compound($cpd);
351 :     print STDERR "\t$stoich\t$cpd\t$names[0]\t$all_compounds_to_main{$cpd}\n" if $debug;
352 :     }
353 :    
354 :     $reactions_to_substrate_arrays{$drxn} = \@substrArr;
355 :    
356 :     close M_INPUTS;
357 :    
358 :     open (M_OUTPUTS, $paths_dir."/outputs") or die("Failed to open $paths_dir"."/outputs");
359 :     my @prodArr;
360 :    
361 :     print STDERR "Gathering outputs:\n" if $debug;
362 :    
363 :     while (<M_OUTPUTS>)
364 :     {
365 :     my ($cpd, $stoich) = split "\t", $_;
366 :     print STDERR "Found $stoich $cpd\n" if $debug;
367 :    
368 :     #We are going to assume everything is a main...
369 :     if(!defined $all_compounds_to_main{$cpd})
370 :     {
371 :     $all_compounds_to_main{$cpd} = 1;
372 :     }
373 :    
374 :     if ($all_compounds_to_main{$cpd})
375 :     {
376 :     push(@{$reactions_to_products->{$drxn}}, $cpd);
377 :     push(@{$products_to_reactions->{$cpd}}, $drxn);
378 :     }
379 :    
380 :    
381 :     #This adds cycles from 'assemblys' because they weren't added earlier
382 :     foreach my $ele (@{$reactions_to_substrates->{$drxn}})
383 :     {
384 :     if($ele eq $cpd)
385 :     {
386 :     $scenario_cycles{$cpd} = 1;
387 :     }
388 :     }
389 :    
390 :     if($all_compounds_to_main{$cpd} !=0 || !defined $all_compounds_to_main{$cpd})
391 :     {
392 :     $all_outputs{$cpd} = 1;
393 :     }
394 :     push @prodArr, [$cpd,$stoich,$all_compounds_to_main{$cpd}];
395 :     my @names = $fig->names_of_compound($cpd);
396 :     print STDERR "\t$cpd\t$names[0]\t$all_compounds_to_main{$cpd}\n" if $debug;
397 :     }
398 :    
399 :     $reactions_to_product_arrays{$drxn} = \@prodArr;
400 :    
401 :     close M_OUTPUTS;
402 :    
403 :     }
404 :     }
405 :    
406 :    
407 :     sub load_substrate_and_product_arrays
408 :     {
409 :     my ($reactions, $map_ids) = @_;
410 :    
411 :     # determine whether the reaction is in one of the maps, and get directionality accordingly
412 :     my (%reactions_in_maps, %reactions_not_in_maps);
413 :    
414 :     foreach my $rxn (keys %$reactions)
415 :     {
416 :     my $direction;
417 :    
418 :     if($fig->valid_reaction_id($rxn))
419 :     {
420 :     # get an array of triplets. The triplets are [reaction id][map id]
421 :     # [left to right - R, right to left - L, or both - B]
422 :     my @triplets = $fig->reaction_direction($rxn);
423 :    
424 :     foreach my $trip (@triplets)
425 :     {
426 :     foreach my $map_id (@$map_ids)
427 :     {
428 :     if (@{$trip}[1] eq $map_id)
429 :     {
430 :     my $this_direction = @{$trip}[2];
431 :    
432 :     # bidirectional in one map overrules unidirectional in another.
433 :     # opposite directions in two maps becomes bidirectional
434 :     if (! defined $direction)
435 :     {
436 :     $direction = $this_direction;
437 :     }
438 :     elsif ($direction ne "B" && ($this_direction eq "B" ||
439 :     $this_direction ne $direction))
440 :     {
441 :     $direction = "B";
442 :     }
443 :    
444 :     $reactions_in_maps{$rxn} = 1;
445 :     }
446 :     }
447 :     }
448 :    
449 :    
450 :     if(! $reactions_in_maps{$rxn})
451 :     {
452 :     my $found_in_other_map = 0;
453 :    
454 :     #reaction not in scenario map ids, try to get directionality from other maps
455 :     foreach my $trip (@triplets)
456 :     {
457 :     my $this_direction = @{$trip}[2];
458 :    
459 :     #bidreactional in one map overrules unidirectional in another
460 :     #opposite directions in two maps becomes bidirectional
461 :     if(! defined $direction)
462 :     {
463 :     $direction = $this_direction;
464 :     }
465 :     elsif($direction ne "B" && ($this_direction eq "B" || $this_direction ne $direction))
466 :     {
467 :     $direction = "B";
468 :     }
469 :    
470 :     $found_in_other_map = 1;
471 :     }
472 :     if (!$found_in_other_map)
473 :     {
474 :     # reaction not in map, get directionality without reference to map
475 :     if($fig->reversible($rxn) eq "1")
476 :     {
477 :     $direction = "B";
478 :     }
479 :     else
480 :     {
481 :     $direction = "R";
482 :     }
483 :     }
484 :     }
485 :    
486 :     if (! defined $all_reactions{$rxn} || $direction eq "B")
487 :     {
488 :     $all_reactions{$rxn} = $direction;
489 :     }
490 :     elsif ($all_reactions{$rxn} ne $direction)
491 :     {
492 :     $all_reactions{$rxn} = "B";
493 :     }
494 :    
495 :     my (@substrArr, @prodArr);
496 :    
497 :     if ($direction eq "L")
498 :     {
499 :     @substrArr = $fig->reaction2comp($rxn, 1, $map_ids);
500 :     @prodArr = $fig->reaction2comp($rxn, 0, $map_ids);
501 :     $reactions_to_substrate_arrays{$rxn . "_L"} = \@substrArr;
502 :     $reactions_to_product_arrays{$rxn . "_L"} = \@prodArr;
503 :    
504 :     }
505 :     else
506 :     {
507 :     if ($reactions_in_maps{$rxn})
508 :     {
509 :     @substrArr = $fig->reaction2comp($rxn, 0, $map_ids);
510 :     @prodArr = $fig->reaction2comp($rxn, 1, $map_ids);
511 :     }
512 :     else
513 :     {
514 :     @substrArr = $fig->reaction2comp($rxn, 0);
515 :     @prodArr = $fig->reaction2comp($rxn, 1);
516 :     }
517 :    
518 :     $reactions_to_substrate_arrays{$rxn."_R"} = \@substrArr;
519 :     $reactions_to_product_arrays{$rxn."_R"} = \@prodArr;
520 :    
521 :     if ($direction eq "B")
522 :     {
523 :     $reactions_to_substrate_arrays{$rxn."_L"} = \@prodArr;
524 :     $reactions_to_product_arrays{$rxn."_L"} = \@substrArr;
525 :     }
526 :     }
527 :    
528 :     print STDERR "\nFor $rxn, found substrates:\n" unless !$debug;
529 :     map { print STDERR "\t$_->[0]\t$_->[1]\t$_->[2]\n" unless !$debug } @substrArr;
530 :     print STDERR "For $rxn, found products:\n" unless !$debug;
531 :     map { print STDERR "\t$_->[0]\t$_->[1]\t$_->[2]\n" unless !$debug } @prodArr;
532 :    
533 :     # load "main" designation based on reactions that are in the maps
534 :     if ($reactions_in_maps{$rxn})
535 :     {
536 :     foreach my $cinfo ((@substrArr, @prodArr))
537 :     {
538 :     my $cpd = $cinfo->[0];
539 :     my $main = $cinfo->[2];
540 :    
541 :     if (defined $all_compounds_to_main{$cpd})
542 :     {
543 :     # only main if it's main in all reactions
544 :     $all_compounds_to_main{$cpd} &= $main;
545 :     }
546 :     else
547 :     {
548 :     $all_compounds_to_main{$cpd} = $main;
549 :     }
550 :     }
551 :     }
552 :     else
553 :     {
554 :     # save subs and prods for processing at end
555 :     $reactions_not_in_maps{$rxn} = [ (@substrArr, @prodArr) ];
556 :     }
557 :     }
558 :     }
559 :    
560 :     # now load "main" designation based on reactions not in the maps - but don't overrule
561 :     # what's already been loaded
562 :     my %additional_compounds_to_main;
563 :    
564 :     foreach my $rxn (keys %reactions_not_in_maps)
565 :     {
566 :     foreach my $cinfo (@{$reactions_not_in_maps{$rxn}})
567 :     {
568 :     my $cpd = $cinfo->[0];
569 :     my $main = $cinfo->[2];
570 :    
571 :     if (defined $additional_compounds_to_main{$cpd})
572 :     {
573 :     # main if it's main in any reactions not in map
574 :     $additional_compounds_to_main{$cpd} |= $main;
575 :     }
576 :     else
577 :     {
578 :     $additional_compounds_to_main{$cpd} = $main;
579 :     }
580 :     }
581 :     }
582 :    
583 :     foreach my $cpd (keys %additional_compounds_to_main)
584 :     {
585 :     if (! defined $all_compounds_to_main{$cpd})
586 :     {
587 :     $all_compounds_to_main{$cpd} = $additional_compounds_to_main{$cpd};
588 :     }
589 :     }
590 :     }
591 :    
592 :     sub process_paths
593 :     {
594 :     my ($input_cpds, $output_cpds, $outputs_lists, $reactions_to_substrates, $reactions_to_products, $substrates_to_reactions, $products_to_reactions, $create_assembly, $find_first ) = @_;
595 :    
596 :     my (%path_inputs, %path_outputs);
597 :     map { $path_inputs{$_} = 0 } keys %$input_cpds;
598 :     map { $path_outputs{$_} = 0 } keys %$output_cpds;
599 :    
600 :     my %data_results = ("infinite" => 0);
601 :    
602 :     # %compounds_to_tokens maps from compound ids to tokens placed on those compounds
603 :     # the tokens are organized in hashes mapping from token id to number of tokens with that id
604 :     my %compounds_to_tokens;
605 :     map { $compounds_to_tokens{$_} = {} } keys %all_compounds_to_main;
606 :    
607 :     # %tokens maps from token_ids to the token data structures
608 :     my %tokens;
609 :     my $token_id_counter = 1;
610 :    
611 :     # %compounds_borrowed_to_tokens maps from compounds to lists of token ids that borrowed
612 :     # compound in order to run a reaction
613 :     my %compounds_borrowed_to_tokens;
614 :    
615 :     print STDERR "\nIn process_paths, path_inputs are @{[ keys %path_inputs ]}, path_outputs are @{[ keys %path_outputs] }, scenario_cycles are @{[ keys %scenario_cycles ]} \n\n" unless !$debug;
616 :    
617 :     my $initial_pass = 1;
618 :     my $done = 0;
619 :     my $loop_counter = 1;
620 :     my $infinite_loop_check = $create_assembly ? $loop_max_assembly : $loop_max;
621 :    
622 :     # we may get to the point where we need to add some more path inputs into the mix
623 :     # to push stalled tokens
624 :     my $add_path_inputs = 0;
625 :    
626 :     while(!$done)
627 :     {
628 :     if ($initial_pass || $add_path_inputs)
629 :     {
630 :     foreach my $cpd (keys %path_inputs)
631 :     {
632 :     # place a token on each path input
633 :     my $new_token_id = $token_id_counter++;
634 :     my %new_token;
635 :     $new_token{visited_reactions} = {};
636 :     $new_token{visited_compounds} = { $cpd => 0 }; # 0 means supplied from "outside"
637 :     $new_token{token_path_inputs} = { $cpd => 1 }; # 1 means one was supplied
638 :     $new_token{initial_pass} = $initial_pass;
639 :     $compounds_to_tokens{$cpd}->{$new_token_id}++;
640 :     $tokens{$new_token_id} = \%new_token;
641 :    
642 :     print STDERR "\t\tCreated new token '$new_token_id' for path input $cpd\n" unless !$debug;
643 :     }
644 :    
645 :     $initial_pass = 0;
646 :     $add_path_inputs = 0;
647 :     }
648 :    
649 :     # Find the reactions that can run.
650 :     my %reactions_to_try;
651 :    
652 :     foreach my $cpd (keys %compounds_to_tokens)
653 :     {
654 :     foreach my $token_id (keys %{$compounds_to_tokens{$cpd}})
655 :     {
656 :     if ($compounds_to_tokens{$cpd}->{$token_id} > 0 &&
657 :     ! $tokens{$token_id}->{done})
658 :     {
659 :     # this compound has tokens that aren't done
660 :     map { $reactions_to_try{$_} = 1 } @{$substrates_to_reactions->{$cpd}};
661 :     last;
662 :     }
663 :     }
664 :     }
665 :    
666 :     print STDERR "\n\tIn loop, trying reactions @{[keys %reactions_to_try]}\n\n" unless !$debug;
667 :    
668 :     # Map the reactions that can run to the tokens they can use
669 :     my %reactions_to_tokens_available;
670 :     # Keep track of the main substrates defined by each reaction
671 :     my %reactions_to_main_substrates;
672 :    
673 :     # count up the total number of tokens needed for each compound to run
674 :     # every reaction that is ready to go
675 :     my %reactions_to_tokens_needed;
676 :    
677 :     rxn: foreach my $reaction (keys %reactions_to_try)
678 :     {
679 :     print STDERR "\tChecking reaction $reaction\n" unless !$debug;
680 :    
681 :     my @substrArr = @{$reactions_to_substrate_arrays{$reaction}};
682 :     my @prodArr = @{$reactions_to_product_arrays{$reaction}};
683 :     my %main_substrates;
684 :    
685 :     # Determine if this reaction has necessary inputs to run.
686 :     # There must be tokens available for at least one main substrate that isn't
687 :     # a path output (unless it's an initial scenario cycled compound).
688 :     # Also, any path input must have a token.
689 :     # Count number of tokens needed for each main substrate.
690 :     my %tokens_available;
691 :     my %tokens_needed;
692 :     my $reaction_can_run = 0;
693 :    
694 :     foreach my $substr (@substrArr)
695 :     {
696 :     my $cpd = @{$substr}[0];
697 :     my $stoich = @{$substr}[1];
698 :     my $main = @{$substr}[2] || @all_compounds_to_main{$cpd}; #main either way
699 :     $main_substrates{$cpd} = 1 if $main;
700 :    
701 :     print STDERR "\t\tSubstrate: $cpd\tstoich: $stoich\tmain: $main\n" unless !$debug;
702 :    
703 :     if (! $main)
704 :     {
705 :     # on any pass we can take in non-main compounds
706 :     $tokens_needed{$cpd} = $stoich;
707 :     }
708 :     else
709 :     {
710 :     # if tokens are available for compound, check their history for the
711 :     # main compounds produced by the reaction so we don't loop back over
712 :     # previous main compounds. Also, don't use tokens on scenario inputs
713 :     # moved to in steps other than initial token creation.
714 :     my %ok_tokens;
715 :     my $num_ok_tokens = 0;
716 :    
717 :     foreach my $token_id (keys %{$compounds_to_tokens{$cpd}})
718 :     {
719 :     next if $tokens{$token_id}->{done} ||
720 :     $compounds_to_tokens{$cpd}->{$token_id} == 0;
721 :    
722 :     # now check that we aren't running an already visited reaction in reverse
723 :     my %visited_reactions = %{$tokens{$token_id}->{visited_reactions}};
724 :    
725 :     if (($reaction =~ /(.*)_R/ && defined $visited_reactions{$1."_L"}) ||
726 :     ($reaction =~ /(.*)_L/ && defined $visited_reactions{$1."_R"}))
727 :     {
728 :     print STDERR "\t\tToken '$token_id' has run the reverse reaction already\n" unless !$debug;
729 :     next;
730 :     }
731 :    
732 :     my %visited_compounds = %{$tokens{$token_id}->{visited_compounds}};
733 :    
734 :     print STDERR "\t\tToken '$token_id' has visited @{[map { ($_, $visited_compounds{$_} ) } sort { $visited_compounds{$a} <=> $visited_compounds{$b} } keys %visited_compounds]}\n" unless !$debug;
735 :    
736 :     # need to find at least one prod that hasn't been visited yet
737 :     # or was visited in a loop cycle not before the loop cycle in which
738 :     # it visited the substrate,
739 :     # or is a path output
740 :     my $prods_are_ok = 0;
741 :    
742 :     # check each main product
743 :     foreach my $prod (@{$reactions_to_products->{$reaction}})
744 :     {
745 :     if (! defined $visited_compounds{$prod} ||
746 :     $visited_compounds{$prod} >= $visited_compounds{$cpd} ||
747 :     defined $path_outputs{$prod} ||
748 :     $compounds_borrowed_to_tokens{$prod}->{$token_id} > 0)
749 :     {
750 :     print STDERR "\t\tToken can visit $prod\n" unless !$debug;
751 :     $prods_are_ok = 1;
752 :     last;
753 :     }
754 :     }
755 :    
756 :     if ($prods_are_ok)
757 :     {
758 :     print STDERR "\t\tToken is OK\n" unless !$debug;
759 :     $ok_tokens{$token_id} = $compounds_to_tokens{$cpd}->{$token_id};
760 :     $num_ok_tokens += $compounds_to_tokens{$cpd}->{$token_id};
761 :     }
762 :     }
763 :    
764 :     map { $tokens_available{$_}->{$cpd} = $ok_tokens{$_} } keys %ok_tokens;
765 :     $tokens_needed{$cpd} = $stoich;
766 :    
767 :     if ($main && $num_ok_tokens >= 1)
768 :     {
769 :     if (! defined $path_outputs{$cpd} || defined $scenario_cycles{$cpd})
770 :     {
771 :     print STDERR "\t\tgot at least one token on main compound\n" unless !$debug;
772 :     $reaction_can_run = 1;
773 :     }
774 :     }
775 :     elsif (defined $path_inputs{$cpd})
776 :     {
777 :     print STDERR "\t\tno tokens available for path input: $cpd\n" unless !$debug;
778 :     next rxn;
779 :     }
780 :     elsif (defined $path_outputs{$cpd} && ! defined $scenario_cycles{$cpd})
781 :     {
782 :     print STDERR "\t\tno tokens available for path output: $cpd\n" unless !$debug;
783 :     next rxn;
784 :     }
785 :     }
786 :     }
787 :    
788 :     if ($reaction_can_run)
789 :     {
790 :     $reactions_to_tokens_available{$reaction} = \%tokens_available;
791 :     $reactions_to_tokens_needed{$reaction} = \%tokens_needed;
792 :     $reactions_to_main_substrates{$reaction} = \%main_substrates;
793 :     print STDERR "\tReaction $reaction can run\n" unless !$debug;
794 :     }
795 :     }
796 :    
797 :     # keep track of tokens used that will be used to run rxns. Clone tokens if necessary.
798 :     my %reactions_to_tokens_to_use;
799 :     my %tokens_to_use_to_reactions;
800 :     my %copy_of_compounds_to_tokens; # for determining which reaction uses which tokens
801 :    
802 :     foreach my $cpd (keys %compounds_to_tokens)
803 :     {
804 :     my %cpd_token_ids = %{$compounds_to_tokens{$cpd}};
805 :     my %new_cpd_token_ids;
806 :     map { $new_cpd_token_ids{$_} = $cpd_token_ids{$_} } keys %cpd_token_ids;
807 :     $copy_of_compounds_to_tokens{$cpd} = \%new_cpd_token_ids;
808 :     }
809 :    
810 :     foreach my $reaction (keys %reactions_to_tokens_available)
811 :     {
812 :     print STDERR "\tPreparing to run reaction $reaction\n" unless !$debug;
813 :    
814 :     # assemble tokens to run reaction, cloning ones that were used by
815 :     # other reactions during this cycle if necessary
816 :     my %tokens_available = %{$reactions_to_tokens_available{$reaction}};
817 :     my %tokens_needed = %{$reactions_to_tokens_needed{$reaction}};
818 :     my @final_tokens_to_use; # list of maps from substrates to tokens to use
819 :     my %clone_history; # map from token ids to ids of their new clones
820 :    
821 :     # check to see if any available tokens are already commited to the reverse reaction
822 :     my @token_ids = keys %tokens_available;
823 :    
824 :     foreach my $token_id (keys %tokens_available)
825 :     {
826 :     if (($reaction =~ /(.*)_R/ && defined $tokens_to_use_to_reactions{$token_id}->{$1."_L"}) ||
827 :     ($reaction =~ /(.*)_L/ && defined $tokens_to_use_to_reactions{$token_id}->{$1."_R"}))
828 :     {
829 :     # clone the token
830 :     my $new_token_id = $token_id_counter++;
831 :     &clone_token($token_id, $new_token_id, \%tokens, \%compounds_to_tokens,
832 :     \%compounds_borrowed_to_tokens);
833 :    
834 :     foreach my $icpd (keys %compounds_to_tokens)
835 :     {
836 :     if ($compounds_to_tokens{$icpd}->{$token_id} > 0)
837 :     {
838 :     $copy_of_compounds_to_tokens{$icpd}->{$new_token_id} =
839 :     $compounds_to_tokens{$icpd}->{$token_id};
840 :     }
841 :     }
842 :    
843 :     print STDERR "\t\tCloned token '$token_id', new token is '$new_token_id'\n" unless !$debug;
844 :    
845 :     $tokens_available{$new_token_id} = $tokens_available{$token_id};
846 :     delete $tokens_available{$token_id};
847 :     }
848 :     }
849 :    
850 :     # first, assemble tokens that have all the main compounds they need to run
851 :     @token_ids = keys %tokens_available;
852 :    
853 :     foreach my $token_id (keys %tokens_available)
854 :     {
855 :     my $has_all_main_cpds = 1;
856 :     my $need_to_clone = 0;
857 :    
858 :     foreach my $cpd (keys %tokens_needed)
859 :     {
860 :     if ($reactions_to_main_substrates{$reaction}->{$cpd})
861 :     {
862 :     if ($compounds_to_tokens{$cpd}->{$token_id} >= $tokens_needed{$cpd})
863 :     {
864 :     if ($copy_of_compounds_to_tokens{$cpd}->{$token_id} < $tokens_needed{$cpd})
865 :     {
866 :     $need_to_clone = 1;
867 :     }
868 :     }
869 :     else
870 :     {
871 :     $has_all_main_cpds = 0;
872 :     last;
873 :     }
874 :     }
875 :     }
876 :    
877 :     if ($has_all_main_cpds)
878 :     {
879 :     print STDERR "\t\ttoken '$token_id' has all main compounds\n" unless !$debug;
880 :    
881 :     delete $tokens_available{$token_id};
882 :    
883 :     if ($need_to_clone)
884 :     {
885 :     my $new_token_id = $token_id_counter++;
886 :     &clone_token($token_id, $new_token_id, \%tokens,
887 :     \%compounds_to_tokens,
888 :     \%compounds_borrowed_to_tokens);
889 :    
890 :     foreach my $icpd (keys %compounds_to_tokens)
891 :     {
892 :     if ($compounds_to_tokens{$icpd}->{$token_id} > 0)
893 :     {
894 :     $copy_of_compounds_to_tokens{$icpd}->{$new_token_id} =
895 :     $compounds_to_tokens{$icpd}->{$token_id};
896 :     }
897 :     }
898 :    
899 :     print STDERR "\t\tCloned token '$token_id', new token is '$new_token_id'\n" unless !$debug;
900 :    
901 :     $clone_history{$token_id} = $new_token_id;
902 :     $token_id = $new_token_id;
903 :     }
904 :    
905 :     # now assemble the compound to tokens map
906 :     my %cpd_to_tokens;
907 :    
908 :     foreach my $cpd (keys %tokens_needed)
909 :     {
910 :     if ($reactions_to_main_substrates{$reaction}->{$cpd})
911 :     {
912 :     for (my $i = 0; $i < $tokens_needed{$cpd}; $i++)
913 :     {
914 :     push @{$cpd_to_tokens{$cpd}}, $token_id;
915 :     $copy_of_compounds_to_tokens{$cpd}->{$token_id}--;
916 :     }
917 :     }
918 :     }
919 :    
920 :     push @final_tokens_to_use, \%cpd_to_tokens;
921 :     }
922 :     }
923 :    
924 :     if (scalar keys %tokens_available > 0)
925 :     {
926 :     # try to merge left over available tokens in all combinations that fulfill
927 :     # needed main substrates. Create map from main substrates to tokens.
928 :     my %tokens_available_for_cpds;
929 :     my %tokens_to_use_for_cpds;
930 :    
931 :     foreach my $token_id (keys %tokens_available)
932 :     {
933 :     foreach my $cpd (keys %{$tokens_available{$token_id}})
934 :     {
935 :     if ($reactions_to_main_substrates{$reaction}->{$cpd})
936 :     {
937 :     $tokens_available_for_cpds{$cpd}->{$token_id} =
938 :     $tokens_available{$token_id}->{$cpd};
939 :     }
940 :     }
941 :     }
942 :    
943 :     foreach my $cpd (keys %{$reactions_to_main_substrates{$reaction}})
944 :     {
945 :     my %available_token_ids;
946 :    
947 :     foreach my $token_id (keys %{$tokens_available_for_cpds{$cpd}})
948 :     {
949 :     my $updated_token_id = $token_id;
950 :    
951 :     # in case the token has already been cloned for another cpd in this reaction
952 :     while ($clone_history{$updated_token_id})
953 :     {
954 :     $updated_token_id = $clone_history{$updated_token_id};
955 :     }
956 :    
957 :     $available_token_ids{$updated_token_id} = 1;
958 :    
959 :     if ($token_id != $updated_token_id)
960 :     {
961 :     $tokens_available_for_cpds{$cpd}->{$updated_token_id} =
962 :     $tokens_available_for_cpds{$cpd}->{$token_id};
963 :     delete $tokens_available_for_cpds{$cpd}->{$token_id};
964 :     }
965 :     }
966 :    
967 :     my $num_tokens_needed = $tokens_needed{$cpd};
968 :     my $num_available_tokens = 0;
969 :    
970 :     foreach my $token_id (keys %available_token_ids)
971 :     {
972 :     $num_available_tokens += $tokens_available_for_cpds{$cpd}->{$token_id};
973 :     }
974 :    
975 :     # if not enough tokens are available to fill out sets, create new ones
976 :     my $num_short_of_full;
977 :    
978 :     if ($num_available_tokens == 0)
979 :     {
980 :     $num_short_of_full = $num_tokens_needed;
981 :     }
982 :     else
983 :     {
984 :     $num_short_of_full = ($num_tokens_needed - ($num_available_tokens % $num_tokens_needed)) % $num_tokens_needed;
985 :     }
986 :    
987 :     print STDERR "\t\tFor $cpd, $num_tokens_needed tokens are needed, $num_available_tokens are available. Need to create $num_short_of_full to fill out sets\n" unless !$debug;
988 :    
989 :     for (my $i = 0; $i < $num_short_of_full; $i++)
990 :     {
991 :     my $new_token_id = $token_id_counter++;
992 :     my %new_token;
993 :     print STDERR "\t\tCreating new token '$new_token_id' for $cpd\n" unless !$debug;
994 :    
995 :     $new_token{visited_reactions} = {};
996 :     $new_token{visited_compounds} = {};
997 :     $compounds_to_tokens{$cpd}->{$new_token_id}++;
998 :     $copy_of_compounds_to_tokens{$cpd}->{$new_token_id}++;
999 :     $tokens{$new_token_id} = \%new_token;
1000 :     $available_token_ids{$new_token_id} = 1;
1001 :     $tokens_available_for_cpds{$cpd}->{$new_token_id}++;
1002 :    
1003 :     # if it's not a path input, remember that we've "borrowed" it and
1004 :     # will need to pay it back.
1005 :     if (! defined $path_inputs{$cpd})
1006 :     {
1007 :     $new_token{visited_compounds}->{$cpd} = $loop_counter;
1008 :     $compounds_borrowed_to_tokens{$cpd}->{$new_token_id}++;
1009 :     }
1010 :     else
1011 :     {
1012 :     $new_token{token_path_inputs} = { $cpd => 1 };
1013 :     $new_token{visited_compounds}->{$cpd} = 0;
1014 :     }
1015 :     }
1016 :    
1017 :     # for main compounds, there may be more tokens available than needed,
1018 :     # so we may assemble multiple token sets.
1019 :     my %tokens_not_yet_used;
1020 :    
1021 :     foreach my $token_id (keys %available_token_ids)
1022 :     {
1023 :     if ($copy_of_compounds_to_tokens{$cpd}->{$token_id} > 0)
1024 :     {
1025 :     $tokens_not_yet_used{$token_id} = $tokens_available_for_cpds{$cpd}->{$token_id};
1026 :     }
1027 :     }
1028 :    
1029 :     my @token_sets_for_cpd;
1030 :    
1031 :     print STDERR "\t\tNeed $num_tokens_needed tokens for $cpd, '@{[ sort { $a <=> $b } keys %available_token_ids ]}' are usable, '@{[ sort { $a <=> $b } keys %tokens_not_yet_used ]}' are not yet used\n" unless !$debug;
1032 :    
1033 :     my @token_set;
1034 :     my $num_tokens_still_needed = $num_tokens_needed;
1035 :    
1036 :     foreach my $token_id (sort { $a <=> $b } keys %available_token_ids)
1037 :     {
1038 :     # need to clone the token if it is all used up
1039 :     if ($copy_of_compounds_to_tokens{$cpd}->{$token_id} == 0)
1040 :     {
1041 :     my $new_token_id = $token_id_counter++;
1042 :     &clone_token($token_id, $new_token_id, \%tokens,
1043 :     \%compounds_to_tokens,
1044 :     \%compounds_borrowed_to_tokens);
1045 :    
1046 :     foreach my $icpd (keys %compounds_to_tokens)
1047 :     {
1048 :     if ($compounds_to_tokens{$icpd}->{$token_id} > 0)
1049 :     {
1050 :     $copy_of_compounds_to_tokens{$icpd}->{$new_token_id} =
1051 :     $compounds_to_tokens{$icpd}->{$token_id};
1052 :     }
1053 :     }
1054 :    
1055 :     print STDERR "\t\tCloned token '$token_id' for $cpd, new token is '$new_token_id'\n" unless !$debug;
1056 :    
1057 :     $clone_history{$token_id} = $new_token_id;
1058 :     $token_id = $new_token_id;
1059 :     }
1060 :    
1061 :     while ($copy_of_compounds_to_tokens{$cpd}->{$token_id} > 0)
1062 :     {
1063 :     push @token_set, $token_id;
1064 :     $copy_of_compounds_to_tokens{$cpd}->{$token_id}--;
1065 :     $num_tokens_still_needed--;
1066 :    
1067 :     if ($num_tokens_still_needed == 0)
1068 :     {
1069 :     print STDERR "\t\tPushing token set '@token_set' for $cpd\n" unless !$debug;
1070 :     my @copy_of_token_set = @token_set;
1071 :     push @token_sets_for_cpd, \@copy_of_token_set;
1072 :     @token_set = ();
1073 :     $num_tokens_still_needed = $num_tokens_needed;
1074 :     }
1075 :     }
1076 :     }
1077 :    
1078 :     $tokens_to_use_for_cpds{$cpd} = \@token_sets_for_cpd;
1079 :     }
1080 :    
1081 :     # in case a token had to be cloned for this reaction after another
1082 :     # compound already determined to use it, check history and use new token id
1083 :     foreach my $cpd (keys %tokens_to_use_for_cpds)
1084 :     {
1085 :     foreach my $token_set (@{$tokens_to_use_for_cpds{$cpd}})
1086 :     {
1087 :     for (my $i = 0; $i < scalar @$token_set; $i++)
1088 :     {
1089 :     my $updated_token_id = $token_set->[$i];
1090 :    
1091 :     while ($clone_history{$updated_token_id})
1092 :     {
1093 :     $updated_token_id = $clone_history{$updated_token_id};
1094 :     }
1095 :    
1096 :     if ($token_set->[$i] != $updated_token_id)
1097 :     {
1098 :     print STDERR "\t\tReplacing '$token_set->[$i]' with '$updated_token_id' for $cpd\n" unless !$debug;
1099 :     splice @$token_set, $i, 1, ($updated_token_id);
1100 :     }
1101 :     }
1102 :     }
1103 :     }
1104 :    
1105 :     # we may have multiple sets of tokens to use for some compounds, so
1106 :     # make sure we're prepared for each combination by cloning sets as necessary
1107 :     my %cpd_to_token_set_index;
1108 :     my $num_combinations = 1;
1109 :     my %used_token_sets_for_cpd;
1110 :    
1111 :     foreach my $cpd (keys %tokens_to_use_for_cpds)
1112 :     {
1113 :     $cpd_to_token_set_index{$cpd} = 0;
1114 :     $num_combinations *= scalar @{$tokens_to_use_for_cpds{$cpd}};
1115 :     }
1116 :    
1117 :     for (my $i = 0; $i < $num_combinations; $i++)
1118 :     {
1119 :     my %combination_cpds_to_tokens;
1120 :    
1121 :     print STDERR "\t\tPreparing combination ", $i+1, " out of $num_combinations, indices are @{[ map { $cpd_to_token_set_index{$_} } sort keys %cpd_to_token_set_index ]}\n" unless !$debug;
1122 :    
1123 :     # keep track of who was cloned to what for this combination in case
1124 :     # different compounds are using the same tokens
1125 :     my %clone_history_this_combination;
1126 :    
1127 :     foreach my $cpd (sort keys %cpd_to_token_set_index)
1128 :     {
1129 :     my $token_set_index = $cpd_to_token_set_index{$cpd};
1130 :     my @token_set = @{$tokens_to_use_for_cpds{$cpd}->[$token_set_index]};
1131 :     my @new_token_set;
1132 :    
1133 :     # don't clone if this is the first time using this token set
1134 :     # should be able to do this mathematically
1135 :     if (! defined $used_token_sets_for_cpd{$cpd}->{$token_set_index})
1136 :     {
1137 :     @new_token_set = @token_set;
1138 :     $used_token_sets_for_cpd{$cpd}->{$token_set_index} = 1;
1139 :     }
1140 :     else
1141 :     {
1142 :     foreach my $token_id (@token_set)
1143 :     {
1144 :     my $new_token_id;
1145 :    
1146 :     if ($clone_history_this_combination{$token_id})
1147 :     {
1148 :     $new_token_id = $clone_history_this_combination{$token_id};
1149 :     }
1150 :     else
1151 :     {
1152 :     $new_token_id = $token_id_counter++;
1153 :     &clone_token($token_id, $new_token_id, \%tokens,
1154 :     \%compounds_to_tokens,
1155 :     \%compounds_borrowed_to_tokens);
1156 :    
1157 :     print STDERR "\t\t\tCloned token '$token_id' for $cpd, new token is '$new_token_id'\n" unless !$debug;
1158 :    
1159 :     $clone_history_this_combination{$token_id} = $new_token_id;
1160 :     }
1161 :    
1162 :     push @new_token_set, $new_token_id;
1163 :     }
1164 :     }
1165 :    
1166 :     push @{$combination_cpds_to_tokens{$cpd}}, @new_token_set;
1167 :     }
1168 :    
1169 :     push @final_tokens_to_use, \%combination_cpds_to_tokens;
1170 :    
1171 :     # move the cpd to token set indices for the next combination
1172 :     foreach my $cpd (sort keys %cpd_to_token_set_index)
1173 :     {
1174 :     if ($cpd_to_token_set_index{$cpd} < scalar @{$tokens_to_use_for_cpds{$cpd}} - 1)
1175 :     {
1176 :     $cpd_to_token_set_index{$cpd}++;
1177 :     last;
1178 :     }
1179 :     else
1180 :     {
1181 :     $cpd_to_token_set_index{$cpd} = 0;
1182 :     }
1183 :     }
1184 :     }
1185 :     }
1186 :    
1187 :     # last step, need to create place-holder tokens for the non-main substrates
1188 :     # and record the tokens being used for this reaction
1189 :     foreach my $combination (@final_tokens_to_use)
1190 :     {
1191 :     foreach my $cpd (keys %tokens_needed)
1192 :     {
1193 :     if (! defined $reactions_to_main_substrates{$reaction}->{$cpd})
1194 :     {
1195 :     my $new_token_id = $token_id_counter++;
1196 :     my %new_token;
1197 :     $new_token{visited_reactions} = {};
1198 :     $new_token{visited_compounds} = {};
1199 :     $compounds_to_tokens{$cpd}->{$new_token_id} += $tokens_needed{$cpd};
1200 :     $copy_of_compounds_to_tokens{$cpd}->{$new_token_id} += $tokens_needed{$cpd};
1201 :     $new_token{token_path_inputs} = { $cpd => $tokens_needed{$cpd} };
1202 :     $tokens{$new_token_id} = \%new_token;
1203 :    
1204 :     for (my $i = 0; $i < $tokens_needed{$cpd}; $i++)
1205 :     {
1206 :     push @{$combination->{$cpd}}, $new_token_id;
1207 :     }
1208 :     }
1209 :     }
1210 :    
1211 :     foreach my $cpd (keys %$combination)
1212 :     {
1213 :     map { $tokens_to_use_to_reactions{$_}->{$reaction} = 1 } @{$combination->{$cpd}};
1214 :     }
1215 :     }
1216 :    
1217 :     $reactions_to_tokens_to_use{$reaction} = \@final_tokens_to_use;
1218 :     }
1219 :    
1220 :     # keep track of tokens merged during this round
1221 :     my %token_merge_history;
1222 :    
1223 :     foreach my $reaction (keys %reactions_to_tokens_to_use)
1224 :     {
1225 :     # we may have multiple sets of tokens to use
1226 :     my @final_tokens_to_use = @{$reactions_to_tokens_to_use{$reaction}};
1227 :     my $num_combinations = scalar @final_tokens_to_use;
1228 :    
1229 :     # since we may be running this reaction several times with some of the same
1230 :     # tokens, don't process token merge history until all sets have been run
1231 :     my %token_merge_history_this_reaction;
1232 :    
1233 :     for (my $i = 0; $i < $num_combinations; $i++)
1234 :     {
1235 :     print STDERR "\tRunning reaction $reaction (", $i+1, " out of $num_combinations)\n" unless !$debug;
1236 :    
1237 :     # assemble list of tokens to use for this combination
1238 :     my %tokens_to_use;
1239 :     # find the most recently visited compound's step
1240 :     my $most_recent_step = 0;
1241 :    
1242 :     # loop through substrates
1243 :     foreach my $cpd (keys %{$reactions_to_tokens_to_use{$reaction}})
1244 :     {
1245 :     # remove the token ids from the real compounds_to_tokens map
1246 :     my @cpd_token_ids = @{$final_tokens_to_use[$i]->{$cpd}};
1247 :     print STDERR "\t\tFound tokens '@cpd_token_ids' for $cpd\n" unless !$debug;
1248 :    
1249 :     foreach my $token_id (@cpd_token_ids)
1250 :     {
1251 :     # check if token_id has been merged into a new token by a previous reaction
1252 :     while (defined $token_merge_history{$token_id})
1253 :     {
1254 :     $token_id = $token_merge_history{$token_id};
1255 :     }
1256 :    
1257 :     $compounds_to_tokens{$cpd}->{$token_id}--;
1258 :    
1259 :     if ($compounds_to_tokens{$cpd}->{$token_id} == 0)
1260 :     {
1261 :     delete $compounds_to_tokens{$cpd}->{$token_id};
1262 :     }
1263 :    
1264 :     $tokens_to_use{$token_id} = 1;
1265 :    
1266 :     if ($tokens{$token_id}->{visited_compounds}->{$cpd} > $most_recent_step)
1267 :     {
1268 :     $most_recent_step = $tokens{$token_id}->{visited_compounds}->{$cpd};
1269 :     }
1270 :     }
1271 :     }
1272 :    
1273 :     # process list of unique token ids
1274 :     my @tokens_to_use = sort { $a <=> $b } keys %tokens_to_use;
1275 :     my $go_forward_token_id;
1276 :    
1277 :     if (scalar @tokens_to_use == 1)
1278 :     {
1279 :     $go_forward_token_id = shift @tokens_to_use;
1280 :     print STDERR "\t\tGoing forward with '$go_forward_token_id'\n" unless !$debug;
1281 :     }
1282 :     else
1283 :     {
1284 :     $go_forward_token_id = $token_id_counter++;
1285 :     $tokens{$go_forward_token_id} = {};
1286 :     print STDERR "\t\tRemember to merge tokens '@tokens_to_use' into '$go_forward_token_id'\n" unless !$debug;
1287 :    
1288 :     # record the need to merge - we'll do it after processing all sets of substrates
1289 :     foreach my $token_id (@tokens_to_use)
1290 :     {
1291 :     push @{$token_merge_history_this_reaction{$token_id}}, $go_forward_token_id;
1292 :     }
1293 :     }
1294 :    
1295 :     my $go_forward_token = $tokens{$go_forward_token_id};
1296 :     my @prodArr = @{$reactions_to_product_arrays{$reaction}};
1297 :    
1298 :     # add current reaction and products to accumulated token history.
1299 :     # reaction is mapped to loop counter to maintain history of order of execution
1300 :     $go_forward_token->{visited_reactions}->{$reaction} = $loop_counter;
1301 :    
1302 :     foreach my $prod (@prodArr)
1303 :     {
1304 :     my $cpd = @{$prod}[0];
1305 :     my $stoich = @{$prod}[1];
1306 :     my $main = @{$prod}[2];
1307 :    
1308 :     # keep track of path outputs we've seen
1309 :     if (defined $path_outputs{$cpd})
1310 :     {
1311 :     $path_outputs{$cpd} += $stoich;
1312 :     }
1313 :    
1314 :     if ($main)
1315 :     {
1316 :     $go_forward_token->{visited_compounds}->{$cpd} = $most_recent_step + 1;
1317 :     }
1318 :    
1319 :     # push tokens
1320 :     $compounds_to_tokens{$cpd}->{$go_forward_token_id} += $stoich;
1321 :     }
1322 :     }
1323 :    
1324 :     # now process this reaction's token merge history
1325 :     foreach my $token_id (sort { $a <=> $b } keys %token_merge_history_this_reaction)
1326 :     {
1327 :     # find the unique set of up to date merge ids
1328 :     my @merge_ids = @{$token_merge_history_this_reaction{$token_id}};
1329 :     my %updated_merge_ids;
1330 :    
1331 :     foreach my $token_id (@merge_ids)
1332 :     {
1333 :     while (defined $token_merge_history{$token_id})
1334 :     {
1335 :     $token_id = $token_merge_history{$token_id};
1336 :     }
1337 :    
1338 :     $updated_merge_ids{$token_id} = 1;
1339 :     }
1340 :    
1341 :     print STDERR "\t\tupdated merge id list for '$token_id': '@{[ keys %updated_merge_ids ]}'\n" unless !$debug;
1342 :    
1343 :     my $wrap_up_token_id = $token_id_counter++;
1344 :     $tokens{$wrap_up_token_id} = {};
1345 :     my $wrap_up_token = $tokens{$wrap_up_token_id};
1346 :     my @tokens_to_merge;
1347 :     push @tokens_to_merge, keys %updated_merge_ids, $token_id;
1348 :    
1349 :     # merge from oldest to youngest to update visited_compounds history
1350 :     foreach my $itoken_id (sort { $a <=> $b } @tokens_to_merge)
1351 :     {
1352 :     print STDERR "\t\t\tmerging '$itoken_id' into '$wrap_up_token_id'\n" unless !$debug;
1353 :    
1354 :     my $itoken = $tokens{$itoken_id};
1355 :     map { $wrap_up_token->{visited_reactions}->{$_} = $itoken->{visited_reactions}->{$_} } keys %{$itoken->{visited_reactions}};
1356 :     map { $wrap_up_token->{visited_compounds}->{$_} = $itoken->{visited_compounds}->{$_} } keys %{$itoken->{visited_compounds}};
1357 :     map { $wrap_up_token->{token_path_inputs}->{$_} += $itoken->{token_path_inputs}->{$_} } keys %{$itoken->{token_path_inputs}};
1358 :     $wrap_up_token->{initial_pass} |= $itoken->{initial_pass};
1359 :     $token_merge_history{$itoken_id} = $wrap_up_token_id;
1360 :    
1361 :     # tokens might be spread across multiple compounds; change them all
1362 :     # to new id
1363 :     foreach my $cpd (keys %compounds_to_tokens)
1364 :     {
1365 :     if ($compounds_to_tokens{$cpd}->{$itoken_id} > 0)
1366 :     {
1367 :     $compounds_to_tokens{$cpd}->{$wrap_up_token_id} +=
1368 :     $compounds_to_tokens{$cpd}->{$itoken_id};
1369 :     }
1370 :     }
1371 :    
1372 :     # tokens might have borrowed compounds; change them all to new id
1373 :     foreach my $cpd (keys %compounds_borrowed_to_tokens)
1374 :     {
1375 :     if ($compounds_borrowed_to_tokens{$cpd}->{$itoken_id} > 0)
1376 :     {
1377 :     $compounds_borrowed_to_tokens{$cpd}->{$wrap_up_token_id} +=
1378 :     $compounds_borrowed_to_tokens{$cpd}->{$itoken_id};
1379 :     }
1380 :     }
1381 :     }
1382 :     }
1383 :     }
1384 :    
1385 :     # now delete the tokens that were used merged in these reactions
1386 :     foreach my $token_id (keys %token_merge_history)
1387 :     {
1388 :     foreach my $icpd (keys %compounds_to_tokens)
1389 :     {
1390 :     delete $compounds_to_tokens{$icpd}->{$token_id};
1391 :     }
1392 :    
1393 :     foreach my $icpd (keys %compounds_borrowed_to_tokens)
1394 :     {
1395 :     delete $compounds_borrowed_to_tokens{$icpd}->{$token_id};
1396 :     }
1397 :    
1398 :     print STDERR "\t\tDeleting token '$token_id'\n" unless !$debug;
1399 :     delete $tokens{$token_id};
1400 :     }
1401 :    
1402 :     print STDERR "\nBalancing tokens\n" unless !$debug;
1403 :    
1404 :     foreach my $token_id (keys %tokens)
1405 :     {
1406 :     &balance_borrowing_and_giving($token_id, \%compounds_to_tokens,
1407 :     \%compounds_borrowed_to_tokens);
1408 :     }
1409 :    
1410 :     &print_token_status([sort { $a <=> $b } keys %tokens], \%tokens, \%compounds_to_tokens, \%compounds_borrowed_to_tokens, $fig);
1411 :    
1412 :     print STDERR "\nChecking for done\n" unless !$debug;
1413 :    
1414 :     print STDERR "\n\ntoken ids: @{[ sort { $a <=> $b } map { $_ if ! defined $tokens{$_}->{done} } keys %tokens ]}\n" unless !$debug;
1415 :    
1416 :     # we're done when all the main compounds in initial-pass tokens
1417 :     # have reached path outputs and repaid their borrowed tokens,
1418 :     # or have reached a dead end.
1419 :     # Check if we're done pushing and borrowing tokens first.
1420 :     my %not_done_tokens;
1421 :    
1422 :     foreach my $token_id (keys %tokens)
1423 :     {
1424 :     if (! defined $tokens{$token_id}->{done})
1425 :     {
1426 :     if (! &check_token_for_done($token_id, \%compounds_to_tokens,
1427 :     \%compounds_borrowed_to_tokens,
1428 :     \%all_compounds_to_main, \%path_outputs,
1429 :     \%scenario_cycles, \%tokens, $fig, $outputs_lists))
1430 :     {
1431 :     $not_done_tokens{$token_id} = 1;
1432 :     }
1433 :     }
1434 :     }
1435 :    
1436 :     print STDERR "\nChecking if we can pay back borrowed compounds from other tokens\n" unless !$debug;
1437 :    
1438 :     foreach my $bcpd (keys %compounds_borrowed_to_tokens)
1439 :     {
1440 :     next if $path_outputs{$bcpd}; # tokens must manage their own path outputs
1441 :    
1442 :     if (scalar keys %{$compounds_borrowed_to_tokens{$bcpd}} > 0 &&
1443 :     scalar keys %{$compounds_to_tokens{$bcpd}} > 0)
1444 :     {
1445 :     my %borrowers_to_givers;
1446 :    
1447 :     foreach my $borrower_id (keys %{$compounds_borrowed_to_tokens{$bcpd}})
1448 :     {
1449 :     next if defined $tokens{$borrower_id}->{done}; # don't repay deadenders
1450 :    
1451 :     my $num_needed = $compounds_borrowed_to_tokens{$bcpd}->{$borrower_id};
1452 :    
1453 :     giver: foreach my $giver_id (keys %{$compounds_to_tokens{$bcpd}})
1454 :     {
1455 :     next if defined $tokens{$giver_id}->{done};
1456 :    
1457 :     my $num_to_give = $compounds_to_tokens{$bcpd}->{$giver_id};
1458 :    
1459 :     print STDERR "\tToken '$giver_id' has $num_to_give $bcpd to give to '$borrower_id', which needs $num_needed\n" unless !$debug;
1460 :    
1461 :     my $borrower = $tokens{$borrower_id};
1462 :     my $giver = $tokens{$giver_id};
1463 :    
1464 :     # check whether the giver and borrower have conflicting histories
1465 :     foreach my $visited_reaction (keys %{$giver->{visited_reactions}})
1466 :     {
1467 :     if (($visited_reaction =~ /(.*)_R/ &&
1468 :     defined $borrower->{visited_reactions}->{$1."_L"}) ||
1469 :     ($visited_reaction =~ /(.*)_L/ &&
1470 :     defined $borrower->{visited_reactions}->{$1."_R"}))
1471 :     {
1472 :     print STDERR "\t\tConflict on $visited_reaction\n" unless !$debug;
1473 :     next giver;
1474 :     }
1475 :    
1476 :     }
1477 :    
1478 :     push @{$borrowers_to_givers{$borrower_id}}, $giver_id;
1479 :     }
1480 :     }
1481 :    
1482 :     # we have a list of potential givers for each borrower for this compound.
1483 :     # Now figure out who the lucky givers will be.
1484 :     my %givers_to_borrowers;
1485 :    
1486 :     foreach my $borrower_id (keys %borrowers_to_givers)
1487 :     {
1488 :     my %lucky_givers;
1489 :     my $num_needed = $compounds_borrowed_to_tokens{$bcpd}->{$borrower_id};
1490 :    
1491 :     print STDERR "\tCollecting lucky givers for '$borrower_id' for $bcpd, need $num_needed\n" unless !$debug;
1492 :    
1493 :     # check potential givers starting with those with the most
1494 :     my @potential_givers = reverse sort { $compounds_to_tokens{$bcpd}->{$a} <=> $compounds_to_tokens{$bcpd}->{$b} } @{$borrowers_to_givers{$borrower_id}};
1495 :    
1496 :     foreach my $giver_id (@potential_givers)
1497 :     {
1498 :     if (! defined $lucky_givers{$giver_id})
1499 :     {
1500 :     my $num_to_give = $compounds_to_tokens{$bcpd}->{$giver_id};
1501 :     print STDERR "\t\t'$giver_id' has $num_to_give to give\n" unless !$debug;
1502 :     $lucky_givers{$giver_id} = 1;
1503 :     $num_needed -= $num_to_give;
1504 :     last if $num_needed <= 0;
1505 :     }
1506 :     }
1507 :    
1508 :     foreach my $giver_id (keys %lucky_givers)
1509 :     {
1510 :     push @{$givers_to_borrowers{$giver_id}}, $borrower_id;
1511 :     }
1512 :     }
1513 :    
1514 :    
1515 :     foreach my $orig_giver_id (keys %givers_to_borrowers)
1516 :     {
1517 :     my @borrowers_list = @{$givers_to_borrowers{$orig_giver_id}};
1518 :     my @givers_list = ($orig_giver_id);
1519 :    
1520 :     # clone enough givers so that every borrower gets one. Last borrower
1521 :     # gets the orgiinal giver.
1522 :    
1523 :     while (scalar @borrowers_list > scalar @givers_list)
1524 :     {
1525 :     my $new_giver_id = $token_id_counter++;
1526 :     &clone_token($orig_giver_id, $new_giver_id, \%tokens,
1527 :     \%compounds_to_tokens, \%compounds_borrowed_to_tokens);
1528 :     push @givers_list, $new_giver_id;
1529 :     }
1530 :    
1531 :     for (my $k = 0; $k < scalar @givers_list; $k++)
1532 :     {
1533 :     my $giver_id = $givers_list[$k];
1534 :     my $giver = $tokens{$giver_id};
1535 :     my $borrower_id = $borrowers_list[$k];
1536 :     my $borrower = $tokens{$borrower_id};
1537 :    
1538 :     print STDERR "\n\tMerging '$giver_id' into '$borrower_id'\n" unless !$debug;
1539 :    
1540 :     # bump the borrower's visited reactions and compounds counters forward,
1541 :     # then merge the giver's visited reactions and compounds, unless
1542 :     # the borrower has already visited them
1543 :     map { $borrower->{visited_reactions}->{$_} += $loop_counter } keys %{$borrower->{visited_reactions}};
1544 :     map { $borrower->{visited_compounds}->{$_} += $loop_counter } keys %{$borrower->{visited_compounds}};
1545 :     map { $borrower->{visited_reactions}->{$_} = $giver->{visited_reactions}->{$_} unless defined $borrower->{visited_reactions}->{$_} } keys %{$giver->{visited_reactions}};
1546 :     map { $borrower->{visited_compounds}->{$_} = $giver->{visited_compounds}->{$_} unless defined $borrower->{visited_compounds}->{$_} } keys %{$giver->{visited_compounds}};
1547 :     map { $borrower->{token_path_inputs}->{$_} += $giver->{token_path_inputs}->{$_} } keys %{$giver->{token_path_inputs}};
1548 :     $borrower->{initial_pass} |= $giver->{initial_pass};
1549 :    
1550 :     foreach my $icpd (keys %compounds_to_tokens)
1551 :     {
1552 :     if ($compounds_to_tokens{$icpd}->{$giver_id} > 0)
1553 :     {
1554 :     $compounds_to_tokens{$icpd}->{$borrower_id} += $compounds_to_tokens{$icpd}->{$giver_id};
1555 :     delete $compounds_to_tokens{$icpd}->{$giver_id};
1556 :     }
1557 :     }
1558 :    
1559 :     foreach my $icpd (keys %compounds_borrowed_to_tokens)
1560 :     {
1561 :     if ($compounds_borrowed_to_tokens{$icpd}->{$giver_id} > 0)
1562 :     {
1563 :     $compounds_borrowed_to_tokens{$icpd}->{$borrower_id} += $compounds_borrowed_to_tokens{$icpd}->{$giver_id};
1564 :     delete $compounds_borrowed_to_tokens{$icpd}->{$giver_id};
1565 :     }
1566 :     }
1567 :    
1568 :     delete $tokens{$giver_id};
1569 :     delete $not_done_tokens{$giver_id};
1570 :    
1571 :     &balance_borrowing_and_giving($borrower_id, \%compounds_to_tokens,
1572 :     \%compounds_borrowed_to_tokens);
1573 :    
1574 :     &print_token_status([$borrower_id], \%tokens, \%compounds_to_tokens,
1575 :     \%compounds_borrowed_to_tokens, $fig);
1576 :    
1577 :     if (&check_token_for_done($borrower_id, \%compounds_to_tokens,
1578 :     \%compounds_borrowed_to_tokens,
1579 :     \%all_compounds_to_main, \%path_outputs,
1580 :     \%scenario_cycles,\%tokens, $fig, $outputs_lists))
1581 :     {
1582 :     delete $not_done_tokens{$borrower_id};
1583 :     }
1584 :     }
1585 :     }
1586 :     }
1587 :     }
1588 :    
1589 :     # Now check if we've reached a dead end, either a compound we can't push or a
1590 :     # borrowed compound we can't repay. Also determine whether there is a reaction
1591 :     # to run that can move an initial pass token forward.
1592 :    
1593 :     print STDERR "\nChecking for dead ends\n" unless !$debug;
1594 :    
1595 :     my $found_reaction_for_initial_pass_token = 0;
1596 :    
1597 :     check: foreach my $token_id (keys %not_done_tokens)
1598 :     {
1599 :     # determine which compounds the token is sitting on, and whether a
1600 :     # reaction can proceed from those compounds that isn't a loop
1601 :     # back to compounds already visited
1602 :     my %visited_compounds = %{$tokens{$token_id}->{visited_compounds}};
1603 :     my %visited_reactions = %{$tokens{$token_id}->{visited_reactions}};
1604 :     my $dead_end_cpd;
1605 :    
1606 :     print STDERR "\tChecking if '$token_id' can run\n" unless !$debug;
1607 :    
1608 :     my $found_reaction_for_token = 0;
1609 :    
1610 :     substrate: foreach my $cpd (keys %compounds_to_tokens)
1611 :     {
1612 :     if ($compounds_to_tokens{$cpd}->{$token_id} > 0 &&
1613 :     ! defined $path_outputs{$cpd})
1614 :     {
1615 :     print STDERR "\t\tChecking substrate $cpd (main: $all_compounds_to_main{$cpd})\n" unless !$debug;
1616 :    
1617 :     foreach my $reaction (@{$substrates_to_reactions->{$cpd}})
1618 :     {
1619 :     next if ($reaction =~ /(.*)_R/ && defined $visited_reactions{$1."_L"}) ||
1620 :     ($reaction =~ /(.*)_L/ && defined $visited_reactions{$1."_R"});
1621 :    
1622 :     print STDERR "\t\t\tChecking reaction $reaction\n" unless !$debug;
1623 :    
1624 :     my $prods_are_ok = 0;
1625 :    
1626 :     foreach my $prod (@{$reactions_to_products->{$reaction}})
1627 :     {
1628 :     print STDERR "\t\t\t\tChecking product $prod\n" unless !$debug;
1629 :    
1630 :     if (! defined $visited_compounds{$prod} ||
1631 :     $visited_compounds{$prod} >= $visited_compounds{$cpd} ||
1632 :     defined $path_outputs{$prod} ||
1633 :     $compounds_borrowed_to_tokens{$prod}->{$token_id} > 0)
1634 :     {
1635 :     $prods_are_ok = $prod;
1636 :     last;
1637 :     }
1638 :     }
1639 :    
1640 :     if ($prods_are_ok)
1641 :     {
1642 :     print STDERR "\tToken '$token_id' can run $reaction on $cpd to produce $prods_are_ok\n" unless !$debug;
1643 :     $found_reaction_for_token = 1;
1644 :    
1645 :     if ($tokens{$token_id}->{initial_pass})
1646 :     {
1647 :     $found_reaction_for_initial_pass_token = 1;
1648 :     }
1649 :    
1650 :     next substrate;
1651 :     }
1652 :     }
1653 :    
1654 :     # didn't find a reaction for this substrate
1655 :     $dead_end_cpd = $cpd if $all_compounds_to_main{$cpd} &&
1656 :     ! defined $path_outputs{$cpd};
1657 :     }
1658 :     }
1659 :    
1660 :     if ($dead_end_cpd)
1661 :     {
1662 :     print STDERR "\tToken '$token_id' has reached a dead end on $dead_end_cpd\n" unless !$debug;
1663 :     $tokens{$token_id}->{done} = "dead end on $dead_end_cpd";
1664 :     }
1665 :     elsif (! $found_reaction_for_token)
1666 :     {
1667 :     # didn't find any reaction to run.
1668 :     # check to see if there are borrowed compounds to repay
1669 :     product: foreach my $cpd (keys %compounds_borrowed_to_tokens)
1670 :     {
1671 :     if ($compounds_borrowed_to_tokens{$cpd}->{$token_id} > 0)
1672 :     {
1673 :     print STDERR "\t\tChecking product $cpd\n" unless !$debug;
1674 :    
1675 :     rxn: foreach my $reaction (@{$products_to_reactions->{$cpd}})
1676 :     {
1677 :     next if ($reaction =~ /(.*)_R/ && defined $visited_reactions{$1."_L"})
1678 :     || ($reaction =~ /(.*)_L/ && defined $visited_reactions{$1."_R"});
1679 :    
1680 :     print STDERR "\t\t\tChecking reaction $reaction\n" unless !$debug;
1681 :    
1682 :     my $substrates_are_ok = 0;
1683 :    
1684 :     foreach my $sub (@{$reactions_to_substrates->{$reaction}})
1685 :     {
1686 :     print STDERR "\t\t\t\tChecking substrate $sub\n" unless !$debug;
1687 :    
1688 :     if (defined $path_outputs{$sub})
1689 :     {
1690 :     # don't run reactions that use up outputs
1691 :     next rxn;
1692 :     }
1693 :    
1694 :     if (! defined $visited_compounds{$sub} ||
1695 :     $visited_compounds{$sub} <= $visited_compounds{$cpd} ||
1696 :     defined $scenario_cycles{$sub})
1697 :     {
1698 :     $substrates_are_ok = $sub;
1699 :     }
1700 :     }
1701 :    
1702 :     if ($substrates_are_ok)
1703 :     {
1704 :     print STDERR "\tToken '$token_id' can wait for $reaction on $substrates_are_ok to produce borrowed compound $cpd\n" unless !$debug;
1705 :     $found_reaction_for_token = 1;
1706 :    
1707 :     if ($tokens{$token_id}->{initial_pass})
1708 :     {
1709 :     $found_reaction_for_initial_pass_token = 1;
1710 :     }
1711 :    
1712 :     last product;
1713 :     }
1714 :     }
1715 :    
1716 :     # didn't find a reaction for this product
1717 :     $dead_end_cpd = $cpd if $all_compounds_to_main{$cpd} &&
1718 :     ! defined $path_outputs{$cpd};
1719 :     }
1720 :     }
1721 :    
1722 :     # didn't find any reaction to run.
1723 :     if (! $found_reaction_for_token)
1724 :     {
1725 :     if ($dead_end_cpd)
1726 :     {
1727 :     print STDERR "\tToken '$token_id' has reached a dead end on borrowed compound $dead_end_cpd\n" unless !$debug;
1728 :     $tokens{$token_id}->{done} = "dead end on borrowed compound $dead_end_cpd";
1729 :     }
1730 :     else
1731 :     {
1732 :     # nothing to push, borrow or do
1733 :     print STDERR "\tToken '$token_id' has reached a dead end\n" unless !$debug;
1734 :     $tokens{$token_id}->{done} = "dead end";
1735 :     }
1736 :     }
1737 :     }
1738 :     }
1739 :    
1740 :     if($find_first)
1741 :     {
1742 :     foreach my $token_id (sort { $tokens{$a}->{done} <=> $tokens{$b}->{done} } keys %tokens)
1743 :     {
1744 :     if($tokens{$token_id}->{done} == 1)
1745 :     {
1746 :     $done = 1;
1747 :     }
1748 :     }
1749 :     }
1750 :     # is there an initial pass token that can make progress?
1751 :     if ($found_reaction_for_initial_pass_token)
1752 :     {
1753 :     if (scalar keys %reactions_to_tokens_to_use == 0)
1754 :     {
1755 :     # Couldn't run any reactions this time around.
1756 :     # Push more tokens through from the beginning of the path to
1757 :     # supply more substrates.
1758 :     $add_path_inputs = 1;
1759 :     print STDERR "\nSupplying more path inputs to push stalled tokens\n" unless !$debug;
1760 :     }
1761 :     }
1762 :     else
1763 :     {
1764 :     $done = 1;
1765 :     }
1766 :    
1767 :     $loop_counter++;
1768 :    
1769 :     if ($loop_counter >= $infinite_loop_check)
1770 :     {
1771 :     $data_results{"infinite"} = 1;
1772 :     print STDERR "Encountered an infinite loop\n" unless !$debug;
1773 :     $done = 1;
1774 :     }
1775 :     }
1776 :    
1777 :     # reverse %compounds_to_tokens, since all tokens should be at path outputs now
1778 :     my %tokens_to_compounds;
1779 :    
1780 :     foreach my $cpd (keys %compounds_to_tokens)
1781 :     {
1782 :     foreach my $token_id (keys %{$compounds_to_tokens{$cpd}})
1783 :     {
1784 :     my $num_tokens = $compounds_to_tokens{$cpd}->{$token_id};
1785 :     $tokens_to_compounds{$token_id}->{$cpd} = $num_tokens if $num_tokens > 0;
1786 :     }
1787 :     }
1788 :    
1789 :     print STDERR "\n\ntoken ids: @{[ sort { $a <=> $b } map { $_ if ! defined $tokens{$_}->{done} } keys %tokens ]}\n" unless !$debug;
1790 :    
1791 :     my $path_counter = 1;
1792 :    
1793 :     foreach my $token_id (sort { $tokens{$a}->{done} <=> $tokens{$b}->{done} } keys %tokens)
1794 :     {
1795 :     my $token = $tokens{$token_id};
1796 :     my %visited_reactions = %{$token->{visited_reactions}};
1797 :     my @path = sort { $visited_reactions{$a} <=> $visited_reactions{$b} }
1798 :     keys %visited_reactions;
1799 :     my %visited_compounds = %{$token->{visited_compounds}};
1800 :     my @compounds = sort { $visited_compounds{$a} <=> $visited_compounds{$b} }
1801 :     keys %visited_compounds;
1802 :    
1803 :     print STDERR "Adding token id: $token_id\n" unless !$debug;
1804 :    
1805 :    
1806 :     #each key in data_results is a token which points to an array
1807 :     # [0]=initial pass [1]=0/1 if its done [2]=reaction path [3]=compounds
1808 :     # [4]= html string of inputs
1809 :     # [5]= html string of outputs
1810 :     # [6]= html string of borrowed compounds
1811 :     # [7] = array of path input compounds
1812 :     # [8] = array of path output compounds
1813 :    
1814 :    
1815 :     $data_results{$token_id} = [$token->{initial_pass},$token->{done},\@path,\@compounds,[],[],[],$token->{token_path_inputs},$tokens_to_compounds{$token_id}];
1816 :    
1817 :     foreach my $input (keys %{$token->{token_path_inputs}})
1818 :     {
1819 :     my $input_stoich = $token->{token_path_inputs}->{$input};
1820 :     my $output_stoich = $tokens_to_compounds{$token_id}->{$input};
1821 :    
1822 :     # don't balance scenario cycled compounds until final assembly
1823 :     if ($scenario_cycles{$input} && ! $create_assembly)
1824 :     {
1825 :     my @names = $fig->names_of_compound($input);
1826 :     push @{$data_results{$token_id}->[4]}, "\t\t$input_stoich\t$input $names[0]\n";
1827 :     next;
1828 :     }
1829 :    
1830 :     if ($input_stoich > $output_stoich)
1831 :     {
1832 :     delete $tokens_to_compounds{$token_id}->{$input};
1833 :     $input_stoich -= $output_stoich;
1834 :     $token->{token_path_inputs}->{$input} -= $output_stoich;
1835 :     my @names = $fig->names_of_compound($input);
1836 :     push @{$data_results{$token_id}->[4]}, "\t\t$input_stoich\t$input $names[0]\n";
1837 :     }
1838 :     elsif ($output_stoich > $input_stoich)
1839 :     {
1840 :     delete $token->{token_path_inputs}->{$input};
1841 :     $tokens_to_compounds{$token_id}->{$input} -= $input_stoich;
1842 :     }
1843 :     else
1844 :     {
1845 :     delete $token->{token_path_inputs}->{$input};
1846 :     delete $tokens_to_compounds{$token_id}->{$input};
1847 :     }
1848 :     }
1849 :    
1850 :     foreach my $output (keys %{$tokens_to_compounds{$token_id}})
1851 :     {
1852 :     my @names = $fig->names_of_compound($output);
1853 :     push @{$data_results{$token_id}->[5]},"\t\t$tokens_to_compounds{$token_id}->{$output}\t$output $names[0]\n";
1854 :     }
1855 :    
1856 :     if ($token->{done} != 1)
1857 :     {
1858 :     foreach my $cpd (sort keys %compounds_borrowed_to_tokens)
1859 :     {
1860 :     my $num = $compounds_borrowed_to_tokens{$cpd}->{$token_id};
1861 :     my @names = $fig->names_of_compound($cpd);
1862 :     push @{$data_results{$token_id}->[6]},"\t\t$num $cpd\t$names[0]\n" if ($num > 0);
1863 :     }
1864 :     }
1865 :     }
1866 :    
1867 :    
1868 :    
1869 :    
1870 :     return \%data_results;
1871 :     }
1872 :    
1873 :     sub balance_borrowing_and_giving
1874 :     {
1875 :     my ($token_id, $compounds_to_tokens, $compounds_borrowed_to_tokens) = @_;
1876 :    
1877 :     my %merged_compounds;
1878 :     map { $merged_compounds{$_} = 1 } keys %{$compounds_to_tokens};
1879 :     map { $merged_compounds{$_} = 1 } keys %{$compounds_borrowed_to_tokens};
1880 :    
1881 :     foreach my $icpd (keys %merged_compounds)
1882 :     {
1883 :     my $inum_to_give = $compounds_to_tokens->{$icpd}->{$token_id};
1884 :    
1885 :     if ($inum_to_give > 0)
1886 :     {
1887 :     my $inum_needed = $compounds_borrowed_to_tokens->{$icpd}->{$token_id};
1888 :    
1889 :     if ($inum_to_give == $inum_needed)
1890 :     {
1891 :     delete $compounds_borrowed_to_tokens->{$icpd}->{$token_id};
1892 :     delete $compounds_to_tokens->{$icpd}->{$token_id};
1893 :     }
1894 :     elsif ($inum_to_give > $inum_needed)
1895 :     {
1896 :     delete $compounds_borrowed_to_tokens->{$icpd}->{$token_id};
1897 :     $compounds_to_tokens->{$icpd}->{$token_id} -= $inum_needed;
1898 :     }
1899 :     else
1900 :     {
1901 :     $compounds_borrowed_to_tokens->{$icpd}->{$token_id} -= $inum_to_give;
1902 :     delete $compounds_to_tokens->{$icpd}->{$token_id};
1903 :     }
1904 :     }
1905 :     }
1906 :     }
1907 :    
1908 :     sub print_token_status
1909 :     {
1910 :     my ($token_id_list, $tokens, $compounds_to_tokens, $compounds_borrowed_to_tokens, $fig) = @_;
1911 :    
1912 :     print STDERR "\nToken status:\n" unless !$debug;
1913 :    
1914 :     foreach my $token_id (@$token_id_list)
1915 :     {
1916 :     next if defined $tokens->{$token_id}->{done};
1917 :    
1918 :     print STDERR "\n\ttoken: '$token_id', initial: $tokens->{$token_id}->{initial_pass}\n" unless !$debug;
1919 :    
1920 :     foreach my $cpd (sort keys %{$tokens->{$token_id}->{token_path_inputs}})
1921 :     {
1922 :     my $num = $tokens->{$token_id}->{token_path_inputs}->{$cpd};
1923 :     my @names = $fig->names_of_compound($cpd);
1924 :     print STDERR "\t\tInput: $num $cpd\t$names[0]\n" unless !$debug;
1925 :     }
1926 :    
1927 :     foreach my $cpd (sort keys %$compounds_to_tokens)
1928 :     {
1929 :     my $num = $compounds_to_tokens->{$cpd}->{$token_id};
1930 :     my @names = $fig->names_of_compound($cpd);
1931 :     print STDERR "\t\tStatus: $num $cpd\t$names[0]\n" if ($num > 0 && $debug);
1932 :     }
1933 :    
1934 :     foreach my $cpd (sort keys %$compounds_borrowed_to_tokens)
1935 :     {
1936 :     my $num = $compounds_borrowed_to_tokens->{$cpd}->{$token_id};
1937 :     my @names = $fig->names_of_compound($cpd);
1938 :     print STDERR "\t\tBorrowed: $num $cpd\t$names[0]\n" if ($num > 0 && $debug);
1939 :     }
1940 :    
1941 :     my %visited_compounds = %{$tokens->{$token_id}->{visited_compounds}};
1942 :     print STDERR "\t\tvisited_compounds: @{[map { ($_, $visited_compounds{$_} ) } sort { $visited_compounds{$a} <=> $visited_compounds{$b} } keys %visited_compounds]}\n" unless !$debug;
1943 :    
1944 :     my %visited_reactions = %{$tokens->{$token_id}->{visited_reactions}};
1945 :     print STDERR "\t\tvisited_reactions: @{[map { ($_, $visited_reactions{$_} ) } sort { $visited_reactions{$a} <=> $visited_reactions{$b} } keys %visited_reactions]}\n" unless !$debug;
1946 :    
1947 :     }
1948 :    
1949 :     print STDERR "\n" unless !$debug;
1950 :     }
1951 :    
1952 :     sub clone_token
1953 :     {
1954 :     my ($clone_id, $new_token_id, $tokens, $compounds_to_tokens, $compounds_borrowed_to_tokens) = @_;
1955 :     my (%new_token, %new_visited_reactions, %new_visited_compounds, %new_token_path_inputs);
1956 :    
1957 :     $tokens->{$new_token_id} = \%new_token;
1958 :    
1959 :     my $clone_token = $tokens->{$clone_id};
1960 :     map {$new_visited_reactions{$_} = $clone_token->{visited_reactions}->{$_}} keys %{$clone_token->{visited_reactions}};
1961 :     map {$new_visited_compounds{$_} = $clone_token->{visited_compounds}->{$_}} keys %{$clone_token->{visited_compounds}};
1962 :     map {$new_token_path_inputs{$_} = $clone_token->{token_path_inputs}->{$_}} keys %{$clone_token->{token_path_inputs}};
1963 :    
1964 :     $new_token{visited_reactions} = \%new_visited_reactions;
1965 :     $new_token{visited_compounds} = \%new_visited_compounds;
1966 :     $new_token{token_path_inputs} = \%new_token_path_inputs;
1967 :     $new_token{initial_pass} = $clone_token->{initial_pass};
1968 :    
1969 :     # tokens might be spread across multiple compounds
1970 :     foreach my $icpd (keys %$compounds_to_tokens)
1971 :     {
1972 :     if ($compounds_to_tokens->{$icpd}->{$clone_id} > 0)
1973 :     {
1974 :     $compounds_to_tokens->{$icpd}->{$new_token_id} =
1975 :     $compounds_to_tokens->{$icpd}->{$clone_id};
1976 :     }
1977 :     }
1978 :    
1979 :     # tokens might have borrowed compounds
1980 :     foreach my $icpd (keys %$compounds_borrowed_to_tokens)
1981 :     {
1982 :     if ($compounds_borrowed_to_tokens->{$icpd}->{$clone_id} > 0)
1983 :     {
1984 :     $compounds_borrowed_to_tokens->{$icpd}->{$new_token_id} =
1985 :     $compounds_borrowed_to_tokens->{$icpd}->{$clone_id};
1986 :     }
1987 :     }
1988 :    
1989 :     return \%new_token;
1990 :     }
1991 :    
1992 :     sub check_token_for_done
1993 :     {
1994 :     my ($token_id, $compounds_to_tokens, $compounds_borrowed_to_tokens, $all_compounds_to_main,
1995 :     $path_outputs, $scenario_cycles, $tokens, $fig, $outputs_lists) = @_;
1996 :    
1997 :     my $token_is_done_pushing = 1;
1998 :     my $token_is_done_borrowing = 1;
1999 :    
2000 :     # first determine if there is a main compound that isn't a path output
2001 :     foreach my $cpd (keys %$compounds_to_tokens)
2002 :     {
2003 :     if ($compounds_to_tokens->{$cpd}->{$token_id} > 0)
2004 :     {
2005 :     # also check if scenario cycle compounds need to be pushed
2006 :     if ($all_compounds_to_main->{$cpd} &&
2007 :     (! defined $path_outputs->{$cpd} ||
2008 :     ($scenario_cycles->{$cpd} &&
2009 :     $tokens->{$token_id}->{visited_compounds}->{$cpd} == 0)))
2010 :     {
2011 :     my @names = $fig->names_of_compound($cpd);
2012 :     print STDERR "\ttoken '$token_id' needs to push $cpd $names[0]\n" unless !$debug;
2013 :     $token_is_done_pushing = 0;
2014 :     }
2015 :     }
2016 :     }
2017 :    
2018 :     # now determine if one of the output lists has been satisfied
2019 :     if ($token_is_done_pushing)
2020 :     {
2021 :     my $found_a_list = 0;
2022 :    
2023 :     foreach my $cpd_list (@$outputs_lists)
2024 :     {
2025 :     print STDERR "\t\tchecking outputs_list @$cpd_list\n" unless !$debug;
2026 :    
2027 :     $found_a_list = 1;
2028 :    
2029 :     foreach my $cpd (@$cpd_list)
2030 :     {
2031 :     if (! $compounds_to_tokens->{$cpd}->{$token_id} > 0)
2032 :     {
2033 :     $found_a_list = 0;
2034 :     last;
2035 :     }
2036 :     }
2037 :    
2038 :     last if $found_a_list;
2039 :     }
2040 :    
2041 :     if (! $found_a_list)
2042 :     {
2043 :     print STDERR "\ttoken '$token_id' hasn't satisfied output compound list\n" unless !$debug;
2044 :     $token_is_done_pushing = 0;
2045 :     }
2046 :     }
2047 :    
2048 :     if ($token_is_done_pushing)
2049 :     {
2050 :     foreach my $cpd (keys %$compounds_borrowed_to_tokens)
2051 :     {
2052 :     if ($compounds_borrowed_to_tokens->{$cpd}->{$token_id} > 0)
2053 :     {
2054 :     if ($all_compounds_to_main{$cpd})
2055 :     {
2056 :     my @names = $fig->names_of_compound($cpd);
2057 :     print STDERR "\ttoken '$token_id' has borrowed $cpd $names[0]\n" unless !$debug;
2058 :     $token_is_done_borrowing = 0;
2059 :     }
2060 :     }
2061 :     }
2062 :     }
2063 :    
2064 :     if (! $token_is_done_pushing || ! $token_is_done_borrowing)
2065 :     {
2066 :     return 0;
2067 :     }
2068 :     else
2069 :     {
2070 :     $tokens->{$token_id}->{done} = 1;
2071 :     print STDERR "\tToken '$token_id' is done\n" unless !$debug;
2072 :     return 1;
2073 :     }
2074 :     }
2075 :    
2076 :    
2077 :     sub write_fluxanalyzer_files
2078 :     {
2079 :     my ($dir, $path_inputs, $path_outputs, $path_array,
2080 :     $all_reactions,$reactions_to_substrate_arrays,$reactions_to_product_arrays,
2081 :     $cidToName) = @_;
2082 :    
2083 :     my $x_pos = 10;
2084 :     my $y_pos = 20;
2085 :    
2086 :     #Write the inputs/outputs to a seperate file, along with $stoich and if its main
2087 :     open(A_INPUT, ">$dir/inputs_main");
2088 :    
2089 :     print A_INPUT map {"$_\t$all_compounds_to_main{$_}\n"} keys %$path_inputs;
2090 :    
2091 :     close(A_INPUT);
2092 :    
2093 :     open(A_OUTPUT, ">$dir/outputs_main");
2094 :    
2095 :     print A_OUTPUT map {"$_\t$all_compounds_to_main{$_}\n"} keys %$path_outputs;
2096 :    
2097 :     close(A_OUTPUT);
2098 :    
2099 :    
2100 :    
2101 :     open(REACTIONS, ">$dir/reactions");
2102 :     open(INPUTS, ">$dir/inputs");
2103 :     open(OUTPUTS, ">$dir/outputs");
2104 :     open(PATH, ">$dir/path_info");
2105 :    
2106 :     my @inputs = keys %$path_inputs;
2107 :    
2108 :     foreach my $elem(@{$path_array}){
2109 :     print PATH $elem ."\n";
2110 :     }
2111 :     close(PATH);
2112 :    
2113 :     foreach my $cpd (@inputs)
2114 :     {
2115 :     my $toPrint = $cpd."up\t = 1 $cpd \t| \t";
2116 :     $toPrint .= $path_inputs->{$cpd};
2117 :     $toPrint .= " \t0 100 0 \t$x_pos $y_pos 1 1\t0.01\n";
2118 :     print REACTIONS $toPrint;
2119 :     $y_pos += 20;
2120 :    
2121 :     if ($y_pos == 300)
2122 :     {
2123 :     $x_pos += 60;
2124 :     $y_pos = 20;
2125 :     }
2126 :     }
2127 :    
2128 :     $x_pos += 60;
2129 :     $y_pos = 20;
2130 :    
2131 :     my (@display_array);
2132 :     foreach my $rxn (keys %$all_reactions)
2133 :     {
2134 :     my $direction = $all_reactions->{$rxn};
2135 :    
2136 :     my (@substrate_array, @product_array);
2137 :    
2138 :     push @display_array, $rxn;
2139 :    
2140 :     if ($direction eq "L")
2141 :     {
2142 :     @product_array = @{$reactions_to_substrate_arrays->{$rxn."_L"}};
2143 :     @substrate_array = @{$reactions_to_product_arrays->{$rxn."_L"}};
2144 :     }
2145 :     else
2146 :     {
2147 :     @substrate_array = @{$reactions_to_substrate_arrays->{$rxn."_R"}};
2148 :     @product_array = @{$reactions_to_product_arrays->{$rxn."_R"}};
2149 :     }
2150 :    
2151 :     foreach my $subTuple (@substrate_array)
2152 :     {
2153 :     my @temp = $fig->names_of_compound($subTuple->[0]);
2154 :     $cidToName->{$subTuple->[0]} = $temp [0] if ! defined $cidToName->{$subTuple->[0]};
2155 :     }
2156 :    
2157 :     foreach my $prodTuple(@product_array)
2158 :     {
2159 :     my @temp = $fig->names_of_compound($prodTuple->[0]);
2160 :     $cidToName->{$prodTuple->[0]} = $temp[0] if ! defined $cidToName->{$prodTuple->[0]};
2161 :     }
2162 :    
2163 :     if($direction eq "R" || $direction eq "B")
2164 :     {
2165 :     #write data in a strign for copying to file later
2166 :     my $toFile = '';
2167 :     $toFile.= $rxn."\t";
2168 :    
2169 :     #add all the substrates
2170 :     foreach my $curSub(@substrate_array){
2171 :     $toFile .= $curSub -> [1].' '. $curSub -> [0].' + ';
2172 :     }
2173 :    
2174 :     ##chop off the +
2175 :     chop($toFile);
2176 :     chop($toFile);
2177 :    
2178 :     $toFile.='= ';
2179 :    
2180 :     #add all the products
2181 :     foreach my $curProd(@product_array){
2182 :     $toFile .= $curProd -> [1].' '. $curProd -> [0].' + ';
2183 :     }
2184 :    
2185 :     #chop off the plus
2186 :     chop($toFile);
2187 :     chop($toFile);
2188 :    
2189 :     $toFile.="\t|\t#\t";
2190 :    
2191 :     if($direction eq "B"){
2192 :     $toFile.="-Inf";
2193 :     }
2194 :     else{
2195 :     $toFile.="0";
2196 :     }
2197 :    
2198 :     $toFile.=" Inf 0\t$x_pos $y_pos 1 1 \t0.01\n";
2199 :    
2200 :     print REACTIONS $toFile;
2201 :     }
2202 :     elsif($direction eq "L")
2203 :     {
2204 :     #write data in a strign for copying to file later
2205 :     my $toFile = '';
2206 :     $toFile.= $rxn."\t";
2207 :    
2208 :     #add all the substrates
2209 :     foreach my $curProd(@product_array){
2210 :     $toFile .= $curProd -> [1].' '. $curProd -> [0]." + ";
2211 :     }
2212 :    
2213 :     ##chop off the +
2214 :     chop($toFile);
2215 :     chop($toFile);
2216 :    
2217 :     $toFile.="= ";
2218 :    
2219 :     #add all the products
2220 :     foreach my $curSubstrate(@substrate_array){
2221 :     $toFile .= $curSubstrate -> [1].' '. $curSubstrate -> [0]." + ";
2222 :     }
2223 :    
2224 :     #chop off the plus
2225 :     chop($toFile);
2226 :     chop($toFile);
2227 :    
2228 :     $toFile.="\t|\t#\t";
2229 :    
2230 :     $toFile.="0";
2231 :    
2232 :     $toFile.=" Inf 0\t$x_pos $y_pos 1 1 \t0.01\n";
2233 :    
2234 :     print REACTIONS $toFile;
2235 :     }
2236 :    
2237 :     $y_pos += 20;
2238 :    
2239 :     if ($y_pos == 300)
2240 :     {
2241 :     $x_pos += 60;
2242 :     $y_pos = 20;
2243 :     }
2244 :     }
2245 :    
2246 :     my @outputs = keys %$path_outputs;
2247 :    
2248 :     $x_pos += 60;
2249 :     $y_pos = 20;
2250 :    
2251 :     foreach my $cpd (@inputs)
2252 :     {
2253 :     print INPUTS $cpd, "\t", $path_inputs->{$cpd}, "\t", $cidToName->{$cpd}, "\n";
2254 :     }
2255 :    
2256 :     foreach my $cpd (@outputs)
2257 :     {
2258 :     print OUTPUTS $cpd, "\t", $path_outputs->{$cpd}, "\t", $cidToName->{$cpd}, "\n";
2259 :     my $toPrint = $cpd."ex\t 1 $cpd = \t| \t# \t0 100 0 \t$x_pos $y_pos 1 1\t0.01\n";
2260 :     print REACTIONS $toPrint;
2261 :     $y_pos += 20;
2262 :    
2263 :     if ($y_pos == 300)
2264 :     {
2265 :     $x_pos += 60;
2266 :     $y_pos = 20;
2267 :     }
2268 :     }
2269 :    
2270 :     $x_pos += 60;
2271 :     $y_pos = 20;
2272 :    
2273 :     #print the macromolecule_synthesis and assembly file
2274 :     open(MACRO_SYTH,">$dir/macromolecule_synthesis");
2275 :     open(ASSEM,">$dir/assembly");
2276 :     my $toPrint = "M1 = ";
2277 :    
2278 :     foreach my $cpd (keys %$path_outputs)
2279 :     {
2280 :     $toPrint.="$path_outputs->{$cpd} $cpd + ";
2281 :     print ASSEM "$cpd\tM1\t-100 -100 1\n";
2282 :     $y_pos += 25;
2283 :     }
2284 :    
2285 :     chop $toPrint;
2286 :     chop $toPrint;
2287 :     chop $toPrint;
2288 :     print MACRO_SYTH $toPrint;
2289 :     close(MACRO_SYTH);
2290 :     close(ASSEM);
2291 :    
2292 :     #Print the metabolites for these subsystems.
2293 :     open(METABOLITES,">$dir/metabolites");
2294 :    
2295 :     foreach my $cid (keys %$cidToName)
2296 :     {
2297 :     my $name = $cidToName->{$cid};
2298 :     $name =~ s/\s/-/g;
2299 :     print METABOLITES $cid."\t".$name."\t0.001\t0\n";
2300 :     }
2301 :     close(METABOLITES);
2302 :    
2303 :     #Print the macromolucules file
2304 :     open(MACRO,">$dir/macromolecules");
2305 :     print MACRO "M1 \tM1 \t1 \t-100 -100 1 1\n";
2306 :     close(MACRO);
2307 :    
2308 :     $x_pos += 60;
2309 :     $y_pos = 20;
2310 :    
2311 :     print REACTIONS "mue\t\t\t|\t#\t0 100 0\t$x_pos $y_pos 1 1\t0.01\n";
2312 :    
2313 :     #close reaction equation file
2314 :     close(REACTIONS);
2315 :    
2316 :     # FluxAnalyzer requires this file
2317 :     open(APP, ">$dir/app_para.m");
2318 :     print APP "epsilon=1e-10;\nbasic_color=[0.7 0.7 0.7];\ncr_color=[0.5 0.5 1];\nbr_color=[1 0.2 0.2];\nnbr_color=[0.2 1 0.2];\ntext_color=[0 0 0];\nmacro_synth_color=[0 0 1];\nmacro_color=[0.6 0.6 1];\nbox_reaction_width=[0.12];\nbox_reaction_height=[0.06];\nbox_macro_width=[0.08];\nbox_macro_height=[0.06];\nfontsize_reaction=[11];\nfontsize_macro=[11];\nfluxmaps={'Fluxmap','dummy.pcx'};\n";
2319 :     close(APP);
2320 :     }
2321 :    
2322 :     sub write_final_fluxanalyzer_files
2323 :     {
2324 :     my ($dir, $path_inputs, $path_outputs, $all_reactions, $transport_reactions,
2325 :     $reactions_to_substrate_arrays,$reactions_to_product_arrays,
2326 :     $cidToName,$bioMass,$minSubstrates) = @_;
2327 :    
2328 :     #Write the inputs/outputs to a seperate file, along with $stoich and if its main
2329 :     open(A_INPUT, ">$dir/inputs_main");
2330 :    
2331 :     print A_INPUT map {"$_\t$all_compounds_to_main{$_}\n"} keys %$path_inputs;
2332 :    
2333 :     close(A_INPUT);
2334 :    
2335 :     open(A_OUTPUT, ">$dir/outputs_main");
2336 :    
2337 :     print A_OUTPUT map {"$_\t$all_compounds_to_main{$_}\n"} keys %$path_outputs;
2338 :    
2339 :     close(A_OUTPUT);
2340 :    
2341 :     my %open_transports;
2342 :    
2343 :     foreach my $cpd (keys %$minSubstrates)
2344 :     {
2345 :     map { $open_transports{$_} = 1 } @{$minSubstrates->{$cpd}};
2346 :     }
2347 :    
2348 :     open(REACTIONS, ">$dir/reactions");
2349 :     open(INPUTS, ">$dir/inputs");
2350 :     open(OUTPUTS, ">$dir/outputs");
2351 :    
2352 :     my @inputs = keys %$path_inputs;
2353 :    
2354 :     my $x_pos = 10;
2355 :     my $y_pos = 30;
2356 :    
2357 :     foreach my $cpd (@inputs)
2358 :     {
2359 :     my $toPrint = $cpd."up\t = 1 $cpd \t| \t";
2360 :    
2361 :     if (defined $minSubstrates->{$cpd})
2362 :     {
2363 :     $toPrint .= "#";
2364 :     }
2365 :     else
2366 :     {
2367 :     $toPrint .= "0";
2368 :     }
2369 :    
2370 :     $toPrint .= " \t0 Inf 0 \t$x_pos $y_pos 1 1\t0.01\n";
2371 :     print REACTIONS $toPrint;
2372 :     $y_pos += 30;
2373 :    
2374 :     if ($y_pos > 600)
2375 :     {
2376 :     $x_pos += 60;
2377 :     $y_pos = 30;
2378 :     }
2379 :     }
2380 :    
2381 :     $x_pos += 60;
2382 :     $y_pos = 30;
2383 :    
2384 :     foreach my $rxn (keys %$all_reactions)
2385 :     {
2386 :     my $direction = $all_reactions->{$rxn};
2387 :    
2388 :     my (@substrate_array, @product_array);
2389 :    
2390 :     if ($direction eq "L")
2391 :     {
2392 :     @product_array = @{$reactions_to_substrate_arrays->{$rxn."_L"}};
2393 :     @substrate_array = @{$reactions_to_product_arrays->{$rxn."_L"}};
2394 :     }
2395 :     else
2396 :     {
2397 :     @substrate_array = @{$reactions_to_substrate_arrays->{$rxn."_R"}};
2398 :     @product_array = @{$reactions_to_product_arrays->{$rxn."_R"}};
2399 :     }
2400 :    
2401 :     foreach my $subTuple (@substrate_array)
2402 :     {
2403 :     my @temp = $fig->names_of_compound($subTuple->[0]);
2404 :     $cidToName->{$subTuple->[0]} = $temp [0] if ! defined $cidToName->{$subTuple->[0]};
2405 :     }
2406 :    
2407 :     foreach my $prodTuple(@product_array)
2408 :     {
2409 :     my @temp = $fig->names_of_compound($prodTuple->[0]);
2410 :     $cidToName->{$prodTuple->[0]} = $temp[0] if ! defined $cidToName->{$prodTuple->[0]};
2411 :     }
2412 :    
2413 :     if($direction eq "R" || $direction eq "B")
2414 :     {
2415 :     #write data in a strign for copying to file later
2416 :     my $toFile = '';
2417 :     $toFile.= $rxn."\t";
2418 :    
2419 :     #add all the substrates
2420 :     foreach my $curSub(@substrate_array){
2421 :     $toFile .= $curSub -> [1].' '. $curSub -> [0].' + ';
2422 :     }
2423 :    
2424 :     ##chop off the +
2425 :     chop($toFile);
2426 :     chop($toFile);
2427 :    
2428 :     $toFile.='= ';
2429 :    
2430 :     #add all the products
2431 :     my $found_prod = 0;
2432 :     foreach my $curProd(@product_array){
2433 :     $toFile .= $curProd -> [1].' '. $curProd -> [0].' + ';
2434 :     $found_prod = 1;
2435 :     }
2436 :    
2437 :     if ($found_prod)
2438 :     {
2439 :     #chop off the plus
2440 :     chop($toFile);
2441 :     chop($toFile);
2442 :     }
2443 :    
2444 :     if (defined $transport_reactions->{$rxn})
2445 :     {
2446 :     if (defined $open_transports{$rxn})
2447 :     {
2448 :     $toFile.="\t|\t#\t";
2449 :     }
2450 :     else
2451 :     {
2452 :     $toFile.="\t|\t0\t";
2453 :     }
2454 :    
2455 :     if($direction eq "B"){
2456 :     $toFile.="-Inf";
2457 :     }
2458 :     else{
2459 :     $toFile.="0";
2460 :     }
2461 :    
2462 :     $toFile.=" Inf 0\t$x_pos $y_pos 1 1 \t0.01\n";
2463 :     $y_pos += 30;
2464 :     }
2465 :     elsif ($rxn =~ /sink/)
2466 :     {
2467 :     $toFile.="\t|\t0\t";
2468 :    
2469 :     if($direction eq "B"){
2470 :     $toFile.="-0.00001";
2471 :     }
2472 :     else{
2473 :     $toFile.="0";
2474 :     }
2475 :    
2476 :     $toFile.=" 0.00001 0\t$x_pos $y_pos 1 1 \t0.01\n";
2477 :     $y_pos += 30;
2478 :     }
2479 :     else
2480 :     {
2481 :     $toFile.="\t|\t#\t";
2482 :    
2483 :     if($direction eq "B"){
2484 :     $toFile.="-Inf";
2485 :     }
2486 :     else{
2487 :     $toFile.="0";
2488 :     }
2489 :    
2490 :     $toFile.=" Inf 0\t-10 -10 1 1 \t0.01\n";
2491 :     }
2492 :    
2493 :     print REACTIONS $toFile;
2494 :     }
2495 :     elsif($direction eq "L")
2496 :     {
2497 :     #write data in a strign for copying to file later
2498 :     my $toFile = '';
2499 :     $toFile.= $rxn."\t";
2500 :    
2501 :     #add all the substrates
2502 :     foreach my $curProd(@product_array){
2503 :     $toFile .= $curProd -> [1].' '. $curProd -> [0]." + ";
2504 :     }
2505 :    
2506 :     ##chop off the +
2507 :     chop($toFile);
2508 :     chop($toFile);
2509 :    
2510 :     $toFile.="= ";
2511 :    
2512 :     #add all the products
2513 :     foreach my $curSubstrate(@substrate_array){
2514 :     $toFile .= $curSubstrate -> [1].' '. $curSubstrate -> [0]." + ";
2515 :     }
2516 :    
2517 :     #chop off the plus
2518 :     chop($toFile);
2519 :     chop($toFile);
2520 :    
2521 :    
2522 :     $toFile.="\t|\t#\t";
2523 :     $toFile.="0";
2524 :     $toFile.=" Inf 0\t-10 -10 1 1 \t0.01\n";
2525 :    
2526 :     print REACTIONS $toFile;
2527 :     }
2528 :    
2529 :     if ($y_pos > 600)
2530 :     {
2531 :     $x_pos += 60;
2532 :     $y_pos = 30;
2533 :     }
2534 :     }
2535 :    
2536 :     my @outputs = keys %$path_outputs;
2537 :    
2538 :     $x_pos += 60;
2539 :     $y_pos = 30;
2540 :    
2541 :     foreach my $cpd (@inputs)
2542 :     {
2543 :     print INPUTS $cpd, "\t", $path_inputs->{$cpd}, "\t", $cidToName->{$cpd}, "\n";
2544 :     }
2545 :    
2546 :     foreach my $cpd (@outputs)
2547 :     {
2548 :     print OUTPUTS $cpd, "\t", $path_outputs->{$cpd}, "\t", $cidToName->{$cpd}, "\n";
2549 :     my $toPrint = $cpd."ex\t 1 $cpd = \t| \t# \t0 Inf 0 \t$x_pos $y_pos 1 1\t0.01\n";
2550 :     print REACTIONS $toPrint;
2551 :     $y_pos += 30;
2552 :    
2553 :     if ($y_pos > 600)
2554 :     {
2555 :     $x_pos += 60;
2556 :     $y_pos = 30;
2557 :     }
2558 :     }
2559 :    
2560 :     $x_pos += 60;
2561 :     $y_pos = 30;
2562 :    
2563 :     #print the macromolecule_synthesis and assembly file
2564 :     open(MACRO,">$dir/macromolecules");
2565 :     open(MACRO_SYTH,">$dir/macromolecule_synthesis");
2566 :     open(ASSEM,">$dir/assembly");
2567 :    
2568 :     my $toPrint = "M1 = ";
2569 :    
2570 :     foreach my $cpd (keys %$bioMass)
2571 :     {
2572 :     $toPrint .= "$bioMass->{$cpd} $cpd + ";
2573 :     print ASSEM "$cpd\tM1\t-100 -100 1\n";
2574 :     }
2575 :    
2576 :     chop $toPrint;
2577 :     chop $toPrint;
2578 :     chop $toPrint;
2579 :    
2580 :     print MACRO "M1 \tM1 \t1 \t-100 -100 1 1\n";
2581 :     print MACRO_SYTH $toPrint, "\n";
2582 :    
2583 :     close(MACRO);
2584 :     close(MACRO_SYTH);
2585 :     close(ASSEM);
2586 :    
2587 :     #Print the metabolites for these subsystems.
2588 :     open(METABOLITES,">$dir/metabolites");
2589 :    
2590 :     foreach my $cid (keys %$cidToName)
2591 :     {
2592 :     my $name = $cidToName->{$cid};
2593 :     $name =~ s/\s/-/g;
2594 :     print METABOLITES $cid."\t".$name."\t0.001\t0\n";
2595 :     }
2596 :     close(METABOLITES);
2597 :    
2598 :     $x_pos += 60;
2599 :     $y_pos = 30;
2600 :    
2601 :     print REACTIONS "mue\t\t\t|\t#\t0 100 0\t$x_pos $y_pos 1 1\t0.01\n";
2602 :    
2603 :     #close reaction equation file
2604 :     close(REACTIONS);
2605 :    
2606 :     # FluxAnalyzer requires this file
2607 :     open(APP, ">$dir/app_para.m");
2608 :     print APP "epsilon=1e-10;\nbasic_color=[0.7 0.7 0.7];\ncr_color=[0.5 0.5 1];\nbr_color=[1 0.2 0.2];\nnbr_color=[0.2 1 0.2];\ntext_color=[0 0 0];\nmacro_synth_color=[0 0 1];\nmacro_color=[0.6 0.6 1];\nbox_reaction_width=[0.06];\nbox_reaction_height=[0.03];\nbox_macro_width=[0.06];\nbox_macro_height=[0.03];\nfontsize_reaction=[11];\nfontsize_macro=[11];\nfluxmaps={'Fluxmap','dummy_medium.pcx'};\n";
2609 :     close(APP);
2610 :     }
2611 :    
2612 :    
2613 :     sub clear_arrays
2614 :     {
2615 :     undef %reactions_to_substrate_arrays;
2616 :     undef %reactions_to_product_arrays;
2617 :     undef %all_compounds_to_main;
2618 :     undef %all_reactions;
2619 :     undef %scenario_cycles;
2620 :     undef @all_outputs_lists;
2621 :     undef %all_inputs;
2622 :     undef %all_outputs;
2623 :    
2624 :     %reactions_to_substrate_arrays = ();
2625 :     %reactions_to_product_arrays = ();
2626 :     %all_compounds_to_main = ();
2627 :     %all_reactions = ();
2628 :     %scenario_cycles = ();
2629 :     @all_outputs_lists = ();
2630 :     %all_inputs = ();
2631 :     %all_outputs = ();
2632 :     }
2633 :    
2634 :    
2635 :     sub clear_dir_for_genome
2636 :     {
2637 :     my ($genome) = @_;
2638 : olson 1.13 rmtree($fig->model_directory($genome));
2639 : olson 1.1 }
2640 :    
2641 :     sub load_superset_file
2642 :     {
2643 :     my ($filename) = @_;
2644 :    
2645 :     %superset_to_ss = ();
2646 :     %ss_to_superset = ();
2647 :    
2648 :     open(FILE,"<$filename") or die("Failed to open $filename");
2649 :     while(<FILE>)
2650 :     {
2651 :     my @line = split(/\t/,$_);
2652 :     map { s/ /_/g } @line;
2653 :     map { s/\"//g } @line;
2654 :     map { chomp } @line;
2655 :     $superset_to_ss{$line[0]} = [] if !defined $superset_to_ss{$line[0]};
2656 :     $ss_to_superset{$line[1]} = $line[0];
2657 :     push(@{$superset_to_ss{$line[0]}},$line[1]);
2658 :     }
2659 :     close(FILE);
2660 :    
2661 :     return \%superset_to_ss
2662 :     }
2663 :    
2664 :     # This function runs a given scenario that is defined the specified subsystem
2665 :     # It returns the data as it is found by process_paths in a hash reference
2666 :     # This is used internally by model.pm, and shouldn't be called externally
2667 :    
2668 :     sub load_scenario
2669 :     {
2670 :     my ($genome,$ssa,$scenario) = @_;
2671 :    
2672 :     #load up the arrays with the info we need
2673 :     process_init($ssa,$scenario,$genome,0);
2674 :    
2675 :     #assume all path inputs and outputs are main
2676 :     map { $all_compounds_to_main{$_} = 1 } keys %all_inputs;
2677 :     map { $all_compounds_to_main{$_} = 1 } keys %all_outputs;
2678 :    
2679 :     }
2680 :    
2681 :     sub internal_scenario
2682 :     {
2683 :     my ($genome,$ssa,$scenario,$find_first) = @_;
2684 :    
2685 : olson 1.2 print STDERR "\nIn internal_scenario with '$genome', '$ssa', '$scenario', '$find_first'\n" if $debug;
2686 : olson 1.1
2687 :     load_scenario($genome,$ssa,$scenario);
2688 :    
2689 :     return execute_paths([],$find_first,[],[]);
2690 :     }
2691 :    
2692 :     sub run_scenario
2693 :     {
2694 :     my($genome,$superset,$subsystem,$scenario,$find_first) = @_;
2695 : olson 1.13 my $scenario_dir = $fig->model_directory($genome) . "/Scenarios/$superset/$subsystem/$scenario";
2696 : olson 1.2
2697 :     system("rm", "-rf", $scenario_dir);
2698 :    
2699 : olson 1.10 &FIG::verify_dir($scenario_dir);
2700 : olson 1.1
2701 :     #make sure the arrays are empty to start out
2702 :     &clear_arrays;
2703 :     write_scenario(internal_scenario($genome,$subsystem,$scenario,$find_first),$scenario_dir);
2704 :     }
2705 :    
2706 : olson 1.2 sub compare_scenario
2707 :     {
2708 :     my($genome,$superset,$ss_name,$scenario_name) = @_;
2709 :     my @genome_paths;
2710 : olson 1.13 my $scenario_dir_all = $fig->model_directory('All') . "/Scenarios/$superset/$ss_name/$scenario_name";
2711 : olson 1.2 my $subsystem = $fig->get_subsystem($ss_name);
2712 :     my @additional_reactions = @{$subsystem->get_hope_additional_reactions($scenario_name)};
2713 :     my %additional_reactions;
2714 :     map { $additional_reactions{$_} = 1 } @additional_reactions;
2715 :    
2716 : dejongh 1.4 my %ss_reactions;
2717 :    
2718 :     if ($genome eq "All")
2719 : olson 1.2 {
2720 : dejongh 1.4 my %all_reactions = %{$subsystem->get_hope_reactions};
2721 :     foreach my $role (keys %all_reactions)
2722 : olson 1.2 {
2723 : dejongh 1.4 map { $ss_reactions{$_} = 1 } @{$all_reactions{$role}};
2724 : olson 1.2 }
2725 :     }
2726 : dejongh 1.4 else
2727 : olson 1.2 {
2728 : dejongh 1.4 my $reactions_for_genome = $subsystem->get_hope_reactions_for_genome($genome);
2729 : dejongh 1.7 map { $ss_reactions{$_} = 1 } keys %{$reactions_for_genome} if defined $reactions_for_genome;
2730 : olson 1.2 }
2731 :    
2732 :     # first find paths in the All directory that should be valid for the genome
2733 :     # based on the reactions associated with it in the subsystems
2734 : olson 1.3 opendir (DIR_ALL,$scenario_dir_all) or die("cannot open directory $scenario_dir_all: $!");
2735 : olson 1.2 my @sub_dirs = readdir DIR_ALL; shift @sub_dirs; shift @sub_dirs; # get rid of . and ..
2736 :     close DIR_ALL;
2737 :    
2738 :     my %paths_all;
2739 :    
2740 :     for my $path (@sub_dirs)
2741 :     {
2742 :     my $match = 1;
2743 :     open (PATH, "$scenario_dir_all/$path/path_info");
2744 :     my @reactions = <PATH>;
2745 :     close PATH;
2746 :    
2747 :     my $reaction_string = "";
2748 :    
2749 :     foreach my $reaction (sort @reactions)
2750 :     {
2751 :     if ($reaction =~ /(R\d\d\d\d\d)/)
2752 :     {
2753 :     $reaction_string .= $reaction;
2754 :    
2755 :     if (! exists($ss_reactions{$1}) && ! exists($additional_reactions{$1}))
2756 :     {
2757 :     $match = 0;
2758 :     }
2759 :     }
2760 :     }
2761 :    
2762 :     $paths_all{$reaction_string} = $match;
2763 :     push @genome_paths, $path if $match;
2764 :     }
2765 :    
2766 :     # now check all paths found for this particular organism, and make sure they
2767 :     # are in the appropriate All subdirectory
2768 : olson 1.13 my $scenario_dir_genome = $fig->model_directory($genome). "/Scenarios/$superset/$ss_name/$scenario_name";
2769 : olson 1.2
2770 :     opendir (DIR_GENOME,$scenario_dir_genome) or die("$scenario_dir_genome");
2771 :     @sub_dirs = readdir DIR_GENOME; shift @sub_dirs; shift @sub_dirs; # get rid of . and ..
2772 :     close DIR_GENOME;
2773 :    
2774 :     my $path_counter = scalar keys %paths_all;
2775 :    
2776 :     for my $path (@sub_dirs)
2777 :     {
2778 :     my $match = 1;
2779 :     open (PATH, "$scenario_dir_genome/$path/path_info");
2780 :     my @reactions = <PATH>;
2781 :     close PATH;
2782 :    
2783 :     my $reaction_string = "";
2784 :    
2785 :     foreach my $reaction (sort @reactions)
2786 :     {
2787 :     if ($reaction =~ /(R\d\d\d\d\d)/)
2788 :     {
2789 :     $reaction_string .= $reaction;
2790 :     }
2791 :     }
2792 :    
2793 :     if (! exists($paths_all{$reaction_string}))
2794 :     {
2795 :     $path_counter++;
2796 :     my $new_path_name = "path_".$path_counter;
2797 :     my $temp_sdg = $scenario_dir_genome;
2798 :     $temp_sdg =~ s/\(/\\\(/g;
2799 :     $temp_sdg =~ s/\)/\\\)/g;
2800 :     my $temp_sda = $scenario_dir_all;
2801 :     $temp_sda =~ s/\(/\\\(/g;
2802 :     $temp_sda =~ s/\)/\\\)/g;
2803 :     `cp -R $temp_sdg/$path $temp_sda/$new_path_name`;
2804 :     push @genome_paths, $new_path_name;
2805 :     print "Copied $temp_sdg/$path to $temp_sda/$new_path_name\n";
2806 :     }
2807 : dejongh 1.5
2808 :     # remove genome-specific paths
2809 :     rmtree("$scenario_dir_genome/$path");
2810 : olson 1.2 }
2811 :    
2812 : dejongh 1.6 # create soft links for each genome-specific path, with the same name
2813 : dejongh 1.5 # as the path in the "All" directory
2814 : dejongh 1.6 foreach my $path (@genome_paths)
2815 :     {
2816 :     my $temp_sdg = $scenario_dir_genome;
2817 :     $temp_sdg =~ s/\(/\\\(/g;
2818 :     $temp_sdg =~ s/\)/\\\)/g;
2819 :     my $temp_sda = $scenario_dir_all;
2820 :     $temp_sda =~ s/\(/\\\(/g;
2821 :     $temp_sda =~ s/\)/\\\)/g;
2822 :     `ln -s $temp_sda/$path $temp_sdg`;
2823 :     }
2824 : olson 1.2
2825 :     return \@genome_paths;
2826 :     }
2827 :    
2828 : olson 1.1 sub write_scenario
2829 :     {
2830 :     my($scenario_data,$scenario_dir) = @_;
2831 :     delete $scenario_data->{"infinite"};
2832 :     my $path_count = 1;
2833 :     my @list_of_done_tokens=();
2834 :    
2835 :     print STDERR "Paths: ", keys %{$scenario_data}, "\n" if $debug;
2836 :    
2837 :     foreach my $try_path (keys %{$scenario_data})
2838 :     {
2839 :     print STDERR "\t Checking $try_path\n" if $debug;
2840 :     if($scenario_data->{$try_path}->[1] != 1)
2841 :     {
2842 :     print STDERR "\t Token $try_path is not complete\n" if $debug;
2843 :     next;
2844 :     }
2845 :     print STDERR "These are the contents of the list: " , @list_of_done_tokens, "\n" if $debug;
2846 :     if(scalar @list_of_done_tokens == 0){
2847 :     push @list_of_done_tokens, $try_path;
2848 :     next;
2849 :     }
2850 :    
2851 :     # Check this token's ($try_path) values against the values of the keys($elem) stored in
2852 :     # list_of_done_tokens. If they match, don't add it to the finished token list, if it doesn't
2853 :     # match, add it.
2854 :    
2855 :     print STDERR "These are the contents of the list: " , @list_of_done_tokens, "\n" if $debug;
2856 :    
2857 :     my $found_match = 0;
2858 :    
2859 :     foreach my $elem(@list_of_done_tokens){
2860 :     my @done_reactions = @{$scenario_data->{$elem}->[2]};
2861 :    
2862 :     print STDERR "This is the path we're trying: " , $try_path, "\t","This is the path already in the array: " , $elem , "\nThis is the size of the array: " . @list_of_done_tokens ."\n" if $debug;
2863 :    
2864 :     # if the list of reactions match, they represent the same path
2865 :    
2866 :     my @path_reactions = @{$scenario_data->{$try_path}->[2]};
2867 :     my (%diff_reactions_1, %diff_reactions_2);
2868 :    
2869 :     map {$diff_reactions_1{$_} = 1} @path_reactions;
2870 :     map {delete $diff_reactions_1{$_}} @done_reactions;
2871 :     map {$diff_reactions_2{$_} = 1} @done_reactions;
2872 :     map {delete $diff_reactions_2{$_}} @path_reactions;
2873 :    
2874 :     if (scalar keys %diff_reactions_1 == 0 && scalar keys %diff_reactions_2 == 0)
2875 :     {
2876 :     print STDERR "They match.\n" if $debug;
2877 :     $found_match = 1;
2878 :     last;
2879 :     }
2880 :     }
2881 :    
2882 :     if (! $found_match)
2883 :     {
2884 :     push @list_of_done_tokens, $try_path;
2885 :     print STDERR $try_path, " Added to the array\n" if $debug;
2886 :    
2887 :     }
2888 :     }
2889 :    
2890 :     foreach my $path (@list_of_done_tokens){
2891 :     if($scenario_data->{$path}->[1] != 1)
2892 :     {
2893 :     next;
2894 :     }
2895 :     if(@list_of_done_tokens == 0){
2896 :     push @list_of_done_tokens, $path;
2897 :     }
2898 :    
2899 :     #create input/output info
2900 :     my $input_hash = $scenario_data->{$path}->[7];
2901 :     my $output_hash = $scenario_data->{$path}->[8];
2902 :     my $reaction_path = $scenario_data->{$path}->[2];
2903 :     my @reaction_array = @$reaction_path;
2904 :    
2905 :     print STDERR "\nInputs:\n" if $debug;
2906 :     print STDERR map{"$_ => $input_hash->{$_}" } keys %$input_hash, "\n" if $debug;
2907 :     print STDERR "\nOutputs:\n" if $debug;
2908 :     print STDERR map{"$_ => $output_hash->{$_}"} keys %$output_hash, "\n" if $debug;
2909 :    
2910 :     # divide stoichiometry by greatest common denominator
2911 :     my ($min_stoich, @all_stoichs);
2912 :    
2913 :     map { push @all_stoichs, $input_hash->{$_}; $min_stoich = $input_hash->{$_} if $input_hash->{$_} < $min_stoich || $min_stoich == 0 } keys %{$input_hash};
2914 :     map { push @all_stoichs, $output_hash->{$_}; $min_stoich = $output_hash->{$_} if $output_hash->{$_} < $min_stoich || $min_stoich == 0 } keys %{$output_hash};
2915 :    
2916 :     my ($gcd, @gcd_candidates);
2917 :    
2918 :     outer: for ($gcd = $min_stoich; $gcd > 1; $gcd--)
2919 :     {
2920 :     foreach my $stoich (@all_stoichs)
2921 :     {
2922 :     next outer if $stoich % $gcd != 0;
2923 :     }
2924 :    
2925 :     last; # found a gcd
2926 :     }
2927 :    
2928 :     map { $input_hash->{$_} /= $gcd } keys %{$input_hash};
2929 :     map { $output_hash->{$_} /= $gcd } keys %{$output_hash};
2930 :    
2931 :     mkdir "$scenario_dir/path_$path_count";
2932 :    
2933 :     open(FILE, ">$scenario_dir/path_$path_count/path_info");
2934 :     foreach my $elem(@reaction_array){
2935 :     print FILE scalar @reaction_array, "\t", $elem, "\n";
2936 :     }
2937 :     close(FILE);
2938 :    
2939 :     &write_fluxanalyzer_files("$scenario_dir/path_$path_count",$input_hash,
2940 :     $output_hash, \@reaction_array,\%all_reactions,
2941 :     \%reactions_to_substrate_arrays,
2942 :     \%reactions_to_product_arrays,
2943 :     {});
2944 :     $path_count++;
2945 :     }
2946 :     @list_of_done_tokens=();
2947 :     undef %{$scenario_data};
2948 :    
2949 :     }
2950 :    
2951 :    
2952 :     sub load_subsystem
2953 :     {
2954 :     my ($genome,$ss_name) = @_;
2955 :     my $subsystem = $fig->get_subsystem($ss_name);
2956 :     my @ss_scenarios = $subsystem->get_hope_scenario_names;
2957 :     foreach my $name (@ss_scenarios)
2958 :     {
2959 :     load_scenario($genome,$ss_name,$name);
2960 :     }
2961 :     }
2962 :    
2963 :     sub internal_subsystem
2964 :     {
2965 :     my ($genome,$ss_name,$find_first) = @_;
2966 :     my %scenario_to_paths;
2967 :    
2968 :     my $subsystem = $fig->get_subsystem($ss_name);
2969 :     my @ss_scenarios = $subsystem->get_hope_scenario_names;
2970 :    
2971 :     foreach my $name (@ss_scenarios)
2972 :     {
2973 :     $scenario_to_paths{$name} = internal_scenario($genome,$ss_name,$name,$find_first);
2974 :     }
2975 :    
2976 :     return \%scenario_to_paths;
2977 :     }
2978 :    
2979 :     sub run_subsystem
2980 :     {
2981 :     my ($genome,$superset,$subsystem,$find_first) = @_;
2982 :    
2983 :     my $subsystem_obj = $fig->get_subsystem($subsystem);
2984 : olson 1.10
2985 :     if (!$subsystem_obj)
2986 :     {
2987 :     warn "Cannot open subsystem $subsystem\n";
2988 :     return;
2989 :     }
2990 :    
2991 : olson 1.1 my @ss_scenarios = $subsystem_obj->get_hope_scenario_names;
2992 : olson 1.10
2993 : olson 1.13 my $dir = $fig->model_directory($genome) . "/Scenarios/$superset/$subsystem";
2994 : olson 1.10 system("rm", "-rf", $dir);
2995 :     &FIG::verify_dir($dir);
2996 : olson 1.1
2997 :     foreach my $name (@ss_scenarios)
2998 :     {
2999 :     run_scenario($genome,$superset,$subsystem,$name,$find_first);
3000 :     }
3001 :     }
3002 :    
3003 : olson 1.2 sub compare_subsystem
3004 :     {
3005 :     my ($genome,$superset,$subsystem) = @_;
3006 :     my %genome_scenarios;
3007 :    
3008 :     my $subsystem_obj = $fig->get_subsystem($subsystem);
3009 : olson 1.11
3010 :     if (!$subsystem_obj)
3011 :     {
3012 :     warn "Cannot open subsystem $subsystem\n";
3013 :     return;
3014 :     }
3015 :    
3016 :    
3017 : olson 1.2 my @ss_scenarios = $subsystem_obj->get_hope_scenario_names;
3018 :    
3019 :     foreach my $name (@ss_scenarios)
3020 :     {
3021 :     $genome_scenarios{$name} = compare_scenario($genome,$superset,$subsystem,$name);
3022 :     }
3023 :    
3024 :     return \%genome_scenarios;
3025 :     }
3026 :    
3027 : olson 1.1 sub load_superset
3028 :     {
3029 :     my($genome, $superset_name) = @_;
3030 :    
3031 :     my @subsystems = @{$superset_to_ss{$superset_name}};
3032 :     foreach my $ss_name (@subsystems)
3033 :     {
3034 :     load_subsystem($genome,$ss_name);
3035 :     }
3036 :     }
3037 :    
3038 :     sub internal_superset
3039 :     {
3040 :     my($genome, $superset_name,$find_first) = @_;
3041 :    
3042 :     my @subsystems = @{$superset_to_ss{$superset_name}};
3043 :    
3044 :     my %supersets_data;
3045 :    
3046 :     foreach my $ss_name (@subsystems)
3047 :     {
3048 :     $supersets_data{$ss_name} = internal_subsystem($genome,$ss_name,$find_first);
3049 :     }
3050 :    
3051 :     return \%supersets_data;
3052 :     }
3053 :    
3054 :     sub run_superset
3055 :     {
3056 :     my($genome, $superset_name,$find_first) = @_;
3057 :    
3058 :     my @subsystems = @{$superset_to_ss{$superset_name}};
3059 :    
3060 : olson 1.10
3061 : olson 1.13 my $dir = $fig->model_directory($genome) . "/Scenarios/$superset_name";
3062 : olson 1.10 system("rm", "-rf", $dir);
3063 :     &FIG::verify_dir($dir);
3064 : olson 1.1
3065 :     foreach my $ss_name (@subsystems)
3066 :     {
3067 :     print STDERR "Running Scenarios for subsystem $ss_name\n";
3068 :     run_subsystem($genome,$superset_name,$ss_name,$find_first);
3069 :     }
3070 :     }
3071 :    
3072 : olson 1.2 sub compare_superset
3073 :     {
3074 :     my($genome, $superset_name) = @_;
3075 :    
3076 :     my @subsystems = @{$superset_to_ss{$superset_name}};
3077 :     my %genome_subsystems;
3078 :    
3079 :     foreach my $ss_name (@subsystems)
3080 :     {
3081 :     print STDERR "Comparing Scenarios for $genome in subsystem $ss_name\n";
3082 :     $genome_subsystems{$ss_name} = compare_subsystem($genome,$superset_name,$ss_name);
3083 :     }
3084 :    
3085 :     return \%genome_subsystems;
3086 :     }
3087 :    
3088 : olson 1.1
3089 :     sub load_supersets
3090 :     {
3091 :     my($genome) = @_;
3092 :     foreach my $superset (keys %superset_to_ss)
3093 :     {
3094 :     load_superset($genome,$superset);
3095 :     }
3096 :    
3097 :     return (\%all_reactions,\%reactions_to_substrate_arrays,\%reactions_to_product_arrays);
3098 :    
3099 :     }
3100 :    
3101 :     sub run_supersets
3102 :     {
3103 :     my($genome,$find_first) = @_;
3104 :    
3105 :     foreach my $superset (keys %superset_to_ss)
3106 :     {
3107 :     run_superset($genome,$superset,$find_first);
3108 :     }
3109 :    
3110 :     }
3111 :    
3112 : olson 1.2 sub compare_supersets
3113 :     {
3114 :     my($genome) = @_;
3115 :     my %genome_supersets;
3116 :    
3117 :     foreach my $superset (keys %superset_to_ss)
3118 :     {
3119 :     $genome_supersets{$superset} = compare_superset($genome,$superset);
3120 :     }
3121 :    
3122 :     return \%genome_supersets;
3123 :     }
3124 :    
3125 : olson 1.1 sub run_genome_report
3126 :     {
3127 :     my ($genome) = @_;
3128 :     my @string_out;
3129 :     push @string_out,"Genome $genome\n";
3130 :     #get all the subsystems this genome is involved in
3131 :     foreach my $superset (keys %superset_to_ss)
3132 :     {
3133 :     foreach my $name (@{$superset_to_ss{$superset}})
3134 :     {
3135 :     push @string_out, @{print_ss_report($name,internal_subsystem($genome,$name,0))};
3136 :     }
3137 :     }
3138 :     return \@string_out;
3139 :     }
3140 :    
3141 :     sub print_ss_report
3142 :     {
3143 :     my ($ss_name,$scenario_to_paths) = @_;
3144 :     my @output = ();
3145 :     my %scenario_path_count;
3146 :    
3147 :     push(@output,"\tSubsystem $ss_name\n");
3148 :    
3149 :     foreach my $scenario (keys %$scenario_to_paths)
3150 :     {
3151 :     if($scenario_to_paths->{$scenario}->{"infinite"})
3152 :     {
3153 :     push(@output,"\tWarning: Possible Infinite loop\n");
3154 :     }
3155 :     delete $scenario_to_paths->{$scenario}->{"infinite"};
3156 :     foreach my $token (keys %{$scenario_to_paths->{$scenario}})
3157 :     {
3158 :     $scenario_path_count{$scenario}++ if ($scenario_to_paths->{$scenario}->{$token}->[1]);
3159 :     }
3160 :     }
3161 :    
3162 :     push @output , map { "\t\t$_ has $scenario_path_count{$_} path(s).\n" } keys %scenario_path_count;
3163 :    
3164 :     return \@output;
3165 :     }
3166 :    
3167 :    
3168 :     sub internal_assembly
3169 :     {
3170 :     #lets get the genome, and a array reference to the paths we want to build togather
3171 :     my ($paths,$input_path,$output_path,$one_path) = @_;
3172 :    
3173 :    
3174 : olson 1.2 print STDERR $paths."\n" if $debug;
3175 : olson 1.1 clear_arrays();
3176 :    
3177 :     #This gets us an array of arrays, each subarray holds
3178 : dejongh 1.12 # [0] = genome [1] = Scenarios [2] = superset [3] = subsystem [4] = scenario [5] = path
3179 : olson 1.1 # OR [0] = genome [1] = assembly [2] = path_name
3180 :     my @assembly_scenarios = @{parse_assembly_scenarios($paths)};
3181 :    
3182 :     #split and the input/output path for later as well
3183 :     #these should only return one path array...so just grab that one
3184 :     my @input_arr;
3185 :     my @output_arr;
3186 :    
3187 :     if($input_path != undef && $output_path != undef )
3188 :     {
3189 :     @input_arr = @{parse_assembly_scenarios($input_path)};
3190 :     @output_arr = @{parse_assembly_scenarios($output_path)};
3191 :     }
3192 :    
3193 :     #load all the kegg information for each 'scenario' from the paths we have selected
3194 :     foreach my $scenario (@assembly_scenarios)
3195 :     {
3196 : dejongh 1.12 if(scalar @$scenario > 5) #this is a normal scenario path
3197 : olson 1.1 {
3198 : dejongh 1.12 print STDERR "Checking $scenario->[3] $scenario->[4] $scenario->[5] \n" if $debug;
3199 :     process_init($scenario->[3],$scenario->[4],$scenario->[0],1);
3200 : olson 1.1 }
3201 :     else #This is a assembly path
3202 :     {
3203 :     #read in the input/output compounds and mark main's correctly
3204 : olson 1.13 my $path = $fig->model_directory() . "/" . join "/" , @$scenario;
3205 : olson 1.1
3206 :     open(M_IN,"$path/inputs_main");
3207 :     while(<M_IN>)
3208 :     {
3209 :     my @line = split(/\t/,$_);
3210 :     $all_compounds_to_main{$line[0]} = $line[1];
3211 :     }
3212 :     close(M_IN);
3213 :    
3214 :     open(M_OUT,"$path/outputs_main");
3215 :     while(<M_OUT>)
3216 :     {
3217 :     my @line = split(/\t/,$_);
3218 :     $all_compounds_to_main{$line[0]} = $line[1];
3219 :     }
3220 :     close(M_OUT);
3221 :     }
3222 :     }
3223 :     #assume all path inputs and outputs are main
3224 :     map { $all_compounds_to_main{$_} = 1 } keys %all_inputs;
3225 :     map { $all_compounds_to_main{$_} = 1 } keys %all_outputs;
3226 :    
3227 :     print STDERR "Inputs: " if $debug;
3228 : olson 1.2 print STDERR map { $_."\n" } keys %all_inputs if $debug;
3229 : olson 1.1 print STDERR "Outputs: " if $debug;
3230 : olson 1.2 print STDERR map { $_."\n" } keys %all_outputs if $debug;
3231 : olson 1.1
3232 :     #run process paths
3233 :     return execute_paths(\@assembly_scenarios,$one_path,\@input_arr,\@output_arr);
3234 :     }
3235 :    
3236 :     sub run_assembly
3237 :     {
3238 :     my ($paths,$genome,$write_name,$one_path) = @_;
3239 :     print STDERR "\nThis is the passed information.\n";
3240 :     print STDERR $paths , "\n" , @$paths, "\n";
3241 :     print STDERR $genome . "\n";
3242 :     print STDERR $write_name . "\n";
3243 : olson 1.13 my $dir = $fig->model_directory($genome) . "/Assemblies/$write_name";
3244 : olson 1.10 system("rm", "-rf", $dir);
3245 :     &FIG::verify_dir($dir);
3246 :     write_scenario(internal_assembly($paths,[],[],$one_path),$dir);
3247 : olson 1.1 }
3248 :    
3249 :     sub expand_paths
3250 :     {
3251 :     my ($paths) = @_;
3252 :    
3253 :     my @final_paths;
3254 :    
3255 :     foreach my $path (@$paths)
3256 :     {
3257 :     if($path eq "" || $path eq "//")
3258 :     {
3259 :     next;
3260 :     }
3261 : dejongh 1.12 my $length = 6;
3262 :     if($path =~ /Assemblies/)
3263 : olson 1.1 {
3264 :     $length = 4;
3265 :     }
3266 :     print STDERR "Expanding $path \n" if $debug;
3267 :     my @parts = split "/", $path;
3268 :     shift @parts; # get ride of the first blank entry from /$genome
3269 :     my $length =$length - scalar @parts;
3270 :     $path = join "/" , @parts;
3271 :     print "Length : $length Path: $path\n" if $debug;
3272 :     my @temp = @{expand_recursive($path, $length)};
3273 :     push @final_paths , @temp if scalar @temp > 0;
3274 :     }
3275 :    
3276 :    
3277 :     return \@final_paths;
3278 :     }
3279 :    
3280 :     sub expand_recursive
3281 :     {
3282 :     my ($path,$count) = @_;
3283 :     my @sub_dirs;
3284 : dejongh 1.12 if($path =~ m\Assemblies$\ || $path =~ m\Analysis$\)
3285 : olson 1.1 {
3286 :     return [];
3287 :     }
3288 :     if($count !=0)
3289 :     {
3290 :     #read this path, and pull out all the sub-directories.
3291 : olson 1.13 my $model_dir = $fig->model_directory() . "/$path/";
3292 : olson 1.10
3293 :     print STDERR "reading directory $model_dir\n" if $debug;
3294 : formsma 1.16 opendir (DIR, $model_dir) or die("$model_dir");
3295 : olson 1.10 print STDERR "reading directory $model_dir\n" if $debug;
3296 : olson 1.1 @sub_dirs = readdir DIR; shift @sub_dirs; shift @sub_dirs; # get rid of . and ..
3297 :     close DIR;
3298 :     print STDERR "Found: " if $debug;
3299 :     print STDERR @sub_dirs , "," if $debug;
3300 :     }
3301 :     else
3302 :     {
3303 :    
3304 :     return [$path];
3305 :     }
3306 :     $count--;
3307 :     my @to_return;
3308 :     foreach my $sub_path (@sub_dirs)
3309 :     {
3310 :     print STDERR "Calling on $sub_path , $count \n" if $debug;
3311 :     push @to_return , @{expand_recursive("$path/$sub_path",$count)};
3312 :     }
3313 :     print STDERR "Returning" ,@to_return if $debug;
3314 :     return \@to_return;
3315 :    
3316 :     }
3317 :    
3318 :     sub parse_assembly_scenarios
3319 :     {
3320 :     my ($paths) = @_;
3321 :    
3322 :     $paths = expand_paths($paths);
3323 :     my @array_of_path_arrays;
3324 :    
3325 :     foreach my $path (@$paths)
3326 :     {
3327 :     my @parts = split "/", $path;
3328 :     #shift @parts;
3329 :     push(@array_of_path_arrays, \@parts);
3330 :     }
3331 :    
3332 :     return \@array_of_path_arrays;
3333 :     }
3334 :    
3335 :    
3336 :     sub write_selected_scenarios
3337 :     {
3338 :     my($checked,$genome,$ssa,$sc_name) = @_;
3339 :     my (@tempArray);
3340 :    
3341 :     #Load this scenario again with all of its rxns and cpds
3342 :    
3343 :     model::clear_arrays();
3344 :    
3345 :     model::process_init($ssa,$sc_name,$genome,0);
3346 :    
3347 :     #assume all path inputs and outputs are main
3348 :     map { $all_compounds_to_main{$_} = 1 } keys %all_inputs;
3349 :     map { $all_compounds_to_main{$_} = 1 } keys %all_outputs;
3350 :    
3351 :     model::create_reactions({},{},{},{});
3352 :    
3353 :     ##End of scenario loading
3354 :    
3355 :    
3356 :     #setup the filesystem to store the scenario/paths
3357 :     my $superset = $ss_to_superset{$ssa};
3358 : olson 1.13 my $base_dir = $fig->model_directory($genome) . "/Scenarios/$superset/$ssa/$sc_name/";
3359 : olson 1.2 system("rm", "-rf", $base_dir);
3360 : olson 1.10 &FIG::verify_dir($base_dir);
3361 : olson 1.1
3362 :     #for the selected paths, lets gather their cpd from the checkbox and write
3363 :     #the path that we need
3364 :     foreach my $path (@$checked)
3365 :     {
3366 :     my (%input_hash, %output_hash, $path_name);
3367 :     #process the strings to get the information from the parameters
3368 :     my @items = split(";", $path);
3369 :     $path_name = $items[0];
3370 :     #next we have the input compounds ids/stoich/main
3371 :     map { if ($_ =~ /(.*):(.*):(.*)/)
3372 :     { $input_hash{$1}+= $2 } } split ",", $items[1];
3373 :     #the third part has the output compounds ids/stoich/main
3374 :     map { if ($_ =~ /(.*):(.*):(.*)/)
3375 :     { $output_hash{$1} += $2 } } split ",",$items[2];
3376 :     #the fourth part has the strings of reactions visited
3377 :     @tempArray = split("#" , $items[3]);
3378 :    
3379 :    
3380 :     print STDERR "\nInputs:\n" if $debug;
3381 :     print STDERR map{"$_ => $input_hash{$_}" } keys %input_hash, "\n" if $debug;
3382 :     print STDERR "\nOutputs:\n" if $debug;
3383 :     print STDERR map{"$_ => $output_hash{$_}"} keys %output_hash, "\n" if $debug;
3384 :    
3385 :    
3386 :     # divide stoichiometry by greatest common denominator
3387 :     my ($min_stoich, @all_stoichs);
3388 :    
3389 :     map { push @all_stoichs, $input_hash{$_}; $min_stoich = $input_hash{$_} if $input_hash{$_} < $min_stoich || $min_stoich == 0 } keys %input_hash;
3390 :     map { push @all_stoichs, $output_hash{$_}; $min_stoich = $output_hash{$_} if $output_hash{$_} < $min_stoich || $min_stoich == 0 } keys %output_hash;
3391 :    
3392 :     my ($gcd, @gcd_candidates);
3393 :    
3394 :     outer: for ($gcd = $min_stoich; $gcd > 1; $gcd--)
3395 :     {
3396 :     foreach my $stoich (@all_stoichs)
3397 :     {
3398 :     next outer if $stoich % $gcd != 0;
3399 :     }
3400 :    
3401 :     last; # found a gcd
3402 :     }
3403 :    
3404 :     map { $input_hash{$_} /= $gcd } keys %input_hash;
3405 :     map { $output_hash{$_} /= $gcd } keys %output_hash;
3406 :    
3407 :     mkdir "$base_dir/$path_name";
3408 :     &write_fluxanalyzer_files("$base_dir/$path_name",\%input_hash,
3409 :     \%output_hash,\@tempArray,\%all_reactions,
3410 :     \%reactions_to_substrate_arrays,
3411 :     \%reactions_to_product_arrays,
3412 :     {});
3413 :     }
3414 :     return $base_dir;
3415 :     }
3416 :    
3417 :     #This write function assumes that we have just run a assembly (and we haven't cleared the arrays)
3418 :     # becuase the write_fluxanalyzer_files function is depended on those global arrays for the reactions.
3419 :    
3420 :     sub write_assembly
3421 :     {
3422 :     my($input,$genome,$name) = @_;
3423 :    
3424 :     my $paths = $input->[1];
3425 :     my $file_paths = $input->[0];
3426 :     print STDERR "Paths: @$paths \n File_Dirs: @$file_paths \n" if $debug;
3427 :     my @tempArray;
3428 :    
3429 :     chomp $genome;
3430 :     chomp $name;
3431 :     #setup the filesystem to store the assembly
3432 : olson 1.13 my $base_dir = $fig->model_directory($genome). "/Assemblies/$name";
3433 : olson 1.10 system("rm", "-rf", $base_dir);
3434 :     &FIG::verify_dir($base_dir);
3435 :    
3436 : olson 1.1
3437 :     ##Here we want to reload the cpd and rxn info so we can write it later
3438 :     clear_arrays();
3439 :    
3440 :     #This gets us an array of arrays, each subarray holds
3441 : dejongh 1.12 # [0] = genome [1] = Scenarios [2] = superset [3] = subsystem [4] = scenario [5] = path
3442 : olson 1.1 my @assembly_scenarios = @{parse_assembly_scenarios($file_paths)};
3443 :    
3444 :     #load all the kegg information for each 'scenario' from the paths we have selected
3445 :     foreach my $scenario (@assembly_scenarios)
3446 :     {
3447 : dejongh 1.12 print STDERR "Checking $scenario->[3] $scenario->[4] $scenario->[5] \n" if $debug;
3448 :     process_init($scenario->[3],$scenario->[4],$scenario->[0],1);
3449 : olson 1.1 }
3450 :     #assume all path inputs and outputs are main
3451 :     map { $all_compounds_to_main{$_} = 1 } keys %all_inputs;
3452 :     map { $all_compounds_to_main{$_} = 1 } keys %all_outputs;
3453 :    
3454 :     create_assembly_reactions({},{},{},{});
3455 :    
3456 :     ##End of rxn,cpd loading
3457 :    
3458 :     #for the selected paths, lets gather their cpd from the checkbox and write
3459 :     #the path that we need
3460 :     foreach my $path (@$paths)
3461 :     {
3462 :     my (%input_hash, %output_hash, $path_name);
3463 :     #process the strings to get the information from the parameters
3464 :     my @items = split(";", $path);
3465 :     $path_name = $items[0];
3466 :     #next we have the input compounds ids/stoich/main
3467 :     map { if ($_ =~ /(.*):(.*):(.*)/)
3468 :     { $input_hash{$1}+= $2 } } split ",", $items[1];
3469 :     #the third part has the output compounds ids/stoich/main
3470 :     map { if ($_ =~ /(.*):(.*):(.*)/)
3471 :     { $output_hash{$1} += $2 } } split ",",$items[2];
3472 :     #the fourth part has the strings of reactions visited
3473 :     @tempArray = split("#" , $items[3]);
3474 :    
3475 :     print STDERR "\nInputs:\n" if $debug;
3476 :     print STDERR map{"$_ => $input_hash{$_}" } keys %input_hash, "\n" if $debug;
3477 :     print STDERR "\nOutputs:\n" if $debug;
3478 :     print STDERR map{"$_ => $output_hash{$_}"} keys %output_hash, "\n" if $debug;
3479 :    
3480 :     # divide stoichiometry by greatest common denominator
3481 :     my ($min_stoich, @all_stoichs);
3482 :    
3483 :     map { push @all_stoichs, $input_hash{$_}; $min_stoich = $input_hash{$_} if $input_hash{$_} < $min_stoich || $min_stoich == 0 } keys %input_hash;
3484 :     map { push @all_stoichs, $output_hash{$_}; $min_stoich = $output_hash{$_} if $output_hash{$_} < $min_stoich || $min_stoich == 0 } keys %output_hash;
3485 :    
3486 :     my ($gcd, @gcd_candidates);
3487 :    
3488 :     outer: for ($gcd = $min_stoich; $gcd > 1; $gcd--)
3489 :     {
3490 :     foreach my $stoich (@all_stoichs)
3491 :     {
3492 :     next outer if $stoich % $gcd != 0;
3493 :     }
3494 :    
3495 :     last; # found a gcd
3496 :     }
3497 :    
3498 :     map { $input_hash{$_} /= $gcd } keys %input_hash;
3499 :     map { $output_hash{$_} /= $gcd } keys %output_hash;
3500 :    
3501 :     print STDERR "Making directory $base_dir" if $debug;
3502 :    
3503 :    
3504 :     mkdir "$base_dir/$path_name";
3505 :     &write_fluxanalyzer_files("$base_dir/$path_name",\%input_hash,\%output_hash,
3506 :     \@tempArray,\%all_reactions,
3507 :     \%reactions_to_substrate_arrays,
3508 :     \%reactions_to_product_arrays,
3509 :     {});
3510 :     }
3511 :     }
3512 :    
3513 :     sub show_path_results
3514 :     {
3515 :     my ($data_results,$html,$cgi) = @_;
3516 :    
3517 :     print STDERR "Starting Results Display\n";
3518 :    
3519 :    
3520 :     #Display infinite loop warning if the indicator is on
3521 :     if($data_results->{"infinite"})
3522 :     {
3523 :     push(@$html, "<h3>Warning: Looks like an infinite loop</h3>");
3524 :     }
3525 :    
3526 :     #Delete the infinite loop indicator, so we don't need to have a if statment to check for it
3527 :     delete $data_results->{"infinite"};
3528 :    
3529 :     my $path_counter = 1;
3530 :     my $reactionPath;
3531 :     foreach my $token_id (sort { $data_results->{$a}->[1] <=> $data_results->{$b}->[1] }keys %$data_results)
3532 :     {
3533 :     print STDERR "Token id : $token_id\n";
3534 :    
3535 :     if(!($token_id =~ /^\d/))
3536 :     {
3537 :     next;
3538 :     }
3539 :    
3540 :     my @path = @{$data_results->{$token_id}->[2]};
3541 :     my @compounds = @{$data_results->{$token_id}->[3]};
3542 :    
3543 :     push(@$html, "<pre>Token: $token_id\tInitial Pass: $data_results->{$token_id}->[0]\tDone:$data_results->{$token_id}->[1]\n\tReactions: @path\n\tVisted Compounds: @compounds\n\tPath Inputs\n@{$data_results->{$token_id}->[4]}\n\tPath Outputs\n@{$data_results->{$token_id}->[5]}\n\tBorrowed\n@{$data_results->{$token_id}->[6]}\n</pre>");
3544 :    
3545 :    
3546 :     if ($data_results->{$token_id}->[1] == 1)
3547 :     {
3548 :     my $path_name = "path_".$path_counter++;
3549 :     my @tempArray;
3550 :     foreach my $elem(@{$data_results->{$token_id}->[2]}){
3551 :     push @tempArray, $elem;
3552 :     }
3553 :     $reactionPath = join "#", @tempArray;
3554 :     my $checkbox=$cgi->checkbox(-name=>"$path_name", -label=>'',
3555 :     -value=>"$path_name;@{[ join ',', map { $_ . ':' . $data_results->{$token_id}->[7]->{$_} . ':' . $all_compounds_to_main{$_} } keys %{$data_results->{$token_id}->[7]} ]};@{[ join ',', map { $_ . ':' . $data_results->{$token_id}->[8]->{$_} . ':' . $all_compounds_to_main{$_} } keys %{$data_results->{$token_id}->[8]} ]};$reactionPath");
3556 :     push @$html, $checkbox, "&nbsp;$path_name", $cgi->br;
3557 :     }
3558 :    
3559 :     push @$html, "<hr>";
3560 :    
3561 :    
3562 :     }
3563 :    
3564 :    
3565 :     push @$html, $cgi->hidden(-name=>'reaction_info',
3566 :     -value=>$reactionPath);
3567 :    
3568 :     }
3569 :    
3570 :     sub show_path_results_two
3571 :     {
3572 :     my ($data_results,$html,$cgi) = @_;
3573 :    
3574 :     print STDERR "Starting Results Display\n";
3575 :    
3576 :    
3577 :     #Display infinite loop warning if the indicator is on
3578 :     if($data_results->{"infinite"})
3579 :     {
3580 :     push(@$html, "<h3>Warning: Looks like an infinite loop</h3>");
3581 :     }
3582 :    
3583 :     #Delete the infinite loop indicator, so we don't need to have a if statment to check for it
3584 :     delete $data_results->{"infinite"};
3585 :    
3586 :     my $path_counter = 1;
3587 :     my $reactionPath;
3588 :     foreach my $token_id (sort { $data_results->{$a}->[1] <=> $data_results->{$b}->[1] }keys %$data_results)
3589 :     {
3590 :     print STDERR "Token id : $token_id\n";
3591 :    
3592 :     if(!($token_id =~ /^\d/))
3593 :     {
3594 :     next;
3595 :     }
3596 :    
3597 :     my @path = @{$data_results->{$token_id}->[2]};
3598 :     my @compounds = @{$data_results->{$token_id}->[3]};
3599 :    
3600 :     push(@$html, "<pre>Token: $token_id\tInitial Pass: $data_results->{$token_id}->[0]\tDone:$data_results->{$token_id}->[1]\n\tReactions: @path\n\tVisted Compounds: @compounds\n\tPath Inputs\n@{$data_results->{$token_id}->[4]}\n\tPath Outputs\n@{$data_results->{$token_id}->[5]}\n\tBorrowed\n@{$data_results->{$token_id}->[6]}\n</pre>");
3601 :    
3602 :    
3603 :     if ($data_results->{$token_id}->[1] == 1)
3604 :     {
3605 :     my $path_name = "path_".$path_counter++;
3606 :     my @tempArray;
3607 :     foreach my $elem(@{$data_results->{$token_id}->[2]}){
3608 :     push @tempArray, $elem;
3609 :     }
3610 :     $reactionPath = join "#", @tempArray;
3611 :     my $checkbox=$cgi->checkbox(-name=>"checked", -label=>'',
3612 :     -value=>"$path_name;@{[ join ',', map { $_ . ':' . $data_results->{$token_id}->[7]->{$_} . ':' . $all_compounds_to_main{$_} } keys %{$data_results->{$token_id}->[7]} ]};@{[ join ',', map { $_ . ':' . $data_results->{$token_id}->[8]->{$_} . ':' . $all_compounds_to_main{$_} } keys %{$data_results->{$token_id}->[8]} ]};$reactionPath");
3613 :     push @$html, $checkbox, "&nbsp;$path_name", $cgi->br;
3614 :     }
3615 :    
3616 :     push @$html, "<hr>";
3617 :     }
3618 :    
3619 :     }
3620 :    
3621 :    
3622 :     sub set_loop_max
3623 :     {
3624 :     my ($number) = @_;
3625 :     $loop_max = $number;
3626 :     }
3627 :    
3628 :     sub set_loop_max_assembly
3629 :     {
3630 :     my ($number) = @_;
3631 :     $loop_max_assembly = $number;
3632 :     }
3633 :    
3634 : dejongh 1.8 sub analyze_scenario_connections
3635 :     {
3636 :     my ($genome_id) = @_;
3637 : olson 1.13 my $scenario_dir = $fig->model_directory($genome_id)."/Scenarios";
3638 :    
3639 :     #
3640 :     # Mac and Linux don't have the same find options for following symlinks.
3641 :     #
3642 :     my $uname = `uname`;
3643 :     my @paths;
3644 :     if ($uname =~ /^Darwin/)
3645 :     {
3646 :     @paths = `find -L $scenario_dir -type d -name "path_*"`;
3647 :     }
3648 :     else
3649 :     {
3650 :     @paths = `find $scenario_dir -follow -type d -name "path_*"`;
3651 :     }
3652 : olson 1.1
3653 : dejongh 1.8 my %inputs;
3654 :     my %outputs;
3655 : olson 1.1
3656 : dejongh 1.12 foreach my $dir (@paths)
3657 : dejongh 1.8 {
3658 : dejongh 1.12 chomp $dir;
3659 : dejongh 1.8 my ($cat, $subsys, $scenario);
3660 : olson 1.1
3661 : dejongh 1.12 print STDERR "Processing $dir\n";
3662 :    
3663 :     if ($dir =~ (/$genome_id\/Scenarios\/(.*)\/(.*)\/(.*)\//)){
3664 : dejongh 1.8 $cat = $1;
3665 :     $subsys = $2;
3666 :     $scenario = $3;
3667 :     }
3668 :     else
3669 :     {
3670 :     next;
3671 :     }
3672 : olson 1.1
3673 : dejongh 1.8 open(M_INPUTS,$dir."/inputs_main") or die("Failed to open $dir/inputs_main");
3674 :    
3675 :     while (<M_INPUTS>)
3676 :     {
3677 :     chomp;
3678 :     my ($cpd, $main) = split "\t" , $_;
3679 :     my $info = join "\t", $subsys, $scenario;
3680 :     $inputs{$cpd}->{$info} = 1 if $main eq "1";
3681 :     }
3682 :     close M_INPUTS;
3683 :    
3684 :     open(M_OUTPUTS, $dir."/outputs_main");
3685 :    
3686 :     while (<M_OUTPUTS>)
3687 :     {
3688 :     chomp;
3689 :     my ($cpd, $main) = split "\t" , $_;
3690 :     my $info = join "\t", $subsys, $scenario;
3691 :     $outputs{$cpd}->{$info} = 1 if $main eq "1";
3692 :     }
3693 :     close M_OUTPUTS;
3694 : dejongh 1.12 }
3695 : dejongh 1.8
3696 : olson 1.13 my $analysis_dir = $fig->model_directory($genome_id) . "/Analysis";
3697 : formsma 1.15 #Commented out. was deleting model data from run_model_generation
3698 :     #rmtree $analysis_dir;
3699 : dejongh 1.12 mkdir $analysis_dir;
3700 : dejongh 1.8
3701 : dejongh 1.12 open (IN_CONN, ">$analysis_dir/inputs_to_scenarios");
3702 :     foreach my $cpd (sort keys %inputs)
3703 :     {
3704 :     map { print IN_CONN "$cpd\t$_\n"; } keys %{$inputs{$cpd}};
3705 :     }
3706 :     close IN_CONN;
3707 : dejongh 1.8
3708 : dejongh 1.12 open (OUT_CONN, ">$analysis_dir/outputs_to_scenarios");
3709 :     foreach my $cpd (sort keys %outputs)
3710 :     {
3711 :     map { print OUT_CONN "$cpd\t$_\n"; } keys %{$outputs{$cpd}};
3712 : dejongh 1.8 }
3713 : dejongh 1.12 close OUT_CONN;
3714 : olson 1.1 }
3715 :    
3716 : formsma 1.14 sub predict_pegs_used
3717 :     {
3718 :     my ($genome_id) = @_;
3719 :     my @scenarios = @{Scenario->get_genome_scenarios("All",1)};
3720 :     unless(scalar(@scenarios))
3721 :     {
3722 :     return undef;
3723 :     }
3724 :     my %reaction_to_pegs;
3725 :     my $ss_file = "$FIG_Config::global/Models/hope_supersets.txt";
3726 :    
3727 :     my @ss_names;
3728 :     my %superset_to_ss = %{model::load_superset_file($ss_file)};
3729 :     foreach (keys %superset_to_ss)
3730 :     {
3731 :     foreach my $subsys (@{$superset_to_ss{$_}})
3732 :     {
3733 :     push @ss_names, $subsys;
3734 :     }
3735 :    
3736 :     }
3737 :     foreach my $subsystem_name(@ss_names)
3738 :     {
3739 :     my $subsystem = $fig->get_subsystem($subsystem_name);
3740 :     next if(!defined $subsystem);
3741 :     my $reactions_for_ss = $subsystem->get_hope_reactions_for_genome($genome_id);
3742 :     next if(!defined $reactions_for_ss);
3743 :     foreach my $reaction (keys %$reactions_for_ss)
3744 :     {
3745 :     if(defined $reaction_to_pegs{$reaction})
3746 :     {
3747 :     push @{$reaction_to_pegs{$reaction}} , @{$reactions_for_ss->{$reaction}};
3748 :     }
3749 :     else
3750 :     {
3751 :     $reaction_to_pegs{$reaction} = $reactions_for_ss->{$reaction};
3752 :     }
3753 :     }
3754 :     }
3755 :    
3756 :     my %peg_to_scenario;
3757 :     foreach my $scenario (@scenarios)
3758 :     {
3759 :     my @scenario_reactions = @{$scenario->get_reaction_ids};
3760 :     my $path_valid = 1;
3761 :     my %pegs;
3762 :     foreach my $reaction (@scenario_reactions)
3763 :     {
3764 :     if(!defined $reaction_to_pegs{$reaction})
3765 :     {
3766 :     $path_valid = 0;
3767 :     last;
3768 :     }
3769 :     else
3770 :     {
3771 :     map {$pegs{$_} = 1} @{$reaction_to_pegs{$reaction}};
3772 :     }
3773 :     }
3774 :     if($path_valid)
3775 :     {
3776 :     foreach my $peg (keys %pegs)
3777 :     {
3778 :     if(!defined $peg_to_scenario{$peg})
3779 :     {
3780 :     $peg_to_scenario{$peg} = [$scenario->get_id()];
3781 :     }
3782 :     else
3783 :     {
3784 :     push @{$peg_to_scenario{$peg}} , $scenario->get_id();
3785 :     }
3786 :     }
3787 :     }
3788 :     }
3789 :    
3790 :     return \%peg_to_scenario;
3791 :     }
3792 : olson 1.1 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3