hensmith 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hensmith/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ # -*- coding: utf-8 -*-
2
+ # hensmith: Heat Exchanger Network Synthesis, Modeling, Integration,
3
+ # Thermodynamics, and Heuristics
4
+ # Copyright (C) 2020-, Sarang Bhagwat <sarangbhagwat.developer@gmail.com>
5
+ #
6
+ # This module is under the UIUC open-source license. See
7
+ # github.com/BioSTEAMDevelopmentGroup/hensmith/blob/master/LICENSE.txt
8
+ # for license details.
9
+ """
10
+ hensmith: automated heat exchanger network synthesis, modeling, integration,
11
+ thermodynamics, and heuristics for BioSTEAM systems.
12
+ """
13
+ __version__ = '0.1.0'
14
+
15
+ from ._heat_exchanger_network import *
16
+ from .hxn_synthesis import *
17
+
18
+ from . import _heat_exchanger_network
19
+ from . import hxn_synthesis
20
+
21
+ __all__ = (
22
+ *_heat_exchanger_network.__all__,
23
+ *hxn_synthesis.__all__,
24
+ )
@@ -0,0 +1,489 @@
1
+ # -*- coding: utf-8 -*-
2
+ # hensmith: Heat Exchanger Network Synthesis, Modeling, Integration,
3
+ # Thermodynamics, and Heuristics
4
+ # Copyright (C) 2020-, Sarang Bhagwat <sarangb2@illinois.edu>, Yoel Cortes-Pena <yoelcortes@gmail.com>
5
+ #
6
+ # This module is under the UIUC open-source license. See
7
+ # github.com/BioSTEAMDevelopmentGroup/hensmith/blob/master/LICENSE.txt
8
+ # for license details.
9
+ """
10
+ Created on Sat Aug 22 21:58:19 2020
11
+ @author: sarangbhagwat and yoelcp
12
+ """
13
+ import biosteam as bst
14
+ import thermosteam as tmo
15
+ import numpy as np
16
+ from .hxn_synthesis import synthesize_network, StreamLifeCycle, plot_pinch_diagram
17
+ from warnings import warn
18
+ import warnings
19
+
20
+ __all__ = ('HeatExchangerNetwork',)
21
+
22
+
23
+ class HeatExchangerNetwork(bst.Facility):
24
+ """
25
+ Create a HeatExchangerNetwork object that will perform a pinch analysis
26
+ on the entire system's heating and cooling utility objects. The heat
27
+ exchanger network reduces the heating and cooling utility requirements
28
+ of the system and may add additional capital cost.
29
+
30
+ Parameters
31
+ ----------
32
+ ID : str
33
+ Unique name for the facility.
34
+ T_min_app : float
35
+ Minimum approach temperature observed during synthesis of heat exchanger network.
36
+ units : Iterable[Unit], optional
37
+ All unit operations available to the heat exchanger network. Defaults
38
+ to all unit operations in the system.
39
+
40
+ Notes
41
+ -----
42
+ Original system stream and heat exchanger objects are preserved. All stream
43
+ copies and new HX objects can be found in a newly created flowsheet
44
+ '<sys>_HXN' where <sys> is the name of the system associated to the
45
+ HeatExchangerNetwork object.
46
+
47
+ References
48
+ ----------
49
+ .. [1] Seider, W. D., Lewin, D. R., Seader, J. D., Widagdo, S., Gani, R.,
50
+ & Ng, M. K. (2017). Product and Process Design Principles. Wiley.
51
+ Heat Exchanger Networks (Chapter 9)
52
+
53
+ Examples
54
+ --------
55
+ >>> import biosteam as bst
56
+ >>> bst.settings.set_thermo(['Water', 'Methanol', 'Glycerol'])
57
+ >>> feed1 = bst.Stream('feed1', flow=(8000, 100, 25))
58
+ >>> feed2 = bst.Stream('feed2', flow=(10000, 1000, 10))
59
+ >>> D1 = bst.ShortcutColumn('D1', ins=feed1,
60
+ ... outs=('distillate', 'bottoms_product'),
61
+ ... LHK=('Methanol', 'Water'),
62
+ ... y_top=0.99, x_bot=0.01, k=2,
63
+ ... is_divided=True)
64
+ >>> D1_H1 = bst.HXutility('D1_H1', ins = D1.outs[1], T = 300)
65
+ >>> D1_H2 = bst.HXutility('D1_H2', ins = D1.outs[0], T = 300)
66
+ >>> F1 = bst.Flash('F1', ins=feed2,
67
+ ... outs=('vapor', 'liquid'), V = 0.9, P = 101325)
68
+ >>> HXN = bst.HeatExchangerNetwork('HXN', T_min_app = 5.)
69
+ >>> sys = bst.System.from_units('sys', units=[D1, D1_H1, D1_H2, F1, HXN])
70
+ >>> sys.simulate()
71
+ >>> # See all results
72
+ >>> round(HXN.actual_heat_util_load/HXN.original_heat_util_load, 2)
73
+ 0.82
74
+ >>> abs(HXN.energy_balance_percent_error) < 0.01
75
+ True
76
+ >>> HXN.stream_life_cycles
77
+ [<StreamLifeCycle: Stream_0, cold
78
+ life_cycle = [
79
+ <LifeStage: <HXprocess: HX_0_2_hs>, H_in = 5.38e+06 kJ, H_out = 4.24e+07 kJ>
80
+ <LifeStage: <HXutility: Util_0_hs>, H_in = 4.24e+07 kJ, H_out = 6.92e+07 kJ>
81
+ ]>, <StreamLifeCycle: Stream_1, cold
82
+ life_cycle = [
83
+ <LifeStage: <HXprocess: HX_1_4_hs>, H_in = 0 kJ, H_out = 3.34e+04 kJ>
84
+ <LifeStage: <HXprocess: HX_1_2_hs>, H_in = 3.34e+04 kJ, H_out = 5.06e+06 kJ>
85
+ <LifeStage: <HXprocess: HX_1_3_hs>, H_in = 5.06e+06 kJ, H_out = 2.3e+07 kJ>
86
+ <LifeStage: <HXutility: Util_1_hs>, H_in = 2.3e+07 kJ, H_out = 2.79e+08 kJ>
87
+ ]>, <StreamLifeCycle: Stream_2, hot
88
+ life_cycle = [
89
+ <LifeStage: <HXprocess: HX_0_2_hs>, H_in = 4.52e+07 kJ, H_out = 8.12e+06 kJ>
90
+ <LifeStage: <HXprocess: HX_1_2_hs>, H_in = 8.12e+06 kJ, H_out = 3.1e+06 kJ>
91
+ <LifeStage: <HXutility: Util_2_cs>, H_in = 3.1e+06 kJ, H_out = 1.14e+06 kJ>
92
+ ]>, <StreamLifeCycle: Stream_3, hot
93
+ life_cycle = [
94
+ <LifeStage: <HXprocess: HX_1_3_hs>, H_in = 2.04e+07 kJ, H_out = 2.47e+06 kJ>
95
+ <LifeStage: <HXutility: Util_3_cs>, H_in = 2.47e+06 kJ, H_out = 2.47e+06 kJ>
96
+ ]>, <StreamLifeCycle: Stream_4, hot
97
+ life_cycle = [
98
+ <LifeStage: <HXprocess: HX_1_4_hs>, H_in = 7.51e+05 kJ, H_out = 7.18e+05 kJ>
99
+ <LifeStage: <HXutility: Util_4_cs>, H_in = 7.18e+05 kJ, H_out = 7.18e+05 kJ>
100
+ ]>]
101
+
102
+ """
103
+ ticket_name = 'HXN'
104
+ acceptable_energy_balance_error = 0.02
105
+ raise_energy_balance_error = False
106
+ network_priority = -2
107
+ _N_ins = 0
108
+ _N_outs = 0
109
+ _units= {'Flow rate': 'kg/hr',
110
+ 'Work': 'kW'}
111
+
112
+ def __init__(self, ID='', T_min_app=5., units=None, ignored=None, Qmin=1e-3,
113
+ force_ideal_thermo=False, cache_network=False, avoid_recycle=False,
114
+ acceptable_energy_balance_error=None, replace_unit_heat_utilities=False,
115
+ sort_hus_by_T=False):
116
+ bst.Facility.__init__(self, ID, None, None)
117
+ self.T_min_app = T_min_app
118
+ self.units = units
119
+ self.ignored = ignored
120
+ self.Qmin = Qmin
121
+ self.force_ideal_thermo = force_ideal_thermo
122
+ self.cache_network = cache_network
123
+ self.avoid_recycle = avoid_recycle
124
+ self.replace_unit_heat_utilities = replace_unit_heat_utilities
125
+ self.sort_hus_by_T = sort_hus_by_T
126
+ if acceptable_energy_balance_error is not None:
127
+ self.acceptable_energy_balance_error = acceptable_energy_balance_error
128
+
129
+ def _get_original_heat_utilties(self):
130
+ sys = self.system
131
+ if self.units:
132
+ units = self.units
133
+ if callable(units): units = units()
134
+ else:
135
+ units = sys.units
136
+ ignored = self.ignored
137
+ if ignored:
138
+ if callable(ignored): ignored = ignored()
139
+ ignored_hx_utils = sum([i.heat_utilities for i in ignored], [])
140
+ else:
141
+ ignored_hx_utils = ()
142
+ hx_utils = bst.process_tools.heat_exchanger_utilities_from_units(units)
143
+ return [i for i in hx_utils if i.duty and i not in ignored_hx_utils]
144
+
145
+ def _run(self): pass
146
+ def _design(self): pass
147
+ def _load_capital_costs(self): pass # Do not replace installed costs
148
+
149
+ def _cost(self):
150
+ sys = self.system
151
+ hx_utils = self._get_original_heat_utilties()
152
+ flowsheet = bst.Flowsheet(sys.ID + '_HXN')
153
+ use_cached_network = False
154
+ if self.cache_network and hasattr(self, 'original_heat_utils'):
155
+ # Units are the stable key: HeatUtility objects are recreated each
156
+ # simulation, and IDs may be duplicated (e.g., several
157
+ # 'condenser'/'reboiler' auxiliaries). Compare as identity sets.
158
+ hu_by_unit = {hu.unit: hu for hu in hx_utils}
159
+ use_cached_network = (
160
+ hu_by_unit.keys() == set(self.original_heat_exchangers)
161
+ )
162
+ with flowsheet.temporary(), bst.IgnoreDockingWarnings():
163
+ if use_cached_network:
164
+ # Keep the stored synthesis (duty-sorted) order, which is
165
+ # aligned index-by-index with stream_life_cycles.
166
+ hxs = self.original_heat_exchangers
167
+ hx_heat_utils_rearranged = [hu_by_unit[hx] for hx in hxs]
168
+ stream_life_cycles = self.stream_life_cycles
169
+ new_HXs = self.new_HXs
170
+ new_HX_utils = self.new_HX_utils
171
+ for i, life_cycle in enumerate(stream_life_cycles):
172
+ hx = hxs[i]
173
+ s_util_in = hx.ins[0]
174
+ stage = life_cycle.life_cycle[0]
175
+ s_lc = stage.unit.ins[stage.index]
176
+ s_lc.copy_like(s_util_in)
177
+ s_util_out = hx.outs[0]
178
+ H = s_util_out.H
179
+ for lc in life_cycle.life_cycle:
180
+ if isinstance(lc.unit, bst.HXutility):
181
+ lc.unit.H = H
182
+ else:
183
+ setattr(lc.unit, f'H_lim{lc.index}', s_util_out.H)
184
+ sys = self.HXN_sys
185
+ for unit in sys.units:
186
+ for s_in, s_out in zip(unit.ins, unit.outs):
187
+ if isinstance(s_out, bst.MultiStream):
188
+ s_out.F_mol = s_in.F_mol
189
+ if not s_out.mol.sparse_equal(s_in.mol):
190
+ s_out.copy_flow(s_in)
191
+ s_out.vle(T=s_out.T, P=s_out.P)
192
+ else:
193
+ s_out.mol[:] = s_in.mol
194
+ else:
195
+ hx_utils.sort(key = lambda x: x.duty)
196
+ self.HXN_flowsheet = HXN_F = bst.main_flowsheet
197
+ for i in HXN_F.registries: i.clear()
198
+ HXs_hot_side, HXs_cold_side, new_HX_utils, hxs, T_in_arr,\
199
+ T_out_arr, pinch_T_arr, C_flow_vector, hx_heat_utils_rearranged, streams_inlet, stream_HXs_dict,\
200
+ hot_indices, cold_indices = \
201
+ synthesize_network(hx_utils, self.T_min_app, self.Qmin,
202
+ self.force_ideal_thermo, self.avoid_recycle,
203
+ self.sort_hus_by_T)
204
+ new_HXs = HXs_hot_side + HXs_cold_side
205
+ self.new_HXs_hot_side = HXs_hot_side
206
+ self.new_HXs_cold_side = HXs_cold_side
207
+ self.cold_indices = cold_indices
208
+ self.original_heat_exchangers = hxs
209
+ self.new_HXs = new_HXs
210
+ self.new_HX_utils = new_HX_utils
211
+ self.streams_inlet = streams_inlet
212
+ stream_life_cycles = self._get_stream_life_cycles()
213
+ self.stream_HXs_dict = stream_HXs_dict
214
+ self.pinch_Ts = pinch_T_arr
215
+ self.inlet_Ts = T_in_arr
216
+ self.outlet_Ts = T_out_arr
217
+ all_units = new_HXs + new_HX_utils
218
+ IDs = set([i.ID for i in all_units])
219
+ assert len(all_units) == len(IDs)
220
+ for i, life_cycle in enumerate(stream_life_cycles):
221
+ stage = life_cycle.life_cycle[0]
222
+ s_util = hx_heat_utils_rearranged[i].unit.ins[0]
223
+ s_lc = stage.unit.ins[stage.index]
224
+ s_lc.copy_like(s_util)
225
+ for life_cycle in stream_life_cycles:
226
+ s_out = None
227
+ for i in life_cycle.life_cycle:
228
+ unit = i.unit
229
+ if s_out: unit.ins[i.index] = s_out
230
+ s_out = unit.outs[i.index]
231
+ # Order the path by the rewired stream connections (and
232
+ # detect recycle loops) rather than using synthesis order: a
233
+ # hot-side exchanger is synthesized before the cold-side
234
+ # exchangers that feed it, and a single pass in synthesis
235
+ # order would leave it with stale inlets. HXprocess units are
236
+ # interaction units, which Network.from_units strips out (and
237
+ # disconnects) by default; keep them with interaction=False.
238
+ with warnings.catch_warnings(record=True) as caught:
239
+ warnings.simplefilter('always', RuntimeWarning)
240
+ network = tmo.Network.from_units(all_units, interaction=False)
241
+ for w in caught:
242
+ if 'network path could not be determined' in str(w.message):
243
+ warn('heat exchanger network path could not be fully '
244
+ 'ordered from its stream connections; exchangers '
245
+ 'fed by later ones in the path may be simulated '
246
+ 'with stale inlets until convergence', RuntimeWarning)
247
+ else:
248
+ warn(w.message, w.category)
249
+ self.HXN_sys = sys = bst.System._from_network(None, network)
250
+ sys.set_tolerance(method='fixedpoint', subsystems=True)
251
+
252
+ original_purchase_costs = [hx.purchase_cost for hx in hxs]
253
+ original_installed_costs = [hx.installed_cost for hx in hxs]
254
+ # # Handle special case for heat exchanger crossing the pinch
255
+ # for hx in new_HXs:
256
+ # if all([isinstance(i.sink, bst.HXutility) for i in hx.outs]):
257
+ # hx.Tlim1 = None
258
+ # hx.Hlim1 = hx.outs[1].sink.H
259
+ sys._setup()
260
+ try:
261
+ sys.converge()
262
+ except:
263
+ for i in sys.units: i._run()
264
+ warn('heat exchanger network was not able to converge', RuntimeWarning)
265
+ for i in sys.units: i._summary()
266
+ for i in range(len(stream_life_cycles)):
267
+ hx = hx_heat_utils_rearranged[i].unit
268
+ P = hx.ins[0].P
269
+ s_util = hx.outs[0]
270
+ lc = stream_life_cycles[i].life_cycle[-1]
271
+ s_lc = lc.unit.outs[lc.index]
272
+ IDs = tuple([i.ID for i in s_util.available_chemicals])
273
+ if use_cached_network:
274
+ try:
275
+ assert np.isfinite(hx.installed_cost)
276
+ np.testing.assert_allclose(s_util.imol[IDs], s_lc.imol[IDs])
277
+ np.testing.assert_allclose(P, s_lc.P, rtol=1e-3, atol=0.1)
278
+ np.testing.assert_allclose(s_util.H, s_lc.H, rtol=1e-3, atol=1.)
279
+ except AssertionError as e:
280
+ msg = ("heat exchanger network cache algorithm failed, "
281
+ f"cached network ignored: {e}")
282
+ warn(msg, RuntimeWarning, stacklevel=2)
283
+ del self.original_heat_utils
284
+ self._cost()
285
+ return
286
+ else:
287
+ np.testing.assert_allclose(s_util.imol[IDs], s_lc.imol[IDs], rtol=1e-3, atol=0.1)
288
+ np.testing.assert_allclose(P, s_lc.P, rtol=1e-3, atol=0.1)
289
+ np.testing.assert_allclose(s_util.H, s_lc.H, rtol=1e-3, atol=1.)
290
+ new_purchase_costs_HXp = []
291
+ new_purchase_costs_HXu = []
292
+ new_installed_costs_HXp = []
293
+ new_installed_costs_HXu = []
294
+ new_utility_costs = []
295
+ for hx in new_HX_utils:
296
+ new_installed_costs_HXu.append(hx.installed_cost)
297
+ new_purchase_costs_HXu.append(hx.purchase_cost)
298
+ new_utility_costs.append(hx.utility_cost)
299
+ for new_HX in new_HXs:
300
+ new_purchase_costs_HXp.append(new_HX.purchase_cost)
301
+ new_installed_costs_HXp.append(new_HX.installed_cost)
302
+ hu_sums1 = bst.HeatUtility.sum_by_agent(hx_heat_utils_rearranged)
303
+ new_heat_utils = sum([hx.heat_utilities for hx in new_HX_utils], [])
304
+ hu_sums2 = bst.HeatUtility.sum_by_agent(new_heat_utils)
305
+ # to change sign on duty without switching heat/cool (i.e. negative costs):
306
+ for hu in hu_sums1: hu.reverse()
307
+ hus_final = bst.HeatUtility.sum_by_agent(hu_sums1 + hu_sums2)
308
+ Q_bal = (
309
+ (2.*sum([abs(i.Q) for i in new_HXs])
310
+ + sum([abs(i.duty * i.agent.heat_transfer_efficiency) for i in hu_sums2]))
311
+ / sum([abs(i.duty * i.agent.heat_transfer_efficiency) for i in hu_sums1])
312
+ )
313
+ energy_balance_error = Q_bal - 1
314
+ self.energy_balance_percent_error = 100 * energy_balance_error
315
+
316
+ if new_HXs:
317
+ self.installed_costs['Heat exchangers'] = max(0, (
318
+ sum(new_installed_costs_HXp)
319
+ + sum(new_installed_costs_HXu)
320
+ - sum(original_installed_costs)
321
+ ))
322
+ self.purchase_costs['Heat exchangers'] = self.baseline_purchase_costs['Heat exchangers'] = max(0, (
323
+ sum(new_purchase_costs_HXp)
324
+ + sum(new_purchase_costs_HXu)
325
+ - sum(original_purchase_costs)
326
+ ))
327
+ if self.replace_unit_heat_utilities:
328
+ self.heat_utilities = []
329
+ for hx_heat_util, new_hx_util in zip(hx_heat_utils_rearranged, new_HX_utils):
330
+ hx_heat_util.copy_like(new_hx_util.heat_utilities[0])
331
+ hx_heat_util.unit.owner._load_utility_cost() # Update new utility cost
332
+ else:
333
+ self.heat_utilities = hus_final
334
+ else: # if no matches were made, retain all original HXutilities (i.e., don't add the -- relatively minor -- differences between new and original HXutilities)
335
+ self.installed_costs['Heat exchangers'] = 0.
336
+ self.baseline_purchase_costs['Heat exchangers'] = self.purchase_costs['Heat exchangers'] = 0.
337
+ self.heat_utilities = []
338
+ self.original_heat_utils = hx_heat_utils_rearranged
339
+ self.original_purchase_costs = original_purchase_costs
340
+ self.original_utility_costs = hu_sums1
341
+ self.new_purchase_costs_HXp = new_purchase_costs_HXp
342
+ self.new_purchase_costs_HXu = new_purchase_costs_HXu
343
+ self.new_utility_costs = hu_sums2
344
+ new_hus = bst.process_tools.heat_exchanger_utilities_from_units(new_HX_utils)
345
+ hus_heating = [hu for hu in hx_utils if hu.duty > 0]
346
+ hus_cooling = [hu for hu in hx_utils if hu.duty < 0]
347
+ self.original_heat_util_load = sum([hu.duty for hu in hus_heating])
348
+ self.original_cool_util_load = sum([abs(hu.duty) for hu in hus_cooling])
349
+ self.actual_heat_util_load = sum([hu.duty for hu in new_hus if hu.duty>0])
350
+ self.actual_cool_util_load = sum([abs(hu.duty) for hu in new_hus if hu.duty<0])
351
+ if abs(energy_balance_error) > self.acceptable_energy_balance_error:
352
+ if use_cached_network:
353
+ del self.original_heat_utils
354
+ self._cost()
355
+ return
356
+ msg = ("heat exchanger network energy balance is off by "
357
+ f"{energy_balance_error:.2%} (an absolute error greater "
358
+ f"than {self.acceptable_energy_balance_error:.2%})")
359
+ if self.raise_energy_balance_error:
360
+ raise RuntimeError(msg)
361
+ else:
362
+ warn(msg, RuntimeWarning, stacklevel=2)
363
+
364
+ def _energy_balance_error_contributions(self):
365
+ original_ignored = ignored = self.ignored
366
+ if ignored and callable(ignored): ignored = ignored()
367
+ energy_balance_errors = {}
368
+ for hu in self._get_original_heat_utilties():
369
+ self.ignored = list(ignored or ()) + [hu.unit]
370
+ if hasattr(hu.unit, 'owner'):
371
+ ID = hu.unit.owner.ID, hu.unit.ID
372
+ else:
373
+ ID = hu.unit.ID
374
+ try:
375
+ self.simulate()
376
+ except:
377
+ energy_balance_errors[ID] = (hu, None)
378
+ else:
379
+ energy_balance_errors[ID] = (hu, self.energy_balance_percent_error)
380
+ self.ignored = original_ignored
381
+ return energy_balance_errors
382
+
383
+ def _get_stream_life_cycles(self):
384
+ cold_indices = self.cold_indices
385
+ new_HXs = self.new_HXs
386
+ new_HX_utils = self.new_HX_utils
387
+ streams = self.streams_inlet
388
+ indices = [i for i in range(len(streams))]
389
+ SLCs = [StreamLifeCycle(index, index in cold_indices) for index in indices]
390
+ for SLC in SLCs:
391
+ SLC.get_life_cycle(new_HXs, new_HX_utils)
392
+ stream_life_cycles = SLCs
393
+ self.stream_life_cycles = stream_life_cycles
394
+ return stream_life_cycles
395
+
396
+ def plot_pinch_diagram(self, file=None, **kwargs):
397
+ """
398
+ Draw the pinch diagram of the synthesized network; see
399
+ :func:`~hensmith.hxn_synthesis.plot_pinch_diagram`
400
+ for the keyword arguments. Returns the matplotlib figure and axes.
401
+ """
402
+ if not hasattr(self, 'new_HXs_hot_side'):
403
+ raise RuntimeError('simulate the heat exchanger network before '
404
+ 'plotting its pinch diagram')
405
+ return plot_pinch_diagram(
406
+ self.stream_life_cycles, self.inlet_Ts, self.outlet_Ts,
407
+ self.new_HXs_hot_side, self.new_HXs_cold_side,
408
+ Qmin=self.Qmin, original_hxs=self.original_heat_exchangers,
409
+ file=file, **kwargs,
410
+ )
411
+
412
+ def get_original_hxs_associated_with_streams(self): # pragma: no cover
413
+ original_units = self.system.units
414
+ original_heat_utils = self.original_heat_utils
415
+ original_hx_utils = [i.unit for i in original_heat_utils]
416
+ original_hxs = {}
417
+ stream_index = 0
418
+ for hx in original_hx_utils:
419
+ if '.' in hx.ID: # Names like 'U.1', i.e. non-explicitly named unit (e.g. auxillary HX)
420
+ for unit in original_units:
421
+ if isinstance(unit, bst.units.MultiEffectEvaporator):
422
+ for key, component in unit.components.items():
423
+ if isinstance(component, list):
424
+ for subcomponent in component:
425
+ if subcomponent is hx:
426
+ original_hxs[stream_index] = (unit, key)
427
+ elif component is hx:
428
+ original_hxs[stream_index] = (unit, key)
429
+ elif isinstance(unit, bst.units.BinaryDistillation)\
430
+ or isinstance(unit, bst.units.ShortcutColumn):
431
+ if unit.boiler is hx:
432
+ original_hxs[stream_index] = (unit, 'boiler')
433
+ elif unit.condenser is hx:
434
+ original_hxs[stream_index] = (unit, 'condenser')
435
+ elif hasattr(unit, 'heat_exchanger'):
436
+ if unit.heat_exchanger is hx:
437
+ original_hxs[stream_index] = (unit, 'heat exchanger')
438
+ else: # Explicitly named unit
439
+ original_hxs[stream_index] = (hx, '')
440
+ stream_index += 1
441
+ self.original_hxs = original_hxs
442
+ return original_hxs
443
+
444
+ def save_stream_life_cycles_as_csv(self): # pragma: no cover
445
+ if not hasattr(self, 'stream_life_cycles'):
446
+ self.stream_life_cycles = self._get_stream_life_cycles()
447
+ stream_life_cycles = self.stream_life_cycles
448
+ if not hasattr(self, 'original_hxs'):
449
+ self.original_hxs = self.get_original_hxs_associated_with_streams()
450
+ original_hxs = self.original_hxs
451
+ import csv
452
+ from datetime import datetime
453
+ dateTimeObj = datetime.now()
454
+ filename = 'HXN-%s_%s.%s.%s.%s.%s.csv'%(self.system.ID, dateTimeObj.year,
455
+ dateTimeObj.month, dateTimeObj.day,
456
+ dateTimeObj.hour, dateTimeObj.minute)
457
+ csvWriter = csv.writer(open(filename, 'w'), delimiter=',')
458
+ csvWriter.writerow(['Stream', 'Type', 'Original unit', 'HXN unit', 'H_in (kJ)',
459
+ 'H_out (kJ)', 'T_in (C)', 'T_out (C)'])
460
+ stream, streamtype, original_unit, hxn_unit, H_in, H_out, T_in, T_out =\
461
+ 0, 0, 0, 0, 0, 0, 0, 0
462
+
463
+ inlet_Ts = self.inlet_Ts
464
+ outlet_Ts = self.outlet_Ts
465
+ for life_cycle in stream_life_cycles:
466
+ stream = life_cycle.index
467
+ streamtype = 'Cold' if life_cycle.cold else 'Hot'
468
+ stage_no = 0
469
+ stages = life_cycle.life_cycle
470
+ len_stages = len(stages)
471
+ for stage in stages:
472
+ original_unit = original_hxs[stream][0].ID
473
+ if original_hxs[stream][1]:
474
+ original_unit+= ' - ' + original_hxs[stream][1]
475
+
476
+ hxn_unit = stage.unit
477
+ hxn_unit_ID = hxn_unit.ID
478
+ H_in = stage.H_in
479
+ H_out = stage.H_out
480
+ T_in, T_out = None, None
481
+ if stage_no == 0:
482
+ T_in = inlet_Ts[stream] - 273.15
483
+ if stage_no == len_stages - 1:
484
+ T_out = outlet_Ts[stream] - 273.15
485
+
486
+ row = [stream, streamtype, original_unit, hxn_unit_ID,
487
+ H_in, H_out, T_in, T_out]
488
+ csvWriter.writerow(row)
489
+ stage_no += 1