Skip to content

Instantly share code, notes, and snippets.

@oxyflour
Last active September 3, 2023 04:25
Show Gist options
  • Save oxyflour/a374a5874c1d9f200b516026ada0e18e to your computer and use it in GitHub Desktop.
Save oxyflour/a374a5874c1d9f200b516026ada0e18e to your computer and use it in GitHub Desktop.
cst + gp
import os
import tempfile
import numpy as np
import math
from skopt import gp_minimize
exe = r"D:\Program Files (x86)\CST STUDIO SUITE 2019\AMD64\CST DESIGN ENVIRONMENT_AMD64.exe"
cst = r"C:\Users\oxyfl\Downloads\三频.cst"
ret_tree_path = '1D Results\S-Parameters\S1,1'
ret_skip_rows = 24
# 感兴趣的频段(GHz)
ret_freq_range = [
[2.515, 2.675],
[3.4, 3.6],
[4.8, 4.96],
]
# 参数名,最小值,最大值
# 暂时不支持约束
par = {
'a': (25., 45.),
'b': (35., 55.),
}
# 一开始根据参数数量确定跑多少次
opt_init_calls = 3 * len(par)
# 最多执行 100 次
opt_max_calls = max(opt_init_calls * 2, 100)
def run(cst, par, x):
print('PAR: ', par)
lines = ''
for k, v in zip(par.keys(), x):
lines += f'\nStoreDoubleParameter("{k}", {v})'
bas = os.path.join(tempfile.mktemp("run.bas"))
script = f"""'#Language "WWB-COM"
Option Explicit
Sub Main
OpenFile("{cst}")
{lines}
Rebuild
Solver.Start()
SelectTreeItem("{ret_tree_path}")
StoreCurvesInASCIIFile("{bas}.txt")
End Sub
"""
with open(bas, 'w') as fn:
fn.write(script)
cmd = f'start /wait "title" "{exe}" -m "{bas}" >"{bas}.log" 2>&1'
print('RUN:', cmd)
code = os.system(cmd)
os.unlink(bas)
if code == 0:
with open(bas + '.txt') as fn:
loaded = np.loadtxt(fn, skiprows=ret_skip_rows)
ret = []
for f0, f1 in ret_freq_range:
ret.append(np.average([math.hypot(u, v) for f, u, v, *m in loaded if f > f0 and f < f1]))
print('RET:', ret)
return np.average(ret)
else:
with open(bas + '.log') as fn:
raise ValueError(fn.read())
res = gp_minimize(lambda x: run(cst, par, x), par.values(), n_initial_points=opt_init_calls, n_calls=opt_max_calls)
print(res.x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment