Skill: yongjie666888/motor-parameter-calculator (version 1.2.0)

--- name: motor-parameter-calculator description: 电机设计参数计算助手 | 根据基本参数计算极槽配合、匝数、磁密、反电动势等核心设计数据 version: 1.2.0 tags: [motor, design, calculation, pole-slot, winding, flux, back-emf] category: motor-engineering --- # 电机设计参数计算助手 v1.2 根据输入的基本电机参数，快速计算极槽配合、每槽导体数、绕组系数、磁密、反电动势等关键设计数据。 **v1.2新增：完整参数计算脚本(param_calculator.py)、槽数扫描分析、性能估算。** ## 计算脚本 ```bash # 标准计算 python scripts/param_calculator.py --poles 8 --Q 36 --L 60 --Di 54 --delta 0.5 --Bg 0.75 # 指定绕组参数 python scripts/param_calculator.py --poles 8 --Q 36 --Nph 120 --Imax 15 --R 0.8 # 槽数扫描分析（方案比选） python scripts/param_calculator.py --sweep_slots --poles 8 --L 60 --Di 54 # 交互模式 python scripts/param_calculator.py --mode interactive ``` ## 适用场景 - 电机设计初期参数估算 - 极槽配合方案比选（槽数扫描） - 匝数/线径设计计算 - 磁密验算 ## 输入参数 | 参数 | 说明 | 示例值 | |------|------|--------| | 极数 (2p) | 极数，必须为偶数 | 8 | | 槽数 (Q) | 定子槽数 | 36 | | 相数 (m) | 相数，通常为3 | 3 | | 频率 (f) | 电源频率 Hz | 50 | | 转速 (n) | 额定转速 rpm | 1500 | | 极距 (τ) | 极距 mm | 56.5 | | 气隙直径 (D) | 定子内径 mm | 120 | | 铁心长度 (L) | 铁心长度 mm | 100 | | 气隙磁密 (Bg) | 气隙磁密 T | 0.75 | | 每相串联匝数 Nph | 匝数 | 100 | | 额定电流 Imax | 相电流峰值 A | 10 | | 相电阻 R | Ω | 1.0 | ## 计算内容 | 计算项 | 公式 | 说明 | |--------|------|------| | 极距 τ | π×Di/2p | mm | | 每极每相槽数 q | Q/(2p×m) | 分数槽判断 | | 分布系数 Kd | sin(q×αe/2)/(q×sin(αe/2)) | q>1时生效 | | 短距系数 Kp | sin(πy/2τ) | y=节距槽数 | | 总绕组系数 Kw | Kd×Kp | 通常>0.85 | | 每极气隙磁通 Φg | Bg×τ×L | mWb | | 反电动势常数 Ke | 4.44×f×Nph×Kw×Φg | V（线间有效值）| | 转矩常数 Kt | 1.5×p×Kw×Nph×Φg | Nm/A | | 机械时间常数 Tm | J×R/(3×(Nph×Kw×Φg×p)²) | s | ## 槽数扫描分析 扫描不同槽数方案，对比 q、Kw、τ、Kt 等参数，辅助选型： ```bash python scripts/param_calculator.py --sweep_slots --poles 8 --L 60 --Di 54 ``` 典型扫描结果格式： ``` Q q Kw τ/mm Bg/T Kt 36 1.500 0.9450 21.2 0.750 0.1234 48 2.000 0.9660 16.9 0.750 0.1234 24 1.000 1.0000 42.4 0.750 0.1234 ``` ## 常见极槽配合参考 | 极数 | 槽数 | q | 特点 | |------|------|---|------| | 8 | 36 | 1.5 | 分数槽，常见伺服电机 | | 8 | 48 | 2.0 | 整数槽，低齿槽转矩 | | 6 | 36 | 2.0 | 整数槽，平衡性好 | | 10 | 60 | 2.0 | 整数槽，低振动 | | 4 | 24 | 2.0 | 整数槽，简单绕制 | ## 示例对话 ``` 用户：帮我计算极数8，槽数48，相数3，频率50Hz，转速1500rpm的极槽配合参数 助手：运行 param_calculator.py，自动计算 q值、每槽角度、绕组系数等 用户：对比8极36槽和8极48槽 助手：运行 --sweep_slots 模式，给出对比表格 ```

path: calculator.js
content: /**
 * 电机设计参数计算器 v2
 * 支持：极槽配合、匝数设计、磁密验算、反电动势、转矩常数、选型推荐
 *
 * 用法:
 *   node calculator.js poles=8 slots=36 freq=50 speed=3000 boreD=54 coreL=60 airGap=0.5 Br=1.25 Ns=28 a=2
 *   node calculator.js --interactive
 *   node calculator.js --mode compare_slots
 */

const assert = require('assert');

// ============================================================
// 核心计算函数
// ============================================================

function deg2rad(d) { return d * Math.PI / 180; }
function rad2deg(r) { return r * 180 / Math.PI; }

/**
 * 极槽配合计算
 */
function calculatePoleSlot(poles, slots, phases = 3) {
    const p = poles / 2;
    const q = slots / (poles * phases);  // 每极每相槽数
    const slotPerPole = slots / poles;
    const isFractional = !Number.isInteger(q);

    // 每槽机械角度
    const mechAnglePerSlot = 360 / slots;  // deg
    const elecAnglePerSlot = mechAnglePerSlot * p;  // deg

    // 绕组分布系数（60°相带）
    const alpha = deg2rad(elecAnglePerSlot);  // 每槽电气角度
    let kd = 1.0;
    if (q > 1) {
        kd = Math.sin(q * alpha / 2) / (q * Math.sin(alpha / 2));
    }

    // 短距系数（默认 5/6 节距 y=5τ/6）
    const y = Math.round(slotPerPole * 5 / 6);  // 槽数
    const shortPitchRatio = y / slotPerPole;
    const kp = shortPitchRatio < 1 ? shortPitchRatio : 1.0;
    const kw = kd * kp;

    // 槽配合类型判断
    let slotType = '整数槽绕组';
    if (isFractional) {
        if (q < 1) slotType = '分数槽集中绕组';
        else slotType = '分数槽绕组';
    }

    return {
        p, q, slotPerPole, isFractional, slotType,
        mechAnglePerSlot, elecAnglePerSlot,
        kd, kp, kw, y, shortPitchRatio,
        slots, poles, phases
    };
}

/**
 * 气隙磁密与磁通计算
 */
function calculateFluxDensity(poles, slots, boreDiameter, coreLength, airGap, Br, hm, sigma = 1.2) {
    const p = poles / 2;
    const tau = Math.PI * boreDiameter / poles;  // 极距 mm

    // 极弧宽度估算（假设极弧系数 0.8）
    const poleArcWidth = tau * 0.8;
    const Am = poleArcWidth * coreLength;  // 永磁体投影面积 mm²
    const Ae = tau * coreLength;           // 气隙截面积 mm²

    // 气隙磁密估算
    const Bg = sigma * Br * Am / (airGap * Ae);
    const Phi_g = Bg * Ae * 1e-6;  // Wb

    // 齿部磁密估算（简化）
    const toothWidth = tau / 3;  // 齿宽约为极距的1/3
    const slotPitch = Math.PI * boreDiameter / slots;
    const slotWidth = slotPitch - toothWidth;
    const At = toothWidth * coreLength;  // 齿部截面积 mm²
    const B_t = Phi_g * 2 / (At * 1e-6);  // 齿部磁密 T（双侧通量）

    // 轭部磁密估算
    const yokeHeight = tau / 3;
    const Ay = yokeHeight * coreLength;
    const B_y = Phi_g / (Ay * 1e-6) / 2;  // 轭部磁密 T

    return { tau, Bg, Phi_g, B_t, B_y, Am, Ae };
}

/**
 * 每相串联匝数和反电动势计算
 */
function calculateEMF(params) {
    const {
        poles, slots, phases, freq, speed,
        boreDiameter, coreLength, airGap, Br, hm, Ns = 28, a = 2,
        sigma = 1.2, kw = 0.933
    } = params;

    const p = poles / 2;

    // 每相串联匝数
    const Nph = slots * Ns / (2 * a);

    // 气隙磁通
    const fd = calculateFluxDensity(poles, slots, boreDiameter, coreLength, airGap, Br, hm, sigma);
    const Phi_g = fd.Phi_g;

    // 反电动势（线间有效值）
    // E = 4.44 * f * Nph * Kw * Phi_g * 2 (线间)
    const Ke_line_rms = 4.44 * freq * Nph * kw * Phi_g * 2;  // V @ freq Hz
    // 机械转速对应
    const n_sync = 120 * freq / poles;  // 同步转速 rpm
    const Ke_at_speed = Ke_line_rms * speed / n_sync;  // V @ 实际转速

    // 转矩常数
    const omega_e = 2 * Math.PI * freq;  // rad/s 电气角速度
    const Psi_m = Phi_g * kw * Nph;     // 简化磁链
    const Kt = 1.5 * p * Psi_m;         // Nm/A

    return {
        Nph, Kw: kw, Phi_g,
        Ke_line_rms, Ke_at_speed,
        Kt, n_sync,
        freq, speed
    };
}

/**
 * 齿槽转矩估算
 */
function estimateCoggingTorque(poles, slots, Br, R_ro, L) {
    // 齿槽转矩与 (Br^2 * slot_num * pole_num) 相关
    // 简化经验公式：T_cog ∝ (Br^2 * Q * p * R^2 * L) / (g^2)
    // 此处给出一个相对估算值
    const p = poles / 2;
    const airGap = 0.5;  // 默认气隙
    const T_cog_ratio = Br * Br * slots * p * Math.pow(R_ro/50, 2) * (L/50) / Math.pow(airGap, 2);
    const T_cog_estimate = T_cog_ratio * 0.0001;  // Nm，经验系数

    // 判断大小
    let level = '正常';
    if (T_cog_ratio > 500) level = '⚠️ 偏大，建议斜槽/斜极';
    if (T_cog_ratio > 1000) level = '❌ 过大，必须优化';

    return { T_cog_estimate, T_cog_ratio, level };
}

/**
 * 绕组电流和功率估算
 */
function calculatePower(params) {
    const {
        slots, phases, Ns = 28, a = 2,
        Vdc = 48, Idc = 10,
        boreDiameter, coreLength, airGap,
        poles, Br, hm, freq, kw
    } = params;

    const Nph = slots * Ns / (2 * a);
    const Jc = Idc / (Ns * Math.PI * 0.4 * 0.4);  // 估算电流密度 A/mm²
    const I_phase_rms = Idc / Math.sqrt(2);  // 方波驱动有效值

    const fd = calculateFluxDensity(poles, slots, boreDiameter, coreLength, airGap, Br, hm);
    const n_sync = 120 * freq / poles;
    const Ke = 4.44 * freq * Nph * kw * fd.Phi_g * 2;
    const E_line_rms = Ke * Idc / n_sync;  // 近似

    const P_mech = 3 * I_phase_rms * E_line_rms / 2 * 0.85;  // W（效率约0.85）
    const T_out = P_mech / (n_sync * 2 * Math.PI / 60);  // Nm

    return {
        Jc, I_phase_rms,
        P_mech, T_out,
        E_line_rms, Vdc,
        efficiency: 0.85
    };
}

/**
 * 完整极槽配合报告
 */
function generateReport(params) {
    const {
        poles = 8, slots = 36, phases = 3,
        freq = 50, speed = 3000,
        boreDiameter = 54, coreLength = 60,
        airGap = 0.5, Br = 1.25, Hc = 955,
        Ns = 28, a = 2
    } = params;

    const ps = calculatePoleSlot(poles, slots, phases);
    const fd = calculateFluxDensity(poles, slots, boreDiameter, coreLength, airGap, Br, 3, 1.2);
    const emf = calculateEMF({...params, kw: ps.kw});
    const cogging = estimateCoggingTorque(poles, slots, Br, boreDiameter / 2000, coreLength / 1000);
    const power = calculatePower({...params, kw: ps.kw});

    // 磁密合理性检查
    let magCheck = '✅ 磁密分布合理';
    if (fd.Bg > 1.1) magCheck = '⚠️ 气隙磁密偏高(Bg>' + fd.Bg.toFixed(3) + 'T)，铁心可能饱和';
    if (fd.B_t > 1.8) magCheck = '⚠️ 齿部磁密偏高(Bt>' + fd.B_t.toFixed(3) + 'T)';
    if (fd.B_y > 1.6) magCheck = '⚠️ 轭部磁密偏高(By>' + fd.B_y.toFixed(3) + 'T)';

    // 反电动势合理性
    let emfCheck = '✅ 反电动势合理';
    if (emf.Ke_at_speed > Vdc * 0.9) emfCheck = '⚠️ 反电动势接近母线电压，电压裕量不足';
    if (emf.Ke_at_speed < Vdc * 0.2) emfCheck = '⚠️ 反电动势偏低，电机出力可能不足';

    const Vdc = params.Vdc || 48;

    const lines = [
        '',
        '╔══════════════════════════════════════════════════════════╗',
        '║           电机设计参数计算报告                           ║',
        '╠══════════════════════════════════════════════════════════╣',
        '║  基本参数                                               ║',
        `║    极数/极对数    ${String(poles).padEnd(6)} / ${String(ps.p).padEnd(6)}                          ║`,
        `║    槽数/相数      ${String(slots).padEnd(6)} / ${String(phases).padEnd(6)}                          ║`,
        `║    频率/同步转速  ${String(freq+'Hz').padEnd(6)} / ${String(emf.n_sync+'rpm').padEnd(6)}                      ║`,
        `║    额定转速       ${String(speed+' rpm').padEnd(20)}                        ║`,
        '╠══════════════════════════════════════════════════════════╣',
        '║  极槽配合                                               ║',
        `║    每极每相槽数 q = ${ps.q.toFixed(2).padEnd(18)}                     ║`,
        `║    绕组类型       ${ps.slotType.padEnd(32)}   ║`,
        `║    节距           ${String(y+'槽 (短距'+Math.round(ps.shortPitchRatio*100)+'%)').padEnd(32)}   ║`,
        `║    分布系数 Kd    ${ps.kd.toFixed(4).padEnd(32)}   ║`,
        `║    绕组系数 Kw    ${ps.kw.toFixed(4).padEnd(32)}   ║`,
        '╠══════════════════════════════════════════════════════════╣',
        '║  磁路参数                                               ║',
        `║    定子内径/铁长  ${String(boreDiameter+' / '+coreLength+' mm').padEnd(32)}   ║`,
        `║    气隙长度       ${String(airGap+' mm').padEnd(32)}   ║`,
        `║    极距 τ         ${String(fd.tau.toFixed(2)+' mm').padEnd(32)}   ║`,
        `║    气隙磁密 Bg    ${String(fd.Bg.toFixed(4)+' T').padEnd(32)}   ║`,
        `║    齿部磁密 Bt    ${String(fd.B_t.toFixed(4)+' T').padEnd(32)}   ║`,
        `║    轭部磁密 By    ${String(fd.B_y.toFixed(4)+' T').padEnd(32)}   ║`,
        `║    每极磁通 Φg    ${String(fd.Phi_g.toFixed(4)+' mWb').padEnd(32)}   ║`,
        '╠══════════════════════════════════════════════════════════╣',
        '║  绕组与性能                                               ║',
        `║    每槽导体数     ${String(Ns+' 根').padEnd(32)}   ║`,
        `║    并联支路数     ${String(a+' 路').padEnd(32)}   ║`,
        `║    每相串联匝数   ${String(emf.Nph.toFixed(0)+' 匝').padEnd(32)}   ║`,
        `║    反电动势 Ke    ${String(emf.Ke_at_speed.toFixed(1)+' V（线间@'+speed+'rpm）').padEnd(32)}   ║`,
        `║    转矩常数 Kt    ${String(emf.Kt.toFixed(4)+' Nm/A').padEnd(32)}   ║`,
        '╠══════════════════════════════════════════════════════════╣',
        '║  功率估算（参考）                                         ║',
        `║    电流密度 Jc    ${String(power.Jc.toFixed(1)+' A/mm²').padEnd(32)}   ║`,
        `║    估算功率       ${String(power.P_mech.toFixed(0)+' W').padEnd(32)}   ║`,
        `║    估算转矩       ${String(power.T_out.toFixed(2)+' Nm').padEnd(32)}   ║`,
        `║    效率（估）     ${String((power.efficiency*100).toFixed(0)+'%').padEnd(32)}   ║`,
        '╠══════════════════════════════════════════════════════════╣',
        '║  合理性检查                                               ║',
        `║    ${magCheck.padEnd(48).substring(0,48)}  ║`,
        `║    ${emfCheck.padEnd(48).substring(0,48)}  ║`,
        `║    ${cogging.level.padEnd(48).substring(0,48)}  ║`,
        '╚══════════════════════════════════════════════════════════╝',
        ''
    ];

    return lines.join('\n');
}

// ============================================================
// 极槽配合方案对比
// ============================================================

function compareSlotOptions(poles = 8, baseParams = {}) {
    const options = [
        { slots: 24, q: 24/(8*3), name: '24槽(q=1)' },
        { slots: 36, q: 36/(8*3), name: '36槽(q=1.5)' },
        { slots: 48, q: 48/(8*3), name: '48槽(q=2)' },
        { slots: 54, q: 54/(8*3), name: '54槽(q=2.25)' },
    ];

    console.log('\n═══════════════════════════════════════════════════════');
    console.log('           极槽配合方案对比（极数=8）');
    console.log('═══════════════════════════════════════════════════════');
    console.log(' Q     q        Kw       Bg(T)    Ke(V)    特点');
    console.log('────────────────────────────────────────────────────');

    for (const opt of options) {
        const ps = calculatePoleSlot(poles, opt.slots, 3);
        const emf = calculateEMF({...baseParams, slots: opt.slots, kw: ps.kw});
        console.log(
            `${String(opt.slots).padEnd(4)} ` +
            `${String(ps.q.toFixed(2)).padEnd(6)} ` +
            `${ps.kw.toFixed(4).padEnd(9)} ` +
            `${emf.Phi_g > 0 ? (emf.Phi_g*1e6/157).toFixed(4) : 'N/A'.padEnd(7)} ` +
            `${emf.Ke_at_speed.toFixed(1).padEnd(7)} ` +
            `${opt.name}`
        );
    }
    console.log('═══════════════════════════════════════════════════════\n');
}

// ============================================================
// 交互模式
// ============================================================

function interactiveMode() {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

    const question = (q) => new Promise(r => rl.question(q, r));

    (async () => {
        console.log('\n╔═══════════════════════════════════════╗');
        console.log('║     电机设计参数计算器 v2（交互模式）   ║');
        console.log('╚═══════════════════════════════════════╝\n');

        const poles   = parseInt(await question('极数 (8): ') || '8');
        const slots    = parseInt(await question('槽数 (36): ') || '36');
        const freq     = parseInt(await question('频率 Hz (50): ') || '50');
        const speed    = parseInt(await question('额定转速 rpm (3000): ') || '3000');
        const boreD    = parseFloat(await question('定子内径 mm (54): ') || '54');
        const coreL    = parseFloat(await question('铁心长度 mm (60): ') || '60');
        const airGap   = parseFloat(await question('气隙长度 mm (0.5): ') || '0.5');
        const Br       = parseFloat(await question('永磁体Br T (1.25): ') || '1.25');
        const Ns       = parseInt(await question('每槽导体数 (28): ') || '28');
        const a        = parseInt(await question('并联支路数 (2): ') || '2');
        const Vdc      = parseFloat(await question('母线电压 V (48): ') || '48');

        rl.close();

        const params = { poles, slots, freq, speed, boreDiameter: boreD,
                         coreLength: coreL, airGap, Br, Ns, a, Vdc };

        console.log(generateReport(params));
        compareSlotOptions(poles, params);
    })();
}

// ============================================================
// 主入口
// ============================================================

function main() {
    const args = process.argv.slice(2);

    if (args.includes('--interactive') || args.includes('-i')) {
        interactiveMode();
        return;
    }

    if (args.includes('--compare_slots')) {
        const params = parseArgs(args);
        compareSlotOptions(params.poles || 8, params);
        return;
    }

    const params = parseArgs(args);
    console.log(generateReport(params));
}

function parseArgs(args) {
    const result = {};
    for (const arg of args) {
        const [key, value] = arg.split('=');
        if (value === undefined) continue;
        const num = parseFloat(value);
        result[key] = isNaN(num) ? value : num;
    }
    return result;
}

if (require.main === module) {
    main();
}

module.exports = { calculatePoleSlot, calculateFluxDensity, calculateEMF,
                   estimateCoggingTorque, generateReport, compareSlotOptions };


path: scripts/param_calculator.py
content: #!/usr/bin/env python3
"""
电机设计参数计算器
快速计算极槽配合、绕组参数、磁密、反电动势、转矩等核心设计数据

用法：
  python param_calculator.py --poles 8 --Q 36 --L 60 --Di 54 --delta 0.5 --Bg 0.75
  python param_calculator.py --mode interactive
  python param_calculator.py --sweep_slots --poles 8 --L 60 --Di 54
"""

import argparse
import math
import sys

try:
    import numpy as np
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    HAS_PLOT = True
except ImportError:
    HAS_PLOT = False


def calc_pole_slot(poles, Q, m=3):
    """极槽配合计算"""
    p = poles // 2
    q = Q / (poles * m)  # 每极每相槽数
    tau = Q / poles  # 每极槽数
    return {
        'p': p,
        'q': q,
        'tau_slots': tau,
        'is_fractional': q != int(q) if q else False,
    }


def calc_winding_factor(poles, Q, m=3, coil_pitch=None):
    """绕组系数计算"""
    p = poles // 2
    q_raw = Q / (poles * m)
    q_int = int(q_raw) if q_raw == int(q_raw) else int(q_raw)

    # 每槽电气角度
    alpha_s = 2 * math.pi / Q  # 机械角度 rad
    alpha_e = alpha_s * p  # 电气角度 rad

    # 分布系数
    if q_int > 1:
        kd = math.sin(q_int * alpha_e / 2) / (q_int * math.sin(alpha_e / 2))
    else:
        kd = 1.0

    # 短距系数
    if coil_pitch is None:
        # 默认 5/6 节距 (coil_pitch_y = 5/6 * tau_slots)
        tau_slots = Q / poles
        coil_pitch = round(5 * tau_slots / 6)
    y = coil_pitch  # 节距
    tau_slots = Q / poles  # 极距（槽数）
    kp = math.sin(math.pi * y / (2 * tau_slots))  # 简化：sin(πy/2τ)

    kw = kd * kp
    return {
        'kd': kd,
        'kp': kp,
        'kw': kw,
        'coil_pitch': coil_pitch,
        'pitch_ratio': coil_pitch / tau_slots if tau_slots else 0,
    }


def calc_magnetic(poles, Q, L, Di, delta, Bg, sigma=1.2):
    """磁路计算（简化）"""
    tau = math.pi * Di / poles  # 极距 mm
    Ae = tau * L  # 气隙截面积 mm²
    Phi_g = Bg * Ae * 1e-6  # 每极气隙磁通 Wb

    return {
        'tau_mm': tau,
        'Ae_mm2': Ae,
        'Phi_g_mWb': Phi_g * 1000,
    }


def calc_ke_kt(poles, Q, m, Nph, kw, L, Di, Bg, freq=None, speed=None):
    """反电动势和转矩常数"""
    p = poles // 2
    tau = math.pi * Di / poles
    Ae = tau * L
    Phi_g = Bg * Ae * 1e-6

    # Ke (V/(rad/s))
    if freq:
        Ke = 2.22 * freq * Nph * kw * Phi_g  # 线间有效值近似
    else:
        Ke = 2 * math.pi * Nph * kw * Phi_g / 60  # 简化

    # Kt (Nm/A)
    Kt = 1.5 * p * kw * Nph * Phi_g

    # 线间反电动势（rms）
    if freq and speed:
        n_rpm = speed
        f_elec = n_rpm * p / 60
        E_line_rms = 4.44 * f_elec * Nph * kw * Phi_g
    else:
        E_line_rms = None

    return {
        'Ke_V_rad_s': Ke,
        'Kt_Nm_A': Kt,
        'E_line_rms_V': E_line_rms,
    }


def calc_performance(poles, Q, m, Nph, kw, L, Di, Bg, J, R, Imax):
    """性能估算"""
    p = poles // 2
    tau = math.pi * Di / poles
    Ae = tau * L
    Phi_g = Bg * Ae * 1e-6

    Kt = 1.5 * p * kw * Nph * Phi_g
    Ke_mech = 2 * math.pi * Nph * kw * Phi_g / 60

    # 额定转矩
    T_rated = Kt * Imax

    # 额定功率（近似机械同步功率）
    omega_sync = 2 * math.pi * 50  # 假设 50Hz
    P_sync = 2 * math.pi * p * 50 * T_rated / p  # 简化

    # 机械时间常数
    Tm = J * R / (3 * (Nph * kw * Phi_g * p)**2 + 1e-12)

    # 电气时间常数
    Te = L * 1e-3 / R  # L in mH -> H

    return {
        'Kt_Nm_A': Kt,
        'Ke_V_krpm': Ke_mech * 1000 / (2 * math.pi),
        'T_rated_Nm': T_rated,
        'Tm_s': Tm,
        'Te_s': Te,
    }


def format_output(pole_slot, winding, mag, perf, poles, Q, L, Di, delta, Bg, Nph, m):
    p = poles // 2
    out = f"""
{'='*60}
       电机设计参数计算结果
{'='*60}
【基本参数】
  极数 2p      = {poles} (极对数 p = {p})
  槽数 Q        = {Q}
  相数 m        = {m}
  定子内径 Di   = {Di} mm
  铁心长度 L    = {L} mm
  气隙长度 δ    = {delta} mm
  气隙磁密 Bg   = {Bg} T
  每相串联匝数 Nph = {Nph:.0f}

【极槽配合】
  极距 τ        = {pole_slot['tau_mm']:.2f} mm
  每极槽数      = {pole_slot['tau_slots']:.1f}
  每极每相槽数 q = {pole_slot['q']:.3f}
  分数槽？      = {'是' if pole_slot['is_fractional'] else '否'}

【绕组系数】
  分布系数 Kd   = {winding['kd']:.4f}
  短距系数 Kp   = {winding['kp']:.4f}
  总绕组系数 Kw = {winding['kw']:.4f}
  节距 y        = {winding['coil_pitch']:.0f} 槽
  节距比         = {winding['pitch_ratio']:.3f}

【磁路参数】
  极距 τ        = {mag['tau_mm']:.2f} mm
  气隙截面积 Ae = {mag['Ae_mm2']:.1f} mm²
  每极气隙磁通 Φg = {mag['Phi_g_mWb']:.3f} mWb

【性能估算】
  转矩常数 Kt   = {perf['Kt_Nm_A']:.4f} Nm/A
  反电动势常数 Ke = {perf['Ke_V_krpm']:.3f} V/krpm
  额定转矩（@{Nph:.0f}匝，{m}相，{Bg}T）= {perf['T_rated_Nm']:.3f} Nm (@ Imax)
  机械时间常数 Tm = {perf['Tm_s']:.4f} s
  电气时间常数 Te = {perf['Te_s']:.4f} s
{'='*60}
"""
    return out


def sweep_slots(poles, L, Di, delta, Bg, Nph=100):
    """槽数扫描分析"""
    # 常见槽数选项
    q_options = {1, 1.5, 2, 2.5, 3}
    p = poles // 2

    print(f"\n===== 槽数扫描分析 (2p={poles}, L={L}mm, Di={Di}mm) =====")
    print(f"{'Q':>4} {'q':>6} {'Kw':>8} {'τ/mm':>8} {'Bg/T':>8} {'Kt':>8}")
    print("-" * 50)

    for q in sorted(q_options):
        Q = int(q * poles * 3)
        if Q < 6:
            continue
        ws = calc_winding_factor(poles, Q)
        mag = calc_magnetic(poles, Q, L, Di, delta, Bg)
        perf = calc_performance(poles, Q, 3, Nph, ws['kw'], L, Di, Bg, 1e-3, 1.0, 10)
        print(f"{Q:4d} {q:6.1f} {ws['kw']:8.4f} {mag['tau_mm']:8.2f} "
              f"{Bg:8.3f} {perf['Kt_Nm_A']:8.4f}")


def interactive():
    print("\n" + "="*60)
    print("      电机设计参数计算器（交互模式）")
    print("="*60)

    try:
        poles = int(input("极数 (8): ") or 8)
        Q = int(input("槽数 (36): ") or 36)
        L = float(input("铁心长度 mm (60): ") or 60)
        Di = float(input("定子内径 mm (54): ") or 54)
        delta = float(input("气隙长度 mm (0.5): ") or 0.5)
        Bg = float(input("气隙磁密 T (0.75): ") or 0.75)
        Nph = float(input("每相串联匝数 (100): ") or 100)
        Imax = float(input("额定相电流峰值 A (10): ") or 10)
        R = float(input("相电阻 Ω (1.0): ") or 1.0)
        J = float(input("转动惯量 kg·m² (0.001): ") or 0.001)

        pole_slot = calc_pole_slot(poles, Q)
        winding = calc_winding_factor(poles, Q)
        mag = calc_magnetic(poles, Q, L, Di, delta, Bg)
        perf = calc_performance(poles, Q, 3, Nph, winding['kw'], L, Di, Bg, J, R, Imax)

        print(format_output(pole_slot, winding, mag, perf, poles, Q, L, Di, delta, Bg, Nph, 3))

        # 可选槽数扫描
        ans = input("\n是否进行槽数扫描分析？(y/N): ").strip().upper()
        if ans == 'Y':
            sweep_slots(poles, L, Di, delta, Bg, Nph)

    except KeyboardInterrupt:
        print("\n已退出")


def main():
    parser = argparse.ArgumentParser(description='电机设计参数计算器')
    parser.add_argument('--poles', type=int, default=8, help='极数')
    parser.add_argument('--Q', type=int, default=36, help='槽数')
    parser.add_argument('--L', type=float, default=60, help='铁心长度 mm')
    parser.add_argument('--Di', type=float, default=54, help='定子内径 mm')
    parser.add_argument('--delta', type=float, default=0.5, help='气隙长度 mm')
    parser.add_argument('--Bg', type=float, default=0.75, help='气隙磁密 T')
    parser.add_argument('--Nph', type=float, default=100, help='每相串联匝数')
    parser.add_argument('--Imax', type=float, default=10, help='额定相电流峰值 A')
    parser.add_argument('--R', type=float, default=1.0, help='相电阻 Ω')
    parser.add_argument('--J', type=float, default=1e-3, help='转动惯量 kg·m²')
    parser.add_argument('--sweep_slots', action='store_true', help='槽数扫描分析')
    parser.add_argument('--mode', default='calc', choices=['calc', 'interactive'])

    args = parser.parse_args()

    if args.mode == 'interactive' or (not args.sweep_slots and args.Q == 36 and args.poles == 8):
        if args.mode == 'interactive' or len(sys.argv) == 1:
            interactive()
            return

    if args.sweep_slots:
        sweep_slots(args.poles, args.L, args.Di, args.delta, args.Bg, args.Nph)
        return

    pole_slot = calc_pole_slot(args.poles, args.Q)
    winding = calc_winding_factor(args.poles, args.Q)
    mag = calc_magnetic(args.poles, args.Q, args.L, args.Di, args.delta, args.Bg)
    perf = calc_performance(args.poles, args.Q, 3, args.Nph, winding['kw'],
                           args.L, args.Di, args.Bg, args.J, args.R, args.Imax)

    print(format_output(pole_slot, winding, mag, perf, args.poles, args.Q,
                       args.L, args.Di, args.delta, args.Bg, args.Nph, 3))


if __name__ == '__main__':
    if len(sys.argv) == 1:
        interactive()
    else:
        main()


path: _meta.json
content: {
  "name": "motor-parameter-calculator",
  "version": "1.0.0",
  "description": "电机设计参数计算助手 - 计算极槽配合、匝数、磁密、反电动势等核心参数",
  "tags": ["电机", "设计", "计算", "FOC", "极槽配合"],
  "author": "永杰团队",
  "license": "MIT",
  "language": "中文"
}


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)