83
0
0

根据老学长的建模py脚本写了个机翼参数自动优化脚本

2026-05-13
2026-11-29
根据老学长的建模py脚本写了个机翼参数自动优化脚本
文章摘要
|

最近折腾机翼结构有限元分析,基于老学长留下的 Abaqus 建模脚本,顺手把整套流程改造成了一套 参数化求解 + 自动结构优化 脚本:在满足最大 Mises 应力不超标的前提下,让优化器自动压低机翼结构质量。

整体分三步走:

  1. 原始建模脚本(autowing2.2.py):老学长打好的地基,负责把机翼几何、梁肋长桁、载荷和边界条件一口气建出来。
  2. 参数化求解器(wing_solver.py):把建模脚本封装成可反复调用的函数,加入「拓扑不变时免重建几何」的加速模式,并自动读取 .odb 提取质量与最大应力。
  3. 自动优化主程序(optimizer.py):套上 SciPy 的 SLSQP 优化器,配合仿真缓存与 CSV 日志,自动迭代找最轻方案。

Chapter 1:从建模脚本开始

感谢老学长的贡献,感觉最难的一部分就是建模脚本化了(((,赞美老学长.jpg

这份脚本负责从翼型 .dat 坐标文件出发,自动完成 蒙皮拉伸 → 基准面切分 → 肋板/腹板盖面 → 梁与长桁 Stringer 建立 → 材料与截面指派 → 挂弹/油箱集中质量耦合 → 过载与翼根边界条件施加 → 划分网格并提交计算 整条链路。下面在保持原逻辑不变的前提下,顺手把缩进、排版和分段注释整理了一遍,方便对照阅读。

原始建模脚本:autowing2.2.py

介里系完整代码(点击展开)
# -*- coding: utf-8 -*-
from abaqus import *
from abaqusConstants import *
from caeModules import *
from odbMaterial import *
from odbSection import *
from odbAccess import *
import interaction
import mesh
import part
import regionToolset
import visualization

from math import *
from struct import *
from string import *
import glob
import os
import os.path
import time

from te2 import *
from te3 import *
if org == 1:
    from te1 import *
else:
    from te import *
    from te4 import *

# ==============================================================================
# 1. 材料参数定义
# ==============================================================================
# LY-4 铝合金
DLY4 = 2850
ELY4 = (68000000000.0, 0.33)
# LY-9 铝合金
DLY9 = 2800
ELY9 = (68000000000.0, 0.33)
# LY-12 铝合金
DLY12 = 2800
ELY12 = (68000000000.0, 0.33)
# OCr15Ni7Mo2Al 不锈钢
DOCr15 = 7800
EOCr15 = (199000000000.0, 0.33)

# ==============================================================================
# 2. 翼型草图绘制与弦长缩放
# ==============================================================================
dataName = str(profile3)
# dataName = path3 + "wingprofile/" + profile3
print(dataName)
with open(dataName, 'r') as f:
    data = f.readlines()

aa0 = []
aa1 = []
for line in data:
    cols = line.split()
    aa0.append(cols[0])
    aa1.append(cols[1])

session.viewports['Viewport: 1'].setValues(displayedObject=None)
model = mdb.models['Model-1']

s = model.ConstrainedSketch(name='__profile__', sheetSize=1000.0)
g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
s.setPrimaryObject(option=STANDALONE)

bb = []
for i in range(len(data)):
    pt = (float(aa0[i]), float(aa1[i]))
    s.Spot(point=pt)
    bb.append(pt)
bb.append((float(aa0[0]), float(aa1[0])))

s.Spline(points=bb)
model.sketches.changeKey(fromName='__profile__', toName='Sketch-1')

# 按弦长 l 缩放翼型草图
scale_objs = [g[2]]
for i in range(len(v)):
    scale_objs.append(v[i])
s.scale(scaleValue=l, scaleCenter=(0.0, 0.0), objectList=scale_objs)
s.unsetPrimaryObject()

# 分析步时间参数(保留原脚本字段)
st = 0.004
IT_target = 5.0e-8

# ==============================================================================
# 3. 创建 Abaqus 材料
# ==============================================================================
for mat_name, density, elastic in [
    ('LY-4', DLY4, ELY4),
    ('LY-9', DLY9, ELY9),
    ('LY-12', DLY12, ELY12),
    ('OCr15Ni7Mo2Al', DOCr15, EOCr15),
]:
    mat = model.Material(name=mat_name)
    mat.Density(table=((density,),))
    mat.Elastic(table=(elastic,))

# ==============================================================================
# 4. 拉伸生成机翼蒙皮壳体 (plate-1)
# ==============================================================================
session.viewports['Viewport: 1'].setValues(displayedObject=None)
s = model.ConstrainedSketch(name='__profile__', sheetSize=200.0)
g, v1, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
s.setPrimaryObject(option=STANDALONE)
s.sketchOptions.setValues(gridOrigin=(0.4997, 0.0154334306716919))
s.retrieveSketch(sketch=model.sketches['Sketch-1'])
session.viewports['Viewport: 1'].view.fitView()

p = model.Part(
    name='plate-1',
    dimensionality=THREE_D,
    type=DEFORMABLE_BODY,
)
p.BaseShellExtrude(sketch=s, depth=W)
s.unsetPrimaryObject()
session.viewports['Viewport: 1'].setValues(displayedObject=p)
del model.sketches['__profile__']

c = p.faces
p.Set(faces=c[0:len(c)], name='mengpi')

# ==============================================================================
# 5. 创建基准面并切分蒙皮(翼肋 / 翼梁 / 长桁位置)
# ==============================================================================
sum1 = 0.0
for i in range(A1 - 1):
    sum1 += D1
    p.DatumPlaneByPrincipalPlane(principalPlane=XYPLANE, offset=sum1)

p.DatumPlaneByPrincipalPlane(principalPlane=YZPLANE, offset=l1 * l)
A2 = int((1.0 - l1) * l // D2) - 1
A3 = int(l1 * l // D2)

sum2 = 0.0
sum3 = 0.0
d = p.datums
for i in range(A2 - 1):
    sum2 += D2
    p.DatumPlaneByOffset(plane=d[2 + A1], flip=SIDE1, offset=sum2)
for i in range(A3 - 1):
    sum3 += D2
    p.DatumPlaneByOffset(plane=d[2 + A1], flip=SIDE2, offset=sum3)

for i in range(A1 + A2 + A3 - 2):
    c, e, v, d = p.faces, p.edges, p.vertices, p.datums
    p.PartitionFaceByDatumPlane(datumPlane=d[i + 3], faces=c[0:len(c)])

# ==============================================================================
# 6. 盖面生成肋板与梁腹板 (CoverEdges) 及集合划分
# ==============================================================================
# 内部肋板盖面
for i in range(A1 - 1):
    feat_name = 'Partition face' + str(-(i + 1))
    p.CoverEdges(edgeList=p.getFeatureEdges(feat_name), tryAnalytical=True)

# 翼根与翼尖端面盖面
e, f = p.edges, p.faces
e1 = e.getByBoundingBox(-50.0, -50.0, -0.1, 50.0, 50.0, 0.1)
e2 = e.getByBoundingBox(-50.0, -50.0, W - 0.1, 50.0, 50.0, W + 0.1)
p.CoverEdges(edgeList=e1 + e2, tryAnalytical=True)

p.PartitionFaceByDatumPlane(datumPlane=d[A1 + 2], faces=c[0:len(c)])
p.PartitionFaceByDatumPlane(datumPlane=d[int(A1 + 2 + 0.6 * A2)], faces=c[0:len(c)])

# 普通肋板集合 (PTleiban)
fff = []
for i in range(0, 1):
    ff = f.getByBoundingBox(-50.0, -50.0, i * D1 - 0.01, 50.0, 50.0, i * D1 + 0.01)
    fff.append(ff)
for i in range(2, int(0.5 * A1)):
    ff = f.getByBoundingBox(-50.0, -50.0, i * D1 - 0.001, 50.0, 50.0, i * D1 + 0.001)
    fff.append(ff)
for i in range(int(0.5 * A1 + 1), A1 + 1):
    ff = f.getByBoundingBox(-50.0, -50.0, i * D1 - 0.001, 50.0, 50.0, i * D1 + 0.001)
    fff.append(ff)
p.Set(faces=fff, name='PTleiban')

# 加强肋板集合 (JQleiban)
jq_z1 = 1 * D1
jq_z2 = int(0.5 * A1) * D1
ff1 = f.getByBoundingBox(-50.0, -50.0, jq_z1 - 0.0001, 50.0, 50.0, jq_z1 + 0.0001)
ff2 = f.getByBoundingBox(-50.0, -50.0, jq_z2 - 0.0001, 50.0, 50.0, jq_z2 + 0.0001)
p.Set(faces=[ff1, ff2], name='JQleiban')

# 前梁腹板 (qianliangfuban)
str2 = 'Partition face' + str(-A1)
e3 = e.findAt(((l * l1, 0, 0),))
e4 = e.findAt(((l * l1, 0, W),))
p.CoverEdges(edgeList=p.getFeatureEdges(str2) + e3 + e4, tryAnalytical=True)
str4 = 'Cover edges' + str(-(A1 + 1))
p.Set(faces=p.getFeatureFaces(str4), name='qianliangfuban')

# 后梁腹板 (houliangfuban)
x_rear_spar = l * l1 + int(0.6 * A2) * D2
e1 = e.getByBoundingBox(x_rear_spar - 0.001, 0, -50, x_rear_spar + 0.001, 50, 50)
e2 = e.getByBoundingBox(x_rear_spar - 0.001, -50, -50, x_rear_spar + 0.001, 0, 50)
e3 = e.findAt(((x_rear_spar, 0, 0),))
e4 = e.findAt(((x_rear_spar, 0, W),))
p.CoverEdges(edgeList=e1 + e2 + e3 + e4, tryAnalytical=True)
str4 = 'Cover edges' + str(-(A1 + 2))
p.Set(faces=p.getFeatureFaces(str4), name='houliangfuban')

# ==============================================================================
# 7. 创建梁、长桁与加强肋缘条 (Stringer)
# ==============================================================================
e = p.edges

# 长桁 1(前梁之后)
eee = []
for i in range(0, int(A2 * 0.6) - 1):
    x_pos = l * l1 + (i + 1) * D2
    eee.append(e.getByBoundingBox(x_pos - 0.001, -50.0, -50.0, x_pos + 0.001, 50.0, 50.0))
for i in range(int(A2 * 0.6), A2):
    x_pos = l * l1 + (i + 1) * D2
    eee.append(e.getByBoundingBox(x_pos - 0.001, -50.0, -50.0, x_pos + 0.001, 50.0, 50.0))
p.Stringer(edges=eee, name='STchanghang1')
p.Set(stringerEdges=(('STchanghang1', eee),), name='changhang1')

# 长桁 2(前梁之前)
eee = []
for i in range(0, A3):
    x_pos = l * l1 - (i + 1) * D2
    eee.append(e.getByBoundingBox(x_pos - 0.001, -50.0, -50.0, x_pos + 0.001, 50.0, 50.0))
p.Stringer(edges=eee, name='STchanghang2')
p.Set(stringerEdges=(('STchanghang2', eee),), name='changhang2')

# 前梁缘条 (qianliang)
eee = [
    e.getByBoundingBox(l * l1 - 0.001, 0, -50, l * l1 + 0.001, 50, 50),
    e.getByBoundingBox(l * l1 - 0.001, -50, -50, l * l1 + 0.001, 0, 50),
]
p.Stringer(edges=eee, name='STqianliang')
p.Set(stringerEdges=(('STqianliang', eee),), name='qianliang')

# 后梁缘条 (houliang)
eee = [
    e.getByBoundingBox(x_rear_spar - 0.001, 0, -50, x_rear_spar + 0.001, 50, 50),
    e.getByBoundingBox(x_rear_spar - 0.001, -50, -50, x_rear_spar + 0.001, 0, 50),
]
p.Stringer(edges=eee, name='SThouliang')
p.Set(stringerEdges=(('SThouliang', eee),), name='houliang')

# 加强肋缘条 1 & 2
for name_jq, z_pos in [('jiangqianglei1', jq_z1), ('jiangqianglei2', jq_z2)]:
    eee = [
        e.getByBoundingBox(-50.0, 0, z_pos - 0.00001, 50.0, 50.0, z_pos + 0.00001),
        e.getByBoundingBox(-50.0, -50.0, z_pos - 0.00001, 50.0, 0, z_pos + 0.00001),
        e.getByBoundingBox(l1 * l + 0.0001, -50.0, z_pos - 0.00001, 50.0, 50.0, z_pos + 0.00001),
        e.getByBoundingBox(-50.0, -50.0, z_pos - 0.00001, l1 * l - 0.0001, 50.0, z_pos + 0.00001),
    ]
    p.Stringer(edges=eee, name=name_jq)
    p.Set(stringerEdges=((name_jq, eee),), name=name_jq)

# ==============================================================================
# 8. 截面轮廓 (Profile) 与截面属性 (Section)
# ==============================================================================
if poumian == 1:
    model.LProfile(name='changhang', a=numA2, b=numB2, t1=numt1, t2=numt2)
    model.RectangularProfile(name='liang', a=numA1, b=numB1)
    model.RectangularProfile(name='leibanyuantiao', a=0.5 * numA1, b=0.5 * numB1)
elif poumian == 2:
    model.IProfile(
        name='liang', l=numL1, h=numH1, b1=numB1, b2=numB2,
        t1=numT1, t2=numT2, t3=numT3,
    )
    model.TProfile(name='changhang', b=numB3, h=numH2, l=numL2, tf=numTF, tw=numTW)
    model.RectangularProfile(name='leibanyuantiao', a=0.5 * numB1, b=0.5 * numB1)
elif poumian == 3:
    model.TProfile(name='liang', b=numB4, h=numH3, l=numL3, tf=numTF2, tw=numTW2)
    model.LProfile(name='changhang', a=numA2, b=numB2, t1=numt1, t2=numt2)
    model.RectangularProfile(name='leibanyuantiao', a=0.5 * numB4, b=0.25 * numB4)

# 梁截面
model.BeamSection(
    name='liang', integration=DURING_ANALYSIS, poissonRatio=0.0,
    profile='liang', material='OCr15Ni7Mo2Al',
    temperatureVar=LINEAR, consistentMassMatrix=False,
)
model.BeamSection(
    name='changhang', integration=DURING_ANALYSIS, poissonRatio=0.0,
    profile='changhang', material='LY-4',
    temperatureVar=LINEAR, consistentMassMatrix=False,
)
model.BeamSection(
    name='leibanyuantiao', integration=DURING_ANALYSIS, poissonRatio=0.0,
    profile='leibanyuantiao', material='LY-4',
    temperatureVar=LINEAR, consistentMassMatrix=False,
)

# 壳截面(蒙皮、梁腹板、普通/加强肋板)
shell_specs = [
    ('mp', 'LY-12', 0.002),
    ('liangfuban', 'LY-9', numh1),
    ('PTleiban', 'LY-4', numh2),
    ('JQleiban', 'LY-4', 2 * numh2),
]
for sec_name, mat_name, thick in shell_specs:
    model.HomogeneousShellSection(
        name=sec_name, preIntegrate=OFF, material=mat_name,
        thicknessType=UNIFORM, thickness=thick, thicknessField='',
        idealization=NO_IDEALIZATION, poissonDefinition=DEFAULT,
        thicknessModulus=None, temperature=GRADIENT, useDensity=OFF,
        integrationRule=SIMPSON, numIntPts=5,
    )

# ==============================================================================
# 9. 截面指派与梁方向定义
# ==============================================================================
houliang_sec = 'liang' if num == 2 else ('changhang' if num == 1 else None)
assignments = [
    ('qianliangfuban', 'liangfuban'),
    ('houliangfuban', 'liangfuban'),
    ('PTleiban', 'PTleiban'),
    ('JQleiban', 'JQleiban'),
    ('mengpi', 'mp'),
    ('qianliang', 'liang'),
    ('changhang1', 'changhang'),
    ('changhang2', 'changhang'),
    ('jiangqianglei1', 'leibanyuantiao'),
    ('jiangqianglei2', 'leibanyuantiao'),
]
if houliang_sec is not None:
    assignments.append(('houliang', houliang_sec))

for set_name, sec_name in assignments:
    p.SectionAssignment(
        region=p.sets[set_name],
        sectionName=sec_name,
        offset=0.0,
        offsetType=MIDDLE_SURFACE,
        offsetField='',
        thicknessAssignment=FROM_SECTION,
    )

# 梁截面法向 (N1_COSINES)
p.assignBeamSectionOrientation(region=p.sets['qianliang'], method=N1_COSINES, n1=(1.0, 0.0, 0.0))
p.assignBeamSectionOrientation(region=p.sets['houliang'], method=N1_COSINES, n1=(1.0, 0.0, 0.0))

if poumian in (1, 3):
    orient_specs = [
        ('changhang1', (-1.0, 0.0, 0.0)),
        ('houliang', (-1.0, 0.0, 0.0)),
        ('changhang2', (1.0, 0.0, 0.0)),
    ]
elif poumian == 2:
    orient_specs = [
        ('changhang1', (1.0, 0.0, 0.0)),
        ('houliang', (1.0, 0.0, 0.0)),
        ('changhang2', (-1.0, 0.0, 0.0)),
    ]
else:
    orient_specs = []

for set_name, n1_vec in orient_specs:
    p.assignBeamSectionOrientation(region=p.sets[set_name], method=N1_COSINES, n1=n1_vec)

p.assignBeamSectionOrientation(region=p.sets['jiangqianglei1'], method=N1_COSINES, n1=(0.0, 0.0, -1.0))
p.assignBeamSectionOrientation(region=p.sets['jiangqianglei2'], method=N1_COSINES, n1=(0.0, 0.0, -1.0))

# ==============================================================================
# 10. 装配、分析步与集中质量耦合(挂弹 / 油箱)
# ==============================================================================
a = model.rootAssembly
session.viewports['Viewport: 1'].setValues(displayedObject=a)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(
    optimizationTasks=OFF, geometricRestrictions=OFF, stopConditions=OFF,
)
a.DatumCsysByDefault(CARTESIAN)
a.Instance(name='plate-1-1', part=p, dependent=OFF)

model.StaticStep(
    name='Step-1', previous='Initial',
    stabilizationMagnitude=0.0002,
    stabilizationMethod=DISSIPATED_ENERGY_FRACTION,
    continueDampingFactors=False,
    adaptiveDampingRatio=0.05,
    initialInc=0.1,
    minInc=1e-09,
    nlgeom=ON,
)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='Step-1')
session.viewports['Viewport: 1'].assemblyDisplay.setValues(
    interactions=ON, constraints=ON, connectors=ON, engineeringFeatures=ON,
)

if num == 2:
    RP1 = a.ReferencePoint(point=(0.5 * l, 0.0, jq_z1))
    RP2 = a.ReferencePoint(point=(0.5 * l, 0.0, jq_z2))
    RP3 = a.ReferencePoint(point=(0.5 * l, 0.0, int(0.3 * A1) * D1))
elif num == 1:
    RP1 = a.ReferencePoint(point=(0.5 * l, 0.0, jq_z1))
    RP2 = a.ReferencePoint(point=(0.5 * l, 0.0, jq_z2))
    RP3 = a.ReferencePoint(point=(0.5 * l, 0.0, int(0.3 * A1) * D1))
    RP4 = a.ReferencePoint(point=(x_rear_spar, 0.0, 0.0))

r1 = a.referencePoints
s1 = a.instances['plate-1-1'].faces
face_jq1 = s1.getByBoundingBox(-50.0, -50.0, jq_z1 - 0.001, 50.0, 50.0, jq_z1 + 0.001)
face_jq2 = s1.getByBoundingBox(-50.0, -50.0, jq_z2 - 0.001, 50.0, 50.0, jq_z2 + 0.001)

for cname, rp_idx, surf_faces, m_val in [
    ('zaidan1', 4, face_jq1, mass * 0.5 * 0.05),
    ('zaidan2', 5, face_jq2, mass * 0.5 * 0.05),
    ('youxiang', 6, face_jq1 + face_jq2, mass * 0.5 * 0.35),
]:
    rp_region = regionToolset.Region(referencePoints=(r1[rp_idx],))
    surf_region = regionToolset.Region(side1Faces=surf_faces)
    model.Coupling(
        name=cname, controlPoint=rp_region, surface=surf_region,
        influenceRadius=WHOLE_SURFACE, couplingType=DISTRIBUTING,
        weightingMethod=UNIFORM, localCsys=None,
        u1=ON, u2=ON, u3=ON, ur1=ON, ur2=ON, ur3=ON,
    )
    a.engineeringFeatures.PointMassInertia(
        name=cname, region=rp_region, mass=m_val, alpha=0.0, composite=0.0,
    )

# ==============================================================================
# 11. 边界条件(双梁 / 单梁)与过载载荷
# ==============================================================================
e_inst = a.instances['plate-1-1'].edges
e1 = e_inst.findAt(((l * l1, 0, 0),))
e2 = e_inst.findAt(((x_rear_spar, 0, 0),))

if num == 2:
    # 双梁翼根全固支
    a.Set(edges=e1 + e2, name='BC-1')
    model.EncastreBC(
        name='BC-1', createStepName='Initial',
        region=a.sets['BC-1'], localCsys=None,
    )
elif num == 1:
    # 单梁:前梁固支 + 后梁铰接耦合
    a.Set(edges=e1, name='BC-1')
    a.Set(edges=e2, name='BC-12')
    model.EncastreBC(
        name='BC-1', createStepName='Initial',
        region=a.sets['BC-1'], localCsys=None,
    )
    rp7_region = regionToolset.Region(referencePoints=(r1[7],))
    model.PinnedBC(
        name='BC-2', createStepName='Initial',
        region=rp7_region, localCsys=None,
    )
    model.Coupling(
        name='houliangjiaojie', controlPoint=rp7_region,
        surface=a.sets['BC-12'], influenceRadius=WHOLE_SURFACE,
        couplingType=DISTRIBUTING, weightingMethod=UNIFORM,
        localCsys=None, u1=ON, u2=ON, u3=ON, ur1=ON, ur2=ON, ur3=ON,
    )

# 过载重力场
model.Gravity(
    name='gravity', createStepName='Step-1',
    comp2=9.8 * overload, distributionType=UNIFORM, field='',
)

# ==============================================================================
# 12. 网格划分与提交计算
# ==============================================================================
partInstances = (a.instances['plate-1-1'],)
a.seedPartInstance(
    regions=partInstances, size=SIZE,
    deviationFactor=0.1, minSizeFactor=0.1,
)
a.generateMesh(regions=partInstances)

mdb.Job(
    name='Job-wing', model='Model-1', description='', type=ANALYSIS,
    atTime=None, waitMinutes=0, waitHours=0, queue=None,
    memory=90, memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True,
    explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE,
    echoPrint=OFF, modelPrint=OFF, contactPrint=OFF, historyPrint=OFF,
    userSubroutine='', scratch='', resultsFormat=ODB,
    multiprocessingMode=DEFAULT, numCpus=2, numDomains=2, numGPUs=1,
)
mdb.jobs['Job-wing'].submit(consistencyChecking=OFF)

Chapter 2:参数化求解与自动优化

一顿改改改,报错一顿修修修,电脑逐渐红温,眼皮逐渐打架,精神逐渐涣散……

参数化求解器:wing_solver.py

相比原始的一次性建模脚本,wing_solver.py 主要做了三点改造:

  • 双模式加速(rebuild_geo):当肋间距 D1 或长桁间距 D2 变化时走「模式一:完整建模」重建几何与网格;当拓扑结构不变、仅调整板厚或截面尺寸时,直接走「模式二:属性更新」,原位修改截面参数并复用已有网格,大幅节省迭代耗时。
  • 拓扑自适应划分:按目标间距取整段数后再反算实际间距(D1_real、D2_rear、D2_front),避免翼尖或后缘冒出畸形窄网格。
  • 自动后处理回传:求解结束后自动调用 getMassProperties() 获取结构质量,并读取 .odb 末帧全场最大 von Mises 应力,直接返回 (total_mass, max_mises) 给优化器。

小提示:脚本里的翼型路径 NACA_2412.dat 偷懒写死了本地路径,实际复用时记得替换成你自己的 .dat 文件路径。

点击查看秘密情报(wing_solver.py)
# -*- coding: utf-8 -*-
from abaqus import *
from abaqusConstants import *
from odbMaterial import *
from odbSection import *
from odbAccess import *
import regionToolset
from math import *


def run_wing_simulation(
    W=5.0,
    overload=2.0,
    aircraft_mass=6000.0,
    D1=0.5,
    D2=0.15,
    mp_t=0.002,
    numh1=0.005,
    numh2=0.005,
    st_a=0.03,
    st_b=0.03,
    st_t1=0.005,
    st_t2=0.005,
    bm_a=0.05,
    bm_b=0.05,
    rebuild_geo=True,
):
    """参数化机翼有限元求解器。

    支持两种执行模式:
    - rebuild_geo=True:完整重建几何、集合与网格(D1/D2 拓扑变化时使用)。
    - rebuild_geo=False:复用既有网格,仅原位更新截面尺寸与载荷属性以加速优化。

    Returns:
        tuple[float, float]: (结构总质量 total_mass [kg], 最大 Mises 应力 max_mises [Pa])
    """
    job_name = 'Job-wing'

    try:
        if rebuild_geo:
            # ==================================================================
            # 模式一:完整建模(当 D1 或 D2 发生变化时,重新构建几何与网格)
            # ==================================================================
            Mdb()
            model = mdb.models['Model-1']

            # 懒得写个文件路径选择,直接写死了,反正不改翼型(((x
            profile3 = r"E:\EXP\Fifth\wingprofile\NACA_2412.dat"
            l = 1.5      # 弦长 (m)
            l1 = 0.3     # 前梁弦向位置比例
            num = 1      # 单梁构型
            SIZE = 0.05  # 全局网格尺寸 (m)

            # 拓扑自适应划分:先取整段数再反算实际间距,避免尾部出现畸形窄网格
            A1 = max(2, int(round(W / D1)))
            D1_real = W / A1

            L_rear = (1.0 - l1) * l
            A2 = max(3, int(round(L_rear / D2)))
            D2_rear = L_rear / A2

            L_front = l1 * l
            A3 = max(2, int(round(L_front / D2)))
            D2_front = L_front / A3

            # 材料定义
            materials = [
                ('LY-4', 2850, (680e9, 0.33)),
                ('LY-9', 2800, (680e9, 0.33)),
                ('LY-12', 2800, (680e9, 0.33)),
                ('OCr15Ni7Mo2Al', 7800, (199e9, 0.33)),
            ]
            for mat_name, density, elastic in materials:
                mat = model.Material(name=mat_name)
                mat.Density(table=((density,),))
                mat.Elastic(table=(elastic,))

            # 翼型草图绘制与缩放
            with open(str(profile3), 'r') as f:
                data = f.readlines()

            bb = []
            for line in data:
                cols = line.split()
                bb.append((float(cols[0]), float(cols[1])))
            bb.append(bb[0])

            s = model.ConstrainedSketch(name='__profile__', sheetSize=1000.0)
            g, v = s.geometry, s.vertices
            s.setPrimaryObject(option=STANDALONE)
            for pt in bb[:-1]:
                s.Spot(point=pt)
            s.Spline(points=bb)
            model.sketches.changeKey(fromName='__profile__', toName='Sketch-1')

            scale_objs = [g[2]] + [v[i] for i in range(len(v))]
            s.scale(scaleValue=l, scaleCenter=(0.0, 0.0), objectList=scale_objs)
            s.unsetPrimaryObject()

            # 三维拉伸生成蒙皮壳体
            s = model.ConstrainedSketch(name='__profile__', sheetSize=200.0)
            s.setPrimaryObject(option=STANDALONE)
            s.retrieveSketch(sketch=model.sketches['Sketch-1'])
            p = model.Part(
                name='plate-1',
                dimensionality=THREE_D,
                type=DEFORMABLE_BODY,
            )
            p.BaseShellExtrude(sketch=s, depth=W)
            s.unsetPrimaryObject()
            del model.sketches['__profile__']

            c = p.faces
            p.Set(faces=c[0:len(c)], name='mengpi')

            # 生成展向与弦向切分基准面
            sum1 = 0.0
            for _ in range(A1 - 1):
                sum1 += D1_real
                p.DatumPlaneByPrincipalPlane(principalPlane=XYPLANE, offset=sum1)

            p.DatumPlaneByPrincipalPlane(principalPlane=YZPLANE, offset=l1 * l)
            d = p.datums

            sum2 = 0.0
            for _ in range(A2 - 1):
                sum2 += D2_rear
                p.DatumPlaneByOffset(plane=d[2 + A1], flip=SIDE1, offset=sum2)

            sum3 = 0.0
            for _ in range(A3 - 1):
                sum3 += D2_front
                p.DatumPlaneByOffset(plane=d[2 + A1], flip=SIDE2, offset=sum3)

            # 执行切分与翼肋盖面
            for i in range(A1 + A2 + A3 - 2):
                c = p.faces
                p.PartitionFaceByDatumPlane(datumPlane=d[i + 3], faces=c[0:len(c)])

            for i in range(A1 - 1):
                feat_name = 'Partition face' + str(-(i + 1))
                p.CoverEdges(edgeList=p.getFeatureEdges(feat_name), tryAnalytical=True)

            e, f = p.edges, p.faces
            e1 = e.getByBoundingBox(-50, -50, -0.1, 50, 50, 0.1)
            e2 = e.getByBoundingBox(-50, -50, W - 0.1, 50, 50, W + 0.1)
            p.CoverEdges(edgeList=e1 + e2, tryAnalytical=True)

            c = p.faces
            p.PartitionFaceByDatumPlane(datumPlane=d[A1 + 2], faces=c[0:len(c)])
            p.PartitionFaceByDatumPlane(
                datumPlane=d[int(A1 + 2 + 0.6 * A2)],
                faces=c[0:len(c)],
            )

            # 创建面集合 (Sets)
            jq_z1 = 1 * D1_real
            jq_z2 = int(0.5 * A1) * D1_real
            x_front_spar = l * l1
            x_rear_spar = l * l1 + int(0.6 * A2) * D2_rear

            fff = [f.getByBoundingBox(-50, -50, -0.01, 50, 50, 0.01)]
            for i in range(2, int(0.5 * A1)):
                z = i * D1_real
                fff.append(f.getByBoundingBox(-50, -50, z - 0.001, 50, 50, z + 0.001))
            for i in range(int(0.5 * A1 + 1), A1 + 1):
                z = i * D1_real
                fff.append(f.getByBoundingBox(-50, -50, z - 0.001, 50, 50, z + 0.001))
            p.Set(faces=fff, name='PTleiban')

            fff_jq = [
                f.getByBoundingBox(-50, -50, jq_z1 - 0.0001, 50, 50, jq_z1 + 0.0001),
                f.getByBoundingBox(-50, -50, jq_z2 - 0.0001, 50, 50, jq_z2 + 0.0001),
            ]
            p.Set(faces=fff_jq, name='JQleiban')

            # 前后梁腹板盖面与集合
            str2 = 'Partition face' + str(-A1)
            front_web_edges = (
                p.getFeatureEdges(str2)
                + e.findAt(((x_front_spar, 0, 0),))
                + e.findAt(((x_front_spar, 0, W),))
            )
            p.CoverEdges(edgeList=front_web_edges, tryAnalytical=True)
            p.Set(
                faces=p.getFeatureFaces('Cover edges' + str(-(A1 + 1))),
                name='qianliangfuban',
            )

            e1 = e.getByBoundingBox(x_rear_spar - 0.001, 0, -50, x_rear_spar + 0.001, 50, 50)
            e2 = e.getByBoundingBox(x_rear_spar - 0.001, -50, -50, x_rear_spar + 0.001, 0, 50)
            rear_web_edges = (
                e1 + e2
                + e.findAt(((x_rear_spar, 0, 0),))
                + e.findAt(((x_rear_spar, 0, W),))
            )
            p.CoverEdges(edgeList=rear_web_edges, tryAnalytical=True)
            p.Set(
                faces=p.getFeatureFaces('Cover edges' + str(-(A1 + 2))),
                name='houliangfuban',
            )

            # 创建梁及长桁单元特征 (Stringers)
            eee = []
            for i in range(0, int(A2 * 0.6) - 1):
                x = x_front_spar + (i + 1) * D2_rear
                eee.append(e.getByBoundingBox(x - 0.001, -50, -50, x + 0.001, 50, 50))
            for i in range(int(A2 * 0.6), A2 - 1):
                x = x_front_spar + (i + 1) * D2_rear
                eee.append(e.getByBoundingBox(x - 0.001, -50, -50, x + 0.001, 50, 50))
            p.Stringer(edges=eee, name='STchanghang1')
            p.Set(stringerEdges=(('STchanghang1', eee),), name='changhang1')

            eee = []
            for i in range(0, A3 - 1):
                x = x_front_spar - (i + 1) * D2_front
                eee.append(e.getByBoundingBox(x - 0.001, -50, -50, x + 0.001, 50, 50))
            p.Stringer(edges=eee, name='STchanghang2')
            p.Set(stringerEdges=(('STchanghang2', eee),), name='changhang2')

            front_spar_edges = [
                e.getByBoundingBox(x_front_spar - 0.001, 0, -50, x_front_spar + 0.001, 50, 50),
                e.getByBoundingBox(x_front_spar - 0.001, -50, -50, x_front_spar + 0.001, 0, 50),
            ]
            p.Stringer(edges=front_spar_edges, name='STqianliang')
            p.Set(
                stringerEdges=(('STqianliang', p.stringers['STqianliang'].edges),),
                name='qianliang',
            )

            rear_spar_edges = [
                e.getByBoundingBox(x_rear_spar - 0.001, 0, -50, x_rear_spar + 0.001, 50, 50),
                e.getByBoundingBox(x_rear_spar - 0.001, -50, -50, x_rear_spar + 0.001, 0, 50),
            ]
            p.Stringer(edges=rear_spar_edges, name='SThouliang')
            p.Set(
                stringerEdges=(('SThouliang', p.stringers['SThouliang'].edges),),
                name='houliang',
            )

            for name_jq, z_pos in [('jiangqianglei1', jq_z1), ('jiangqianglei2', jq_z2)]:
                eee = [
                    e.getByBoundingBox(-50, 0, z_pos - 0.00001, 50, 50, z_pos + 0.00001),
                    e.getByBoundingBox(-50, -50, z_pos - 0.00001, 50, 0, z_pos + 0.00001),
                    e.getByBoundingBox(x_front_spar + 0.0001, -50, z_pos - 0.00001, 50, 50, z_pos + 0.00001),
                    e.getByBoundingBox(-50, -50, z_pos - 0.00001, x_front_spar - 0.0001, 50, z_pos + 0.00001),
                ]
                p.Stringer(edges=eee, name=name_jq)
                p.Set(stringerEdges=((name_jq, eee),), name=name_jq)

            # 定义截面轮廓与截面属性
            model.LProfile(name='changhang', a=st_a, b=st_b, t1=st_t1, t2=st_t2)
            model.RectangularProfile(name='liang', a=bm_a, b=bm_b)
            model.RectangularProfile(name='leibanyuantiao', a=0.5 * bm_a, b=0.5 * bm_b)

            for sec_name, prof_name, mat_name in [
                ('liang', 'liang', 'OCr15Ni7Mo2Al'),
                ('changhang', 'changhang', 'LY-4'),
                ('leibanyuantiao', 'leibanyuantiao', 'LY-4'),
            ]:
                model.BeamSection(
                    name=sec_name, integration=DURING_ANALYSIS,
                    poissonRatio=0.0, profile=prof_name, material=mat_name,
                    temperatureVar=LINEAR, consistentMassMatrix=False,
                )

            for sec_name, mat_name, thick in [
                ('mp', 'LY-12', mp_t),
                ('liangfuban', 'LY-9', numh1),
                ('PTleiban', 'LY-4', numh2),
                ('JQleiban', 'LY-4', 2 * numh2),
            ]:
                model.HomogeneousShellSection(
                    name=sec_name, preIntegrate=OFF, material=mat_name,
                    thicknessType=UNIFORM, thickness=thick,
                    integrationRule=SIMPSON, numIntPts=5,
                )

            # 截面指派与梁方向
            section_map = [
                ('qianliangfuban', 'liangfuban'),
                ('houliangfuban', 'liangfuban'),
                ('PTleiban', 'PTleiban'),
                ('JQleiban', 'JQleiban'),
                ('mengpi', 'mp'),
                ('qianliang', 'liang'),
                ('changhang1', 'changhang'),
                ('changhang2', 'changhang'),
                ('jiangqianglei1', 'leibanyuantiao'),
                ('jiangqianglei2', 'leibanyuantiao'),
                ('houliang', 'changhang'),
            ]
            for set_name, sec_name in section_map:
                p.SectionAssignment(
                    region=p.sets[set_name], sectionName=sec_name,
                    offset=0.0, offsetType=MIDDLE_SURFACE,
                    thicknessAssignment=FROM_SECTION,
                )

            orient_map = [
                ('qianliang', (1.0, 0.0, 0.0)),
                ('changhang1', (-1.0, 0.0, 0.0)),
                ('houliang', (-1.0, 0.0, 0.0)),
                ('changhang2', (1.0, 0.0, 0.0)),
                ('jiangqianglei1', (0.0, 0.0, -1.0)),
                ('jiangqianglei2', (0.0, 0.0, -1.0)),
            ]
            for set_name, vec in orient_map:
                p.assignBeamSectionOrientation(
                    region=p.sets[set_name], method=N1_COSINES, n1=vec,
                )

            # 装配、分析步、相互作用、边界条件与网格
            a = model.rootAssembly
            a.DatumCsysByDefault(CARTESIAN)
            a.Instance(name='plate-1-1', part=p, dependent=OFF)
            model.StaticStep(
                name='Step-1', previous='Initial',
                stabilizationMagnitude=0.0002,
                stabilizationMethod=DISSIPATED_ENERGY_FRACTION,
                adaptiveDampingRatio=0.05,
                initialInc=0.1, minInc=1e-09, nlgeom=ON,
            )

            a.ReferencePoint(point=(0.5 * l, 0.0, jq_z1))
            a.ReferencePoint(point=(0.5 * l, 0.0, jq_z2))
            a.ReferencePoint(point=(0.5 * l, 0.0, int(0.3 * A1) * D1_real))
            a.ReferencePoint(point=(x_rear_spar, 0.0, 0.0))

            s1 = a.instances['plate-1-1'].faces
            r1 = a.referencePoints
            face_jq1 = s1.getByBoundingBox(-50, -50, jq_z1 - 0.001, 50, 50, jq_z1 + 0.001)
            face_jq2 = s1.getByBoundingBox(-50, -50, jq_z2 - 0.001, 50, 50, jq_z2 + 0.001)

            for cname, rp_idx, surf_faces, m_val in [
                ('zaidan1', 4, face_jq1, aircraft_mass * 0.5 * 0.05),
                ('zaidan2', 5, face_jq2, aircraft_mass * 0.5 * 0.05),
                ('youxiang', 6, face_jq1 + face_jq2, aircraft_mass * 0.5 * 0.35),
            ]:
                rp_region = regionToolset.Region(referencePoints=(r1[rp_idx],))
                surf_region = regionToolset.Region(side1Faces=surf_faces)
                model.Coupling(
                    name=cname, controlPoint=rp_region, surface=surf_region,
                    influenceRadius=WHOLE_SURFACE, couplingType=DISTRIBUTING,
                    weightingMethod=UNIFORM,
                    u1=ON, u2=ON, u3=ON, ur1=ON, ur2=ON, ur3=ON,
                )
                a.engineeringFeatures.PointMassInertia(
                    name=cname, region=rp_region, mass=m_val,
                )

            e_inst = a.instances['plate-1-1'].edges
            a.Set(edges=e_inst.findAt(((x_front_spar, 0, 0),)), name='BC-1')
            a.Set(edges=e_inst.findAt(((x_rear_spar, 0, 0),)), name='BC-12')

            model.EncastreBC(
                name='BC-1', createStepName='Initial', region=a.sets['BC-1'],
            )
            rp7_region = regionToolset.Region(referencePoints=(r1[7],))
            model.PinnedBC(
                name='BC-2', createStepName='Initial', region=rp7_region,
            )
            model.Coupling(
                name='houliangjiaojie', controlPoint=rp7_region,
                surface=a.sets['BC-12'], influenceRadius=WHOLE_SURFACE,
                couplingType=DISTRIBUTING, weightingMethod=UNIFORM,
                u1=ON, u2=ON, u3=ON, ur1=ON, ur2=ON, ur3=ON,
            )

            model.Gravity(
                name='gravity', createStepName='Step-1',
                comp2=9.8 * overload, distributionType=UNIFORM,
            )

            inst_tuple = (a.instances['plate-1-1'],)
            a.seedPartInstance(
                regions=inst_tuple, size=SIZE,
                deviationFactor=0.1, minSizeFactor=0.1,
            )
            a.generateMesh(regions=inst_tuple)

            mdb.Job(
                name=job_name, model='Model-1', type=ANALYSIS,
                numCpus=2, numDomains=2,
            )

        else:
            # ==================================================================
            # 模式二:属性更新(拓扑不变时,仅更新截面尺寸与载荷,无需重划网格)
            # ==================================================================
            m = mdb.models['Model-1']

            # 1. 更新梁与长桁截面尺寸
            m.profiles['changhang'].setValues(a=st_a, b=st_b, t1=st_t1, t2=st_t2)
            m.profiles['liang'].setValues(a=bm_a, b=bm_b)
            m.profiles['leibanyuantiao'].setValues(a=0.5 * bm_a, b=0.5 * bm_b)

            # 2. 更新蒙皮、梁腹板与肋板厚度
            m.sections['mp'].setValues(thickness=mp_t)
            m.sections['liangfuban'].setValues(thickness=numh1)
            m.sections['PTleiban'].setValues(thickness=numh2)
            m.sections['JQleiban'].setValues(thickness=2 * numh2)

            # 3. 更新过载与集中质量参数
            m.loads['gravity'].setValues(comp2=9.8 * overload)
            inertias = m.rootAssembly.engineeringFeatures.inertias
            inertias['zaidan1'].setValues(mass=aircraft_mass * 0.5 * 0.05)
            inertias['zaidan2'].setValues(mass=aircraft_mass * 0.5 * 0.05)
            inertias['youxiang'].setValues(mass=aircraft_mass * 0.5 * 0.35)

        # 提交任务并等待求解完成
        mdb.jobs[job_name].submit(consistencyChecking=OFF)
        mdb.jobs[job_name].waitForCompletion()

        # 后处理:提取结构总质量与最大 Mises 应力
        mass_prop = mdb.models['Model-1'].parts['plate-1'].getMassProperties()
        total_mass = mass_prop['mass']

        odb = openOdb(path=job_name + '.odb')
        stress_field = odb.steps.values()[-1].frames[-1].fieldOutputs['S']
        max_mises = max([val.mises for val in stress_field.values if val.mises])
        odb.close()

        return total_mass, max_mises

    except Exception as e:
        raise Exception("Abaqus 仿真引擎执行错误: " + str(e))

优化脚本:optimizer.py

Powered by SciPy SLSQP

优化器部分接入了 scipy.optimize.minimize 的 SLSQP(序列二次规划)算法,核心思路如下:

  • 目标与约束归一化:结构质量在 10^2 kg 量级,而应力约束在 10^8 Pa(许用应力 300 MPa)量级,直接丢进梯度优化器很容易数值失衡。因此目标函数归一化为 mass / 100.0,应力约束归一化为 (ALLOWABLE_STRESS - max_stress) / 1e7 >= 0。
  • 为什么 11 个变量里实际只优化 9 个:SLSQP 依赖数值差分梯度,要求目标函数连续可微;而肋间距 D1 和长桁间距 D2 一旦变动就会引发离散段数跳变与网格重建,梯度直接炸掉。因此当前版本先通过上下界锁死 D1 = 0.5 m、D2 = 0.15 m,专注优化其余 9 个连续厚度与截面尺寸变量。
  • 仿真缓存与日志记录:SLSQP 在同一设计点会分别调用 objective(x) 和 stress_constraint(x),通过截断至 8 位小数的 simulation_cache 避免同一点跑两遍 Abaqus;同时每次迭代都会实时追加写入 optimizer_log.csv 方便后续画收敛曲线。
变量 物理含义 初始值 优化范围 备注
D1 肋间距 0.500 m 锁定 0.500 m 离散拓扑变量,暂不放开
D2 长桁间距 0.150 m 锁定 0.150 m 离散拓扑变量,暂不放开
mp_t 蒙皮厚度 6 mm 2 ~ 10 mm 连续变量
numh1 梁腹板厚度 6 mm 2 ~ 20 mm 连续变量
numh2 肋腹板厚度 6 mm 2 ~ 20 mm 连续变量(加强肋自动取 2 * numh2)
st_a, st_b 长桁 L 型截面边长 30 mm 10 ~ 60 mm 连续变量
st_t1, st_t2 长桁 L 型截面壁厚 5 mm 2 ~ 10 mm 连续变量
bm_a, bm_b 主梁矩形截面宽高 50 mm 20 ~ 100 mm 连续变量
点击查看能人智工优化方案(optimizer.py)
# -*- coding: utf-8 -*-
import csv
import os
import numpy as np
from scipy.optimize import minimize

import wing_solver

# 在 Abaqus CAE 交互会话中重复运行时强制重载求解器模块
try:
    reload(wing_solver)
except NameError:
    import importlib
    importlib.reload(wing_solver)

# ==============================================================================
# 全局工况与约束常量
# ==============================================================================
ALLOWABLE_STRESS = 300e6   # 许用应力 300 MPa
W_SPAN = 5.0               # 半展长 (m)
OVERLOAD = 2.0             # 过载倍数 (g)
AIRCRAFT_MASS = 6000.0     # 起飞质量 (kg)

CSV_FILENAME = "optimizer_log.csv"

# 运行态缓存(避免同一设计点在目标/约束函数中重复求解)
last_D1 = -1.0
last_D2 = -1.0
simulation_cache = {}
iteration_count = 0


def init_csv():
    """初始化优化迭代日志 CSV。"""
    if os.path.exists(CSV_FILENAME):
        try:
            os.remove(CSV_FILENAME)
        except Exception:
            pass

    with open(CSV_FILENAME, mode='w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow([
            "迭代数", "模式", "肋间距(mm)", "长桁间距(mm)",
            "蒙皮厚(mm)", "梁腹厚(mm)", "肋腹厚(mm)",
            "长桁a(mm)", "长桁b(mm)", "长桁t1(mm)", "长桁t2(mm)",
            "梁a(mm)", "梁b(mm)",
            "质量(kg)", "最大应力(MPa)", "状态",
        ])


def run_abaqus_cached(x):
    """带结果缓存与双模式切换的 Abaqus 仿真封装。"""
    global iteration_count, last_D1, last_D2
    D1, D2, mp_t, numh1, numh2, st_a, st_b, st_t1, st_t2, bm_a, bm_b = x

    # 截断至 8 位小数作为缓存键值,避免浮点微小误差导致缓存失效
    key = tuple(round(v, 8) for v in x)
    if key in simulation_cache:
        return simulation_cache[key]

    iteration_count += 1

    if abs(D1 - last_D1) > 1e-5 or abs(D2 - last_D2) > 1e-5:
        rebuild_flag = True
        mode_text = "[完整建模]"
    else:
        rebuild_flag = False
        mode_text = "[属性更新]"

    print("\n[Iter {:<3}] {} 迭代计算中...".format(iteration_count, mode_text))

    try:
        mass, max_stress = wing_solver.run_wing_simulation(
            W=W_SPAN,
            overload=OVERLOAD,
            aircraft_mass=AIRCRAFT_MASS,
            D1=D1,
            D2=D2,
            mp_t=mp_t,
            numh1=numh1,
            numh2=numh2,
            st_a=st_a,
            st_b=st_b,
            st_t1=st_t1,
            st_t2=st_t2,
            bm_a=bm_a,
            bm_b=bm_b,
            rebuild_geo=rebuild_flag,
        )

        stress_mpa = max_stress / 1e6
        note = "安全" if max_stress <= ALLOWABLE_STRESS else "超标"
        print(" -> 计算结果: 质量 {:.2f} kg | 应力 {:.2f} MPa | 状态: {}".format(
            mass, stress_mpa, note
        ))

        last_D1 = D1
        last_D2 = D2

    except Exception as e:
        mass, max_stress = 1e6, 1e10
        stress_mpa = max_stress / 1e6
        note = "特征报错"
        print(" -> 计算异常: 几何错误跳过 ({})".format(e))

        last_D1 = -1.0
        last_D2 = -1.0

    simulation_cache[key] = (mass, max_stress)

    try:
        with open(CSV_FILENAME, mode='a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([
                iteration_count, mode_text,
                round(D1 * 1000, 1), round(D2 * 1000, 1),
                round(mp_t * 1000, 2), round(numh1 * 1000, 2), round(numh2 * 1000, 2),
                round(st_a * 1000, 1), round(st_b * 1000, 1),
                round(st_t1 * 1000, 2), round(st_t2 * 1000, 2),
                round(bm_a * 1000, 1), round(bm_b * 1000, 1),
                round(mass, 2), round(stress_mpa, 2), note,
            ])
    except Exception:
        pass

    return mass, max_stress


def objective(x):
    """目标函数:最小化机翼质量(归一化至 O(1) 量级以提升收敛性)。"""
    mass, _ = run_abaqus_cached(x)
    return mass / 100.0


def stress_constraint(x):
    """不等式约束:许用应力 - 最大 Mises 应力 >= 0(归一化避免量级失衡)。"""
    _, max_stress = run_abaqus_cached(x)
    return (ALLOWABLE_STRESS - max_stress) / 1e7


if __name__ == "__main__":
    init_csv()
    print("=" * 60)
    print(" 机翼结构优化程序启动")
    print(" 设定工况: 起飞重量 {} kg | 过载 {} g".format(AIRCRAFT_MASS, OVERLOAD))
    print("=" * 60)

    # 初始设计变量:板厚略微取厚,确保初始构型满足应力约束
    x0 = [
        0.500,  # D1    : 肋间距 (0.5 m)
        0.150,  # D2    : 长桁间距 (0.15 m)
        0.006,  # mp_t  : 蒙皮厚度 (6 mm)
        0.006,  # numh1 : 梁腹板厚度 (6 mm)
        0.006,  # numh2 : 肋腹板厚度 (6 mm)
        0.030,  # st_a  : 长桁截面宽度/高度 a (30 mm)
        0.030,  # st_b  : 长桁截面宽度/高度 b (30 mm)
        0.005,  # st_t1 : 长桁截面厚度 t1 (5 mm)
        0.005,  # st_t2 : 长桁截面厚度 t2 (5 mm)
        0.050,  # bm_a  : 梁截面宽度/高度 a (50 mm)
        0.050,  # bm_b  : 梁截面宽度/高度 b (50 mm)
    ]

    bnds = (
        (0.500, 0.500),  # D1    : 上下界锁死在 0.5 m,保持几何拓扑不变
        (0.150, 0.150),  # D2    : 上下界锁死在 0.15 m,保持几何拓扑不变
        (0.002, 0.010),  # mp_t  : 2 mm ~ 10 mm
        (0.002, 0.020),  # numh1 : 2 mm ~ 20 mm
        (0.002, 0.020),  # numh2 : 2 mm ~ 20 mm
        (0.010, 0.060),  # st_a  : 10 mm ~ 60 mm
        (0.010, 0.060),  # st_b  : 10 mm ~ 60 mm
        (0.002, 0.010),  # st_t1 : 2 mm ~ 10 mm
        (0.002, 0.010),  # st_t2 : 2 mm ~ 10 mm
        (0.020, 0.100),  # bm_a  : 20 mm ~ 100 mm
        (0.020, 0.100),  # bm_b  : 20 mm ~ 100 mm
    )

    cons = {'type': 'ineq', 'fun': stress_constraint}

    res = minimize(
        objective,
        x0,
        method='SLSQP',
        bounds=bnds,
        constraints=cons,
        options={'disp': True, 'eps': 1e-4, 'maxiter': 50},
    )

    print("\n优化任务执行完毕。")

写在最后

这个格式怎么那么难调啊 Ovo

不是,为什么会有半期之后直接开始考试月的啊 QAQ,博主接下来一个月有四门考试,接下来六周大概率有六门考试……不说了,复习去了。至于肋间距、长桁间距这类离散拓扑变量的联合优化,只能等考完试之后再试试遗传算法了。

博主看代码看到崩溃(((

期末月的博主belike

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或者给予支持!

评论