# NXOpen Resources and References

## Overview

This document lists valuable resources for NXOpen development that can inform our implementation without direct code copying.

---

## Primary Resources

### 1. **Official Siemens NXOpen API Documentation**

**URL**: https://docs.sw.siemens.com/en-US/doc/209349590/PL20231101866122454.custom_api.nxopen_net

**Usage**:
- Primary reference for API syntax and methods
- Official namespace documentation
- Method signatures and return types
- Parameter descriptions

**Integration Strategy**:
- MCP tool `search_nxopen_docs` will fetch pages on-demand
- Cache frequently-used API snippets locally
- LLM can reference documentation when generating NXOpen code

---

### 2. **NXOpenTSE by The Scripting Engineer**

**GitHub**: https://github.com/theScriptingEngineer/nxopentse/tree/main
**Documentation**: https://nxopentsedocumentation.thescriptingengineer.com/

#### About NXOpenTSE

NXOpenTSE is an open-source Python library that provides:
- **High-level wrappers** around NXOpen API
- **Utility functions** for common NX operations
- **Well-documented examples** of NX automation patterns
- **Best practices** for NX scripting

**License**: MIT (as of last check - verify before use)

#### Why NXOpenTSE is Valuable for Atomizer

1. **Reference for Design Patterns**:
   - How to structure NXOpen scripts
   - Error handling approaches
   - Session management patterns
   - Part loading/unloading workflows

2. **Understanding API Usage**:
   - See real-world examples of API calls
   - Learn parameter combinations that work
   - Understand method call sequences

3. **Avoiding Common Pitfalls**:
   - See solutions to typical problems
   - Learn about NX-specific gotchas
   - Understand threading/transaction requirements

4. **Inspiration for Features**:
   - Discover what's possible with NXOpen
   - See advanced techniques
   - Learn about lesser-known APIs

#### Integration Strategy for Atomizer

**Approach**: Reference, don't copy

```
✅ DO:
- Study NXOpenTSE documentation for understanding NX concepts
- Reference example patterns when writing our own code
- Learn from error handling approaches
- Use as inspiration for our API wrapper design
- Link to NXOpenTSE docs in our MCP system prompts
- Ask LLM to "check NXOpenTSE documentation for similar examples"

❌ DON'T:
- Copy code verbatim without attribution
- Replicate their library structure
- Import NXOpenTSE as a dependency (we build our own)
- Reuse their code without understanding it
```

#### Specific Areas to Reference

| Our Component | NXOpenTSE Reference Area | What to Learn |
|--------------|-------------------------|---------------|
| `nx_journals/update_and_solve.py` | Expression handling, part updates | How to safely modify expressions |
| `nx_journals/api_dispatcher.py` | Session management | Best practices for NX session handling |
| `mcp_server/tools/model_discovery.py` | Part file reading | How to extract model information |
| `optimization_engine/result_extractors/` | CAE result reading | Methods for accessing simulation results |

---

## Using NXOpenTSE Documentation with MCP

### MCP System Prompt Extension

When generating NXOpen code, the LLM can be instructed to:

```markdown
When writing NXOpen code:
1. First check official Siemens NXOpen API docs for method signatures
2. Reference NXOpenTSE documentation (https://nxopentsedocumentation.thescriptingengineer.com/)
   for real-world usage patterns and best practices
3. Adapt patterns to our specific use case rather than copying directly
4. Always include error handling and validation
5. Add comments explaining NX-specific requirements
```

### Example LLM Workflow

**User**: "I need to read all expressions from a .sim file"

**LLM Reasoning**:
1. Check official API: `NXOpen.Part.Expressions`
2. Look at NXOpenTSE example: https://nxopentsedocumentation.thescriptingengineer.com/expressions.html
3. See pattern: Loop through `work_part.Expressions`, handle edge cases
4. Adapt to our needs: Add filtering, type checking, JSON serialization

**Generated Code** (our implementation, inspired by reference):
```python
def get_expressions(sim_file_path: Path) -> dict:
    """Extract all expressions from a .sim file."""
    import NXOpen

    session = NXOpen.Session.GetSession()

    # Load sim file
    part, status = session.Parts.OpenActiveDisplay(str(sim_file_path))

    expressions = {}
    try:
        for expr in part.Expressions:
            # Filter out system expressions (start with underscore)
            if not expr.Name.startswith("_"):
                expressions[expr.Name] = {
                    "value": expr.Value,
                    "units": expr.Units if expr.Units else "",
                    "type": str(expr.Type)
                }
    finally:
        # Clean up
        session.Parts.SetWork(None)

    return expressions
```

---

## Additional Resources

### 3. **Eng-Tips NXOpen Forum**

**URL**: https://www.eng-tips.com/threadminder.cfm?pid=561

- Community Q&A
- Troubleshooting help
- User-contributed examples

### 4. **Stack Overflow - NXOpen Tag**

**URL**: https://stackoverflow.com/questions/tagged/nxopen

- Specific problem solutions
- Code snippets for common tasks

### 5. **Siemens PLM Community Forums**

**URL**: https://community.sw.siemens.com/

- Official support
- Product announcements
- Beta access information

---

## Best Practices Learned from NXOpenTSE

### 1. **Session Management**

```python
# Always get session at the start
session = NXOpen.Session.GetSession()

# Always check if part is loaded
if session.Parts.Work is None:
    raise ValueError("No work part loaded")
```

### 2. **Error Handling**

```python
# Wrap NX operations in try-finally for cleanup
try:
    # NX operations here
    result = do_something()
finally:
    # Always clean up, even on error
    if temp_part:
        session.Parts.CloseAll(NXOpen.BasePart.CloseWholeTree.True)
```

### 3. **Expression Updates**

```python
# Use Edit method for updating expressions
expr = part.Expressions.FindObject("parameter_name")
if expr:
    expr.Edit(new_value)
else:
    # Create if doesn't exist
    unit = part.UnitCollection.FindObject("MilliMeter")
    part.Expressions.CreateExpression(unit, "parameter_name", str(new_value))
```

### 4. **Simulation Solution Access**

```python
# Access simulation objects safely
sim_simulation = sim_part.Simulation
if sim_simulation:
    solutions = sim_simulation.Solutions
    for solution in solutions:
        if solution.Name == target_name:
            # Found our solution
            pass
```

---

## Attribution and Licensing

### When Using Ideas from NXOpenTSE

1. **Add attribution in comments**:
   ```python
   # Approach inspired by NXOpenTSE expression handling
   # See: https://nxopentsedocumentation.thescriptingengineer.com/expressions.html
   ```

2. **Link in documentation**:
   - Acknowledge inspiration in our docs
   - Link to relevant NXOpenTSE pages
   - Credit The Scripting Engineer for educational resources

3. **Respect MIT License** (verify current license):
   - Give credit to original authors
   - Don't claim their work as ours
   - Contribute back to community if we find improvements

---

## Contributing to NXOpenTSE

If we discover useful patterns or fixes while building Atomizer:
- Consider contributing examples back to NXOpenTSE
- Report issues if we find documentation errors
- Share knowledge with the NX scripting community

---

## Integration with Atomizer MCP

### MCP Tool: `search_nxopen_resources`

```python
{
  "name": "search_nxopen_resources",
  "description": "Search NXOpen documentation and reference materials",
  "inputSchema": {
    "query": "How to update expressions in NX",
    "sources": ["official", "nxopentse", "community"],
    "return_examples": true
  }
}
```

**Output**:
```json
{
  "official_docs": "https://docs.sw.siemens.com/.../Expressions",
  "nxopentse_example": "https://nxopentsedocumentation.thescriptingengineer.com/expressions.html",
  "code_pattern": "Use part.Expressions.CreateExpression() or FindObject().Edit()",
  "community_threads": [...]
}
```

### System Prompt Reference Section

```markdown
## NXOpen Development Resources

When implementing NXOpen functionality:

1. **Official API**: Consult Siemens NXOpen .NET documentation for authoritative API reference
2. **NXOpenTSE**: Reference https://nxopentsedocumentation.thescriptingengineer.com/ for:
   - Practical usage patterns
   - Common parameter combinations
   - Error handling approaches
   - Real-world examples
3. **Adaptation**: Always adapt patterns to Atomizer's specific architecture rather than copying

Remember: NXOpenTSE is a reference for learning, not a dependency to import.
```

---

## Summary

**NXOpenTSE is invaluable** for accelerating Atomizer development by:
- ✅ Showing proven patterns
- ✅ Teaching NX best practices
- ✅ Providing working examples to learn from
- ✅ Documenting edge cases and gotchas

**We will use it as**:
- 📚 Educational reference
- 🎯 Design pattern inspiration
- 🔍 Problem-solving resource
- 🧭 Navigation aid through complex NXOpen API

**Not as**:
- ❌ Code to copy-paste
- ❌ Dependency to import
- ❌ Replacement for understanding

This approach allows us to learn from the community while building something unique and tailored to Atomizer's specific optimization use case.

---

**Last Updated**: 2025-11-15
**Maintainer**: Atomaster Development Team
