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

Annotation of /FigKernelPackages/model.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3