-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunction_AutoFlent.py
More file actions
403 lines (296 loc) · 15.1 KB
/
Copy pathFunction_AutoFlent.py
File metadata and controls
403 lines (296 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import ansys.fluent.core as pyfluent
def runFluent(solver, mass_flow, channel_pitch, mesh_file, cal_iter):
# ------------------ read mesh file -----------------
# mesh_file = r"C:\Users\lichengd\OneDrive - Oregon State University\1. PhD\Chiller\automation\Chiller_auto_Python\Fluent_work_dir\Meshsurface_case\6try_Automesh_coldplate_proximity.msh"
# mesh_file = r"C:\Users\lichengd\OneDrive - Oregon State University\1. PhD\Chiller\automation\Chiller_auto_Python\Fluent_work_dir\Meshsurface_case\Export_Automesh_coldplate_proximity.msh"
# solver.file.read(file_type="mesh", file_name=mesh_file)
solver.settings.file.read(file_type="mesh", file_name=mesh_file)
# --------------Mesh scale and viscous model --------------
solver.tui.define.units("length", "mm")
solver.tui.mesh.scale(0.001, 0.001, 0.001) # change unit from meter to milermeter
solver.mesh.check()
solver.setup.models.energy.enabled = True # turn on heat transfer
solver.setup.models.viscous.model = "k-epsilon" # fluid model use k-epsilon
solver.setup.models.viscous.k_epsilon_model = "realizable"
# ---------------- adding material for this case ----------------
print("1. adding liquid water 正在加载液态水...")
try:
# 尝试从 Fluent 标准库复制 water-liquid
solver.tui.define.materials.copy("fluid", "water-liquid")
except Exception as e:
print(f" 注意: {e}")
# 2. 定义固体: 硅 (Silicon)
print("2. adding Silicion 正在创建材料: Silicon (硅)...")
try:
# 创建名为 'silicon' 的新固体材料
silicon = solver.setup.materials.solid.create("silicon")
# 设置物性参数
silicon.density.value = 2329.5 # Density [kg/m3]
silicon.specific_heat.value = 697.28 # Cp [J/(kg K)]
silicon.thermal_conductivity.value = 153.04 # Thermal Conductivity [W/(m K)]
print(" [成功] Silicon 定义完成 (Rho=2329.5, K=153.04)")
except Exception as e:
print(f" [错误] 定义 Silicon 失败: {e}")
# 3. 定义固体: PEEK (含40%碳纤维)
print("3. Adding PEEK plastic 正在创建材料: PEEK (40% Carbon Fiber)...")
try:
# 创建名为 'peek' 的新固体材料
peek = solver.setup.materials.solid.create("peek")
# 设置物性参数
peek.density.value = 1454.9 # Density [kg/m3]
peek.specific_heat.value = 1800.0 # Cp [J/(kg K)]
peek.thermal_conductivity.value = 0.25 # Thermal Conductivity [W/(m K)]
print(" [成功] PEEK 定义完成 (Rho=1454.9, K=2.0)")
except Exception as e:
print(f" [错误] 定义 PEEK 失败: {e}")
# 4. 检查目前已有的固体材料
print("\n当前已加载的固体材料库:")
print(solver.setup.materials.solid.keys())
# ----------------- Assign Materials and Type to Cell Zones ------------------
# 4 chips, 2 runner lets, and 1 coldplate core. Total 7 Solid zone
solid_mapping = {
# 芯片 (Silicon)
"chip_0_chip_0_part_chip_0_part": "silicon",
"chip_1_chip_1_part_chip_1_part": "silicon",
"chip_2_chip_2_part_chip_2_part": "silicon",
"chip_3_chip_3_part_chip_3_part": "silicon",
# 水冷板基底 (Aluminum - 假设冷板本体是铝)
"coldplate_coldplate_part_coldplate_part": "aluminum",
# 进出口接头 (PEEK - 假设 Let 是塑料接头)
"let_0_let_0_part_let_0_part": "peek",
"let_1_let_1_part_let_1_part": "peek"
}
# only one Fluid zone
fluid_zone_name = "volume_volume"
# assign Fluid material
solver.tui.define.boundary_conditions.zone_type("volume_volume", "fluid")
try:
solver.setup.cell_zone_conditions.fluid[fluid_zone_name].material = "water-liquid"
print(f" [流体] {fluid_zone_name} -> water-liquid")
except Exception as e:
print(f" [错误] 设置流体材料失败: {e}")
# assign Solid material
for zone, material in solid_mapping.items():
try:
# assign solid parts to solid type
solver.tui.define.boundary_conditions.zone_type(zone, "solid")
# assign materials for solid zones
# cell_zone_conditions.solid[" "] ---> find zones in solid type
solver.setup.cell_zone_conditions.solid[zone].material = material
print(f" [固体] {zone} -> {material}")
except Exception as e:
print(f" [警告] 处理区域 {zone} 时遇到问题: {e}")
print("\n所有材料分配完成!")
# ---------------- Assing heat rate for heat sources -------------------
# assign 1 heat source
"""
heat_sources = "chip_0_chip_0_part_chip_0_part"
chip_object = solver.setup.cell_zone_conditions.solid[heat_sources]
# 把当前的设置单拿下来,存到本地变量 chip_state 里
source_obj = chip_object.sources
# --- 调试步骤:看一眼它想要什么格式 ---
# 如果您不确定 key 是什么,取消下面这行的注释跑一次:
# print(f" [调试] 默认结构: {source_obj.get_state()}")
source_data = {
"enable": True,
"terms": {"energy": [{"option": "value","value": 11e9}]}
}
# 把这个数据包填入设置单的 "source_terms"那一栏
source_obj.set_state(source_data)
print(f" {heat_sources} is assigned with 11e9 W/m³ heat rate")
"""
# assign 4 heat source
all_chips = [
"chip_0_chip_0_part_chip_0_part",
"chip_1_chip_1_part_chip_1_part",
"chip_2_chip_2_part_chip_2_part",
"chip_3_chip_3_part_chip_3_part"
]
heat_rate = 11e9 # W/m^3
# write a dictionary for heat source
source_data = {
"enable": True,
"terms": {"energy": [{"option": "value","value": heat_rate}]}
}
for chip_zone in all_chips:
try:
chip_obj = solver.setup.cell_zone_conditions.solid[chip_zone]
# insert heat rate values for chips
chip_obj.sources.set_state(source_data)
print(f" ✅ done {chip_zone}")
except Exception as e:
print(f" ❌ fail {chip_zone}: {e}")
print("\n all heat sources assigned!")
# check chip_3 state
check_chip = "chip_3_chip_3_part_chip_3_part"
try:
print(f"\n抽查 {check_chip} 的状态:")
# 打印出来应该是 enable: True, 且 value 是 1.1e+10
print(solver.setup.cell_zone_conditions.solid[check_chip].sources.get_state())
except:
print("抽查失败")
# --------------- Change inlet/outlet from Wall to true inlet/outlet boundary -------------------
solver.tui.define.boundary_conditions.zone_type("inlet", "mass-flow-inlet")
solver.tui.define.boundary_conditions.zone_type("outlet", "pressure-outlet")
# define values for boundary conditions
v = mass_flow # mass flow rate kg/s
temp = 293.15 # temperature 20C = 293.15K
gauge_p = 0 # gauge pressure= 0 Pa
# assign values for inlet
try:
inlet = solver.setup.boundary_conditions.mass_flow_inlet["inlet"]
inlet.momentum.mass_flow_rate.value = v
inlet.thermal.total_temperature.value = temp
except AttributeError as e:
print(f"{e}")
print("\n looking for correct API terms")
print(inlet.get_state().keys())
print(inlet.momentum.get_state().keys())
print(inlet.thermal.get_state().keys())
# assign values for outlet
try:
outlet = solver.setup.boundary_conditions.pressure_outlet["outlet"]
outlet.momentum.gauge_pressure.value = gauge_p
outlet.thermal.backflow_total_temperature.value = temp
except AttributeError as a:
print(f"{e}")
print(f"✅ inlet/outlet setting completed")
print(f"inlet temperature = {inlet.thermal.total_temperature.value()} K")
print(f"inlet flow rate = {inlet.momentum.mass_flow_rate.value()} kg/s")
print(f"outlet Pressure = {outlet.momentum.gauge_pressure.value()} Pa")
print(f"outlet temperature = {outlet.thermal.backflow_total_temperature.value()} K")
# ------------------- initialize case and calculate ----------------------
print("\n-------- Starting initialization and calculation --------")
# initialization: must do!!!
solver.tui.solve.initialize.hyb_initialization()
print(" ✅ Initialization completed")
# run calculation
print(f"start compute for {cal_iter} interation... ")
try:
# 核心指令:跑 N 步
solver.tui.solve.iterate(cal_iter)
print(" ✅ Calculation completed!collecting data...")
except Exception as e:
print(f" ❌ stop calcualtion: {e}")
# -------------------- create monitors and grap data ----------------------
# define location of monitor at coldplate channel
# syntax: {"name": [x, y, z], ...., ..., }
pitch = channel_pitch
y_in = -7.5 # in Y
y_out = 7.5 # out Y
z_val = 2.0875 # height Z
channel_map = {
1: -3.0, # end channel
2: -2.0,
3: -1.0,
4: 0.0, # middle channel
5: 1.0,
6: 2.0,
7: 3.0 # end channel
}
# for loop to create monitor points
for ch_id, multiplier in channel_map.items():
# calculate x-location for the channel
x_coord = multiplier * pitch
# Inlet Point name
in_name = f"in-{ch_id}"
# TUI: surface -> point-surface -> name -> x y z
solver.tui.surface.point_surface(in_name, x_coord, y_in, z_val)
# Outlet Point name
out_name = f"out-{ch_id}"
# TUI: surface -> point-surface -> name -> x y z
solver.tui.surface.point_surface(out_name, x_coord, y_out, z_val)
print("✅ 14 monitor points for channel are ready")
# obtain Pressure
print(f"\n-------- collect pressure data --------")
simulation_data = {}
# 1. 采集压力
print("正在读取压力...")
for i in range(1, 8):
for loc in ["in", "out"]:
point_name = f"{loc}-{i}"
report_name = f"rpt_p_{point_name}"
try:
# Step A: 使用 TUI 创建报告 (避开 Python 对象操作)
# 指令逻辑: /solve/report-definitions/add [名字] [类型] field [物理量] surface-names [位置] () q
# () 是为了结束列表输入,q 是退出当前菜单
solver.tui.solve.report_definitions.add(
report_name,
"surface-areaavg",
"field", "total-pressure",
"surface-names", point_name, "()",
"q"
)
# Step B: 使用 TUI 计算并抓取数值
# 【关键修正】路径改为 /solve/report-definitions/compute
# pick-a-real 会自动抓取这条指令打印出来的最后一个数字
cmd = f'(pick-a-real "/solve/report-definitions/compute {report_name}")'
val = solver.scheme_eval.scheme_eval(cmd)
simulation_data[point_name] = val
print(f" ✅ {point_name}: {val:.2f} Pa")
# Step C: 删除报告 (清理环境)
# 路径: /solve/report-definitions/delete [名字]
solver.tui.solve.report_definitions.delete(report_name)
except Exception as e:
print(f" ❌ {point_name} 读取失败: {e}")
simulation_data[point_name] = 0.0
print("\n正在读取温度 (Total Temperature)...")
# define the [x,y,z]
chip_coords = {
"chip-1": [-3.567, 3.715, 0.0], # 左上
"chip-2": [ 3.809, 3.803, 0.0], # 右上
"chip-3": [-4.093, -3.820, 0.0], # 左下
"chip-4": [ 3.809, -3.820, 0.0] # 右下
}
for name, coords in chip_coords.items():
report_name = f"rpt_t_{name}"
try:
# Step A: 创建监测点 (Point Surface)
# TUI: /surface/point-surface [名字] [x] [y] [z]
# 这一步是为了确保有一个叫 "chip-1" 的点存在
try:
solver.tui.surface.point_surface(name, coords[0], coords[1], coords[2])
except Exception:
# 如果点已经存在,覆盖或忽略
pass
# Step B: TUI 创建报告 (Surface Area Avg -> Total Temperature)
# 注意: 这里的 field 是 "total-temperature"
solver.tui.solve.report_definitions.add(
report_name, "surface-areaavg",
"field", "total-temperature",
"surface-names", name, "()",
"q"
)
# Step C: 计算并抓取
cmd = f'(pick-a-real "/solve/report-definitions/compute {report_name}")'
val = solver.scheme_eval.scheme_eval(cmd)
simulation_data[name] = val
print(f" 🌡️ {name}: {val:.2f} K")
# Step D: 清理 (删除报告 + 删除点)
solver.tui.solve.report_definitions.delete(report_name)
# 可选:如果您希望保留点用于后处理,注释掉下面这行
# solver.tui.surface.delete_surface(name)
except Exception as e:
print(f" ❌ {name} 读取失败: {e}")
simulation_data[name] = 0.0
# data collection and export for optimization
# ==============================================================================
import pprint # 引入"漂亮打印"模块
print("\n\n========================================================")
print("🎉 仿真全流程结束,完整数据如下:")
print("========================================================")
# 方法 1: 直接打印字典 (Raw Print)
# print(simulation_data)
# 方法 2: 漂亮打印 (Pretty Print) - 推荐,结构清晰
print("\n[Python Dictionary View]:")
pprint.pprint(simulation_data)
return simulation_data
if __name__ =="__main__":
solver = pyfluent.launch_fluent(mode="solver", precision="double", processor_count=4, ui_mode="no_gui", cleanup_on_exit=False)
mesh_file=r'C:\Users\lichengd\OneDrive - Oregon State University\1. PhD\Chiller\automation\Chiller_auto_Python\Fluent_work_dir\Meshsurface_case\Export_Automesh_coldplate_proximity.msh'
data = runFluent(solver, 0.3068, 2.075, mesh_file, 250)
import Function_saveData
data_row = {"width": 1.6, "flowrate": 0.3068}
data_row.update(data)
proc_data = Function_saveData.save_coldplate_result(data_row, raw_name="CFD_1.6mm_0.3068kg.csv", proc_name="CFD_1.6mm_0.3068kg.csv")
solver.exit()