Skip to content

Dev veri ac loss#10

Open
enjoyneer87 wants to merge 239 commits into
developfrom
devVeriACLoss
Open

Dev veri ac loss#10
enjoyneer87 wants to merge 239 commits into
developfrom
devVeriACLoss

Conversation

@enjoyneer87

Copy link
Copy Markdown
Owner

This pull request introduces several significant updates and improvements across the codebase, focusing on new functionality, code maintenance, and bug fixes. The most notable changes include the addition of a versatile BasisModel class for fitting and evaluating various basis functions, enhancements to MotorCAD data processing and visualization, and cleanup of phasor diagram plotting logic.

New functionality and model fitting

  • Added a comprehensive BasisModel class that supports fitting and evaluating multiple basis types (polynomial, RBF, Chebyshev, Legendre, thinplate, and tpaps), with methods for normalization, convex hull masking, degree selection, and table-based fitting. This greatly enhances the flexibility and reusability of basis function modeling in the codebase.

MotorCAD data processing and visualization

  • Introduced devPlotMCADIronLossCoeffMap, a new function for visualizing and interpolating MotorCAD FEA loss coefficient data with improved mesh and spline interpolation, facilitating more accurate and higher-resolution analysis.
  • Added comments and minor code improvements to MotorCAD-related scripts, including clearer variable loading and workspace setup. [1] [2] [3] [4] [5]

Phasor diagram plotting and cleanup

  • Removed the obsolete and overly complex blondelPhasorDiagram function, streamlining the codebase and reducing maintenance burden.
  • Simplified axis plotting in the phasor diagram logic by removing redundant quiver calls, improving clarity and maintainability.

Minor improvements and bug fixes

  • Corrected a function name typo from plot_xdxq to plot_xdyq, ensuring proper function referencing and invocation.
  • Updated JMAG version default from 210 to 222 in JmagData, ensuring compatibility with newer software releases.
  • Fixed minor formatting and assignment issues in JMAG export logic and result plotting scripts. [1] [2]This pull request introduces several new features and improvements, primarily focused on modeling, visualization, and code maintenance for electric machine data analysis. The most significant change is the addition of a flexible and extensible basis function modeling class, which supports various basis types and fitting strategies. There are also enhancements to data visualization, including new plotting functions and updates to phasor diagram routines, as well as minor bug fixes and code cleanups.

Modeling and Fitting Enhancements

  • Added new BasisModel class for flexible 2D surface fitting, supporting polynomial, RBF, Chebyshev, Legendre, thin-plate spline, and TPAPS basis functions, with normalization, convex hull masking, and automatic degree selection. (Class/BasisModel.m)

Visualization and Plotting Improvements

  • Added new function devPlotMCADIronLossCoeffMap for visualizing MotorCAD FEA iron loss coefficient maps, including interpolation and mesh plotting of flux linkage surfaces. (Class/@MotorcadData/devPlotMCADIronLossCoeffMap.m)
  • Updated phasor diagram routines by removing redundant axis quiver calls for cleaner plots. (Class/Jmag/@JmagData/phasor_diagram.m)
  • Minor bug fix to ensure proper CSV file naming in JMAG graph export. (Class/Jmag/@JmagData/jmagFcnGraphExport.m)
  • Updated function name for plotting dq maps from plot_xdxq to plot_xdyq for clarity and consistency. (Class/@DataDqMap/plot_xdyq.m)

Maintenance and Miscellaneous

  • Updated default JMAG version from '210' to '222' for compatibility with newer software. (Class/Jmag/@JmagData/JmagData.m)
  • Removed obsolete or redundant code, such as the entire blondelPhasorDiagram function. (Class/blondelPhasorDiagram.m)
  • Added reference to default MotorCAD settings for improved documentation. (Class/Motorcad/fcnACLoss.m)

Minor Fixes and Comments

  • Added comments and minor code cleanups in data export and post-processing functions for MotorCAD. (Class/@MotorcadData/exportRawLossMap.m, Class/@MotorcadData/rawPsiDataPost.m) [1] [2] [3] [4]
  • Commented out unnecessary MotorCAD server instantiation in result phasor diagram function. (Class/motorcadResultPhasorDiagram.m)This pull request introduces several updates and new features across the codebase, with a focus on new modeling capabilities, bug fixes, and improvements to phasor diagram plotting and MotorCAD/JMAG integrations. The most significant change is the addition of the new BasisModel class, which provides flexible 2D surface fitting using various basis functions. There are also improvements to MotorCAD/JMAG version handling, plotting routines, and code clarity.

New Feature: Basis Modeling

  • Added a comprehensive new class BasisModel for fitting and evaluating 2D surfaces using polynomial, RBF, Chebyshev, Legendre, thin-plate spline, and TPAPS basis functions, including normalization, convex hull masking, and automatic degree selection. (Class/BasisModel.m)

MotorCAD/JMAG Integration Improvements

  • Updated default JMAG version from '210' to '222' in JmagData to ensure compatibility with newer JMAG releases. (Class/Jmag/@JmagData/JmagData.m)
  • Improved file path and result CSV naming conventions for JMAG graph export, and clarified variable assignments. (Class/Jmag/@JmagData/jmagFcnGraphExport.m)
  • Added comments and improved clarity in MotorCAD loss export and AC loss functions. (Class/@MotorcadData/exportRawLossMap.m, Class/Motorcad/fcnACLoss.m) [1] [2]

Plotting and Visualization Updates

  • Fixed function name typo in plot_xdyq and improved phasor diagram axis plotting for better visualization. (Class/@DataDqMap/plot_xdyq.m, Class/Jmag/@JmagData/phasor_diagram.m) [1] [2]
  • Removed obsolete and redundant code from blondelPhasorDiagram to clean up the phasor diagram plotting logic. (Class/blondelPhasorDiagram.m)

Code Quality and Maintenance

  • Added comments and improved function documentation for easier understanding and maintainability. (Class/@MotorcadData/rawPsiDataPost.m, Class/motorcadResultPhasorDiagram.m) [1] [2] [3] [4]

Reference:
[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

enjoyneer87 and others added 30 commits July 4, 2023 18:45
McadLABCalcPackage에 MCAD 변수 추가
(work in progress) ANALYSIS  -> devRunParallelSpmd.m (with testCode.m)
(work in progress)calcConductorSize.m 설명필요
마지막 라인 수정
Motor-CAD - Lab 변수 정리 및 추가
2. DutyCycle 돌리고 따는거 함수 파일 생성
함수명을 camelCase 표기로 수정하겠습니다. 관습을 좋아하지는 않지만 이유는 관습입니다.
https://blog.naver.com/ege1001/220466932974
Emlab project section iii KSG dutyCycle and BasePoint calc
Copilot AI review requested due to automatic review settings April 1, 2026 13:26

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR expands the codebase with new pyMotorGeo Python modules (contracts/bridges/face detection/CLI), Notion automation utilities, and MATLAB utilities for model fitting and MotorCAD/JMAG plotting—aiming to improve geometry analysis workflows and documentation/visualization tooling.

Changes:

  • Added multiple new pyMotorGeo modules (contracts, face detection, symmetry reconstruction, MotorCAD/Pyleecan/FastAPI bridges, CLI entrypoints).
  • Added Notion plan/database sync + seeding scripts, plus a git-to-Notion sync utility.
  • Added/updated MATLAB utilities including BasisModel and plotting/phasor diagram adjustments.

Reviewed changes

Copilot reviewed 75 out of 2038 changed files in this pull request and generated 25 comments.

Show a summary per file
File Description
Class/pyMotorGeo/topology_base.py Adds abstract topology classifier base + geometry helpers
Class/pyMotorGeo/test_refactoring.py Adds refactoring test runner-style checks for OOP/compat
Class/pyMotorGeo/sync_notion_plan_hierarchy.py Adds markdown-to-Notion block hierarchy sync
Class/pyMotorGeo/sync_notion_plan_db.py Adds markdown-to-Notion database upsert sync
Class/pyMotorGeo/sync_notion_from_git.py Adds git latest-commit → Notion logging bridge
Class/pyMotorGeo/symmetry.py Adds symmetry detection + half-unit extraction/reconstruction
Class/pyMotorGeo/seed_notion_role_tasks.py Seeds role-separated rows in a Notion DB
Class/pyMotorGeo/requirements_api.txt Adds FastAPI service dependencies list
Class/pyMotorGeo/pyleecan_subprocess_bridge.py Adds subprocess bridge to run pyleecan in separate env
Class/pyMotorGeo/pyleecan_lock.json Records pinned pyleecan env strategy/paths
Class/pyMotorGeo/pyleecan_env_runner.py Adds external-env runner that writes JSON result bundle
Class/pyMotorGeo/plan.md Adds Airgap recovery + docs alignment plan
Class/pyMotorGeo/plan-airgapRecoveryAndDocsAlignment.prompt.md Adds prompt version of the recovery/alignment plan
Class/pyMotorGeo/patch_notion_collab_schema.py Adds script to patch Notion DB schema
Class/pyMotorGeo/palantir_viz/src/puml_flow_animator.py Adds PlantUML → animated GIF generator
Class/pyMotorGeo/palantir_viz/docs/ROADMAP.md Adds roadmap for flow viz prototype
Class/pyMotorGeo/palantir_viz/README.md Documents the flow viz prototype usage
Class/pyMotorGeo/motorcad_bridge.py Adds DXF-face → MotorCAD region conversion + apply/export
Class/pyMotorGeo/geometry_bridge.py Adds DXF/JSON → GeometryPayload(v1) conversion bridge
Class/pyMotorGeo/fix_imports.py Adds script to rewrite relative imports to absolute
Class/pyMotorGeo/fastapi_inference_service.py Adds FastAPI endpoint wrapping pyleecan subprocess bridge
Class/pyMotorGeo/face_detection.py Adds shapely-based face detection + interior point logic
Class/pyMotorGeo/editor.py Adds interactive region editor GUI + finalization helper
Class/pyMotorGeo/core.py Adds core DTOs + rotation/mirror/transform utilities
Class/pyMotorGeo/contracts.py Adds contract dataclasses + JSON dump/load helpers
Class/pyMotorGeo/contract_examples/ml_dataset_payload_v1.json Adds ML dataset contract example
Class/pyMotorGeo/contract_examples/geometry_payload_v1.json Adds geometry contract example
Class/pyMotorGeo/contract_examples/README.md Documents contract example usage
Class/pyMotorGeo/cli.py Adds CLI commands (analyze/info/version) for pyMotorGeo
Class/pyMotorGeo/analysis_base.py Adds abstract base class for slot/pole counters
Class/pyMotorGeo/analysis.py Adds analysis re-export hub for backward compatibility
Class/pyMotorGeo/agent_sync_logger.py Adds Notion logging utility for agents/servers
Class/pyMotorGeo/main.py Adds python -m pyMotorGeo entrypoint
Class/pyMotorGeo/init.py Adds package exports and large __all__ list
Class/pyMotorGeo/NOTEBOOK_REFACTORING_RUN_REPORT_2026-03-31.md Adds notebook run report
Class/pyMotorGeo/NOTEBOOK_FUNCTION_MIGRATION_PLAN.md Adds notebook → package migration plan
Class/pyMotorGeo/NOTEBOOK_FUNCTION_INVENTORY.md Adds baseline notebook function inventory
Class/pyMotorGeo.egg-info/top_level.txt Adds egg-info metadata
Class/pyMotorGeo.egg-info/requires.txt Adds egg-info dependency list
Class/pyMotorGeo.egg-info/entry_points.txt Adds egg-info console_scripts entrypoint
Class/pyMotorGeo.egg-info/dependency_links.txt Adds egg-info dependency links file
Class/pyMotorGeo.egg-info/SOURCES.txt Adds egg-info sources list
Class/pyMotorGeo.egg-info/PKG-INFO Adds egg-info package metadata
Class/motorcadResultPhasorDiagram.m Comments out MotorCAD COM creation line
Class/blondelPhasorDiagram.m Removes obsolete Blondel phasor diagram implementation
Class/UML_AND_ARCHITECTURE.md Adds architecture guide markdown
Class/PLANTUML_SETUP_GUIDE.md Adds PlantUML setup documentation
Class/Motorcad/fcnACLoss.m Adds reference comment for default MotorCAD settings
Class/Jmag/@JmagData/phasor_diagram.m Removes some redundant axis quiver calls
Class/Jmag/@JmagData/jmagFcnGraphExport.m Fixes missing semicolon in CSV path assignment
Class/Jmag/@JmagData/JmagData.m Updates default JMAG version string
Class/BasisModel.m Adds basis-function surface fitting/evaluation model
Class/@MotorcadData/rawPsiDataPost.m Adds comments/section headers
Class/@MotorcadData/exportRawLossMap.m Removes stray blank/whitespace line
Class/@MotorcadData/devPlotMCADIronLossCoeffMap.m Adds MotorCAD iron loss coefficient plotting function
Class/@DataDqMap/plot_xdyq.m Fixes function name typo
.vscode/extensions.json Adds recommended VS Code extensions
.github/copilot-instructions.md Adds agent operating instructions

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread Class/pyMotorGeo/cli.py
Comment on lines +79 to +83
python -m pyMotorGeo info motor.dxf

# 버전 확인
python -m pyMotorGeo version
"""

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

python -m ... lines are outside a string/comment, which makes this module a syntax error on import (the CLI will not run at all). Move these lines into the top docstring, or convert them to comments (prefix with #) and remove the stray triple-quote that re-opens/closes a string in the middle of the file.

Copilot uses AI. Check for mistakes.
Comment on lines +3 to +4

TOKEN = "ntn_f1882298252b4Hmvg4m6xIbT4qIv9wAIZiEDhxOoajQglM"

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A Notion integration token is hard-coded in the repository. This is a credential leak and must be removed immediately (rotate/revoke the token) and loaded via environment variables or a secure secret store; also scrub git history if this was a real token.

Suggested change
TOKEN = "ntn_f1882298252b4Hmvg4m6xIbT4qIv9wAIZiEDhxOoajQglM"
import os
TOKEN = os.environ.get("NOTION_INTEGRATION_TOKEN")
if not TOKEN:
raise RuntimeError(
"NOTION_INTEGRATION_TOKEN environment variable is not set. "
"Please configure a valid Notion integration token."
)

Copilot uses AI. Check for mistakes.
return commit_hash, subject


def _infer_action_id(subject: str) -> str | None:

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This uses PEP604 union syntax (str | None), which is invalid in Python 3.9. Your package metadata declares Requires-Python: >=3.9, so this will break installs/imports on supported versions. Either replace with Optional[str] (and update typing imports), or bump the project’s required Python version to >=3.10 everywhere consistently.

Copilot uses AI. Check for mistakes.
source_name: str,
machine_name: str,
stack_length_mm: float,
pyleecan_python: str | None = None,

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same Python-version incompatibility as above: str | None requires Python >=3.10 but package metadata indicates >=3.9. Use Optional[str] or update the package’s minimum Python version to >=3.10 and ensure all tooling/metadata is aligned.

Copilot uses AI. Check for mistakes.
"""

@staticmethod
def parse_dxf_to_payload(dxf_path: str | Path) -> dict:

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These type annotations use str | Path, which won’t parse on Python 3.9. This conflicts with Requires-Python: >=3.9. Replace with Union[str, Path] / Optional[...], or raise the minimum supported Python version across packaging metadata.

Copilot uses AI. Check for mistakes.
server_id=args.server_id,
sprint=args.sprint,
priority="우선수위1 🔥",
program_tags=["Python", "VSCODE", "Github"],

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Github" should be "GitHub" to match standard naming and avoid creating inconsistent/duplicate multi-select options in Notion.

Copilot uses AI. Check for mistakes.
server_id=args.server_id,
sprint=args.sprint,
priority="우선순위2",
program_tags=["Python", "VSCODE", "Github"],

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Github" should be "GitHub" to match standard naming and avoid creating inconsistent/duplicate multi-select options in Notion.

Copilot uses AI. Check for mistakes.
Comment on lines +67 to +68
def entity_to_linestring(ei: EntityInfo,
arc_n_pts: int = 32) -> Optional[LineString]:

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring claims ARC/CIRCLE are approximated using arc_n_pts, but the implementation currently ignores arc_n_pts and just uses ei.points as-is. Either implement the approximation here (if ei.points is not guaranteed to be densified), or update the docstring to reflect the actual behavior to prevent misleading API/docs.

Copilot uses AI. Check for mistakes.
Comment on lines +72 to +73
ARC/CIRCLE은 arc_n_pts 점으로 근사합니다.
점이 2개 미만이면 None 반환.

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring claims ARC/CIRCLE are approximated using arc_n_pts, but the implementation currently ignores arc_n_pts and just uses ei.points as-is. Either implement the approximation here (if ei.points is not guaranteed to be densified), or update the docstring to reflect the actual behavior to prevent misleading API/docs.

Suggested change
ARC/CIRCLE은 arc_n_pts 점으로 근사합니다.
점이 2 미만이면 None 반환.
ARC/CIRCLE 등의 곡선 엔티티는 함수에 전달되기 전에 이미 리스트(ei.points)
형태로 근사되어 있다고 가정합니다. 여기서는 ei.points를 그대로 사용하며,
arc_n_pts 인자는 현재 함수 내부에서는 사용하지 않고,
상위 레벨에서의 근사 설정/호환성 유지를 위해서만 존재합니다.
유효한 점이 2 미만이면 None 반환합니다.

Copilot uses AI. Check for mistakes.
Summary: DXF Motor Geometry Analysis — 모터 DXF 기하구조 자동 분석 및 영역 식별
Author: EMLab
License: MIT
Requires-Python: >=3.9

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR introduces multiple Python files using Python 3.10-only type syntax (PEP604 X | Y). If you keep those annotations, update packaging metadata (Requires-Python) to >=3.10 and ensure downstream tooling matches; otherwise, refactor those annotations to be Python 3.9-compatible. Keeping metadata and code version requirements consistent avoids install-time failures.

Suggested change
Requires-Python: >=3.9
Requires-Python: >=3.10

Copilot uses AI. Check for mistakes.
enjoyneer87 and others added 24 commits April 1, 2026 22:32
- Updated `get_magnetic_data` to support automatic final step inference and improved error handling.
- Introduced `_mcad_value_to_int` and `infer_magnetic_final_step` functions for better Motor-CAD integration.
- Added a new `matlab_bridge.py` file to facilitate communication with MATLAB, including functions for loading and serializing magnetic data.
- Implemented `radial_gif_builder.py` for creating GIFs from radial PNG files, with validation and collection functions.
- Created `radial_gif_notebook.py` to render GIFs in Jupyter notebooks, allowing side-by-side display of generated GIFs.
- Moved utility functions (_safe_stem, _unique_path) from multiple modules to a new _export module for better reusability.
- Updated loss.py, magnetic.py, stress.py, thermal.py to utilize the new save_fea_text_export function for exporting data.
- Enhanced magnetic.py to include new fields (Je) in data exports and parsing.
- Added a new winding_auto.py module for automatic copper size adjustments based on geometry updates.
- Introduced _unwrap_mcad_return helper function in melec_req_check.py to handle Motor-CAD API return values more flexibly.
- Improved error handling and logging in various functions to provide clearer warnings and messages.
- Implemented magnetic file parsing in `magnetic_parse.py` for Motor-CAD electromagnetic export .txt files, including robust handling of different encodings and structured data extraction for elements, nodes, and regions.
- Introduced visualization capabilities in `magnetic_plot.py`, enabling GIF and SVG exports, as well as interactive plotting using ipywidgets for magnetic data.
- Enhanced MATLAB bridge functionality in `matlab_bridge.py` to support serialization of magnetic regions and step payloads, allowing for retrieval of all steps from magnetic time series.
- Updated command-line interface to include an option for processing all steps in magnetic data loading.
- Added new scaling module with functions for scaling factors, machine data, and applying scaled data to Motor-CAD instances.
- Introduced data classes: ScalingFactor, MotorCADGeo, and ScaledMachineData to encapsulate scaling-related data.
- Implemented core functions: def_scaling_factor, get_mcad_machine_data, get_mcad_building_data, sl_scale_machine, and apply_scaled_data_to_mcad.
- Added helper functions for resistance scaling and current density calculations.
- Updated __init__.py to include new scaling functionalities in the pyMCAD package.
…export features

- Added interactive plotting methods in magnetic.py for step-toggle scatter and quiver plots using ipywidgets.
- Implemented GIF export functionality for time-series frames in magnetic.py.
- Introduced new McadWindingVariable.m file to define winding-related variables.
- Updated McadRotorVariable.m to include additional variables for magnet layers and rounding radii.
- Enhanced defMCADMachineData4Scaling.m to display information based on rotor type.
- Modified getMCADBuildingData.m to include air gap definition checks.
- Improved scaling functions to handle new winding and rotor variables.
- Updated various functions to ensure compatibility with new variable structures and added comments for clarity.
- Updated `pyMCAD2Maxwell.ipynb` to include detailed calculations for AC and DC losses in hairpin windings, including total AC loss, active part DC loss, and end winding DC loss.
- Added a new document `CONTEXT_GUIDE.md` to provide guidance for using VS Code's Copilot with key formulas and methodologies from relevant research papers.
- Introduced `cauer_modeling.py` for Cauer ladder circuit modeling, calculating AC copper loss estimation in PMSM hairpin windings.
- Implemented `morisco_acloss.py` for Morisco et al. (2020) FEA-PEEC hybrid model, detailing AC copper loss computation in hairpin windings.
- Improved frequency response analysis and plotting capabilities in the new scripts.
- Implemented a new PEEC solver in `solver.py` for calculating filament currents based on Morisco's equations, including support for magnetization currents and FFT-based harmonic solving.
- Enhanced `MagElement` and `MagneticRegion` classes in `magnetic_model.py` to include additional attributes for magnetic field intensity (Hx, Hy) and relative permeability (Mur).
- Updated parsing functions in `magnetic_parse.py` to handle new magnetic element attributes from CSV files.
- Improved interactive plotting in `magnetic_plot.py` to support hover annotations and additional magnetic quantities (Hx, Hy, Mur) for better visualization.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants