2022年4月30日 星期六

建立參數化複雜結構

參數化之複雜結構過往都要透過UDP來編寫,困難度很高。PyAEDT可以用幾行程式碼達到要求。以下提供四個範例給各位參考。

from pyaedt import Hfss

hfss = Hfss(specified_version='2022.1', designname='case1')

hfss['Nx'] = '4'
hfss['wx'] = '1mm'
hfss['wy'] = '10mm'
u = 1

models = []
for i in range(100):
x = hfss.modeler.create_rectangle(2,
[f'if(Nx>{i}, {u}*wx, wx)', '0mm', '0mm'],
[f'if(Nx>{i}, {i+1}*wx, wx)', 'wy'],
name='rect')
x.color = (255, 0, 0)
u += i + 2
models.append(x)

hfss.modeler.unite(models)

# %%

from pyaedt import Hfss

hfss = Hfss(specified_version='2022.1', designname='case2')

hfss['Nr'] = 4
hfss['dr'] = '1mm'
hfss['dz'] = '1mm'
hfss['ratio'] = 0.7

rings = []
for i in range(0, 20):
c1 = hfss.modeler.create_circle(2, (0, 0, f'if({i}<Nr, {i}*dz, 0)'), f'if({i}<Nr, {2*i+1}*dr, 1*dr)',
is_covered=False, name=f'c_{2*i}')
c2 = hfss.modeler.create_circle(2, (0, 0, f'if({i}<Nr, ({i}+ratio)*dz, ratio*dz)'), f'if({i}<Nr, {2*i+2}*dr, 2*dr)',
is_covered=False, name=f'c_{2*i+1}')
ring = hfss.modeler.connect([c1, c2])

sheets = hfss.modeler.get_objects_in_group('Sheets')
hfss.modeler.unite(sheets)

# %%

hfss = Hfss(specified_version='2022.1', designname='case3')
N = 4

hfss['dx'] = '4mm'
hfss['dy'] = '3mm'
hfss['dz1'] = '0.2mm'
hfss['dz2'] = '0.1mm'
hfss['configuration'] = [1] * (N ** 2)

create_rectangle = hfss.modeler.create_rectangle
keys = [(i, j) for i in range(N) for j in range(N)]

x = create_rectangle(2, ('0mm', '0mm', '0mm'), (f'{N}*dx', f'{N}*dy'), name='m0')
hfss.modeler.thicken_sheet(x, 'dz2')
for n, (nx, ny) in enumerate(keys):
x = create_rectangle(2,
(f'if(configuration[{n}]==1, {nx}*dx, 0)', f'if(configuration[{n}]==1, {ny}*dy, 0)',
f'if(configuration[{n}]==1, 1mm, 0mm)'),
(f'if(configuration[{n}]==1, dx, {N}*dx)', f'if(configuration[{n}]==1, dy, {N}*dy)'),
name=f'mp{nx}_{ny}_0')
hfss.modeler.thicken_sheet(x, f'if(configuration[{n}]==1, dz1, dz2)')

# %%
from pyaedt import Hfss

hfss = Hfss(specified_version='2022.1', designname='case4')

hfss['Nr'] = 6
hfss['R0'] = '100um'
hfss['W0'] = '20um'
hfss['Pitch'] = '40um'
hfss['Nn'] = 4
hfss['T0'] = '5um'

locations = []
for i in range(200):
locations.append(
(f'if({i}<Nr*Nn, (R0+(Pitch/cos(pi/Nr))*{i}/Nr)*cos(2*pi*{i}/Nr), (R0+(Pitch/cos(pi/Nr))*Nn)*cos(2*pi*Nn))',
f'if({i}<Nr*Nn, (R0+(Pitch/cos(pi/Nr))*{i}/Nr)*sin(2*pi*{i}/Nr), (R0+(Pitch/cos(pi/Nr))*Nn)*sin(2*pi*Nn))',
'0mm'))

hfss.modeler.create_polyline(locations, xsection_type='Line', xsection_width='W0', name='spiral')
hfss.modeler.thicken_sheet('spiral', 'T0')




2022年3月28日 星期一

如何列出特定目錄底下所有.aedt專案與專案包含的設計名稱

當累積的專案數量很多時,想要查找某個設計是放在哪一個.aedt檔當中相當花時間,用下面pyaedt腳本可以輸出所有專案與專案當中的設計名稱與設計類型(HFSS, Q3D, Circuit...)。不須開啟GUI便可完成輸出。

folder = r"D:\demo\Examples"

import os
import pyaedt
from pyaedt import Desktop

aedts = []
for dirPath, dirNames, fileNames in os.walk(folder):
for f in fileNames:
if f.endswith('.aedt'):
aedts.append(os.path.join(dirPath, f))

info = {}
desktop = Desktop(specified_version='2022.1', non_graphical=True)
for n, i in enumerate(aedts):
if os.path.isfile(i + '.lock'):
os.remove(i + '.lock')
print(f'{n}/{len(aedts)}:{i}')
try:
oproject = desktop.odesktop.OpenProject(i)
designs = oproject.GetChildNames()
types = [oproject.GetChildObject(j).GetDesignType() for j in designs]
info[i] = list(zip(designs, types))
oproject.Close()
except:
pass
desktop.close_desktop()

# %%
design_map = {'HFSS': pyaedt.Hfss,
'HFSS 3D Layout Design': pyaedt.Hfss3dLayout,
'Q3D Extractor': pyaedt.Q3d,
'2D Extractor': pyaedt.Q2d,
'Circuit Design': pyaedt.Circuit,
'Maxwell 2D': pyaedt.Maxwell2d,
'Maxwell 3D': pyaedt.Maxwell3d,
'Icepak': pyaedt.Icepak,
'Twin Builder': pyaedt.TwinBuilder,
'Mechanical': pyaedt.Mechanical,
'EMIT': pyaedt.Emit,
'RMxprt': pyaedt.Rmxprt
}

k = 0
result = {}
for i, design_info in info.items():
result[i] = []
for m, n in design_info:
try:
app = design_map[n](i, m, specified_version='2022.1')
image_path = os.path.abspath(f'{k}.jpg')
app.export_design_preview_to_jpg(image_path)
k += 1
app.close_project()

result[i].append((m, n, image_path))
except:
raise

# %%

css = '''
<style>
* {
box-sizing: border-box;
}

/* Create three equal columns that floats next to each other */
.column {
float: left;
width: 25%;
padding: 10px;
height: 300px; /* Should be removed. Only for demonstration */
}

/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
</style>
'''

with open('summary.html', 'w') as f:
f.write(css)
for aedt_path, data in result.items():
f.write(f'<H2 style="color:blue;">{aedt_path}</H2>\n')
f.write('<div class="row">\n')
for design_name, design_type, image in data:
f.write('<div class="column">\n')
f.write(f'<H3>{design_name} ({design_type})</H3>\n')
f.write(f'<img src="{image}" width="200">\n')
f.write('</div>\n')
f.write('</div>\n')
os.system('summary.html')
print(result)






2022年3月26日 星期六

如何在AEDT比較不同專案設計的S參數

在AEDT比較不同專案設計的S參數

prj_design = [('bp_filter', 'HFSSDesign1', 'S(2,1)'), 
('OptimTee', 'TeeModel', 'S(1,1)') ]


#%%
from pyaedt import Hfss
import matplotlib.pyplot as plt

color = ['r', 'b', 'g', 'y', 'm', 'c']

cases = []
for prj, design, quantity in prj_design:
cases.append((Hfss(projectname=prj, designname=design, specified_version='2022.1',), quantity))

#%%

fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
for (i, q), c in zip(cases, color):
result = i.post.get_report_data(f'polar({q})')
ax.plot(result.data_imag(), result.data_real(), color=c)

fig.show()

#%%
fig, ax = plt.subplots()
plt.grid()
for (i, q), c in zip(cases, color):
result = i.post.get_report_data(f'db({q})')
ax.plot(result.sweeps['Freq'], result.data_real(), color=c)

fig.show()

#%%
fig, ax = plt.subplots()
plt.grid()
for (i, q), c in zip(cases, color):
result = i.post.get_report_data(f'ang_deg({q})')
ax.plot(result.sweeps['Freq'], result.data_real(), color=c)

fig.show()


2022年3月12日 星期六

如何輸出HFSS近場資料


import numpy as np
import matplotlib.pyplot as plt
from pyaedt import Hfss
hfss = Hfss(specified_version='2022.1')

data = hfss.post.get_solution_data_per_variation('Near Fields', 'Setup1 : LastAdaptive', "Rectangle1", expression='NearEX')
print(data.units_data)

x_real = data.solutions_data_real['NearEX'].values()
x_imag = data.solutions_data_imag['NearEX'].values()
data.sweeps['_u']
NearEX = [complex(i, j) for i, j in zip(x_real, x_imag)]

NearEX = np.array(NearEX)
x = np.reshape(np.absolute(NearEX), (len(data.sweeps['_u']), len(data.sweeps['_v'])))

u_min, u_max = min(data.sweeps['_u'])*1000, max(data.sweeps['_u'])*1000
v_min, v_max = min(data.sweeps['_v']), max(data.sweeps['_v'])

plt.xlabel('u')
plt.ylabel('v')
plt.imshow(x, cmap='jet', extent = [u_min, u_max, v_min, v_max])
(圖一) Python輸出近場
(圖二) HFSS近場



如何輸出HFSS遠場資料

以下方法可以用在HFSS任何遠場物理量輸出,使用np.ndarray可以加快矩陣運算速度。

import numpy as np
import matplotlib.pyplot as plt
from pyaedt import Hfss
hfss = Hfss(specified_version='2022.1')

data = hfss.post.get_far_field_data(['rETheta', 'rEPhi'],
'Setup1 : LastAdaptive',
'3D')
print(data.units_data)

x_real = data.solutions_data_real['rETheta']
x_imag = data.solutions_data_imag['rETheta']
rETheta = [complex(x_real[i], x_imag[i]) for i in x_real]


x_real = data.solutions_data_real['rEPhi']
x_imag = data.solutions_data_imag['rEPhi']
rEPhi = [complex(x_real[i], x_imag[i]) for i in x_real]

rEPhi = np.array(rEPhi)
x = np.reshape(np.absolute(rEPhi), (361, 181))

plt.xlabel('Phi')
plt.ylabel('Theta')
plt.imshow(x.T, cmap='jet')

(圖一) Python輸出
(圖二)HFSS輸出









2022年2月14日 星期一

如何將平面轉變成曲面

使用PyAEDT模組,適合簡單平面。

# -*- coding: utf-8 -*-
"""
Created on Mon Feb 14 23:36:29 2022

@author: mlin
"""
from math import sqrt
from collections import defaultdict
from scipy import interpolate
from pyaedt import Hfss

hfss = Hfss(specified_version='2021.2')

x = hfss.modeler.object_list
path = x[1]
polygon = x[0]

ds = 0
s_map = {}
for edge in path.edges:
v1, v2 = edge.vertices
x1, y1, z1 = v1.position
x2, y2, z2 = v2.position
if len(s_map) == 0:
s_map[ds] = [(0, 0)]
ds += sqrt((x2 - x1) ** 2 + (z2 - z1) ** 2)
s_map[ds] = (x2, z2)

result = defaultdict(list)

for edge in polygon.edges:
v1, v2 = edge.vertices
x1, y1, z1 = v1.position
x2, y2, z2 = v2.position
x = [x1, x2]
y = [y1, y2]
f = interpolate.interp1d(x, y)
if x2 > x1:
new_s = [i for i in s_map.keys() if x2 >= i >= x1]
else:
new_s = [i for i in reversed(s_map.keys()) if x2 <= i <= x1]

print(new_s)
new_y = f(new_s)
for s, y3 in zip(new_s, new_y):
x3, z3 = s_map[s]
result[s].append((x3, y3, z3))

keys = [k for k in result]
pieces = []
for m, n in zip(keys[0:-1], keys[1:]):
v1, v2 = result[m][0:2]
v4, v3 = result[n][0:2]
p = hfss.modeler.primitives.create_polyline([v1, v2, v3, v4], cover_surface=True, close_surface=True)
pieces.append(p)

sheet = hfss.modeler.unite(pieces)
hfss.modeler.purge_history([pieces[0].name])



2022年2月8日 星期二

如何輸出任一AEDT專案3D模型不同視角圖片檔

範例碼如下(當中export3DModel在0.4.26版輸出.obj仍有問題,需手動修改):

import os
from pyaedt import Hfss
from pyaedt.generic.plot import ModelPlotter

hfss = Hfss('d:/demo/RADHAZ_MIL-STD-461C_ICNIRP.aedt', 'HERP', non_graphical=True)

data = {}
for i in hfss.modeler.object_list:
key = (i.color, i.transparency)
if key in data:
data[key].append(i)
else:
data[key] = [i]

cad = {}
for key, objs in data.items():
filename = objs[0].name
hfss.export3DModel(filename, hfss.temp_directory, '.obj', object_list=[i.name for i in objs])
cad[key] = os.path.join(hfss.temp_directory, filename + '.obj')

hfss.close_desktop()

model = ModelPlotter()
model.bounding_box = False
model.show_legend = False
model.show_grid = True
model.show_axes = False
model.off_screen = True
model.background_color = (240,240,240)
model.zoom = 1

for (color, transparency), cad_path in cad.items():
model.add_object(cad_path, cad_color=color, opacity=1-transparency)

for angle in range(0, 360, 30):
model.set_orientation('yz', 0, angle, 30)
model.plot('d:/demo2/view_{}.png'.format(angle))



EDB建立PinGroup

為U2A5建立GND PinGroup,儲存之後匯入EDB from pyaedt import Edb edb = Edb(edbpath= r"D:\demo\Galileo_G87173_20454.aedb" , edbversion= '20...