### Install PyGerber with all extras Source: https://github.com/argmaster/pygerber/blob/main/README.md Installs the library along with optional features like SVG rendering and the language server. ```bash pip install pygerber[all] ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/10_env_setup.md Install all project dependencies, including optional ones and those for documentation and styling, using Poetry. Run this command after cloning or pulling changes to ensure dependencies are up-to-date. ```bash poetry install --sync --extras=all --with=docs,style ``` -------------------------------- ### Install PyGerber Language Server Source: https://github.com/argmaster/pygerber/blob/main/README.md Installs PyGerber with the necessary extras for the Language Server Protocol. ```bash pip install pygerber[language-server] ``` -------------------------------- ### Start Documentation Live Preview Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/30_documentation.md Launches a local development server with automatic reloading when documentation files are modified. ```bash mkdocs serve ``` -------------------------------- ### Install git hooks Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/10_env_setup.md Run this command to set up the pre-commit hooks locally. ```bash poe install-hooks ``` -------------------------------- ### Install PyGerber package Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/20_packaging.md Install the generated distribution file using pip. Replace x.y.z with the actual version number. ```bash pip install dist/pygerber-x.y.z.tar.gz ``` -------------------------------- ### Install PyGerber development version Source: https://github.com/argmaster/pygerber/blob/main/README.md Installs the latest development version directly from the GitHub repository. ```bash pip install git+https://github.com/Argmaster/pygerber ``` -------------------------------- ### Install PyGerber via pip Source: https://github.com/argmaster/pygerber/blob/main/README.md Installs the core features of the PyGerber library. ```bash pip install pygerber ``` -------------------------------- ### Install Poetry with Pip Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/10_env_setup.md Use this command to install the Poetry dependency manager globally using pip. Ensure you install a version that is stable, preferably >=1.8. ```bash pip install poetry ``` -------------------------------- ### Basic Gerber Formatting Example Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/60_formatter/05_api_usage.md Demonstrates the basic usage of the `format` function to format Gerber code. This requires parsing the code first to obtain an abstract syntax tree. ```python from pygerber.gerber.formatter import format from pygerber.gerber.lexer import Lexer from pygerber.gerber.parser import Parser # Example Gerber code gercode = "G71*\nG01*\nX1Y1F100*\nG70*\nM02*" # Parse the code lexer = Lexer(gercode) parser = Parser(lexer) ast = parser.parse() # Format the code to stdout format(ast) ``` -------------------------------- ### Install PyGerber extras Source: https://github.com/argmaster/pygerber/blob/main/docs/50_command_line/20_gerber.md Installs optional dependencies required for specific features like SVG rendering. ```bash pip install pygerber[shapely] ``` ```bash pip install pygerber[all] ``` -------------------------------- ### Install PyGerber with Pip Source: https://context7.com/argmaster/pygerber/llms.txt Install the core PyGerber library or with optional extras for extended functionality like language server support or SVG rendering. ```bash # Core installation pip install pygerber # Install with all extras (language server, SVG support, etc.) pip install pygerber[all] # Install specific extras pip install pygerber[language_server] # Language Server Protocol support pip install pygerber[svg] # SVG rendering via drawsvg pip install pygerber[shapely] # Shapely-based vector rendering pip install pygerber[pygments] # Syntax highlighting support ``` -------------------------------- ### Custom Color Map Example Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/10_custom_color_maps.md Demonstrates how to create a custom color map by defining a dictionary that maps FileTypeEnum values to Style instances and then applying it to a GerberFile object. ```python from pygerber.gerber.api import GerberFile, FileTypeEnum, Style # Define custom colors custom_style_copper = Style(color=(255, 0, 0), alpha=1.0) custom_style_silkscreen = Style(color=(0, 255, 0), alpha=1.0) # Create a custom color map custom_color_map = { FileTypeEnum.COPPER_INNER: custom_style_copper, FileTypeEnum.SILKSCREEN_TOP: custom_style_silkscreen, } # Load a Gerber file g = GerberFile.from_file("path/to/your/gerber.gbr") # Set the custom color map g.set_color_map(custom_color_map) # Render the file with custom colors g.render_to_file("output.svg") ``` -------------------------------- ### Example Coverage Report Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/40_contribution_guidelines.md This is an example of a coverage report generated after running tests. It details the lines of code, missed lines, and coverage percentage for various modules. ```text ---------- coverage: platform linux, python 3.8.18-final-0 ---------- Name Stmts Miss Cover Missing ---------------------------------------------------------------------------------------- src/pygerber/__main__.py 4 4 0% 3-8 src/pygerber/builder/gerber.py 425 30 93% 215, 243, 246, 266, 415-418, 429, 637, 891, 913, 932, 938-939, 942-943, 946-947, 952, 997-998, 1448-1459, 1570-1571, 1640, 1680, 1729, 1745 src/pygerber/builder/rvmc.py 88 16 82% 105-109, 119-124, 175-176, 179-180, 208-209, 236-237, 275-276, 295-296 src/pygerber/common/error.py 4 1 75% 10 src/pygerber/common/position.py 43 43 0% 3-83 src/pygerber/console/commands.py 38 4 89% 21-26 src/pygerber/gerber/api/_composite_view.py 35 1 97% 95 src/pygerber/gerber/api/_enums.py 68 7 90% 123, 129, 136-137, 142, 145, 148 src/pygerber/gerber/api/_gerber_file.py 224 24 89% 109, 114, 122, 130, 248, 278, 283, 309, 329, 398-399, 474, 479-492, 499, 537, 560 src/pygerber/gerber/api/_gerber_job_file.py 119 4 97% 146, 191, 209, 218 src/pygerber/gerber/api/_project.py 19 1 95% 42 src/pygerber/gerber/ast/ast_visitor.py 387 3 99% 781, 794, 798 src/pygerber/gerber/ast/errors.py 32 5 84% 28, 47-48, 57-58 src/pygerber/gerber/ast/expression_eval_visitor.py 59 3 95% 100-102 src/pygerber/gerber/ast/node_finder.py 61 6 90% 51, 54-55, 68-69, 92 src/pygerber/gerber/ast/nodes/aperture/AB.py 13 1 92% 32 src/pygerber/gerber/ast/nodes/aperture/AM.py 13 1 92% 32 src/pygerber/gerber/ast/nodes/aperture/SR.py 13 1 92% 32 src/pygerber/gerber/ast/nodes/attribute/TA.py 53 3 94% 24, 36, 106 src/pygerber/gerber/ast/nodes/attribute/TF.py 107 4 96% 27, 39, 216, 225 ``` -------------------------------- ### Reference output for test-style Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/10_env_setup.md Example output generated after running the poe test-style command. ```text Poe => poetry run pre-commit run --all-files -v prettier.................................................................Passed - hook id: prettier - duration: 0.83s check illegal windows names..........................(no files to check)Skipped - hook id: check-illegal-windows-names check for case conflicts.................................................Passed - hook id: check-case-conflict - duration: 0.5s check for merge conflicts................................................Passed - hook id: check-merge-conflict - duration: 0.38s check for case conflicts.................................................Passed - hook id: check-case-conflict - duration: 0.48s trim trailing whitespace.................................................Passed - hook id: trailing-whitespace - duration: 0.23s debug statements (python)................................................Passed - hook id: debug-statements - duration: 0.23s fix end of files.........................................................Passed - hook id: end-of-file-fixer - duration: 0.2s fix utf-8 byte order marker..............................................Passed - hook id: fix-byte-order-marker - duration: 0.22s check for added large files..............................................Passed - hook id: check-added-large-files - duration: 0.52s check toml...............................................................Passed - hook id: check-toml - duration: 0.09s mixed line ending........................................................Passed - hook id: mixed-line-ending - duration: 0.22s trim trailing whitespace.................................................Passed - hook id: trailing-whitespace - duration: 0.22s debug statements (python)................................................Passed - hook id: debug-statements - duration: 0.22s ruff.....................................................................Passed - hook id: ruff - duration: 0.11s All checks passed! ruff-format..............................................................Passed - hook id: ruff-format - duration: 0.11s 284 files left unchanged mypy.....................................................................Passed - hook id: mypy - duration: 15.95s Poe => poetry run mypy --config-file=pyproject.toml src/pygerber/ test/ Success: no issues found in 279 source files ``` -------------------------------- ### Check PyGerber Version Source: https://github.com/argmaster/pygerber/blob/main/docs/50_command_line/00_introduction.md Use this command to check the installed version of PyGerber. ```bash pygerber --version ``` -------------------------------- ### Check Language Server Availability Source: https://github.com/argmaster/pygerber/blob/main/README.md Verifies if the Gerber Language Server is installed and accessible. ```bash pygerber is-language-server-available ``` -------------------------------- ### PyGerber Pre-commit Configuration Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/40_contribution_guidelines.md This YAML configuration file defines the pre-commit hooks used by PyGerber to ensure code quality and consistency. It should be used in conjunction with the environment setup instructions. ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - id: check-docstring-first - id: check-json - id: check-merge-conflict - id: debug-statements - id: requirements-txt-fixer - repo: https://github.com/psf/black rev: 23.9.2 hooks: - id: black - repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort args: [--profile, black] - repo: https://github.com/pycqa/flake8 rev: 6.1.0 hooks: - id: flake8 args: [--config, setup.cfg] - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.6.1 hooks: - id: mypy args: [--config-file, pyproject.toml] additional_dependencies: [types-requests] ``` -------------------------------- ### VM Initialization Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/40_contribution_guidelines.md Initializes the virtual machine (VM) for processing Gerber commands. Sets up the initial state and environment. ```python class VM: def __init__(self): self.state = {} self.commands = {} def register_command(self, name, func): self.commands[name] = func def execute(self, command_name, *args, **kwargs): if command_name in self.commands: self.commands[command_name](self, *args, **kwargs) else: raise UnknownCommandError(f'Unknown command: {command_name}') ``` -------------------------------- ### Build Documentation with MkDocs Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/30_documentation.md Generates the static HTML, CSS, and JS files for the documentation in the site directory. ```bash mkdocs build ``` -------------------------------- ### List Gerber conversion help Source: https://github.com/argmaster/pygerber/blob/main/docs/50_command_line/20_gerber.md Displays available image conversion formats and options. ```bash pygerber gerber convert --help ``` -------------------------------- ### Creating a region with RegionCreator Source: https://github.com/argmaster/pygerber/blob/main/docs/80_code_generation/10_gerber.md Demonstrates the initialization of a region using GerberX3Builder and the addition of segments to define the outline. ```python from pygerber.builder.gerber import GerberX3Builder builder = GerberX3Builder() region = builder.new_region(0, 0) region.add_line(10, 0) region.add_line(10, 10) region.add_line(0, 10) region.create() ``` -------------------------------- ### Create circle pads with GerberX3Builder Source: https://github.com/argmaster/pygerber/blob/main/docs/80_code_generation/10_gerber.md Demonstrates creating a circle aperture and adding multiple pads at specific coordinates. ```python from pygerber.builder.gerber import GerberX3Builder builder = GerberX3Builder() d10 = builder.new_pad().circle(diameter=1.0) builder.add_pad(d10, (1, 1)) builder.add_pad(d10, (2, 1)) print(builder.get_gerber()) ``` -------------------------------- ### Add pads and traces with GerberX3Builder Source: https://github.com/argmaster/pygerber/blob/main/docs/80_code_generation/10_gerber.md Shows how to combine pad creation with straight line and arc traces in a Gerber image. ```python from pygerber.builder.gerber import GerberX3Builder builder = GerberX3Builder() d10 = builder.new_pad().circle(diameter=0.5) builder.add_pad(d10, (1, 1)) builder.add_pad(d10, (3, 1)) builder.new_trace(width=0.2).move_to((1, 1)).line_to((3, 1)) builder.add_clockwise_arc_trace(width=0.2, center=(3, 2), end=(4, 2)) print(builder.get_gerber()) ``` -------------------------------- ### Build PyGerber package Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/20_packaging.md Use Poetry to generate wheel and source distribution packages from the source code. ```bash poetry build ``` -------------------------------- ### Get image space information Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/01_single_file.md Use get_image_space() on the PillowImage object to retrieve information about the image's coordinate space, size, etc. ```python from pygerber.gerber.api import GerberFile with open("test/examples/gerberx3/api/_50_show_image_info.singlefile.py", "r") as f: gerber_file = GerberFile.from_file(f) image = gerber_file.render_with_pillow() image_space = image.get_image_space() print(f"Image space: {image_space}") ``` -------------------------------- ### Create and Activate Development Virtual Environment Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/10_env_setup.md Navigate to the project root directory and use this command to create a new virtual environment managed by Poetry and activate it. The terminal prompt will indicate the active environment. ```bash poetry shell ``` -------------------------------- ### Format Gerber file code Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/01_single_file.md Use format() to write formatted Gerber code to a text stream, or formats() to get it as a string. Refer to Formatter documentation for options. ```python from pygerber.gerber.api import GerberFile from io import StringIO # Example Gerber code g = "G01X1Y1D2*\nG02X2Y2D1*\n" # Format and write to stdout with StringIO(g) as f: gerber_file = GerberFile.from_file(f) gerber_file.format(StringIO()) # Format and return as string with StringIO(g) as f: gerber_file = GerberFile.from_file(f) formatted_code = gerber_file.formats() print(formatted_code) ``` -------------------------------- ### Gerber Formatting with Options Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/60_formatter/05_api_usage.md Shows how to use the `format` function with custom `Options` to configure the formatting behavior. The `Options` object can be passed as an optional argument. ```python from pygerber.gerber.formatter import format from pygerber.gerber.lexer import Lexer from pygerber.gerber.parser import Parser from pygerber.gerber.formatter.options import Options # Example Gerber code gercode = "G71*\nG01*\nX1Y1F100*\nG70*\nM02*" # Parse the code lexer = Lexer(gercode) parser = Parser(lexer) ast = parser.parse() # Configure formatting options options = Options(indent_spaces=4, newline_char='\n') # Format the code with options to stdout format(ast, options=options) ``` -------------------------------- ### Create a CompositeView instance Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/02_multi_file.md Initialize a CompositeView by passing GerberFile objects in the desired rendering order, from bottom-most to top-most layer. ```python from pygerber.gerber.api import CompositeView, GerberFile # Define Gerber files for the top side of the PCB composite = CompositeView( GerberFile.from_file("top_copper.gbr"), GerberFile.from_file("top_solder_mask.gbr"), GerberFile.from_file("top_silk_screen.gbr"), ) ``` -------------------------------- ### Access Subcommand Help Source: https://github.com/argmaster/pygerber/blob/main/docs/50_command_line/00_introduction.md Access help for subcommands, such as the formatter, by using the subcommand structure. Root package supports direct execution, but subpackages do not. ```bash pygerber gerber format --help ``` -------------------------------- ### Render Gerber to SVG Vector Image with Shapely Source: https://context7.com/argmaster/pygerber/llms.txt Render a Gerber file to SVG vector graphics using the Shapely library. This method performs geometry operations for clean vector output. Requires `pip install pygerber[shapely]`. ```python from pygerber.gerber.api import GerberFile, Style # Requires: pip install pygerber[shapely] gerber_file = GerberFile.from_file("board.gtl") # Render to SVG image = gerber_file.render_with_shapely() image.save("output.svg") # Render with custom style image = gerber_file.render_with_shapely( style=Style.presets.SILK_ALPHA ) save_svg("silkscreen.svg") ``` -------------------------------- ### Using the PyGerber Linter Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/70_diagnostics/00_introduction.md Demonstrates how to use the PyGerber linter by passing a Gerber AST to the `lint` function. Ensure the `pygerber.gerber.lexer` is imported for AST generation. ```python from pygerber.gerber.lexer import Lexer from pygerber.gerber.linter import lint lexer = Lexer() lexer.add_gerber_file("test/examples/gerberx3/linter/_00_linter.example.py") ast = lexer.parse() violations = lint(ast) for violation in violations: print(violation) ``` -------------------------------- ### GerberFile.from_file - Load Gerber From File Source: https://context7.com/argmaster/pygerber/llms.txt Loads Gerber source code from a file on disk, automatically inferring the file type. ```APIDOC ## GerberFile.from_file - Load Gerber From File ### Description Load Gerber source code from a file on disk. File type can be automatically inferred from extension or file attributes. ### Method `GerberFile.from_file(file_path: str, file_type: FileTypeEnum = None) -> GerberFile` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file_path** (str) - Required - The path to the Gerber file. - **file_type** (FileTypeEnum) - Optional - Explicitly specify the file type for correct coloring (e.g., `FileTypeEnum.COPPER`). ### Request Example ```python from pathlib import Path from pygerber.gerber.api import GerberFile, FileTypeEnum # Auto-detect file type from extension/attributes gerber_file = GerberFile.from_file("board.gtl") # Explicitly specify file type for correct coloring gerber_file = GerberFile.from_file( "copper_layer.gbr", file_type=FileTypeEnum.COPPER ) # Render to PNG at 200 dots per millimeter image = gerber_file.render_with_pillow(dpmm=200) image.save_png("copper_layer.png") ``` ### Response #### Success Response (200) - **GerberFile** - An object representing the parsed Gerber file. #### Response Example ```python # The GerberFile object is returned, not a direct JSON response. # Example of using the returned object: # gerber_file = GerberFile.from_file("path/to/file.gbr") ``` ``` -------------------------------- ### Create custom pad shapes in Python Source: https://github.com/argmaster/pygerber/blob/main/docs/80_code_generation/10_gerber.md Shows how to define custom pad geometries by chaining shape methods and finalizing with create(). ```python from pygerber.builder.gerber import GerberBuilder builder = GerberBuilder() # Define a custom pad custom_pad = builder.new_pad(x=50, y=50).custom() custom_pad.add_rectangle(width=10, height=5, x=0, y=0) custom_pad.add_circle(diameter=5, x=5, y=5) pad = custom_pad.create() builder.add_pad(pad) print(builder.get_gerber()) ``` -------------------------------- ### GerberX3Builder - Programmatic Gerber Generation Source: https://context7.com/argmaster/pygerber/llms.txt Use the fluent builder API to define pads, traces, and arcs for Gerber file generation. ```python from pygerber.builder.gerber import GerberX3Builder builder = GerberX3Builder() # Create apertures (pads) circle_pad = builder.new_pad().circle(diameter=1.0) rect_pad = builder.new_pad().rectangle(width=2.0, height=1.0) rounded_pad = builder.new_pad().rounded_rectangle(width=1.5, height=0.8) polygon_pad = builder.new_pad().regular_polygon( outer_diameter=1.2, number_of_vertices=6, base_rotation_degrees=0 ) # Add pads at locations (x, y) pad1 = builder.add_pad(circle_pad, (0, 0)) pad2 = builder.add_pad(circle_pad, (5, 0)) builder.add_pad(rect_pad, (10, 0), rotation=45.0) # Draw traces between pads trace1 = builder.add_line_trace(width=0.2, begin=pad1, end=(2.5, 2.5)) trace2 = builder.add_line_trace(width=0.2, begin=trace1, end=pad2) # Draw arc traces builder.add_clockwise_arc_trace( width=0.15, begin=(0, 5), end=(5, 5), center=(2.5, 5) ) # Generate and output Gerber code code = builder.get_code() print(code.dumps()) # Save to file with open("generated.gbr", "w") as f: code.dump(f) ``` -------------------------------- ### Main VM Execution Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/40_contribution_guidelines.md The primary entry point for executing Gerber commands within the virtual machine. Parses and dispatches commands. ```python class VM: # ... (previous VM code) def run(self, gerber_code): # Parse gerber_code and execute commands pass ``` -------------------------------- ### Create GerberFile from File Path Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/01_single_file.md Use `from_file()` to create a `GerberFile` instance by reading from a specified file path. Accepts `str` or `pathlib.Path` objects. ```python from pygerber.gerber.api import GerberFile GerberFile.from_file("path/to/your/gerber.gbr") ``` -------------------------------- ### Verify git hooks Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/10_env_setup.md Execute this command to check if the hooks are configured correctly and run the style checks. ```bash poe test-style ``` -------------------------------- ### Execute CLI Operations Source: https://context7.com/argmaster/pygerber/llms.txt Perform common tasks like file conversion, formatting, and linting directly from the command line. ```bash # Check version pygerber --version # Convert Gerber to PNG pygerber gerber convert png input.gbr -o output.png -d 200 -s copper_alpha # Convert to JPEG with quality setting pygerber gerber convert jpeg input.gbr -o output.jpg -d 150 -q 90 # Convert to SVG (requires shapely extra) pygerber gerber convert svg input.gbr -o output.svg # Convert with custom colors pygerber gerber convert png input.gbr -o output.png -s CUSTOM \ -f "#00FF00" -b "#000000" # Merge multiple layers to single image pygerber gerber merge-convert png layer1.gbr layer2.gbr layer3.gbr \ -o merged.png -d 100 # Format Gerber file pygerber gerber format input.gbr -o formatted.gbr # Format with JSON config pygerber gerber format input.gbr -o formatted.gbr \ -i '{"indent_character": "\t", "macro_split_mode": "NoSplit"}' # Lint Gerber files pygerber gerber lint board.gbr pygerber gerber lint board.gbr -r DEP001,DEP002 # List available lint rules pygerber gerber list-lint-rules # Check if language server is available pygerber is-language-server-available ``` -------------------------------- ### Load Gerber From File Source: https://context7.com/argmaster/pygerber/llms.txt Load Gerber source code from a file using `GerberFile.from_file`. The file type can be auto-detected or explicitly specified. The loaded file can then be rendered to an image. ```python from pathlib import Path from pygerber.gerber.api import GerberFile, FileTypeEnum # Auto-detect file type from extension/attributes gerber_file = GerberFile.from_file("board.gtl") # Explicitly specify file type for correct coloring gerber_file = GerberFile.from_file( "copper_layer.gbr", file_type=FileTypeEnum.COPPER ) # Render to PNG at 200 dots per millimeter image = gerber_file.render_with_pillow(dpmm=200) image.save_png("copper_layer.png") ``` -------------------------------- ### Shapely VM Implementation Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/40_contribution_guidelines.md Implements the virtual machine using the Shapely library for geometric operations. Handles creation and manipulation of geometric shapes. ```python from shapely.geometry import Polygon, LineString class ShapelyVM: def __init__(self): self.shapes = [] def add_polygon(self, exterior, interiors=None): polygon = Polygon(exterior, interiors) self.shapes.append(polygon) return polygon def add_line(self, coords): line = LineString(coords) self.shapes.append(line) return line ``` -------------------------------- ### Create GerberFile from Buffer Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/01_single_file.md Use `from_buffer()` to create a `GerberFile` instance from an `io.TextIO`-like object. This is suitable for file-like objects in memory. ```python from pygerber.gerber.api import GerberFile import io GerberFile.from_buffer(io.StringIO("G01*\nG71*")) ``` -------------------------------- ### Create GerberJobFile Manually Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/03_project_gerber_job.md Demonstrates manual creation of a GerberJobFile object. Ensure pygerber.gerber.api is imported. ```python from pygerber.gerber.api import GerberJobFile # Example of creating a GerberJobFile manually gbrjob = GerberJobFile( layers=[ { "name": "F.Cu", "type": "copper", "filename": "F_Cu.gbr" }, { "name": "F.Mask", "type": "soldermask", "filename": "F_Mask.gbr" }, { "name": "F.SilkS", "type": "legend", "filename": "F_SilkS.gbr" }, { "name": "Edge.Cuts", "type": "profile", "filename": "Edge_Cuts.gbr" } ] ) # You can also load an existing .gbrjob file using from_file() # gbrjob = GerberJobFile.from_file("path/to/your/file.gbrjob") print(gbrjob.layers[0].name) ``` -------------------------------- ### Execute PyGerber as Main Module Source: https://github.com/argmaster/pygerber/blob/main/docs/50_command_line/00_introduction.md Alternatively, execute the PyGerber package as the main module to achieve the same result as the `pygerber` command. ```bash python -m pygerber --version ``` -------------------------------- ### Run All Tests Locally Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/40_contribution_guidelines.md Execute this command to run both style checks and behavior (unit and end-to-end) tests locally. Ensure style checks are run separately if only behavior tests are needed. ```bash poe test-all ``` -------------------------------- ### Custom Pad Creation With Macros Source: https://context7.com/argmaster/pygerber/llms.txt Define complex custom aperture shapes using the aperture macro builder. ```python from pygerber.builder.gerber import GerberX3Builder builder = GerberX3Builder() # Create custom pad with multiple primitives custom_pad = ( builder.new_pad() .custom() .add_circle(diameter=2.0, center=(0, 0)) .cut_circle(diameter=1.0, center=(0, 0)) # Cut hole in center .add_vector_line(width=0.3, start=(-1.5, 0), end=(1.5, 0)) .add_vector_line(width=0.3, start=(0, -1.5), end=(0, 1.5)) .create() ) # Add thermal relief pad thermal_pad = ( builder.new_pad() .custom() .add_thermal( center=(0, 0), outer_diameter=2.0, inner_diameter=1.0, gap_thickness=0.3, rotation=0 ) .create() ) builder.add_pad(custom_pad, (0, 0)) builder.add_pad(thermal_pad, (5, 0)) code = builder.get_code() print(code.dumps()) ``` -------------------------------- ### Create Git Tag Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/90_release_procedure.md Create a new Git tag for the release version. This is a crucial step for version management and automated publishing. ```bash git tag vx.y.z ``` -------------------------------- ### Pyparsing Grammar Initialization Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/40_contribution_guidelines.md Initializes the pyparsing grammar for parsing Gerber files. Defines rules for various Gerber syntax elements. ```python from pyparsing import Word, alphas, alphanums, nums, Suppress, Group, OneOrMore, Optional, Combine, Literal def create_grammar(): # Define basic elements integer = Word(nums).set_parse_action(lambda t: int(t[0])) decimal = Combine(Optional(Literal('-')) + Word(nums) + Suppress('.') + Word(nums)).set_parse_action(lambda t: float(t[0])) identifier = Word(alphas, alphanums + '_') # Define Gerber commands (simplified) g_code = Combine('G' + integer) d_code = Combine('D' + integer) # Define a simple structure point = Group(decimal.set_results_name('x') + decimal.set_results_name('y')) command_line = Group(g_code.set_results_name('command') + Optional(point).set_results_name('coords')) return command_line.set_name('gerber_line') ``` -------------------------------- ### Convert GerberJobFile to Project Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/03_project_gerber_job.md Shows how to convert a GerberJobFile object into a Project object for rendering. The MaterialStackup field is not considered during conversion. ```python from pygerber.gerber.api import GerberJobFile from pygerber.gerber.project import Project # Assume gbrjob is a GerberJobFile object loaded or created previously # For demonstration, let's create a dummy GerberJobFile gbrjob = GerberJobFile( layers=[ { "name": "F.Cu", "type": "copper", "filename": "F_Cu.gbr" }, { "name": "F.Mask", "type": "soldermask", "filename": "F_Mask.gbr" }, { "name": "F.SilkS", "type": "legend", "filename": "F_SilkS.gbr" }, { "name": "Edge.Cuts", "type": "profile", "filename": "Edge_Cuts.gbr" } ] ) # Convert GerberJobFile to Project project: Project = gbrjob.to_project() # Accessing layers within the project print(f"Top layer: {project.top.layers[0].name}") print(f"Inner layers: {[layer.name for layer in project.inner]}") print(f"Bottom layer: {project.bottom.layers[0].name}") ``` -------------------------------- ### GerberFile.from_str - Load Gerber From String Source: https://context7.com/argmaster/pygerber/llms.txt Loads and parses Gerber source code directly from a string, returning a GerberFile object for further processing. ```APIDOC ## GerberFile.from_str - Load Gerber From String ### Description Load and parse Gerber source code directly from a string. Returns a `GerberFile` object that provides rendering, formatting, and analysis methods. ### Method `GerberFile.from_str(gerber_source_code: str) -> GerberFile` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **gerber_source_code** (str) - Required - The Gerber file content as a string. ### Request Example ```python from pygerber.gerber.api import GerberFile gerber_source_code = """ %FSLAX46Y46*% %MOMM*% %ADD10C,0.5*% G75* D10* X1000000Y1000000D03* X2000000Y1000000D03* M02* """ gerber_file = GerberFile.from_str(gerber_source_code) image = gerber_file.render_with_pillow(dpmm=100) image.save_png("output.png") ``` ### Response #### Success Response (200) - **GerberFile** - An object representing the parsed Gerber file. #### Response Example ```python # The GerberFile object is returned, not a direct JSON response. # Example of using the returned object: # gerber_file = GerberFile.from_str(source) ``` ``` -------------------------------- ### Render a project to a raster image Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/02_multi_file.md Use the render_with_pillow method to merge all grouped Gerber files into a single composite image. ```python from pygerber.gerber.api import CompositeView, GerberFile composite = CompositeView( GerberFile.from_file("top_copper.gbr"), GerberFile.from_file("top_solder_mask.gbr"), GerberFile.from_file("top_silk_screen.gbr"), ) # Render the composite view to a Pillow image image = composite.render_with_pillow() image.save("render_project.png") ``` -------------------------------- ### Pillow VM Implementation Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/40_contribution_guidelines.md Implements the virtual machine using the Pillow library for image manipulation. Handles drawing operations on a canvas. ```python from PIL import Image, ImageDraw class PillowVM: def __init__(self, width, height): self.image = Image.new('RGB', (width, height), 'white') self.draw = ImageDraw.Draw(self.image) self.current_point = (0, 0) def move_to(self, x, y): self.current_point = (x, y) def draw_line(self, x1, y1, x2, y2, fill='black'): self.draw.line([(x1, y1), (x2, y2)], fill=fill, width=1) def save(self, filename): self.image.save(filename) ``` -------------------------------- ### Custom Color Map for Multiple Files Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/10_custom_color_maps.md Illustrates how to use a custom color map when rendering multiple Gerber files from a project. The color map can automatically infer file types and apply appropriate styles. ```python from pygerber.gerber.api import GerberFile, FileTypeEnum, Style # Define custom colors for specific file types custom_style_copper = Style(color=(255, 0, 0), alpha=1.0) custom_style_silkscreen = Style(color=(0, 255, 0), alpha=1.0) # Create a custom color map custom_color_map = { FileTypeEnum.COPPER_INNER: custom_style_copper, FileTypeEnum.SILKSCREEN_TOP: custom_style_silkscreen, } # Load multiple Gerber files from a project directory project_files = GerberFile.from_project("path/to/your/project") # Set the custom color map for the project project_files.set_color_map(custom_color_map) # Render all files in the project with custom colors project_files.render_to_file("output_project.svg") ``` -------------------------------- ### Load Gerber From String Source: https://context7.com/argmaster/pygerber/llms.txt Load and parse Gerber source code directly from a string using `GerberFile.from_str`. This returns a `GerberFile` object for further processing, such as rendering to an image. ```python from pygerber.gerber.api import GerberFile gerber_source_code = """ %FSLAX46Y46*% %MOMM*% %ADD10C,0.5*% G75* D10* X1000000Y1000000D03* X2000000Y1000000D03* M02* """ gerber_file = GerberFile.from_str(gerber_source_code) image = gerber_file.render_with_pillow(dpmm=100) image.save_png("output.png") ``` -------------------------------- ### Gerber Formatting Source: https://context7.com/argmaster/pygerber/llms.txt Configure and apply formatting options to beautify Gerber code. ```python from pygerber.gerber.api import GerberFile, Options from pygerber.gerber.formatter import ( format, formats, Options, MacroSplitMode, StripWhitespace, EmptyLineBeforePolaritySwitch ) from pygerber.gerber.parser import parse # Format using GerberFile API gerber_file = GerberFile.from_file("messy.gbr") # Format to string formatted_code = gerber_file.formats(options=Options( indent_character=" ", # 2 spaces macro_split_mode=MacroSplitMode.SplitOnPrimitives, strip_whitespace=StripWhitespace.StripAll, )) print(formatted_code) # Format to file with open("formatted.gbr", "w") as f: gerber_file.format(f, options=Options( indent_character="\t", empty_line_before_polarity_switch=EmptyLineBeforePolaritySwitch.Yes, )) # Using lower-level formatter API ast = parse(open("input.gbr").read()) with open("output.gbr", "w") as f: format(ast, f, options=Options( macro_split_mode=MacroSplitMode.NoSplit, )) ``` -------------------------------- ### Parse Gerber Files and Access AST Source: https://context7.com/argmaster/pygerber/llms.txt Use the parser to convert Gerber source into an AST and extract state information like units and aperture definitions. ```python from pygerber.gerber.parser import parse from pygerber.gerber.ast import get_final_state from pygerber.gerber.ast.nodes import D01, D03, ADC # Parse Gerber source code source_code = open("board.gbr").read() ast = parse(source_code) # Access parsed nodes for node in ast.nodes: if isinstance(node, D03): # Flash command print(f"Flash at: ({node.x}, {node.y})") elif isinstance(node, ADC): # Circle aperture definition print(f"Circle aperture D{node.aperture_id}: diameter={node.diameter}") # Get final parser state (units, apertures, attributes, etc.) final_state = get_final_state(ast) print(f"Units: {final_state.unit_mode}") print(f"Apertures defined: {list(final_state.apertures.keys())}") ``` -------------------------------- ### Region Creation - Filled Polygons Source: https://context7.com/argmaster/pygerber/llms.txt Create filled polygon regions using line and arc segments. ```python from pygerber.builder.gerber import GerberX3Builder builder = GerberX3Builder() # Create a region with straight edges region = ( builder.new_region((-2, 0)) # Start point .add_line((-2, 2)) .add_line((0, 2)) .add_line((1, 1)) .add_line((0, 0)) .create() # Automatically closes to start point ) # Create region with arc segments arc_region = ( builder.new_region((0, 0)) .add_line((2, 0)) .add_clockwise_arc(to=(2, 2), center=(2, 1)) .add_line((0, 2)) .add_counterclockwise_arc(to=(0, 0), center=(0, 1)) .create() ) code = builder.get_code() print(code.dumps()) ``` -------------------------------- ### Create GerberFile from String Source: https://github.com/argmaster/pygerber/blob/main/docs/40_gerber/20_quick_start/01_single_file.md Use `from_str()` to create a `GerberFile` instance from a string containing Gerber code. This is useful for in-memory Gerber data. ```python from pygerber.gerber.api import GerberFile GerberFile.from_str("G01*\nG71*\nG75*\nG00X00Y00*") ``` -------------------------------- ### Create composite view with multiple layers Source: https://context7.com/argmaster/pygerber/llms.txt Render multiple Gerber files into a single composite image and save individual layers. ```python composite = CompositeView([ GerberFile.from_file("board.gbl", file_type=FileTypeEnum.COPPER), # Bottom copper GerberFile.from_file("board.gbs", file_type=FileTypeEnum.SOLDERMASK), # Bottom solder mask GerberFile.from_file("board.gtl", file_type=FileTypeEnum.COPPER), # Top copper GerberFile.from_file("board.gts", file_type=FileTypeEnum.SOLDERMASK), # Top solder mask GerberFile.from_file("board.gto", file_type=FileTypeEnum.SILK), # Top silkscreen ]) # Render all layers merged into single image result = composite.render_with_pillow(dpmm=100) result.save_png("pcb_composite.png") # Access individual layer images for i, sub_image in enumerate(result.get_sub_images()): sub_image.save_png(f"layer_{i}.png") ``` -------------------------------- ### Reuse Draw objects as locations in Python Source: https://github.com/argmaster/pygerber/blob/main/docs/80_code_generation/10_gerber.md Demonstrates using TraceDraw and PadDraw objects as coordinate references for subsequent drawing operations. ```python from pygerber.builder.gerber import GerberBuilder builder = GerberBuilder() # Create initial pad and trace pad = builder.new_pad(x=0, y=0) builder.add_pad(pad) trace = builder.new_trace(begin=(0, 0), end=(10, 0)) builder.add_line_trace(trace) # Use previous trace as location for new trace new_trace = builder.new_trace(begin=trace, end=(20, 10)) builder.add_line_trace(new_trace) print(builder.get_gerber()) ``` -------------------------------- ### Clone PyGerber Repository Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/10_env_setup.md Clone the PyGerber project repository from GitHub to your local machine. ```bash git clone https://github.com/Argmaster/pygerber ``` -------------------------------- ### State Tracking Visitor Source: https://github.com/argmaster/pygerber/blob/main/docs/90_development/40_contribution_guidelines.md A visitor class for tracking state during AST traversal. It processes various node types to maintain context. ```python class StateTrackingVisitor(Visitor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.state = {} def visit(self, node): method_name = f'visit_{node.__class__.__name__.lower()}' visitor = getattr(self, method_name, self.generic_visit) return visitor(node) def generic_visit(self, node): for child in node.children: self.visit(child) ``` -------------------------------- ### Parse GerberJobFile Metadata Source: https://context7.com/argmaster/pygerber/llms.txt Extract project-level information, file attributes, and design rules from .gbrjob files. ```python from pygerber.gerber.api import GerberJobFile # Load Gerber job file job = GerberJobFile.from_file("project.gbrjob") # Access project information print(f"Project ID: {job.header.project_id}") print(f"Generation software: {job.header.generation_software}") # Access file attributes for file_attr in job.files_attributes: print(f"File: {file_attr.path}, Function: {file_attr.file_function}") # Get design rules if job.design_rules: print(f"Min trace width: {job.design_rules.min_line_width}") ```