# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Overview

This is a Python-based cable routing automation tool for industrial plant layouts. The system reads DXF files containing equipment positions and cable trays, calculates optimal cable paths using graph algorithms, and generates cable lists with SIVAS article numbers for procurement.

## Architecture

The codebase follows a modular three-stage pipeline:

1. **Position Extraction** ([getpositions.py](lib/getpositions.py)) - Extracts equipment positions and cable tray geometries from DXF files
2. **Route Calculation** ([routing.py](lib/routing.py)) - Builds graph models and calculates shortest paths between equipment and distributors
3. **Output Generation** ([drawdxf.py](lib/drawdxf.py)) - Creates DXF files with cable paths and Excel lists with cable specifications

### Pipeline Data Flow

```
DXF file
  → getpositions.py  → *_positionsdraw.json  (positions, racks, distributors, mappings)
  → routing.py       → *_todraw.json         (cable routes with coordinates and lengths)
  → drawdxf.py       → *.dxf + *.xlsx + BOM  (final output files)
```

The JSON intermediate files serve as interfaces between stages and are valuable for debugging. Each stage can be run independently.

### Workflow Modes

The system supports four primary workflows:

1. **Full Cable Routing** (`getexdraw.bat`) - Complete pipeline from DXF input to cable paths and BOMs
2. **I/O Conversion** (`ioconverter.bat`) - Converts DXF equipment data to Excel formats for TIA, WSCAD, and other systems
3. **Text Extraction** (`extract.bat`) - Extracts all TEXT and MTEXT objects from DXF files to multiple formats (Excel, JSON, Text) for translation purposes
4. **Translation** (`tr2dxf.bat`, `tr2dxf_cs.bat`, etc.) - Translates DXF text content into target languages (Czech, English, French, Italian, Spanish)

### Core Modules

- **[plant.py](lib/plant.py)** - Main business logic containing the `Anlage` class that models industrial plants, manages equipment connections, and implements graph-based routing algorithms
- **[model.py](lib/model.py)** - Data classes for points, equipment, distributors, and cable trays using dataclasses and dacite
- **[graphbuild.py](lib/graphbuild.py)** - Graph construction utilities for network topology
- **[linesweep.py](lib/linesweep.py)** - Geometric algorithms for line intersection detection

### Utility Modules

- **[error_collector.py](lib/error_collector.py)** - Centralized error/warning collection system with two severity levels; used across getpositions and drawdxf
- **[utils.py](lib/utils.py)** - Common utility functions: file I/O, environment variable checks, JSON operations, DXF file handling, dictionary merging
- **[updateconfignames.py](lib/updateconfignames.py)** - Updates SIVAS article descriptions in `bezeichner.cfg` from external SIVAS database exports (CSV files in `data/`)
- **[flags.py](lib/flags.py)** - Icon/flag generation using PIL for language flags (EN, FR, IT, ES, CS)

### Export & Conversion Modules

- **[portalexport.py](lib/portalexport.py)** - Exports equipment I/O data to Excel formats for TIA Portal and WSCAD
- **[ioconverter.py](lib/ioconverter.py)** - `ExcelConverter` class for converting I/O lists with input/output identifier mappings
- **[translate.py](lib/translate.py)** - Comprehensive text extraction/translation: extracts TEXT, MTEXT, and block attributes from DXF/DWG files; supports Excel, JSON, Text export formats

### DXF Utility Modules

- **[create_dxf_symbols.py](lib/create_dxf_symbols.py)** - Creates DXF symbol blocks (grounding, switchboard, subdistribution, motor symbols)
- **[create_example.py](lib/create_example.py)** - `TestDataGenerator` for generating synthetic test DXF files with defined layouts
- **[create_numbers.py](lib/create_numbers.py)** - Generates/updates numbered symbols in DXF files based on RENAMER layer configuration

### Configuration System

The system uses configuration files in `cfg/`:

- **`BMK.cfg`** - Equipment identification codes, cable type mappings, routing inclusion/exclusion rules, cabinet/tunnel patterns, length adjustments
- **`kabel.cfg`** - SIVAS article number mappings for different cable types and lengths (sections like `[MA]`, `[WD_Q]`, `[WD_I]`, etc.)
- **`allgemein.cfg`** - Layer names for racks/distributors/tunnels, geometric tolerances, connection parameters
- **`bezeichner.cfg`** - Article number descriptions, auto-populated from SIVAS database
- **`translator.cfg`** - Text filtering for translation (wildcard and regex ignore patterns)
- **`enumerate.cfg`** - Symbol enumeration settings (RENAMER layers, polyline distances)
- **`translation/CS.cfg`** - Czech language translation key mappings

**Important**: When adding a new equipment prefix, it must be added to **both** `[Routing-Include]` and `[Cable-Mapping]` in `BMK.cfg`, and the corresponding cable section must exist in `kabel.cfg`.

**Article-specific mappings**: `[Cable-Mapping]` supports article-number-specific entries like `MB-929012603 = WD_Q-929012603` alongside generic prefix mappings like `MA = MA`. The specific entry takes precedence when the sensor's article number matches.

**Current prefixes in `[Routing-Include]`**: MA, MB, QM, BG, BP, BX, PO, SF, PF, GF

## Common Commands

### Main Execution

```bash
# Process a DXF file for cable routing (drag-and-drop onto desktop shortcut in production)
bin\getexdraw.bat <filename.dxf>

# Convert DXF to I/O lists for TIA Portal, WSCAD, etc.
bin\ioconverter.bat <filename.dxf>

# Extract text from DXF files for translation
bin\extract.bat <filename.dxf>

# Translate DXF to Czech (also: tr2dxf_en, tr2dxf_fr, tr2dxf_it, tr2dxf_es)
bin\tr2dxf_cs.bat <filename.dxf>

# PowerShell alternative for getexdraw
bin\getexdraw.ps1 <filename.dxf>

# Manual execution of pipeline stages
bin\getpositions.bat --filename <file.dxf> -s -r -w <output.json>
bin\routing.bat --filename <positions.json> -w <todraw.json>
bin\draw_dxf.bat --filename <todraw.json> --new <output.dxf> -x <output.xlsx>
bin\portalexport.bat --filename <positions.json> --outname <basename>
bin\translate.bat --filename <file.dxf> --extract --export-type excel,json --outname <output>
```

**Note**: All `.bat` scripts have corresponding `.sh` equivalents for Linux/macOS systems.

### Development and Testing

```bash
# Install Python dependencies
bin\install_py.bat

# Run automated test suite (all test files)
bin\run_tests.bat

# Run test for a single file (most common for development)
bin\run_test.bat <testname>
bin\run_test.bat easy
bin\run_test.bat easy --clean

# Run tests for specific file (alternative syntax)
bin\run_tests.bat --file <testname>

# Run tests in different modes
bin\run_test.bat <testname> --ioconverter
bin\run_test.bat <testname> --translation
bin\run_tests.bat --ioconverter

# Create reference files from current outputs
bin\run_tests.bat --create-references

# Clean up work folders after tests
bin\run_tests.bat --clean

# Run unit tests
bin\run_unittests.bat

# Individual component testing
python lib\getpositions.py --help
python lib\routing.py --graph  # Shows visual graph
python lib\drawdxf.py --help
```

### Production Deployment

```bash
# Create desktop shortcuts with drag-and-drop icons for all tools
bin\dropItem_create.bat

# Remove desktop shortcuts
bin\dropItem_remove.bat
```

### Configuration Management

```bash
# Update SIVAS article descriptions
python lib\updateconfignames.py

# Convert between formats
python lib\ioconverter.py
```

## Development Guidelines

### Code Style

- Use German comments and variable names for consistency with existing codebase
- Follow dataclass patterns established in [model.py](lib/model.py)
- Maintain separation between geometric operations (Shapely) and graph algorithms (NetworkX)

### Configuration Changes

- Always update corresponding `.cfg` files when adding new equipment types or cable categories
- A new equipment prefix needs entries in: `[Routing-Include]`, `[Cable-Mapping]` (both in `BMK.cfg`), and a matching section in `kabel.cfg`
- Test configuration changes with sample DXF files in [testdata/](testdata/) directory
- Configuration files use Windows INI format with specific section naming conventions

### Error Handling

The system uses [error_collector.py](lib/error_collector.py) for centralized error/warning collection with two severity levels:

- **Errors** (critical issues that affect output correctness):
  - Equipment connection failures (distance tolerances)
  - Missing SIVAS article numbers
  - Invalid DXF block attributes
  - Graph routing failures
  - Missing or overdefined tunnel positions
  - Duplicate equipment IDs

- **Warnings** (potential issues, processing continues):
  - Missing or incomplete block attributes
  - Invalid KENNZEICHNUNG format
  - Missing tunnel length specifications

All issues are collected in the `warnings` section of output JSON files (e.g., `*_positionsdraw.json`). Critical errors also generate separate `*_errors.json` files. See [doc/Anwenderdoku_kurz.md](doc/Anwenderdoku_kurz.md) for detailed error descriptions and resolution steps.

### Config Validation

On startup, `getpositions.py` validates configuration consistency and reports:
- Prefixes in `[Routing-Include]` without a `[Cable-Mapping]` entry
- Cable sections referenced in `[Cable-Mapping]` that are missing from `kabel.cfg`

### Testing

The project includes a comprehensive automated test suite:

- Test DXF files stored in [testdata/](testdata/) (e.g., `easy.dxf`, `easy_sps.dxf`, `easy_hoehe.dxf`, `easy_3tunnels.dxf`, `Erdungsbsp.dxf`)
- Reference JSON outputs stored alongside test DXF files
- Test runner ([run_tests.py](lib/run_tests.py)) compares generated outputs against references with diff reporting
- Supports `getexdraw`, `ioconverter`, and `translate` workflow testing
- Visual graph debugging available with `--graph` flag in routing
- Test cases cover: standard routing, SPS integration, height differences, tunnel overdefinition, grounding, duplicate IDs, translation
- Unit tests in `lib/` (`error_collector_test.py`, `utils_test.py`, `flags_test.py`, `create_numbers_test.py`, `getpositions_test.py`)
- Additional edge case tests in [tests/](tests/) directory (e.g., `test_ioconverter_errors.py`)

## File Structure

```text
bin/            # Batch scripts (.bat) and shell scripts (.sh) for all workflows
cfg/            # Configuration files (BMK, cable mappings, tolerances, translation filters)
cfg/translation/# Language-specific translation configs (CS.cfg)
lib/            # Python modules (core pipeline, utilities, tests)
work/           # Working directory for processing results (generated output)
testdata/       # Test DXF files and reference outputs for automated testing
tests/          # Additional test files and edge case test data
doc/            # Comprehensive German documentation (Markdown + PDF)
doc/img/Icons/  # Icons for desktop shortcuts
data/           # SIVAS article number CSV reference files (auto-populated)
translation/    # Translation configurations
```

## Dependencies

Key Python packages (see [lib/requirements.txt](lib/requirements.txt)):

- `ezdxf` - DXF file reading/writing
- `shapely` - Geometric operations
- `networkx` - Graph algorithms
- `openpyxl` - Excel output generation
- `pandas` - Data manipulation
- `matplotlib` - Graph visualization
- `dacite` - Dataclass conversion utilities
- `PyMuPDF` - PDF processing capabilities
- `pillow` - Image processing (flag/icon generation)
- `pytest` - Testing framework

## Output Files

### Cable Routing Workflow (getexdraw)

- `*_cables.dxf` - DXF with drawn cable paths
- `*_cables.xlsx` - Cable list with lengths and SIVAS numbers
- `*_BOM.xlsx` - Complete bill of materials
- `*_positionsdraw.json` - Intermediate position data with routing info
- `*_todraw.json` - Intermediate routing data for drawing
- `*_errors.json` - Error report (if validation fails)

### I/O Conversion Workflow (ioconverter)

- `*-TIA.xlsx` - Excel export for TIA Portal
- `*-WSCAD.xlsx` - Excel export for WSCAD
- `*_positionsconv.json` - Intermediate position data for conversion
- `*_errors.json` - Error report (if validation fails)

### Text Extraction Workflow (extract)

- `*_texts.xlsx` - Excel file with all TEXT and MTEXT entities from DXF for translation

### Translation Workflow (tr2dxf)

- Translated DXF files with text replaced in target language

## Environment Variables

The system uses environment variables defined in [bin/setenv.bat](bin/setenv.bat):

- `PROJECT` - Root directory of the project
- `PROJECT_BIN` - Binary/script directory
- `PROJECT_CFG` - Configuration directory
- `PROJECT_DOC` - Documentation directory
- `PROJECT_LIB` - Python library directory
- `PROJECT_DATA` - SIVAS reference data directory
- `PROJECT_WORK` - Working directory for outputs
- `PROJECT_TEST` - Test data directory (testdata/)
- `PROJECT_LOG` - Log directory
- `PROJECT_TRANSLATION` - Translation directory
- `PROJECT_IO_RESULTS` - Network location for I/O converter results
- `PROJECT_BOM_RESULTS` - Network location for BOM results
- `SIVAS_TEILESTAMM` - Path to SIVAS parts database export tool
- `SIVAS_EXCEL_EXPORT_DIR` - Output directory for SIVAS data exports
- `INSTALL_DIR` - Desktop shortcut installation location

Local overrides can be placed in `bin/_setenv.bat` (not tracked in git).
