1 | # _________________________________________________________________________ |
---|
2 | # |
---|
3 | # Coopr: A COmmon Optimization Python Repository |
---|
4 | # Copyright (c) 2010 Sandia Corporation. |
---|
5 | # This software is distributed under the BSD License. |
---|
6 | # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, |
---|
7 | # the U.S. Government retains certain rights in this software. |
---|
8 | # For more information, see the Coopr README.txt file. |
---|
9 | # _________________________________________________________________________ |
---|
10 | |
---|
11 | from pyutilib.component.core import * |
---|
12 | |
---|
13 | from coopr.pysp import solutionwriter |
---|
14 | from coopr.pysp.scenariotree import * |
---|
15 | |
---|
16 | import string |
---|
17 | |
---|
18 | # |
---|
19 | # a simple utility to munge the index name into something a bit more csv-friendly and |
---|
20 | # in general more readable. at the current time, we just eliminate any leading and trailing |
---|
21 | # parantheses and change commas to colons - the latter because it's a csv file! |
---|
22 | # |
---|
23 | |
---|
24 | def index_to_string(index): |
---|
25 | |
---|
26 | result = str(index) |
---|
27 | result = result.lstrip('(').rstrip(')') |
---|
28 | result = result.replace(',',':') |
---|
29 | result = result.replace(' ','') |
---|
30 | |
---|
31 | return result |
---|
32 | |
---|
33 | class CSVSolutionWriter(SingletonPlugin): |
---|
34 | |
---|
35 | implements (solutionwriter.ISolutionWriterExtension) |
---|
36 | |
---|
37 | def write(self, scenario_tree, output_file_prefix): |
---|
38 | |
---|
39 | if not isinstance(scenario_tree, ScenarioTree): |
---|
40 | raise RuntimeError, "CSVSolutionWriter write method expects ScenarioTree object - type of supplied object="+str(type(scenario_tree)) |
---|
41 | |
---|
42 | output_filename = output_file_prefix + ".csv" |
---|
43 | output_file = open(output_filename,"w") |
---|
44 | |
---|
45 | for stage in scenario_tree._stages: |
---|
46 | stage_name = stage._name |
---|
47 | for tree_node in stage._tree_nodes: |
---|
48 | tree_node_name = tree_node._name |
---|
49 | for var_name, var in tree_node._solutions.items(): |
---|
50 | for idx in var: |
---|
51 | print >>output_file, stage_name, ",", tree_node_name, ",", var_name, ",", index_to_string(idx), ",", var[idx].value |
---|
52 | |
---|
53 | output_file.close() |
---|
54 | |
---|
55 | print "Scenario tree solution written to file="+output_filename |
---|