Skip to content

Commit

Permalink
more enhancements to PO-API
Browse files Browse the repository at this point in the history
  • Loading branch information
yoelcortes committed May 31, 2024
1 parent 8cdc5f8 commit cd91740
Show file tree
Hide file tree
Showing 11 changed files with 205 additions and 86 deletions.
10 changes: 8 additions & 2 deletions benchmark/acetic_acid_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
"""
import biosteam as bst
import numpy as np
from .profile import register
try:
from .profile import register
except:
def register(*args, **kwargs):
return lambda f: f

__all__ = (
'create_acetic_acid_simple_system',
Expand Down Expand Up @@ -77,7 +81,7 @@ def fresh_solvent_flow_rate():

@register(
'acetic_acid_complex', 'Glacial acetic acid\npurification',
80, [0, 10, 20, 30, 40, 50, 60, 70, 80], 'AcOH\nsep.'
60, [0, 10, 20, 30, 40, 50, 60], 'AcOH\nsep.'
)
def create_acetic_acid_complex_system(alg):
thermo = bst.Thermo(['Water', 'AceticAcid', 'EthylAcetate'], cache=True)
Expand Down Expand Up @@ -169,6 +173,7 @@ def adjust_fresh_solvent_flow_rate():
reflux=None,
boilup=3,
use_cache=True,
maxiter=10,
)
settler = bst.StageEquilibrium(
'settler',
Expand Down Expand Up @@ -226,6 +231,7 @@ def adjust_fresh_solvent_flow_rate():
feed_stages=(1, 2),
reflux=1,
boilup=2,
maxiter=10,
)
return sys

10 changes: 7 additions & 3 deletions benchmark/butanol_purification_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@
@author: cortespea
"""
import biosteam as bst
from .profile import register
try:
from .profile import register
except:
def register(*args, **kwargs):
return lambda f: f

__all__ = (
'create_system_butanol_purification',
)

@register(
'butanol_purification', 'Butanol purification',
5, [1, 2, 3, 4, 5], 'BtOH\nsep.'
2, [0.5, 1, 1.5, 2], 'BtOH\nsep.'
)
def create_system_butanol_purification(alg):
bst.settings.set_thermo(['Water', 'Butanol'], cache=True)
Expand Down Expand Up @@ -53,5 +57,5 @@ def create_system_butanol_purification(alg):
LHK=('Water', 'Butanol'),
)

sys = bst.System.from_units(units=[water_distiller, settler, butanol_distiller])
sys = bst.System.from_units(units=[water_distiller, settler, butanol_distiller], algorithm=alg)
return sys
19 changes: 9 additions & 10 deletions benchmark/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ def profile_phenomena_oriented(system, total_time):
po = all_systems[system]('phenomena oriented')
po.flatten()
po._setup_units()
# print(po.algorithm)
# breakpoint()
data = profile(po.run_phenomena, *streams_and_stages(po), total_time)
bst.F.clear()
return data
Expand Down Expand Up @@ -191,7 +193,6 @@ def dT_error(stage):
sum([i.H for i in stage.outs]) - sum([i.H for i in stage.ins])
) / sum([i.C for i in stage.outs])

# @high_precision
def benchmark(f, streams, adiabatic_stages, stages, total_time):
time = bst.TicToc()
net_time = 0
Expand Down Expand Up @@ -361,29 +362,29 @@ def plot_benchmark(systems=None, N=100, load=True, save=True):
# @high_precision
def profile(f, streams, adiabatic_stages, stages, total_time):
time = bst.TicToc()
KB_error = []
flow_error = []
energy_error = []
material_error = []
temperature_error = []
record = []
net_time = 0
KBs = np.array([i.K * i.B for i in stages if hasattr(i, 'K')])
temperatures = np.array([i.T for i in streams])
flows = np.array([i.mol for i in streams])
while net_time < total_time:
time.tic()
f()
net_time += time.toc()
new_KBs = np.array([i.K * i.B for i in stages if hasattr(i, 'K')])
new_temperatures = np.array([i.T for i in streams])
new_flows = np.array([i.mol for i in streams])
record.append(net_time)
dF = np.abs(flows - new_flows).sum()
# sys = f.__self__
# print(sys.algorithm)
# if sys.algorithm == 'Phenomena oriented':
# sys.show()
# breakpoint()
# print(dF)
dT = np.abs(temperatures - new_temperatures).sum()
KB_error.append(
np.log10(np.abs(new_KBs - KBs).sum() + 1e-15)
)
flow_error.append(
np.log10(dF + 1e-15)
)
Expand All @@ -396,12 +397,10 @@ def profile(f, streams, adiabatic_stages, stages, total_time):
material_error.append(
np.log10(sum([abs(i.mass_balance_error()) for i in stages]) + 1e-15)
)
KBs = new_KBs
flows = new_flows
temperatures = new_temperatures
return {
'Time': record,
'Stripping factor': KB_error,
'Stream temperature': temperature_error,
'Component flow rate': flow_error,
'Energy balance': energy_error,
Expand Down Expand Up @@ -436,7 +435,7 @@ def dct_mean_std(dcts: list[dict], keys: list[str]):
return {i: (values[i].mean(), values[i].std()) for i in keys}

def plot_profile(
systems=None, N=10, load=True, save=True
systems=None, N=1, load=True, save=True
):
if systems is None: systems = list(all_systems)
fs = 9
Expand Down
28 changes: 19 additions & 9 deletions biosteam/_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ def solve_material_flows(self):
A = []
b = []
for node in nodes:
if not node._create_material_balance_equations:
raise NotImplementedError(f'{node!r} has no method `_create_material_balance_equations`')
for coefficients, value in node._create_material_balance_equations():
coefficients = {
streams[i.imol]: j for i, j in coefficients.items()
Expand Down Expand Up @@ -139,13 +141,17 @@ def solve_energy_departures(self):
A = []
b = []
for node in nodes:
if not node._create_energy_departure_equations:
raise NotImplementedError(f'{node!r} has no method `_create_energy_departure_equations`')
for coefficients, value in node._create_energy_departure_equations():
A.append(coefficients)
b.append(value)
A, objs = dictionaries2array(A)
values = solve(A, np.array(b).T).T
for obj, value in zip(objs, values):
obj._update_energy_variable(value)
departures = solve(A, np.array(b).T).T
for obj, departure in zip(objs, departures):
if not obj._update_energy_variable:
raise NotImplementedError(f'{obj!r} has no method `_update_energy_variable`')
obj._update_energy_variable(departure)

def __enter__(self):
units = self.stages
Expand Down Expand Up @@ -2293,18 +2299,22 @@ def run_phenomena(self):
except:
for i in path[n+1:]: i.run()
last.run()
for i in self.stages:
if (hasattr(i, '_update_equilibrium_variables')
and getattr(i, 'phases', None) == ('g', 'l')):
i._update_equilibrium_variables()
if hasattr(i, '_update_reaction_conversion'):
i._update_reaction_conversion()
try:
with self.stage_configuration(aggregated=False) as conf:
for i in conf.stages:
if hasattr(i, '_update_equilibrium_variables'):
i._update_equilibrium_variables()
if hasattr(i, '_update_reaction_conversion'):
i._update_reaction_conversion()
conf.solve_energy_departures()
conf.solve_material_flows()
except:
with self.stage_configuration(aggregated=True) as conf:
for i in conf.stages:
if hasattr(i, '_update_equilibrium_variables'):
i._update_equilibrium_variables()
if hasattr(i, '_update_reaction_conversion'):
i._update_reaction_conversion()
conf.solve_energy_departures()
conf.solve_material_flows()

Expand Down
4 changes: 2 additions & 2 deletions biosteam/units/compressor.py
Original file line number Diff line number Diff line change
Expand Up @@ -600,8 +600,8 @@ def _create_material_balance_equations(self):

return equations

def _update_energy_variable(self, variable, value):
self.outs[0].T += value
def _update_energy_variable(self, departure):
self.outs[0].T += departure


class PolytropicCompressor(Compressor, new_graphics=False):
Expand Down
8 changes: 8 additions & 0 deletions biosteam/units/distillation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1514,6 +1514,12 @@ def _create_material_balance_equations(self):
)
return equations

def _get_energy_departure_coefficient(self, stream):
return None

def _create_energy_departure_equations(self):
return []

def _update_equilibrium_variables(self):
outs = top, bottom = self.outs
data = [i.get_data() for i in outs]
Expand Down Expand Up @@ -1940,6 +1946,8 @@ def _recompute_distillate_recoveries(self, distillate_recoveries):
self._distillate_recoveries = distillate_recoveries
return distillate_recoveries

_get_energy_departure_coefficient = BinaryDistillation._get_energy_departure_coefficient
_create_energy_departure_equations = BinaryDistillation._create_energy_departure_equations
_create_material_balance_equations = BinaryDistillation._create_material_balance_equations
_update_equilibrium_variables = BinaryDistillation._update_equilibrium_variables

Expand Down
6 changes: 3 additions & 3 deletions biosteam/units/mixing.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,12 +176,12 @@ def _create_material_balance_equations(self):
)
return equations

def _update_energy_variable(self, value):
def _update_energy_variable(self, departure):
phases = self.phases
if phases == ('g', 'l'):
self._B += value
self._B += departure
else:
self.outs[0].T += value
self.outs[0].T += departure


class SteamMixer(Unit):
Expand Down
4 changes: 2 additions & 2 deletions biosteam/units/splitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ def _create_energy_departure_equations(self, temperature_only=False):
self.ins[0]._update_energy_departure_coefficient(coeff)
return [(coeff, self.H_in - self.H_out)]

def _update_energy_variable(self, value):
self.T = T = self.T + value
def _update_energy_variable(self, departure):
self.T = T = self.T + departure
for i in self.outs: i.T = T

Loading

0 comments on commit cd91740

Please sign in to comment.