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

Annotation of /FigKernelPackages/model.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3