MoDeNa  1.0
Software framework facilitating sequential multi-scale modelling
PolymerDensity.py
1 
31 
32 
41 
42 import os
43 import modena
44 from modena import ForwardMappingModel,BackwardMappingModel,SurrogateModel,CFunction,IndexSet,ModenaFireTask
45 import modena.Strategy as Strategy
46 from fireworks.user_objects.firetasks.script_task import FireTaskBase, ScriptTask
47 from fireworks import Firework, Workflow, FWAction
48 from fireworks.utilities.fw_utilities import explicit_serialize
49 from blessings import Terminal
50 from jinja2 import Template
51 
52 # Create terminal for colour output
53 term = Terminal()
54 
55 
56 blowing_agents = IndexSet(
57  name= 'blowing_agents',
58  names= [ 'air', 'CO2']
59 )
60 
61 monomers = IndexSet(
62  name = 'monomers',
63  names = ['PU', 'THF', 'hexane', 'surfactant']
64 )
65 
66 
67 # ********************************* Class ********************************** #
68 @explicit_serialize
69 
73 class DensityExactSim(ModenaFireTask):
74 
75  def task(self, fw_spec):
76  # Generate input fileblock
77  self.generate_inputfile()
78 
79  # Execute detailed model
80  ret = os.system(os.path.dirname(os.path.abspath(__file__))+'/src/PCSAFT_Density')
81 
82  # Check framework for errors
83  self.handleReturnCode(ret)
84 
85  # Analyse output
86  self.analyse_output()
87 
88 
89 
90 
92  def generate_inputfile(self):
93  Template("""
94  {#
95  Write inputs to the template, one per line.
96  #}
97  {% for k,v in s['point'].iteritems() %}
98  {{ v }}
99  {% endfor %}
100  {#
101  The number of species, one integer.
102  #}
103  {{ s['indices'].__len__() }}
104  {#
105  Write the species (lower case) one per line.
106  #}
107  {% for k,v in s['indices'].iteritems() %}
108  {{ v.lower() }}
109  {% endfor %}
110  {#
111  Set initial feed molar fractions to zero.
112  #}
113  {% for k,v in s['indices'].iteritems() %}
114  {{ 0.0 }}
115  {% endfor %}
116  """, trim_blocks=True,
117  lstrip_blocks=True).stream(s=self).dump('in.txt')
118 
119  #create output file for detailed code
120  with open('out.txt', 'w+') as FILE:
121  pass
122 
123 
124 
128  def analyse_output(self):
129  with open('out.txt', 'r') as FILE: self['point']['rho'] = float(FILE.readline())
130 
131 
132 f = CFunction(
133  Ccode= '''
134 #include "modena.h"
135 #include "math.h"
136 
137 void surroDensity
138 (
139  const modena_model_t* model,
140  const double* inputs,
141  double *outputs
142 )
143 {
144 
145  {% block variables %}{% endblock %}
146 
147  const double P0 = parameters[0];
148  const double P1 = parameters[1];
149  const double P2 = parameters[2];
150 
151  const double expo = 1.0 + (1.0 - T/P2);
152  const double pwr = pow(P1,expo);
153 
154  outputs[0] = P0 / pwr;
155  //outputs[0] = P0 + T*P1 + P2*T*T;
156 }
157 ''',
158  # These are global bounds for the function
159  inputs={
160  'T': { 'min': 270.0, 'max': 550.0},
161  },
162  outputs={
163  'rho': { 'min': 9e99, 'max': -9e99, 'argPos': 0 },
164  },
165  parameters={
166  'param0': { 'min': -1E10, 'max': 1E10+2, 'argPos': 0 }, #check if boundaries are reasonable!!!
167  'param1': { 'min': -1E10, 'max': 1E10+2, 'argPos': 1 },
168  'param2': { 'min': -1E10, 'max': 1E10+2, 'argPos': 2 },
169  },
170  species={
171  'A' : blowing_agents,
172  'B' : monomers
173  }
174 )
175 
176 m = BackwardMappingModel(
177  _id= 'PolymerDensity[A=AIR,B=PU]',
178  surrogateFunction= f,
179  exactTask= DensityExactSim(),
180  substituteModels= [ ],
181  initialisationStrategy= Strategy.InitialPoints(
182  initialPoints=
183  {
184  'T': [270.0, 300.0, 350.0, 400, 450, 500, 550],
185  },
186  ),
187  outOfBoundsStrategy= Strategy.ExtendSpaceStochasticSampling(
188  nNewPoints= 4
189  ),
190  parameterFittingStrategy= Strategy.NonLinFitWithErrorContol(
191  testDataPercentage= 0.2,
192  maxError= 10.0,
193  improveErrorStrategy= Strategy.StochasticSampling(
194  nNewPoints= 2
195  ),
196  maxIterations= 5 # Currently not used
197  ),
198 )
199