2022年2月20日 星期日

inheritance Example

 類別繼承基本

class mylist(list):
def __init__(self, x):
super().__init__(x)

def multiply(self, x):
temp = [i for i in self]
self.clear()
for i in temp:
self.append(i * x)


x = mylist([1, 2, 3])
x.append(4)
x.multiply(3)
print(x)

2022年2月19日 星期六

Dynamically Add Method To Object

 動態加入方法到物件當中

class foo:
def __init__(self, v):
self.value = v


def new_method(self, v=None):
self.value += v


x = foo(3)
setattr(x, 'add', lambda v: new_method(x, v))

x.add(4)
print(x.value)

2022年1月4日 星期二

利用程式物件來快速定義拓樸

使用者可以指定每個格點的材料來定義馬達截面的拓樸結構。可搭配PyAEDT快速生成Maxwell2D的設計並完成模擬。

from matplotlib.patches import Wedge
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt

m1 = 90
m2 = 45

class topology():
def __init__(self):
self.materials = {}
self.wedges = []
dx = 90 / 20
dy = 0.5 / 20

for i in range(1, 21):
for j in range(1, 20 + 1):
self.materials[i, j] = 0
w = Wedge((0, 0), 0.5 + j * dy, (i-1) * dx, i * dx, dy)
self.wedges.append(w)

def getmaterials(self):
result = []
for i in range(1, 21):
for j in range(1, 20 + 1):
result.append(self.materials[i, j])
return result

def show(self):
cmap = plt.cm.get_cmap('jet')
p = PatchCollection(s.wedges, alpha=1, cmap=cmap, )
p.set_clim(0, 100)
p.set_array(self.getmaterials())
p.set_color('w')
fig, ax = plt.subplots(figsize=(15, 15))
ax.add_collection(p)

s = topology()
s.materials[1, 20] = m1
s.materials[10, 10] = m2
s.materials[20, 1] = m2
for i in [5, 6, 7, 8]:
s.materials[i, 14] = m1
s.show()


2021年12月23日 星期四

HFSS API用來載入激發源設定的csv檔

現有的AEDT API不支援載入激發源的csv,這裡我自己寫了一個。

oProject = oDesktop.GetActiveProject()
oDesign = oProject.GetActiveDesign()
oModule = oDesign.GetModule("Solutions")


def loadExcitation(csv_path):
with open(csv_path) as f:
text = f.readlines()

if 'Source,Magnitude,Phase,Terminated,Resistance,Reactance' in text[0]:
items = []
for line in text[1:]:
Source, Magnitude, Phase, Terminated, Resistance, Reactance = line.strip().split(',')
try:
if Terminated == '1':
items.append([
"Name:=" , Source,
"Terminated:=" , True,
"Resistance:=" , Resistance,
"Reactance:=" , Reactance
])
else:
items.append([
"Name:=" , Source,
"Terminated:=" , False,
"Magnitude:=" , Magnitude,
"Phase:=" , Phase
])
except:
pass
AddWarningMessage(str(items))
oModule.EditSources(
[
[
"UseIncidentVoltage:=" , False,
"IncludePortPostProcessing:=", False,
"SpecifySystemPower:=" , False
]
] + items)

else:
items = []
for line in text[1:]:
try:
Source ,Magnitude ,Phase = line.strip().split(',')
items.append([
"Name:=" , Source,
"Magnitude:=" , Magnitude,
"Phase:=" , Phase])
except:
pass
AddWarningMessage(str(items))
oModule.EditSources(
[
[
"IncludePortPostProcessing:=", False,
"SpecifySystemPower:=" , False
]
] + items)


loadExcitation('d:/demo/sss2.csv')


將3D Layout當中沒有封閉的Polyline封閉成Polygon

如果沒有封閉的曲線不是一個polyline,而是多個分離的線段(line),那麼可以先執行Draw > Stitch Lines將其轉換成單一Polyline,再執行下面腳本。形成封閉polygon之後,接下來便可以進行電磁模擬。

oDesktop.ClearMessages("", "", 2)

oProject = oDesktop.GetActiveProject()
oDesign = oProject.GetActiveDesign()
oEditor = oDesign.GetActiveEditor()

selected = oEditor.GetSelections()

for i in selected:
data = []
placement_layer = oEditor.GetPropertyValue('BaseElementTab', i, 'PlacementLayer')

for j in oEditor.GetProperties('BaseElementTab', i):
if j.startswith('Pt'):
location = oEditor.GetPropertyValue('BaseElementTab', i, j)
x, y = [float(k) for k in location.split(',')]
data += ["x:=", x, "y:=", y]

name = oEditor.CreatePolygon(
[
"NAME:Contents",
"polyGeometry:=",
["Name:=", "poly_1002", "LayerName:=", placement_layer, "lw:=", "0", "n:=", len(data), "U:=", "mm", ] + data
])
AddWarningMessage('{} is created!'.format(name))

oEditor.Delete(selected)



2021年12月7日 星期二

在Q3D輸出頻率點

在Q3D當中找不到輸出頻率的API函數。一個方法是在模擬完成之後,用下面程式碼輸出頻率值:

import ScriptEnv
ScriptEnv.Initialize("Ansoft.ElectronicsDesktop")
oDesktop.RestoreWindow()
oDesktop.ClearMessages("", "", 2)
oProject = oDesktop.GetActiveProject()
oDesign = oProject.GetActiveDesign()

oModule = oDesign.GetModule("ReportSetup")
arr = oModule.GetSolutionDataPerVariation(
"Matrix",
"Setup1 : Sweep1",
["Context:=", "Original"],
['Freq:=', ['All']],
["mag(Freq)"])

freqs = arr[0].GetRealDataValues("mag(Freq)")
AddWarningMessage(str(freqs))

2021年12月1日 星期三

匯入.asc的程式碼

 PADS .asc轉檔程式已沒有更新,不建議使用

import os

os.environ['path'] = 'C:\Program Files\AnsysEM\AnsysEM21.2\Win64'

os.system('padstoanf.exe d:/demo/41266AAB-JOB.asc')
os.system('anfv4toanfv2.exe d:/demo/PadsLayout.anf')

oTool = oDesktop.GetTool("ImportExport")
oTool.ImportANFV2("D:/demo/PadsLayout_V2.anf", "D:/temp/PadsLayout_V21.aedb", "", "")