Skip to content

Commit daf133e

Browse files
author
Sai Krishna
committed
trapezodial error function successfully works. setup_case and run_case have been changed to take in temperature index and save .h5 files separately
1 parent 2f06a3d commit daf133e

File tree

2 files changed

+94
-98
lines changed

2 files changed

+94
-98
lines changed

pyteck/jsr_eval_model.py

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -44,18 +44,19 @@ def create_simulations(dataset, properties,target_species_name):
4444
"""
4545

4646
simulations = []
47-
for idx, case in enumerate(properties.datapoints):
48-
sim_meta = {}
49-
# Common metadata
50-
sim_meta['data-file'] = dataset
51-
sim_meta['id'] = splitext(basename(dataset))[0] + '_' + str(idx)
52-
53-
simulations.append(JSRSimulation(properties.experiment_type,
54-
properties.apparatus.kind,
55-
sim_meta,
56-
case,target_species_name
57-
)
58-
)
47+
for case in properties.datapoints:
48+
for idx,temp in enumerate(case.temperature):
49+
sim_meta = {}
50+
# Common metadata
51+
sim_meta['data-file'] = dataset
52+
sim_meta['id'] = splitext(basename(dataset))[0] + '_' + str(idx)
53+
54+
simulations.append(JSRSimulation(properties.experiment_type,
55+
properties.apparatus.kind,
56+
sim_meta,
57+
case,target_species_name
58+
)
59+
)
5960
return simulations
6061

6162
def simulation_worker(sim_tuple):
@@ -77,9 +78,10 @@ def simulation_worker(sim_tuple):
7778

7879
sim.setup_case(model_file, model_spec_key, path)
7980
sim.run_case(restart)
81+
concentration = sim.process_results()
8082

8183
sim = JSRSimulation(sim.kind, sim.apparatus, sim.meta, sim.properties,sim.target_species_name)
82-
return sim
84+
return sim,concentration
8385

8486

8587
def estimate_std_dev(indep_variable, dep_variable):
@@ -319,30 +321,30 @@ def evaluate_model(model_name, spec_keys_file, species_name,
319321

320322
dataset_meta['datapoints'] = []
321323
expt_target_species_profiles = {}
322-
simulated_species_profiles = {}
323-
for idx, sim in enumerate(results):
324-
sim.process_results()
324+
simulated_species_profiles = []
325+
for idx, sim_tuple in enumerate(results):
326+
sim,concentration = sim_tuple
325327

326328

327329
expt_target_species_profile, inlet_temperature = get_changing_variables(properties.datapoints[0],species_name=species_name)
328330
#Only assumes you have one csv : Krishna
329331
dataset_meta['datapoints'].append(
330332
{'experimental species profile': str(expt_target_species_profile),
331-
'simulated species profile': str(sim.meta['simulated_species_profiles']),
333+
'simulated species profile': str(concentration),
332334
'temperature': str(sim.properties.temperature),
333335
'pressure': str(sim.properties.pressure),
334336
})
335337

336338
expt_target_species_profiles[str(idx)] = [quantity.magnitude for quantity in expt_target_species_profile]
337-
simulated_species_profiles[str(idx)] = sim.meta['simulated_species_profiles']
339+
simulated_species_profiles.append(concentration)
338340
#assert (len(expt_target_species_profile)==len(sim.meta['simulated_species_profiles'])), "YOU DONE GOOFED UP SIMULATIONS"
339341

340342
# calculate error function for this dataset
341343
experimental_trapz = numpy.trapz(inlet_temperature,expt_target_species_profile)
342-
print (sim.meta['simulated_species_profiles'])
343-
simulated_trapz = numpy.trapz(inlet_temperature,sim.meta['simulated_species_profiles'])
344+
print (simulated_species_profiles)
345+
simulated_trapz = numpy.trapz(inlet_temperature,simulated_species_profiles)
344346
if print_results:
345-
print ("Difference between AUC:{}".format(experimental_trapz,simulated_trapz))
347+
print ("Difference between AUC:{}".format(experimental_trapz-simulated_trapz))
346348

347349
# Write data to YAML file
348350
with open(splitext(basename(model_name))[0] + '-results.yaml', 'w') as f:

pyteck/jsr_simulation.py

Lines changed: 71 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,15 @@ def __init__(self, kind, apparatus, meta, properties,target_species_name):
3838
:type meta: dict
3939
:param properties: set of properties for this case
4040
:type properties: pyked.chemked.DataPoint
41+
:param target_species_name: target outlet species name as given ChemKED files
42+
:type target_species_name:: str
4143
"""
4244
self.kind = kind
4345
self.apparatus = apparatus
4446
self.meta = meta
4547
self.properties = properties
4648
self.target_species_name = target_species_name
49+
4750
def setup_case(self, model_file, species_key, path=''):
4851
"""Sets up the simulation case to be run.
4952
@@ -56,20 +59,49 @@ def setup_case(self, model_file, species_key, path=''):
5659
self.species_key = species_key
5760
# Set max simulation time, pressure valve coefficient, and max pressure rise for Cantera
5861
# These could be set to something in ChemKED file, but haven't seen these specified at all....
59-
self.maxsimulationtime = 50
62+
self.maxsimulationtime = 60
6063
self.pressurevalcof = 0.01
6164
self.maxpressurerise = 0.01
62-
6365
# Reactor volume needed in m^3 for Cantera
6466
self.volume = self.properties.reactor_volume.magnitude
6567
print (self.properties.reactor_volume.units)
6668
print (self.volume)
67-
6869
# Residence time needed in s for Cantera
6970
self.restime = self.properties.residence_time.magnitude
7071
print (self.properties.residence_time.units)
7172
print (self.restime)
72-
73+
#Create reactants from chemked file
74+
reactants = [self.species_key[self.properties.inlet_composition[spec].species_name] + ':' +
75+
str(self.properties.inlet_composition[spec].amount.magnitude.nominal_value)
76+
for spec in self.properties.inlet_composition
77+
]
78+
#Krishna: Need to double check these numbers
79+
reactants = ','.join(reactants)
80+
print (reactants)
81+
self.properties.pressure.ito('pascal')
82+
# Need to extract values from quantity or measurement object
83+
if hasattr(self.properties.pressure, 'value'):
84+
pres = self.properties.pressure.value.magnitude
85+
elif hasattr(self.properties.pressure, 'nominal_value'):
86+
pres = self.properties.pressure.nominal_value
87+
else:
88+
pres = self.properties.pressure.magnitude
89+
temperature = self.properties.temperature[int(self.meta['id'].split('_')[2])]
90+
temperature.ito('kelvin')
91+
if hasattr(temperature, 'value'):
92+
temp = temperature.value.magnitude
93+
elif hasattr(temperature, 'nominal_value'):
94+
temp = temperature.nominal_value
95+
else:
96+
temp = temperature.magnitude
97+
print (temp,pres)
98+
if self.properties.inlet_composition_type in ['mole fraction', 'mole percent']:
99+
self.gas.TPX = temp,pres,reactants
100+
elif self.properties.inlet_composition_type == 'mass fraction':
101+
self.gas.TPY = temp,pres,reactants
102+
else:
103+
raise(BaseException('error: not supported'))
104+
return
73105
# Upstream and exhaust
74106
self.fuelairmix = ct.Reservoir(self.gas)
75107
self.exhaust = ct.Reservoir(self.gas)
@@ -81,11 +113,9 @@ def setup_case(self, model_file, species_key, path=''):
81113

82114
# Create reactor newtork
83115
self.reactor_net = ct.ReactorNet([self.reactor])
84-
85-
# Set file path
86116
file_path = os.path.join(path, self.meta['id'] + '.h5')
87117
self.meta['save-file'] = file_path
88-
self.meta['target-species-index'] = self.gas.species_index(self.gas.species_index(species_key[self.target_species_name]))
118+
self.meta['target-species-index'] = self.gas.species_index(species_key[self.target_species_name])
89119
def run_case(self, restart=False):
90120
"""Run simulation case set up ``setup_case``.
91121
@@ -96,98 +126,62 @@ def run_case(self, restart=False):
96126
print('Skipped existing case ', self.meta['id'])
97127
return
98128

99-
# Convert reactant names to those needed for model
100-
reactants = [self.species_key[self.properties.inlet_composition[spec].species_name] + ':' +
101-
str(self.properties.inlet_composition[spec].amount.magnitude.nominal_value)
102-
for spec in self.properties.inlet_composition
103-
]
104-
#Krishna: Need to double check these numbers
105-
reactants = ','.join(reactants)
106-
print (reactants)
107-
temperatures = []
108-
for measurement in self.properties.temperature:
109-
if hasattr(measurement, 'value'):
110-
temperatures.append(measurement.value.magnitude)
111-
elif hasattr(measurement, 'nominal_value'):
112-
temperatures.append(measurement.nominal_value)
113-
else:
114-
temperatures.append(measurement.magnitude)
115-
mole_fractions_stack = numpy.zeros([len(temperatures),self.reactor.thermo.n_species])
116-
self.meta['reshape-size'] = [len(temperatures),self.reactor.thermo.n_species]
117-
print (mole_fractions_stack.shape)
118-
# Need to extract values from quantity or measurement object
119-
if hasattr(self.properties.pressure, 'value'):
120-
pres = self.properties.pressure.value.magnitude
121-
elif hasattr(self.properties.pressure, 'nominal_value'):
122-
pres = self.properties.pressure.nominal_value
123-
else:
124-
pres = self.properties.pressure.magnitude
129+
125130
# Save simulation results in hdf5 table format
126131
table_def = {'time': tables.Float64Col(pos=0),
127132
'temperature': tables.Float64Col(pos=1),
128133
'pressure': tables.Float64Col(pos=2),
129134
'volume': tables.Float64Col(pos=3),
130135
'mole_fractions': tables.Float64Col(
131-
shape=(len(temperatures),self.reactor.thermo.n_species), pos=4
136+
shape=(self.reactor.thermo.n_species), pos=4
132137
),
133138
}
134-
for idx,temp in enumerate(temperatures):
135-
if self.properties.inlet_composition_type in ['mole fraction', 'mole percent']:
136-
self.gas.TPX = temp,pres,reactants
137-
elif self.properties.inlet_composition_type == 'mass fraction':
138-
self.gas.TPY = temp,pres,reactants
139-
else:
140-
raise(BaseException('error: not supported'))
141-
return
142-
with tables.open_file(self.meta['save-file'], mode='w',
143-
title=self.meta['id']
144-
) as h5file:
145-
146-
table = h5file.create_table(where=h5file.root,
147-
name='simulation',
148-
description=table_def
149-
)
139+
140+
with tables.open_file(self.meta['save-file'], mode='w',
141+
title=self.meta['id']
142+
) as h5file:
143+
144+
table = h5file.create_table(where=h5file.root,
145+
name='simulation',
146+
description=table_def
147+
)
150148
# Row instance to save timestep information to
151-
timestep = table.row
152-
# Save initial conditions
149+
timestep = table.row
150+
# Save initial conditions
151+
timestep['time'] = self.reactor_net.time
152+
timestep['temperature'] = self.reactor.T
153+
timestep['pressure'] = self.reactor.thermo.P
154+
timestep['volume'] = self.reactor.volume
155+
timestep['mole_fractions'] = self.reactor.thermo.X
156+
# Add ``timestep`` to table
157+
timestep.append()
158+
159+
# Main time integration loop; continue integration while time of
160+
# the ``ReactorNet`` is less than specified end time.
161+
while self.reactor_net.time < self.maxsimulationtime:
162+
self.reactor_net.step()
163+
# Save new timestep information
153164
timestep['time'] = self.reactor_net.time
154165
timestep['temperature'] = self.reactor.T
155166
timestep['pressure'] = self.reactor.thermo.P
156167
timestep['volume'] = self.reactor.volume
157-
mole_fractions_stack[idx:] = self.reactor.thermo.X
158-
timestep['mole_fractions'] = mole_fractions_stack
168+
timestep['mole_fractions'] = self.reactor.thermo.X
159169
# Add ``timestep`` to table
160170
timestep.append()
161171

162-
# Main time integration loop; continue integration while time of
163-
# the ``ReactorNet`` is less than specified end time.
164-
while self.reactor_net.time < self.maxsimulationtime:
165-
self.reactor_net.step()
166-
167-
# Save new timestep information
168-
timestep['time'] = self.reactor_net.time
169-
timestep['temperature'] = self.reactor.T
170-
timestep['pressure'] = self.reactor.thermo.P
171-
timestep['volume'] = self.reactor.volume
172-
mole_fractions_stack[idx:] = self.reactor.thermo.X
173-
timestep['mole_fractions'] = mole_fractions_stack
174-
175-
# Add ``timestep`` to table
176-
timestep.append()
177-
178-
# Write ``table`` to disk
179-
table.flush()
172+
# Write ``table`` to disk
173+
table.flush()
180174

181175
print('Done with case ', self.meta['id'])
182176

183177
def process_results(self):
184-
"""Process integration results to obtain concentrations.
185178
"""
186-
179+
Process integration results to obtain concentrations.
180+
"""
187181
# Load saved integration results
188182
with tables.open_file(self.meta['save-file'], 'r') as h5file:
189183
# Load Table with Group name simulation
190184
table = h5file.root.simulation
191-
concentrations = table.col('mole_fractions')
192-
print (self.meta['target-species-index'])
193-
self.meta['simulated_species_profiles'] = concentrations.reshape(self.meta['reshape-size'][0],self.meta['reshape-size'][1])[:,self.meta['target-species-index']]
185+
concentration = table.col('mole_fractions')[:,self.meta['target-species-index']]
186+
return concentration[-1]
187+

0 commit comments

Comments
 (0)