commit aa3dafbe4b5beca77f5860d6d4c8cbc82b72ba84 Author: Anto01 Date: Sat Nov 15 07:56:35 2025 -0500 Initial commit: NX OptiMaster project structure - Set up Python package structure with pyproject.toml - Created MCP server, optimization engine, and NX journals modules - Added configuration templates - Implemented pluggable result extractor architecture - Comprehensive README with architecture overview - Project ready for GitHub push 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..e6a72438 --- /dev/null +++ b/.gitignore @@ -0,0 +1,82 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST +.pytest_cache/ +.coverage +htmlcov/ +*.cover +.hypothesis/ + +# Virtual Environment +venv/ +ENV/ +env/ +.venv + +# IDEs +.vscode/ +.idea/ +*.swp +*.swo +*~ +.DS_Store + +# NX/FEA Files +*.op2 +*.f06 +*.f04 +*.xdb +*.log +*.diag +*.pch +*.master +*.dball +*.ldra +*.sdb +*.sim.bak +*.prt.bak + +# Optimization Results +optuna_study.db +optuna_study.db-journal +history.csv +history.bak +next.exp +RMS_log.csv +archives/ +temp/ +*.tmp + +# Node modules (for dashboard) +node_modules/ +.npm +.cache +dist/ +build/ + +# Environment variables +.env +.env.local + +# OS +Thumbs.db +desktop.ini diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f2879c11 --- /dev/null +++ b/LICENSE @@ -0,0 +1,12 @@ +Proprietary License + +Copyright (c) 2025 Atomaste + +All rights reserved. + +This software and associated documentation files (the "Software") are the proprietary +property of Atomaste. Unauthorized copying, modification, distribution, or use of this +Software, via any medium, is strictly prohibited without prior written permission from +Atomaste. + +For licensing inquiries, please contact: contact@atomaste.com diff --git a/README.md b/README.md new file mode 100644 index 00000000..7977a7ca --- /dev/null +++ b/README.md @@ -0,0 +1,249 @@ +# NX OptiMaster + +> Advanced optimization platform for Siemens NX Simcenter with LLM-powered configuration + +[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/) +[![License](https://img.shields.io/badge/license-Proprietary-red.svg)](LICENSE) +[![Status](https://img.shields.io/badge/status-alpha-yellow.svg)](https://github.com) + +## Overview + +NX OptiMaster is a next-generation optimization framework for Siemens NX that combines: + +- **LLM-Driven Configuration**: Use natural language to set up complex optimizations +- **Advanced Algorithms**: Optuna-powered TPE, Gaussian Process surrogates, multi-fidelity optimization +- **Real-Time Monitoring**: Interactive dashboards with live updates +- **Flexible Architecture**: Pluggable result extractors for any FEA analysis type +- **MCP Integration**: Extensible via Model Context Protocol + +## Architecture + +``` +┌─────────────────────────────────────────────────────────┐ +│ UI Layer │ +│ Web Dashboard (React) + LLM Chat Interface (MCP) │ +└─────────────────────────────────────────────────────────┘ + ↕ +┌─────────────────────────────────────────────────────────┐ +│ MCP Server │ +│ - Model Discovery - Config Builder │ +│ - Optimizer Control - Result Analyzer │ +└─────────────────────────────────────────────────────────┘ + ↕ +┌─────────────────────────────────────────────────────────┐ +│ Execution Layer │ +│ NX Core (NXOpen) + Optuna Engine + Custom Scripts │ +└─────────────────────────────────────────────────────────┘ +``` + +## Quick Start + +### Prerequisites + +- **Siemens NX 2306+** with NX Nastran solver +- **Python 3.10+** (recommend Anaconda) +- **Node.js 18+** (for dashboard frontend) + +### Installation + +1. **Clone the repository**: + ```bash + git clone https://github.com/atomaste/nx-optimaster.git + cd nx-optimaster + ``` + +2. **Create Python environment**: + ```bash + conda create -n nx-optimaster python=3.10 + conda activate nx-optimaster + ``` + +3. **Install dependencies**: + ```bash + pip install -e . + # For development tools: + pip install -e ".[dev]" + # For MCP server: + pip install -e ".[mcp]" + ``` + +4. **Configure NX path** (edit `config/nx_config.json`): + ```json + { + "nx_executable": "C:/Program Files/Siemens/NX2306/NXBIN/ugraf.exe", + "python_env": "C:/Users/YourName/anaconda3/envs/nx-optimaster/python.exe" + } + ``` + +### Basic Usage + +#### 1. Conversational Setup (via MCP) + +``` +You: My FEA is in C:\Projects\Bracket\analysis.sim, please import its features. + +AI: I've analyzed your model: + - Solution: Static Analysis (NX Nastran) + - Expressions: wall_thickness (5mm), hole_diameter (10mm) + - Mesh: 8234 nodes, 4521 elements + + Which parameters would you like to optimize? + +You: Optimize wall_thickness and hole_diameter to minimize max stress while keeping mass low. + +AI: Configuration created! Ready to start optimization with 100 iterations. + Would you like to review the config or start now? + +You: Start it! + +AI: Optimization launched! 🚀 + Dashboard: http://localhost:8080/dashboard +``` + +#### 2. Manual Configuration (JSON) + +Create `optimization_config.json`: + +```json +{ + "design_variables": { + "wall_thickness": { + "low": 3.0, + "high": 8.0, + "enabled": true + } + }, + "objectives": { + "metrics": { + "max_stress": { + "weight": 10, + "target": 200, + "extractor": "nastran_stress" + } + } + }, + "nx_settings": { + "sim_path": "C:/Projects/Bracket/analysis.sim", + "solution_name": "Solution 1" + } +} +``` + +Run optimization: +```bash +python -m optimization_engine.run_optimizer --config optimization_config.json +``` + +## Features + +### ✨ Core Capabilities + +- **Multi-Objective Optimization**: Weighted sum, Pareto front analysis +- **Smart Sampling**: TPE, Latin Hypercube, Gaussian Process surrogates +- **Result Extraction**: Nastran (OP2/F06), NX Mass Properties, custom parsers +- **Crash Recovery**: Automatic resume from interruptions +- **Parallel Evaluation**: Multi-core FEA solving (coming soon) + +### 📊 Visualization + +- **Real-time progress monitoring** +- **3D Pareto front plots** (Plotly) +- **Parameter importance charts** +- **Convergence history** +- **FEA result overlays** + +### 🔧 Extensibility + +- **Pluggable result extractors**: Add custom metrics easily +- **Custom post-processing scripts**: Python integration +- **MCP tools**: Extend via protocol +- **NXOpen API access**: Full NX automation + +## Project Structure + +``` +nx-optimaster/ +├── mcp_server/ # MCP server implementation +│ ├── tools/ # MCP tool definitions +│ ├── schemas/ # JSON schemas for validation +│ └── prompts/ # LLM system prompts +├── optimization_engine/ # Core optimization logic +│ ├── result_extractors/ # Pluggable metric extractors +│ ├── multi_optimizer.py # Optuna integration +│ ├── config_loader.py # Configuration parser +│ └── history_manager.py # CSV/SQLite persistence +├── nx_journals/ # NXOpen Python scripts +│ ├── update_and_solve.py # CAD update + solver +│ ├── post_process.py # Result extraction +│ └── utils/ # Helper functions +├── dashboard/ # Web UI +│ ├── frontend/ # React app +│ └── backend/ # FastAPI server +├── tests/ # Unit tests +├── examples/ # Example projects +└── docs/ # Documentation + +``` + +## Configuration Schema + +See [docs/configuration.md](docs/configuration.md) for full schema documentation. + +**Key sections**: +- `design_variables`: Parameters to optimize +- `objectives`: Metrics to minimize/maximize +- `nx_settings`: NX/FEA solver configuration +- `optimization`: Optuna sampler settings +- `post_processing`: Result extraction pipelines + +## Development + +### Running Tests + +```bash +pytest +``` + +### Code Formatting + +```bash +black . +ruff check . +``` + +### Building Documentation + +```bash +cd docs +mkdocs build +``` + +## Roadmap + +- [x] MCP server foundation +- [x] Basic optimization engine +- [ ] NXOpen integration +- [ ] Web dashboard +- [ ] Multi-fidelity optimization +- [ ] Parallel evaluations +- [ ] Sensitivity analysis tools +- [ ] Export to engineering reports + +## Contributing + +This is a private repository. Contact [contact@atomaste.com](mailto:contact@atomaste.com) for access. + +## License + +Proprietary - Atomaste © 2025 + +## Support + +- **Documentation**: [docs/](docs/) +- **Examples**: [examples/](examples/) +- **Issues**: GitHub Issues (private repository) +- **Email**: support@atomaste.com + +--- + +**Built with ❤️ by Atomaste** | Powered by Optuna, NXOpen, and Claude diff --git a/config/nx_config.json.template b/config/nx_config.json.template new file mode 100644 index 00000000..2c10b38d --- /dev/null +++ b/config/nx_config.json.template @@ -0,0 +1,8 @@ +{ + "nx_executable": "C:/Program Files/Siemens/NX2306/NXBIN/ugraf.exe", + "python_env": "C:/Users/YourName/anaconda3/envs/nx-optimaster/python.exe", + "journals_dir": "./nx_journals", + "temp_dir": "./temp", + "default_timeout": 300, + "max_parallel_solves": 1 +} diff --git a/config/optimization_config_template.json b/config/optimization_config_template.json new file mode 100644 index 00000000..81170750 --- /dev/null +++ b/config/optimization_config_template.json @@ -0,0 +1,76 @@ +{ + "optimization": { + "max_iterations": 100, + "seed": 42, + "evaluate_baseline_first": true, + "sampler": { + "type": "TPE", + "n_startup_trials": 15, + "n_ei_candidates": 150, + "multivariate": true, + "gamma": 0.25, + "prior_weight": 1.0 + } + }, + "baseline": { + "parameter1": 10.0, + "parameter2": 20.0 + }, + "design_variables": { + "parameter1": { + "type": "float", + "low": 5.0, + "high": 15.0, + "description": "First design parameter", + "enabled": true + }, + "parameter2": { + "type": "float", + "low": 10.0, + "high": 30.0, + "description": "Second design parameter", + "enabled": true + } + }, + "objectives": { + "primary_strategy": "weighted_sum", + "direction": "minimize", + "metrics": { + "max_stress": { + "weight": 10, + "target": 200.0, + "description": "Maximum von Mises stress", + "units": "MPa", + "enabled": true, + "extractor": "nastran_stress", + "extractor_params": { + "subcase": 101, + "stress_type": "von_mises" + } + }, + "mass": { + "weight": 1, + "target": 0.5, + "description": "Total mass", + "units": "kg", + "enabled": true, + "extractor": "nx_mass", + "extractor_params": { + "bodies": "all" + } + } + } + }, + "nx_settings": { + "sim_path": "path/to/model.sim", + "solution_name": "Solution 1", + "post_solve_delay_s": 5, + "op2_timeout_s": 1800, + "op2_stable_s": 4 + }, + "post_processing": { + "archive_results": true, + "export_expressions": true, + "custom_scripts": [] + } +} diff --git a/mcp_server/__init__.py b/mcp_server/__init__.py new file mode 100644 index 00000000..519d81db --- /dev/null +++ b/mcp_server/__init__.py @@ -0,0 +1,8 @@ +""" +NX OptiMaster MCP Server + +Model Context Protocol server for LLM-driven NX optimization configuration. +""" + +__version__ = "0.1.0" +__author__ = "Atomaste" diff --git a/mcp_server/tools/__init__.py b/mcp_server/tools/__init__.py new file mode 100644 index 00000000..ed58d4c8 --- /dev/null +++ b/mcp_server/tools/__init__.py @@ -0,0 +1,23 @@ +""" +MCP Tools for NX OptiMaster + +Available tools: +- discover_fea_model: Analyze .sim files to extract configurable elements +- build_optimization_config: Generate optimization config from LLM instructions +- start_optimization: Launch optimization run +- query_optimization_status: Get current iteration status +- extract_results: Parse FEA result files +- run_nx_journal: Execute NXOpen scripts +- search_nxopen_docs: Search NXOpen API documentation +""" + +from typing import Dict, Any + +__all__ = [ + "discover_fea_model", + "build_optimization_config", + "start_optimization", + "query_optimization_status", + "extract_results", + "run_nx_journal", +] diff --git a/nx_journals/__init__.py b/nx_journals/__init__.py new file mode 100644 index 00000000..86327020 --- /dev/null +++ b/nx_journals/__init__.py @@ -0,0 +1,8 @@ +""" +NXOpen Journal Scripts + +Python scripts that execute within the NX environment using NXOpen API. +These scripts are called via subprocess from the MCP server. +""" + +__version__ = "0.1.0" diff --git a/optimization_engine/__init__.py b/optimization_engine/__init__.py new file mode 100644 index 00000000..558b68ad --- /dev/null +++ b/optimization_engine/__init__.py @@ -0,0 +1,7 @@ +""" +NX OptiMaster Optimization Engine + +Core optimization logic with Optuna integration, reused and enhanced from Atomizer. +""" + +__version__ = "0.1.0" diff --git a/optimization_engine/result_extractors/__init__.py b/optimization_engine/result_extractors/__init__.py new file mode 100644 index 00000000..5a9c17d1 --- /dev/null +++ b/optimization_engine/result_extractors/__init__.py @@ -0,0 +1,66 @@ +""" +Pluggable Result Extractor System + +Base classes and implementations for extracting metrics from FEA results. +""" + +from abc import ABC, abstractmethod +from typing import Dict, Any, Optional +from pathlib import Path + + +class ResultExtractor(ABC): + """Base class for all result extractors.""" + + @abstractmethod + def extract(self, result_files: Dict[str, Path], config: Dict[str, Any]) -> Dict[str, float]: + """ + Extract metrics from FEA results. + + Args: + result_files: Dictionary mapping file types to paths (e.g., {'op2': Path(...), 'f06': Path(...)}) + config: Extractor-specific configuration parameters + + Returns: + Dictionary mapping metric names to values + """ + pass + + @property + @abstractmethod + def required_files(self) -> list[str]: + """List of required file types (e.g., ['op2'], ['f06'], etc.).""" + pass + + @property + def name(self) -> str: + """Extractor name for registration.""" + return self.__class__.__name__.replace("Extractor", "").lower() + + +# Registry of available extractors +_EXTRACTOR_REGISTRY: Dict[str, type[ResultExtractor]] = {} + + +def register_extractor(extractor_class: type[ResultExtractor]) -> type[ResultExtractor]: + """Decorator to register an extractor.""" + _EXTRACTOR_REGISTRY[extractor_class().name] = extractor_class + return extractor_class + + +def get_extractor(name: str) -> Optional[type[ResultExtractor]]: + """Get extractor class by name.""" + return _EXTRACTOR_REGISTRY.get(name) + + +def list_extractors() -> list[str]: + """List all registered extractor names.""" + return list(_EXTRACTOR_REGISTRY.keys()) + + +__all__ = [ + "ResultExtractor", + "register_extractor", + "get_extractor", + "list_extractors", +] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..655a8502 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,76 @@ +[project] +name = "nx-optimaster" +version = "0.1.0" +description = "Advanced optimization platform for Siemens NX Simcenter with MCP integration" +authors = [ + {name = "Atomaste", email = "contact@atomaste.com"} +] +readme = "README.md" +requires-python = ">=3.10" +license = {text = "Proprietary"} + +dependencies = [ + "optuna>=3.5.0", + "pandas>=2.0.0", + "numpy>=1.24.0", + "scipy>=1.10.0", + "scikit-learn>=1.3.0", + "pyNastran>=1.4.0", + "plotly>=5.18.0", + "fastapi>=0.109.0", + "uvicorn>=0.27.0", + "websockets>=12.0", + "pydantic>=2.5.0", + "python-multipart>=0.0.6", + "jinja2>=3.1.3", +] + +[project.optional-dependencies] +dev = [ + "pytest>=7.4.0", + "pytest-cov>=4.1.0", + "black>=23.12.0", + "ruff>=0.1.0", + "mypy>=1.8.0", + "pre-commit>=3.6.0", +] + +mcp = [ + "mcp>=0.1.0", +] + +dashboard = [ + "dash>=2.14.0", + "dash-bootstrap-components>=1.5.0", +] + +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.setuptools.packages.find] +where = ["."] +include = ["mcp_server*", "optimization_engine*", "nx_journals*"] + +[tool.black] +line-length = 100 +target-version = ['py310'] +include = '\.pyi?$' + +[tool.ruff] +line-length = 100 +select = ["E", "F", "I", "N", "W"] +ignore = ["E501"] + +[tool.mypy] +python_version = "3.10" +warn_return_any = true +warn_unused_configs = true +disallow_untyped_defs = false + +[tool.pytest.ini_options] +testpaths = ["tests"] +python_files = ["test_*.py"] +python_classes = ["Test*"] +python_functions = ["test_*"] +addopts = "-v --cov=mcp_server --cov=optimization_engine --cov-report=html --cov-report=term" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..f8dee927 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,23 @@ +# Core Dependencies +optuna>=3.5.0 +pandas>=2.0.0 +numpy>=1.24.0 +scipy>=1.10.0 +scikit-learn>=1.3.0 +pyNastran>=1.4.0 +plotly>=5.18.0 + +# Web Framework +fastapi>=0.109.0 +uvicorn>=0.27.0 +websockets>=12.0 +pydantic>=2.5.0 +python-multipart>=0.0.6 +jinja2>=3.1.3 + +# Development Tools (optional) +pytest>=7.4.0 +pytest-cov>=4.1.0 +black>=23.12.0 +ruff>=0.1.0 +mypy>=1.8.0