Python examples

Nineteen examples, each doing one thing people do with OpenCAD2D from Python: list the layers of a drawing, make a drawing in code, draw one to pictures with no window, cut one solid from another, number points in the app, draw in an app that is running. They are in src/python/examples of the repository, in three folders for the three places Python works with the library (a tool of the app is a folder of its own), and this page shows each as it is, with what it prints. A test of the repository runs every file, on .NET 8 and on .NET Framework 4.8, against a drawing the test builds, and a type check (pyright) finds no error in any of them, so what the page shows is what the files do.

Folder Where it runs How a file is run
library outside the app, on the libraries alone python list_layers.py plan.dxf, in the virtual environment the wheel is installed in (Installing)
tools tools of OpenCAD2D each a folder with a requirements.txt, an __init__.py and a plugin.json: PYLOAD its requirements.txt, or put the folder in the Pythons folder (Python commands and tools)
remote outside the app, driving one that is running python draw_and_read.py while the app runs with "Allow other programs to connect" on (the setting)
File What it does
list_layers.py the objects and the closed area on each layer of a DXF or DWG
coordinates_numpy.py every polyline's vertices as a numpy array, and the extents of all of them
make_drawing.py a layer, a rectangle and a circle added to a new drawing, saved as DXF or DWG
regions.py union, difference, intersection and offset of two squares
solids.py a box with a hole cut through it: volume, surface area and centroid
batch_folder.py one CSV row for each DXF and DWG file of a folder
convert.py a drawing read and written again as DXF or DWG, in a version
render_views.py a drawing drawn to two PNGs, an SVG and a PDF with no window
coco_dataset.py three drawings written as pictures, class masks and one COCO file
batch_export.py every DXF and DWG of a folder written as JSON, graph arrays and a picture, with a manifest
layout_loop.py tags and dimensions placed, scored and moved until the score stops rising
sheet_from_code.py a plate, an A3 layout with a filled title block and two viewports, plotted to a PDF
number_points a number written at each point you pick
drawing_tools the commands RECTC and LAYERCOUNT
selection_lengths the length and closed area of the selected objects
circle_marks the snap CTOP, the setting textHeight, the command MARKTOPS and a ribbon button
draw_and_read.py a grid drawn in a new drawing of the running app, read back
pick_and_mark.py a circle drawn where the user picks
open_documents.py the drawings the app has open and what is in each

Every file follows the same plan. The ones that take arguments are a main(argv) that prints a usage line to the standard error and returns 2 when the arguments are wrong, and ends in sys.exit(main(sys.argv[1:])). Numbers are printed with three decimals, in the drawing's own units. Where a script compares or offsets geometry it passes a Tolerance (Tolerance.Default, a thousandth of a millimetre for points). The numbers below were printed by the files on a drawing of four layers and six objects that the tests build, called the test drawing here: layers 0, Empty, Slabs and Walls; on 0 a line of 100; on Slabs a closed polyline 4 000 by 3 000 and a circle of radius 300 at its middle; on Walls an open polyline of two segments of 1 000 and two lines of 500; Empty holds nothing. The same drawing saved as DXF and as DWG gives the same lines on both runtimes.

Outside the app

List the layers of a drawing

list_layers.py DRAWING reads a DXF or DWG file with open_file and prints one line for each layer of its layer table, sorted by name, with the number of objects of model space on it and the area enclosed by the closed polylines and circles on it.

layer	objects	area
0	1	0.000
Empty	0	0.000
Slabs	2	12282743.339
Walls	3	0.000
total	6	12282743.339

The area of Slabs is 12 000 000 for the polyline and 282 743.339 for the circle (pi times 300 squared). The open polyline of Walls encloses nothing, and list_layers.py counts it as an object only. A DWG gives the same lines as the DXF. A layer name is one name in whatever case, while an object keeps the spelling it was written with, so a line on Walls and a circle of radius 10 on walls are counted together under the layer table's spelling: Walls with 2 objects and an area of 314.159.

"""Lists the layers of a DXF or DWG drawing: the objects of model space on each, and the area of its closed shapes.

Run: python list_layers.py DRAWING   (a .dxf or .dwg file)
Prints one line per layer of the layer table, sorted by name, then the totals. The area is that of the closed
polylines and the circles on the layer, in the drawing's units squared.
"""

import sys
from pathlib import Path

from opencad2d.cad import Entity, open_file
from GeometryHelper.Dxf import DxfCircle, DxfPolyline


def closed_area(entity: Entity) -> float:
    """The area a closed polyline or a circle encloses; nought for any other object."""
    if isinstance(entity.net, DxfPolyline) and entity.net.Closed:
        return entity.net.Area
    if isinstance(entity.net, DxfCircle):
        return entity.net.Area
    return 0.0


def main(argv: list[str]) -> int:
    if len(argv) != 1 or Path(argv[0]).suffix.lower() not in (".dxf", ".dwg"):
        print("usage: python list_layers.py DRAWING   (a .dxf or .dwg file)", file=sys.stderr)
        return 2
    drawing = open_file(argv[0])
    # A layer name is one name in whatever case, but an object keeps the spelling it was written with ("walls" on a
    # layer the table calls "Walls"), so objects are counted under the table's spelling.
    spelling: dict[str, str] = {layer.name.casefold(): layer.name for layer in drawing.layers}
    counts: dict[str, int] = dict.fromkeys(spelling.values(), 0)
    areas: dict[str, float] = dict.fromkeys(counts, 0.0)
    for entity in drawing.entities(layout="Model"):
        layer = spelling.setdefault(entity.layer.casefold(), entity.layer)
        counts[layer] = counts.get(layer, 0) + 1
        areas[layer] = areas.get(layer, 0.0) + closed_area(entity)
    print("layer\tobjects\tarea")
    for name in sorted(counts, key=lambda name: (name.casefold(), name)):
        print(f"{name}\t{counts[name]}\t{areas[name]:.3f}")
    print(f"total\t{sum(counts.values())}\t{sum(areas.values()):.3f}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

The vertices of the polylines in numpy

coordinates_numpy.py DRAWING reads the file with open_file, takes every polyline of model space in the order of its handles, and copies its vertices into a numpy array of shape (n, 2) through opencad2d.arrays, which takes a whole .NET array in one copy where a loop over the points would call into .NET three times a point. It needs numpy (pip install opencad2d[numpy]).

104	4	14000.000
106	3	2000.000
extents	0.000,0.000	4000.000,5000.000

Each line is a polyline's handle, its vertex count and its length: the closed polyline is four corners with a perimeter of 14 000, the open one three vertices with a length of 2 000. The last line is the extents of all the vertices, taken with numpy. A closed polyline's corners come from ToGeoPolygon2, since ToGeoPolyline2 repeats the first corner at the end and would give five.

"""The vertices of every polyline of a DXF or DWG drawing as numpy arrays, and the extents of all of them.

Run: python coordinates_numpy.py DRAWING   (a .dxf or .dwg file; needs numpy: pip install opencad2d[numpy])
Prints, in handle order, each polyline's handle, vertex count and length, then the extents of every vertex.
"""

import sys
from pathlib import Path

import numpy as np
from numpy.typing import NDArray

import opencad2d  # noqa: F401  (starts .NET and loads the assemblies)
from opencad2d.arrays import to_numpy
from opencad2d.cad import open_file
from GeometryHelper.Dxf import DxfPolyline


def vertices(polyline: DxfPolyline) -> NDArray[np.float64]:
    """The vertices of a polyline as an array of shape (n, 2), copied from .NET in one block.

    A closed polyline gives its corners once: ToGeoPolyline2 would repeat the first corner at the end.
    """
    if polyline.Closed:
        return to_numpy(polyline.ToGeoPolygon2().Vertices)
    return to_numpy(polyline.ToGeoPolyline2().Vertices)


def main(argv: list[str]) -> int:
    if len(argv) != 1 or Path(argv[0]).suffix.lower() not in (".dxf", ".dwg"):
        print("usage: python coordinates_numpy.py DRAWING   (a .dxf or .dwg file)", file=sys.stderr)
        return 2
    drawing = open_file(argv[0])
    polylines = drawing.entities(DxfPolyline, layout="Model")  # Entity[DxfPolyline]: its net needs no isinstance
    polylines.sort(key=lambda entity: int(entity.handle, 16))
    arrays: list[NDArray[np.float64]] = []
    for entity in polylines:
        points = vertices(entity.net)
        arrays.append(points)
        print(f"{entity.handle}\t{len(points)}\t{entity.net.Length:.3f}")
    if arrays:
        every = np.vstack(arrays)
        low, high = every.min(axis=0), every.max(axis=0)
        print(f"extents\t{low[0]:.3f},{low[1]:.3f}\t{high[0]:.3f},{high[1]:.3f}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Make a drawing in code

make_drawing.py OUT makes a blank drawing with new_file(), adds a layer Outline and makes it current, adds a rectangle from 0,0 to 4000,3000 and a circle of radius 500 at 2000,1500 on it, applies them with one commit(), and saves the drawing as OUT, DXF or DWG by its extension.

objects 2
layers 0, Outline
saved plan.dwg

Opened again, the file holds a polyline of area 12 000 000 and a circle of radius 500 on Outline, as DXF and as DWG.

"""Makes a drawing in code, with no window, and saves it as DXF or DWG.

Run: python make_drawing.py OUT   (OUT ends in .dxf or .dwg)
An empty drawing gets a layer Outline, made current, then a rectangle 4000 by 3000 and a circle of radius 500 on it,
applied together by one commit; the drawing is then saved as OUT.
"""

import sys
from pathlib import Path

from opencad2d.cad import new_file


def main(argv: list[str]) -> int:
    if len(argv) != 1 or Path(argv[0]).suffix.lower() not in (".dxf", ".dwg"):
        print("usage: python make_drawing.py OUT   (OUT ends in .dxf or .dwg)", file=sys.stderr)
        return 2
    drawing = new_file()  # an empty drawing: layer 0 only
    drawing.layers.add("Outline")
    drawing.commit()  # the layer must exist before it can be made current
    drawing.current_layer = "Outline"
    drawing.add_polyline([(0, 0), (4000, 0), (4000, 3000), (0, 3000)], closed=True, layer="Outline")
    drawing.add_circle((2000, 1500), 500, layer="Outline")
    drawing.commit()
    drawing.save_as(argv[0])
    layers = sorted((layer.name for layer in drawing.layers), key=lambda name: (name.casefold(), name))
    print(f"objects {len(drawing.entities())}")
    print(f"layers {', '.join(layers)}")
    print(f"saved {Path(argv[0]).name}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Union, difference and offset of regions

regions.py takes two squares of 100, A from 0,0 and B from 50,50, and prints the area of the union, of A less B, of what they share, and of A grown and shrunk by 10 with mitred corners (OffsetJoin.Miter).

union 17500.000
subtract 7500.000
intersect 2500.000
offset +10 14400.000
offset -10 6400.000

The squares share 50 by 50, 2 500, so the union is 10 000 plus 10 000 less 2 500. A grown to 120 by 120 is 14 400, shrunk to 80 by 80 6 400. Each call comes back as an array of faces or polygons, and the script adds their areas.

"""Union, difference, intersection and offset of two squares, with GeoPolygon2.

Run: python regions.py
Two squares of 100 (A from 0,0 and B from 50,50) are combined, and A is grown and shrunk by 10; each result is
printed as its area. Every call passes Tolerance.Default (a thousandth of a millimetre).
"""

import sys
from collections.abc import Iterable

import opencad2d  # noqa: F401  (starts .NET and loads the assemblies)
from GeometryHelper import Tolerance
from GeometryHelper.Enums import OffsetJoin
from GeometryHelper.Geometry import GeoFace2, GeoPoint2, GeoPolygon2


def square(x: float, y: float, side: float) -> GeoPolygon2:
    """A square of the given side with its lower left corner at (x, y)."""
    return GeoPolygon2(GeoPoint2(x, y), GeoPoint2(x + side, y), GeoPoint2(x + side, y + side), GeoPoint2(x, y + side))


def faces_area(faces: Iterable[GeoFace2]) -> float:
    """The area of the faces, a hole of a face already taken off."""
    return sum(face.Area for face in faces)


def main(argv: list[str]) -> int:
    if argv:
        print("usage: python regions.py", file=sys.stderr)
        return 2
    tolerance = Tolerance.Default
    a = square(0, 0, 100)
    b = square(50, 50, 100)
    print(f"union {faces_area(a.Union(b, tolerance)):.3f}")
    print(f"subtract {faces_area(a.Subtract(b, tolerance)):.3f}")
    print(f"intersect {faces_area(a.Intersect(b, tolerance)):.3f}")
    for distance in (10, -10):  # a positive distance grows the region, a negative one shrinks it
        grown = a.Offset(distance, OffsetJoin.Miter, tolerance)
        print(f"offset {distance:+d} {sum(polygon.Area for polygon in grown):.3f}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

A box with a hole measured

solids.py makes a box 1 000 by 500 by 200 and cuts a hole of 100 by 100 through it with a second box that sticks out of both faces by 100, so that no face of the cutter lies on one of the box, and prints the volume, the surface area and the centroid of what is left.

volume 98000000.000
area 1660000.000
centroid 500.000,250.000,100.000

The volume is the box's 100 000 000 less 2 000 000 for the hole, 100 by 100 by 200. The area is the box's 1 600 000, less the two openings of 10 000 each, plus the four walls of the hole at 100 by 200 each, 80 000. The measures and the cut take Tolerance.Default. TrySubtract takes it by name, plate.TrySubtract(cutter, tolerance=tolerance), because a parameter that comes after an out parameter is keyword-only in Python, so the script gives the same numbers whatever Tolerance.Global is: run with a global tolerance of 120, wider than the hole, a cut that read the global one would leave the box uncut, 100 000 000 and 1 600 000.

"""A box with a hole cut through it, measured: volume, surface area and centroid, with GeoSolid3.

Run: python solids.py
A box 1000 by 500 by 200 has a hole of 100 by 100 cut through it by a box that sticks out of both faces. The measures
and the cut all take Tolerance.Default, passed by name to TrySubtract, whose tolerance comes after its out parameter.
"""

import sys

import opencad2d  # noqa: F401  (starts .NET and loads the assemblies)
from GeometryHelper import Tolerance
from GeometryHelper.Geometry import GeoAabb3, GeoPoint3, GeoSolid3


def box(x1: float, y1: float, z1: float, x2: float, y2: float, z2: float) -> GeoSolid3:
    """The solid of the box between two opposite corners."""
    return GeoAabb3(GeoPoint3(x1, y1, z1), GeoPoint3(x2, y2, z2)).ToObb().ToSolid()


def main(argv: list[str]) -> int:
    if argv:
        print("usage: python solids.py", file=sys.stderr)
        return 2
    tolerance = Tolerance.Default
    plate = box(0, 0, 0, 1000, 500, 200)
    cutter = box(450, 200, -100, 550, 300, 300)
    done, result = plate.TrySubtract(cutter, tolerance=tolerance)
    if not done:
        print("error: nothing was left of the box", file=sys.stderr)
        return 1
    centroid = result.GetCentroid(tolerance)
    print(f"volume {result.GetVolume(tolerance):.3f}")
    print(f"area {result.GetSurfaceArea(tolerance):.3f}")
    print(f"centroid {centroid.X:.3f},{centroid.Y:.3f},{centroid.Z:.3f}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

A CSV report of a folder

batch_folder.py FOLDER REPORT.csv opens every .dxf and .dwg file of the folder, not those of its subfolders, in the order of their names, and writes one row each to a CSV file: the file, its version, the objects of model space, the layers, and an error. A file that cannot be read is a row with its error and the next one is read. The script prints how many files there were and how many failed, and exits with 1 when any failed.

Run on a folder with the test drawing as a.dxf and b.dwg, a file broken.dxf that holds the words not a drawing, a text file and a subfolder with another drawing, it prints

3 files, 1 failed

and writes

file,version,objects,layers,error
a.dxf,AC1015,6,4,
b.dwg,AC1032,6,4,
broken.dxf,,,,"This is not a DXF that can be read: line 1 should be a group code, a whole number, and is 'not a drawing'."

The version is the one the file says it is: a drawing made in code with DxfWriter is AC1015 (AutoCAD 2000), and DwgWriter writes AC1032 (AutoCAD 2018) unless it is told another. The except Exception takes the .NET exception that a file which is no drawing raises; its first line is the error.

"""Reads every DXF and DWG file of a folder and writes one line each to a CSV report.

Run: python batch_folder.py FOLDER REPORT.csv
The report has the columns file, version, objects, layers and error. A file that cannot be read is a row with its
error, and the next file goes on. Subfolders are not entered. The exit code is 1 when any file failed, else 0.
"""

import csv
import sys
from pathlib import Path

import opencad2d  # noqa: F401  (starts .NET and loads the assemblies)
from GeometryHelper.Dwg import DwgReader
from GeometryHelper.Dxf import DxfDatabase


def open_drawing(path: Path) -> DxfDatabase:
    """Reads a DXF or a DWG file, by its extension."""
    return DwgReader.Open(str(path)) if path.suffix.lower() == ".dwg" else DxfDatabase.Open(str(path))


def main(argv: list[str]) -> int:
    if len(argv) != 2 or not Path(argv[0]).is_dir():
        print("usage: python batch_folder.py FOLDER REPORT.csv", file=sys.stderr)
        return 2
    files = [path for path in Path(argv[0]).iterdir() if path.is_file() and path.suffix.lower() in (".dxf", ".dwg")]
    files.sort(key=lambda path: (path.name.casefold(), path.name))
    failed = 0
    with open(argv[1], "w", newline="", encoding="utf-8") as report:
        writer = csv.writer(report, lineterminator="\n")
        writer.writerow(["file", "version", "objects", "layers", "error"])
        for path in files:
            try:
                database = open_drawing(path)
            except Exception as error:  # a .NET exception arrives as a Python one; its first line says what is wrong
                failed += 1
                writer.writerow([path.name, "", "", "", str(error).splitlines()[0]])
            else:
                layers = sum(1 for _ in database.LayerTable)
                writer.writerow([path.name, database.Version, database.ModelSpace.Count, layers, ""])
    print(f"{len(files)} files, {failed} failed")
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Convert between DXF and DWG

convert.py IN OUT [--version ACnnnn] reads a DXF or DWG and writes OUT as a DXF or DWG by its extension, in the version given or, where none is, that of IN. The DXF writer returns what it could not keep in the version, and each is printed first as a line warning: ...; then the file written and its version.

$ python convert.py plan.dxf plan.dwg
wrote plan.dwg (AC1015)
$ python convert.py plan.dwg plan2.dxf --version AC1024
wrote plan2.dxf (AC1024)

The test drawing converted from DXF to DWG and from there to DXF again keeps its six objects on four layers. A version the writer does not write, AC1009 (R12) for a DWG, is a line on the standard error, error: ..., and the exit code 1. A drawing with an MText converted to AC1009 prints warning: Written as the lines, texts and polylines each breaks into, which AC1009 holds: MTEXT 1. The DWG writer says nothing of what it leaves out: it logs it.

"""Converts a DXF or DWG drawing to a DXF or DWG file, in a version of AutoCAD.

Run: python convert.py IN OUT [--version AC1027]   (IN and OUT end in .dxf or .dwg)
OUT is written in the version given, or in the version of IN. The DXF writer returns what it could not keep in that
version, and each is printed first, a line for each; then the file written and its version.
"""

import sys
from pathlib import Path

import opencad2d  # noqa: F401  (starts .NET and loads the assemblies)
from GeometryHelper.Dwg import DwgReader, DwgWriter
from GeometryHelper.Dxf import DxfDatabase

USAGE = "usage: python convert.py IN OUT [--version ACnnnn]   (IN and OUT end in .dxf or .dwg)"


def open_drawing(path: Path) -> DxfDatabase:
    """Reads a DXF or a DWG file, by its extension."""
    return DwgReader.Open(str(path)) if path.suffix.lower() == ".dwg" else DxfDatabase.Open(str(path))


def main(argv: list[str]) -> int:
    version: str | None = None
    if len(argv) == 4 and argv[2] == "--version":
        version = argv[3]
        argv = argv[:2]
    if len(argv) != 2 or any(Path(name).suffix.lower() not in (".dxf", ".dwg") for name in argv):
        print(USAGE, file=sys.stderr)
        return 2
    source, target = Path(argv[0]), Path(argv[1])
    database = open_drawing(source)
    version = version or database.Version
    if version is None:
        print(f"error: {source.name} names no version of AutoCAD: give one with --version", file=sys.stderr)
        return 1
    warnings: list[str] = []
    try:
        if target.suffix.lower() == ".dwg":
            DwgWriter.Write(database, str(target), version)
        else:
            warnings.extend(database.Save(str(target), version))
    except Exception as error:  # a version the writer does not write is refused; the first line of the error says which
        print(f"error: {str(error).splitlines()[0]}", file=sys.stderr)
        return 1
    for warning in warnings:
        print(f"warning: {warning}")
    print(f"wrote {target.name} ({version})")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Pictures of a drawing with no window

render_views.py DRAWING OUT_FOLDER opens a DXF or DWG, finds the box that holds every object of model space, and writes whole.png (the whole drawing, 800 pixels wide with the margin ZOOM Extents leaves), detail.png (the lower left quarter of that box, fitted to a picture 800 wide with no margin), whole.svg and plan.pdf (one page, fitted to the sheet where the drawing has none) into the folder, and prints the size of each picture. The test drawing spans 4 000 by 6 500, so a picture 800 wide is 1 300 high:

$ python render_views.py plan.dxf views
whole.png 800 by 1300 pixels
detail.png 800 by 1300 pixels
whole.svg and plan.pdf written to views

The pictures are the canvas of the app's, drawn by the same renderer with no window (Rendering without a window). A drawing with nothing in model space says so on the standard error and exits with 1.

"""Draws a drawing to pictures with no window: a PNG of the whole, a PNG of its lower left quarter, an SVG and a PDF.

Run: python render_views.py DRAWING OUT_FOLDER   (DRAWING is a .dxf or .dwg file; OUT_FOLDER is made if it is not there)
Writes whole.png, detail.png, whole.svg and plan.pdf into OUT_FOLDER and prints the size in pixels of each picture.
The pictures are the canvas of the app's: the same renderer and fonts, with the grid and the UCS icon off.
"""

import sys
from pathlib import Path

from opencad2d.cad import Box, Drawing, open_file


def extents(drawing: Drawing) -> Box | None:
    """The least box that holds every object of model space, or None where there is none."""
    boxes = [entity.net.GeometricExtents for entity in drawing.entities(layout="Model")]
    boxes = [box for box in boxes if not box.IsEmpty]
    if not boxes:
        return None
    return Box(
        min(box.Min.X for box in boxes),
        min(box.Min.Y for box in boxes),
        max(box.Max.X for box in boxes),
        max(box.Max.Y for box in boxes),
    )


def main(argv: list[str]) -> int:
    if len(argv) != 2 or Path(argv[0]).suffix.lower() not in (".dxf", ".dwg"):
        print("usage: python render_views.py DRAWING OUT_FOLDER   (DRAWING is a .dxf or .dwg file)", file=sys.stderr)
        return 2
    drawing = open_file(argv[0])
    whole = extents(drawing)
    if whole is None:
        print(f"{Path(argv[0]).name} has nothing in model space to draw", file=sys.stderr)
        return 1
    folder = Path(argv[1])
    folder.mkdir(parents=True, exist_ok=True)
    # The picture of the whole drawing is 800 pixels wide with the margin ZOOM Extents leaves; its height follows.
    drawing.render_png(str(folder / "whole.png"), width=800)
    # A box is fitted with no margin, so the quarter fills the picture.
    quarter = Box(whole.min_x, whole.min_y, (whole.min_x + whole.max_x) / 2, (whole.min_y + whole.max_y) / 2)
    drawing.render_png(str(folder / "detail.png"), box=quarter, width=800)
    drawing.render_svg(str(folder / "whole.svg"), width=800)
    drawing.render_pdf(str(folder / "plan.pdf"))
    for name, picture in (
        ("whole.png", drawing.render_image(width=800)),
        ("detail.png", drawing.render_image(box=quarter, width=800)),
    ):
        height, width = picture.shape[:2]
        print(f"{name} {width} by {height} pixels")
    print(f"whole.svg and plan.pdf written to {folder.name}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

A dataset for a vision model

coco_dataset.py OUT_FOLDER builds three drawings in code (a room with a hatched slab, a dimension, a text, an MTEXT and some bolts inserted, laid out by a seed), and for each writes images/drawingN.png (the picture, 1 200 pixels wide), masks/drawingN.png (the class of each pixel as a grey level from 0 to 5, so it looks black: multiply by 50 to see it) and the objects of all three in one annotations.json in COCO detection format, with the ids of the objects renumbered so that they are unique in the file. It prints the size of each picture and how many objects it holds:

$ python coco_dataset.py dataset
drawing1.png 1200 by 1173 pixels, 9 objects
drawing2.png 1200 by 1025 pixels, 9 objects
drawing3.png 1200 by 1098 pixels, 8 objects
3 pictures and 26 objects written to dataset

The picture and the objects come from one to_coco call and the mask from render_masks with the same arguments, so all three are of one picture (Labelled renders). It needs numpy.

"""Writes a small dataset for training a vision model: three drawings built in code, each a picture, a mask and objects.

Run: python coco_dataset.py OUT_FOLDER   (OUT_FOLDER is made if it is not there; needs numpy)
Writes images/drawingN.png, masks/drawingN.png (the class of each pixel, 0 to 5) and annotations.json in COCO format.
Prints the size of each picture and how many objects it holds; the categories are words, dimensions, lines and so on.
"""

import json
import random
import struct
import sys
import zlib
from pathlib import Path
from typing import Any

import numpy as np
from numpy.typing import NDArray

from opencad2d.cad import LABEL_CLASSES, Drawing, new_file


def make(seed: int) -> Drawing:
    """A drawing of a room with a hatched slab, a dimension, a few labels and some bolts, laid out by the seed."""
    chance = random.Random(seed)
    drawing = new_file()
    width, depth = chance.randrange(4000, 6000, 100), chance.randrange(3000, 4000, 100)
    walls = [(0, 0), (width, 0), (width, depth), (0, depth)]
    drawing.add_polyline(walls, closed=True, color=7)
    slab = [(300, 300), (width / 2, 300), (width / 2, depth - 300), (300, depth - 300)]
    drawing.add_hatch(slab, pattern=chance.choice(["ANSI31", "ANSI37", "SOLID"]), scale=40.0, color=3)
    drawing.add_linear_dim((0, 0), (width, 0), (width / 2, -400))
    drawing.add_text(f"ROOM {seed}", (width * 0.6, depth * 0.7), 250.0, color=2)
    drawing.add_mtext("Slab on grade, see the notes of sheet S-1", (width * 0.6, depth * 0.4), 150.0, 1500.0)
    drawing.blocks.add("BOLT", [drawing_line((0, 0), (200, 0)), drawing_line((100, -100), (100, 100))])
    drawing.commit()
    for _ in range(chance.randrange(2, 6)):
        drawing.add_insert("BOLT", (chance.randrange(400, int(width) - 400), chance.randrange(400, int(depth) - 400)))
    drawing.commit()
    return drawing


def drawing_line(start: tuple[float, float], end: tuple[float, float]) -> Any:
    """A LINE of the library, for the block."""
    from GeometryHelper.Dxf import DxfLine
    from GeometryHelper.Geometry import GeoPoint3

    return DxfLine(GeoPoint3(start[0], start[1], 0), GeoPoint3(end[0], end[1], 0))


def write_grey_png(path: Path, pixels: NDArray[np.uint8]) -> None:
    """Writes an 8-bit grey PNG of a (height, width) array, with no library but zlib."""
    height, width = pixels.shape
    rows = b"".join(b"\x00" + pixels[y].tobytes() for y in range(height))

    def chunk(kind: bytes, data: bytes) -> bytes:
        return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))

    header = struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0)
    path.write_bytes(
        b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")
    )


def add_to_dataset(dataset: dict[str, Any], coco: dict[str, Any], last_id: int) -> int:
    """Adds the pictures and objects of one ``to_coco`` to the dataset, the objects numbered on from ``last_id`` so that
    every id in the file is its own (the ids of one image are numbers within it), and gives the last id used."""
    for annotation in coco["annotations"]:
        last_id += 1
        annotation["id"] = last_id
    dataset["images"] += coco["images"]
    dataset["annotations"] += coco["annotations"]
    dataset["categories"] = coco["categories"]
    return last_id


def main(argv: list[str]) -> int:
    if len(argv) != 1:
        print("usage: python coco_dataset.py OUT_FOLDER", file=sys.stderr)
        return 2
    folder = Path(argv[0])
    (folder / "images").mkdir(parents=True, exist_ok=True)
    (folder / "masks").mkdir(parents=True, exist_ok=True)
    dataset: dict[str, Any] = {"images": [], "annotations": [], "categories": []}
    classes = list(LABEL_CLASSES)
    last_id = 0
    for number in range(1, 4):
        drawing = make(number)
        # The picture and its objects come from one call, so that they are of the same picture; the masks are of it too.
        image = str(folder / "images" / f"drawing{number}.png")
        coco = drawing.to_coco(image, classes=classes, width=1200, image_id=number)
        masks = drawing.render_masks(classes=classes, width=1200)
        write_grey_png(folder / "masks" / f"drawing{number}.png", masks.classes)
        # The ids of the objects are numbers within one image: renumbered, they are unique in the file.
        last_id = add_to_dataset(dataset, coco, last_id)
        height, width = masks.classes.shape
        print(f"drawing{number}.png {width} by {height} pixels, {len(coco['annotations'])} objects")
    (folder / "annotations.json").write_text(json.dumps(dataset, indent=1), encoding="utf-8")
    print(f"{len(dataset['images'])} pictures and {len(dataset['annotations'])} objects written to {folder.name}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

A folder of drawings prepared for a model

batch_export.py FOLDER OUT_FOLDER takes each DXF and DWG file of a folder (subfolders are not entered), in the order of their names with the case ignored, and writes three files named after it and one line to manifest.jsonl. NAME.json is drawing.to_json(), the drawing with its blocks opened and its units made millimetres; NAME.npz holds the NumPy arrays a network is fed with (edge_index of shape (2, E) and edge_kind from to_graph, and for its N nodes, in the order the edges number them, node_box of shape (N, 4), node_kind and node_layer; and the vertices of every polyline of model space with the offsets that say where each starts, copied from .NET by opencad2d.arrays); NAME.png is the picture, 800 pixels wide. It reads the drawing's own header through GeometryHelper.Dxf (Database.Insunits, Version and the reader's Warnings), which the Drawing API does not give, so the manifest says what unit each file was drawn in. A file that cannot be read is a line with its error and the next goes on, the exit code being 1 if any failed. The folder below holds a plate 400 by 300 with a circle, a text, a dimension and a block of two lines inserted twice (6 objects, 8 once the blocks are opened), in three files; a drawing in inches; one of no unit; an empty one; and a file that is no drawing:

$ python batch_export.py drawings out
Beam.dxf: 6 objects, 8 nodes, 9 edges
broken.dxf: This is not a DXF that can be read: line 1 should be a group code, a whole number, and is 'not a drawing'.
empty.dxf: 0 objects, 0 nodes, 0 edges
frame.dwg: 6 objects, 8 nodes, 9 edges
inches.dxf: 2 objects, 2 nodes, 0 edges
plate.dxf: 6 objects, 8 nodes, 9 edges
unitless.dxf: 1 objects, 1 nodes, 0 edges
7 files, 1 failed

The line of plate.dxf in the manifest (the seconds vary):

{"file": "plate.dxf", "version": "AC1027", "insunits": "Millimeters", "to_mm": 1, "normalised": true, "warnings": 0,
 "entities": 6, "flat": 8, "pieces": 4, "nodes": 8, "edges": {"touches": 2, "contains": 6, "dimensions": 1, "annotates": 0},
 "polylines": 1, "vertices": 4, "png": [800, 663], "seconds": {"open": 0.0015, "flatten": 0.001, "json": 0.0008, ...}}

inches.dxf has "insunits": "Inches", "to_mm": 25.4 and its numbers in inches.dxf.json are in millimetres; unitless.dxf has "normalised": false, a drawing of no unit being left as it is. The same folder gives the same files (the .npz zip holds a time stamp, its arrays are equal) and the same manifest but for its seconds. A folder of 10 drawings of 2 000 objects each (2 400 once the blocks are opened) takes 0.3 s a drawing for the five steps after the first, which carries the start of .NET and the index (Batch and AI pipelines). It needs numpy.

"""Prepares every DXF and DWG file of a folder for a model that reads drawings: JSON, graph and a picture.
Run: python batch_export.py FOLDER OUT_FOLDER   (OUT_FOLDER is made if it is not there; needs numpy)
Writes NAME.json (flatten and units), NAME.npz (graph edges, nodes, polyline vertices) and NAME.png for each file, and
manifest.jsonl: a line each with the counts, the seconds of each step and the error of a file that failed (the next file
goes on). The exit code is 1 when any file failed.
"""

import json
import struct
import sys
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any, TypeVar

import numpy as np
from numpy.typing import NDArray

import opencad2d  # noqa: F401  (starts .NET and loads the assemblies)
from opencad2d.arrays import to_numpy
from opencad2d.cad import Drawing, open_file
from GeometryHelper.Dxf import DxfPolyline

T = TypeVar("T")
EDGE_KINDS = ("touches", "contains", "dimensions", "annotates")  # the order of the numbers in edge_kind


def timed(seconds: dict[str, float], step: str, call: Callable[[], T]) -> T:
    """Runs ``call``, adds the seconds it took to ``seconds[step]`` and gives what it gave."""
    start = time.perf_counter()
    try:
        return call()
    finally:
        seconds[step] = round(time.perf_counter() - start, 4)


def polyline_vertices(drawing: Drawing) -> tuple[NDArray[np.float64], NDArray[np.int64]]:
    """The vertices of every polyline of model space, one after the other as an array of shape (n, 2), and the offsets
    that say where each polyline starts in it (one more than there are polylines), in handle order.

    Each is copied from .NET in one block by ``opencad2d.arrays``; a closed polyline gives its corners once.
    """
    polylines = drawing.entities(DxfPolyline, layout="Model")
    polylines.sort(key=lambda entity: int(entity.handle, 16))
    blocks: list[NDArray[np.float64]] = []
    for entity in polylines:
        shape = entity.net.ToGeoPolygon2() if entity.net.Closed else entity.net.ToGeoPolyline2()
        blocks.append(to_numpy(shape.Vertices))
    offsets = np.cumsum([0] + [len(block) for block in blocks]).astype(np.int64)
    return (np.vstack(blocks) if blocks else np.zeros((0, 2))), offsets


def export(path: Path, out: Path) -> dict[str, Any]:
    """Reads one drawing and writes its three files into ``out``; gives the manifest line, without its ``error``."""
    seconds: dict[str, float] = {}
    drawing = timed(seconds, "open", lambda: open_file(str(path)))
    # The drawing's own header, read through GeometryHelper.Dxf: the unit it was drawn in and what the reader said.
    database = drawing.net.Database
    flat = timed(seconds, "flatten", lambda: drawing.flatten())
    text = timed(seconds, "json", lambda: drawing.to_json())
    graph = timed(seconds, "graph", lambda: drawing.to_graph())
    nodes: list[dict[str, Any]] = graph["nodes"]
    vertices, offsets = polyline_vertices(drawing)
    units = json.loads(text)["units"]
    (out / f"{path.name}.json").write_text(text, encoding="utf-8")
    np.savez_compressed(
        out / f"{path.name}.npz",
        edge_index=graph["edge_index"],
        edge_kind=graph["edge_kind"],
        node_box=np.array([n["box"] or [np.nan] * 4 for n in nodes], dtype=np.float64).reshape(-1, 4),
        node_kind=np.array([n["kind"] for n in nodes], dtype="U"),
        node_layer=np.array([n["layer"] for n in nodes], dtype="U"),
        vertices=vertices,
        offsets=offsets,
    )
    picture = out / f"{path.name}.png"
    timed(seconds, "png", lambda: drawing.render_png(str(picture), width=800))
    width, height = struct.unpack(">II", picture.read_bytes()[16:24])  # the size is in the first chunk of a PNG
    edges = np.bincount(graph["edge_kind"], minlength=len(EDGE_KINDS))
    return {
        "file": path.name,
        "version": str(database.Version),
        "insunits": str(database.Insunits),
        "to_mm": units["toMillimetres"],
        "normalised": units["normalised"],
        "warnings": int(database.Warnings.Count),
        "entities": len(drawing.entities()),
        "flat": len(flat),
        "pieces": sum(1 for each in flat if each["path"]),
        "nodes": len(nodes),
        "edges": {kind: int(count) for kind, count in zip(EDGE_KINDS, edges)},
        "polylines": len(offsets) - 1,
        "vertices": int(len(vertices)),
        "png": [width, height],
        "seconds": seconds,
    }


def main(argv: list[str]) -> int:
    if len(argv) != 2 or not Path(argv[0]).is_dir():
        print("usage: python batch_export.py FOLDER OUT_FOLDER", file=sys.stderr)
        return 2
    files = [path for path in Path(argv[0]).iterdir() if path.is_file() and path.suffix.lower() in (".dxf", ".dwg")]
    files.sort(key=lambda path: (path.name.casefold(), path.name))
    out = Path(argv[1])
    out.mkdir(parents=True, exist_ok=True)
    failed = 0
    lines: list[str] = []
    for path in files:
        try:
            line = export(path, out)
        except Exception as error:  # a .NET exception arrives as a Python one; its first line says what is wrong
            failed += 1
            line = {"file": path.name, "error": str(error).splitlines()[0] if str(error) else type(error).__name__}
            print(f"{path.name}: {line['error']}")
        else:
            edges = sum(line["edges"].values())
            print(f"{path.name}: {line['entities']} objects, {line['nodes']} nodes, {edges} edges")
        lines.append(json.dumps(line))
    (out / "manifest.jsonl").write_text("".join(f"{line}\n" for line in lines), encoding="utf-8")
    print(f"{len(files)} files, {failed} failed")
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

A loop that places notes, and the reward that scores it

layout_loop.py OUT_FOLDER [SEED] is the loop of an AI that lays out annotation: generate, render, evaluate, refine. It makes a sheet (A3, 420 by 297 mm) with a border and a grid of beams, a tag B1 to B12 on twelve of the crossings and two linear dimensions below the grid, all put where a first attempt puts them: a tag with its middle on its crossing, so that the beams run through it, and four of the twelve at a height of 4 mm, which the company standard it carries does not allow. reward scores the sheet: half check() against the standard (the heights on paper of 2.5, 3.5, 5 and 7 mm, and 0.5 mm between a word and a line or another word), half the share of the objects with words that overlaps() finds nothing over. Each round moves every note that is scored down: the tag is measured (measure_text), free_space lists the empty rectangles round its anchor that are big enough with 1 mm to spare, and the tag goes to the point of one of them nearest the anchor; a dimension is tried at offsets of its line on both sides (measure_dimension, fits) and takes the nearest that fits; the height is the nearest the standard has. The loop stops on the round that does not raise the reward, and the exit code is 0 when no overlap is left. The sheet and the moves follow the seed (1 where none is given), and before.png and after.png (1 200 by 849) show them:

$ python layout_loop.py loop
round 0: reward 0.321 (standard 0.571, clear 0.071, 25 overlaps)
round 1: moved 13, reward 1.000 (standard 1.000, clear 1.000, 0 overlaps)
round 2: moved 0, reward 1.000 (standard 1.000, clear 1.000, 0 overlaps)
reward 0.321 -> 1.000; before.png and after.png written to loop

Thirteen notes were moved: the twelve tags (a beam runs through each) and the dimension of 300, whose words stood within the gap of the line of the dimension of 150; the second round finds nothing to move and the loop ends. reward is the function an RL agent would call after each action; it is written to be read and copied, and Batch and AI pipelines says what it costs. The words it moves are those of the objects the pairs name as words; a tag whose place is not free anywhere within 60 mm stays where it is, and the reward says so by not reaching 1. It needs numpy.

"""The loop of an AI that places notes on a sheet: place, score, move what offends, repeat while the score rises.
Run: python layout_loop.py OUT_FOLDER [SEED]   (OUT_FOLDER is made if it is not there; SEED is a whole number, 1)
Tags and dimensions go on a plan where an AI would first put them; ``reward`` scores the sheet (overlaps and a standard)
and what offends moves to the nearest free place (``measure_*``, ``free_space``, ``fits``). Prints each round and writes
before.png and after.png. The same seed gives the same sheet and moves. Needs numpy.
"""

import math
import random
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, NamedTuple

from opencad2d.cad import Drawing, Entity, new_file

# A small company standard, as a dict of the schema of docs/schemas/opencad2d-standard-v1.schema.json. The sheet is in
# millimetres drawn 1:1 (model_scale 1), so the heights and gaps are on the paper as they are on the screen.
STANDARD: dict[str, Any] = {
    "schema": "opencad2d.standard",
    "version": 1,
    "name": "Layout loop standard",
    "textHeights": {"paper": [2.5, 3.5, 5.0, 7.0], "tolerance": 0.01},
    "gaps": {"wordLine": 0.5, "wordWord": 0.5},
    "weights": {"text-height": 1, "gap-word-line": 2, "gap-word-word": 2},
}
SHEET = (0.0, 0.0, 420.0, 297.0)  # an A3 sheet, in millimetres
FRAME = (20.0, 20.0, 400.0, 277.0)  # the border drawn on it: what is placed stays inside
MARGIN = 1.0  # the clear space asked of a place, twice the least gap the standard needs
REACH = 60.0  # how far from its anchor a tag may be looked for


class Reward(NamedTuple):
    """What ``reward`` gives: ``value`` from 0 to 1 (higher is better) and the parts it is made of."""

    value: float
    standard: float  # ``check(standard).total``
    clear: float  # the share of the objects with words that no line or word runs through
    overlaps: int  # the pairs ``overlaps()`` found


def reward(drawing: Drawing, standard: dict[str, Any], words: int) -> Reward:
    """The reward of an agent that lays out a sheet: half the score of ``check`` against the standard, half the share
    of the ``words`` objects with words that nothing overlaps, so it reads 1.0 for a sheet within the standard and with
    no word overlapped. The agent knows how many it placed; counting them in the drawing would copy every object.

    It is the call an RL agent makes after each action: ``check`` and ``overlaps`` answer a drawing of 10 000 objects in
    0.05 s and one of hundreds in milliseconds, and the same drawing gives the same number on every run.
    """
    drawing.commit()  # what is queued is not scored
    checked = drawing.check(standard, model_scale=1.0)
    hits = drawing.overlaps()
    clear = 1.0 - len(set(hits.words)) / words if words else 1.0
    return Reward((checked.total + clear) / 2.0, checked.total, clear, len(hits))


@dataclass
class Note:
    """A note to place: a tag (``kind`` ``"text"``) whose insertion point is ``shift`` from its ``anchor``, or a
    dimension (``"dim"``) of ``anchor`` and ``end`` whose line is ``offset`` millimetres above them. ``entity`` is the
    object that stands for it in the drawing."""

    kind: str
    anchor: tuple[float, float]
    text: str
    height: float
    end: tuple[float, float] = (0.0, 0.0)
    offset: float = 0.0
    shift: tuple[float, float] = (0.0, 0.0)
    entity: Entity[Any] | None = None


def put(drawing: Drawing, note: Note) -> None:
    """Adds the note where it says it is and keeps the object that stands for it."""
    if note.kind == "dim":
        middle = ((note.anchor[0] + note.end[0]) / 2.0, note.anchor[1] + note.offset)
        note.entity = drawing.add_linear_dim(note.anchor, note.end, middle)
    else:
        where = (note.anchor[0] + note.shift[0], note.anchor[1] + note.shift[1])
        note.entity = drawing.add_text(note.text, where, note.height)
    drawing.commit()


def generate(seed: int) -> tuple[Drawing, list[Note]]:
    """A plan of a frame with a grid of beams, a tag on twelve of its crossings and two dimensions below it, all put
    where an AI would put them first: a tag with its middle on its crossing, a dimension a little off what it
    measures."""
    chance = random.Random(seed)
    drawing = new_file()
    left, bottom, right, top = FRAME
    drawing.add_polyline([(left, bottom), (right, bottom), (right, top), (left, top)], closed=True)
    columns, rows = [60.0 + 50.0 * i for i in range(7)], [80.0, 140.0, 200.0, 250.0]
    for x in columns:
        drawing.add_line((x, 60.0), (x, 270.0))
    for y in rows:
        drawing.add_line((40.0, y), (390.0, y))
    drawing.commit()
    crossings = sorted(chance.sample([(x, y) for y in rows for x in columns], 12), key=lambda c: (c[1], c[0]))
    notes = [
        Note("text", crossing, f"B{number}", chance.choice([3.5, 3.5, 3.5, 4.0]), shift=(-4.0, -1.75))
        for number, crossing in enumerate(crossings, 1)  # a height of 4.0 is one the standard has not
    ]
    notes.append(Note("dim", (columns[0], 60.0), "", 2.5, (columns[-1], 60.0), -8.0))
    notes.append(Note("dim", (columns[0], 60.0), "", 2.5, (columns[3], 60.0), -4.0))
    for note in notes:
        put(drawing, note)
    return drawing, notes


def dimension_offset(drawing: Drawing, note: Note) -> float:
    """The offset nearest the dimension's own, on either side, at which its words fit with ``MARGIN`` to spare (its
    own where none does)."""
    steps = sorted((k * 6.0 * side for k in range(0, 11) for side in (1, -1) if k or side == 1), key=abs)
    for step in steps:
        middle = ((note.anchor[0] + note.end[0]) / 2.0, note.anchor[1] + note.offset + step)
        frames = drawing.measure_dimension("linear", [note.anchor, note.end, middle]).frames
        if all(drawing.fits(frame, margin=MARGIN) for frame in frames):
            return note.offset + step
    return note.offset


def tag_shift(drawing: Drawing, note: Note) -> tuple[float, float]:
    """The shift from its anchor to the place nearest it where a tag's words fit with ``MARGIN`` to spare (its own where
    there is none). The tag is measured, ``free_space`` lists the empty rectangles round the anchor that are big enough,
    and the tag goes to the point of one of them nearest the anchor, the corner of its words on it."""
    ax, ay = note.anchor
    frame = drawing.measure_text(note.text, (ax, ay), note.height).frames[0]  # its corner is off the insertion point
    left, bottom, right, top = FRAME
    window = (max(left, ax - REACH), max(bottom, ay - REACH), min(right, ax + REACH), min(top, ay + REACH))
    best: tuple[float, float, float] | None = None  # the distance, then the corner: a tie breaks the same way every run
    for room in drawing.free_space(window, margin=MARGIN, min_width=frame.width, min_height=frame.height):
        x = min(max(ax, room.min_x), room.max_x - frame.width)
        y = min(max(ay, room.min_y), room.max_y - frame.height)
        found = (math.hypot(x - ax, y - ay), x, y)
        if best is None or found < best:
            best = found
    return note.shift if best is None else (best[1] - frame.x, best[2] - frame.y)


def refine(drawing: Drawing, notes: list[Note], standard: dict[str, Any]) -> int:
    """One round of refining: every note the drawing scores down (a word over a line or another word, a gap under the
    least, a height off the standard) is taken out and put at the nearest place where its words fit, at the nearest
    height the standard has. Gives how many notes were moved."""
    heights: list[float] = standard["textHeights"]["paper"]
    wrong = {v.handle for v in drawing.check(standard, model_scale=1.0).violations} | set(drawing.overlaps().words)
    moved = 0
    for note in sorted(notes, key=lambda each: (each.anchor[1], each.anchor[0], each.kind, each.end)):
        if note.entity is None or note.entity.handle not in wrong:
            continue
        drawing.erase(note.entity)  # out of the drawing first, so that the note does not count against itself
        drawing.commit()
        note.height = min(heights, key=lambda height: (abs(height - note.height), height))
        if note.kind == "dim":
            note.offset = dimension_offset(drawing, note)
        else:
            note.shift = tag_shift(drawing, note)
        put(drawing, note)
        moved += 1
    return moved


def describe(number: int, now: Reward, moved: int | None = None) -> str:
    """The line printed for a round: how many notes it moved, the reward and its parts."""
    made = "" if moved is None else f"moved {moved}, "
    return (
        f"round {number}: {made}reward {now.value:.3f} "
        f"(standard {now.standard:.3f}, clear {now.clear:.3f}, {now.overlaps} overlaps)"
    )


def main(argv: list[str]) -> int:
    if len(argv) not in (1, 2) or (len(argv) == 2 and not argv[1].isdecimal()):
        print("usage: python layout_loop.py OUT_FOLDER [SEED]", file=sys.stderr)
        return 2
    folder = Path(argv[0])
    folder.mkdir(parents=True, exist_ok=True)
    drawing, notes = generate(int(argv[1]) if len(argv) == 2 else 1)
    drawing.render_png(str(folder / "before.png"), box=SHEET, width=1200, ground="white")
    first = best = reward(drawing, STANDARD, len(notes))
    print(describe(0, first))
    for number in range(1, 11):
        moved = refine(drawing, notes, STANDARD)
        now = reward(drawing, STANDARD, len(notes))
        print(describe(number, now, moved))
        if now.value <= best.value + 1e-9:  # the score has stopped rising
            break
        best = now
    drawing.render_png(str(folder / "after.png"), box=SHEET, width=1200, ground="white")
    print(f"reward {first.value:.3f} -> {best.value:.3f}; before.png and after.png written to {folder.name}")
    return 0 if best.overlaps == 0 else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

A plotted sheet made from code

sheet_from_code.py OUT_FOLDER makes what a drafter makes of a steel plate, with no app and no file to start from. In model space a plate 1 200 by 800 mm with two holes of 60 and their centre marks, and two linear dimensions on the layer Dims in a dimension style whose scale is 10, so that their words are 2.5 mm high on a sheet at 1:10. Then drawing.layouts.add("Plate A3", paper="ISO_A3"), an A3 layout in millimetres, a border drawn on it, and a title block: the block TITLE is a box with three attribute definitions (DRAWING, NUMBER, SCALE) and add_insert(..., layout=..., attributes=...) puts it on the sheet with their words, in the same commit that defines it. Two viewports show the plate: add_viewport at "1:10" with the layer Notes frozen in it, and a detail of the second hole at 0.2 paper millimetres to a unit, which is 1:5, with Dims frozen. plot_pdf writes the sheet through the plot pipeline to plate.pdf, one A3 page at the 1:1 the layout is plotted at (the scales are the viewports'), and the words of the PDF, read back by a test, are the title block's (PLATE PL12, A-101, 1:10, DETAIL 1:5) and the plate's (1200, 800, 2 HOLES D60):

$ python sheet_from_code.py sheet
Plate A3: ISO A3, 2 viewports, title block A-101
plate.pdf: sheet 420 by 297, scale 1:1, written to sheet

Sheets from code says what each call does; the same script drives a drawing of a running app with connect() in place of new_file(), the PDF being plotted here from a copy of the app's drawing.

"""A plotted sheet made from nothing: a steel plate in model space, an A3 layout in millimetres with a filled title
block and two viewports (1:10, and a detail at 1:5), plotted to a PDF.
Run: python sheet_from_code.py OUT_FOLDER   (OUT_FOLDER is made if it is not there)
The plate is 1200 by 800 with two holes of 60; its dimensions are on the layer Dims, in a style of scale 10. The
title block is a block with three attributes, put on the layout with ``add_insert``. Writes plate.dxf and plate.pdf."""

import sys
from pathlib import Path

from opencad2d.cad import Drawing, new_file
from GeometryHelper.Dxf import DxfAttributeDefinition, DxfLine
from GeometryHelper.Geometry import GeoPoint3

SHEET = "Plate A3"
TITLE_AT = (250.0, 10.0)  # the lower left corner of the title block on the sheet, in millimetres
HOLES = [(300.0, 400.0), (900.0, 400.0)]  # the centres of the two holes of 60, in millimetres
VALUES = {"DRAWING": "PLATE PL12", "NUMBER": "A-101", "SCALE": "1:10, DETAIL 1:5"}
FIELDS = [("DRAWING", "UNTITLED", (4.0, 21.0)), ("NUMBER", "A-000", (4.0, 5.0)), ("SCALE", "1:1", (84.0, 5.0))]


def box(width: float, height: float, at: tuple[float, float] = (0.0, 0.0)) -> list[DxfLine]:
    """The four sides of a box, ``width`` by ``height`` millimetres, with its lower left corner at ``at``."""
    x, y = at
    corners = [(x, y), (x + width, y), (x + width, y + height), (x, y + height)]
    return [DxfLine(GeoPoint3(*corners[i], 0.0), GeoPoint3(*corners[(i + 1) % 4], 0.0)) for i in range(4)]


def draw_plate(drawing: Drawing) -> None:
    """The plate with its holes and centre marks, and two dimensions whose words are 2.5 high on a sheet at 1:10."""
    drawing.layers.add("Plate", color=7)
    drawing.layers.add("Centre", color=1)
    drawing.layers.add("Notes", color=3)
    drawing.layers.add("Dims", color=2)
    drawing.dimension_styles.add("PLATE-10", scale=10.0, text_height=2.5, arrow_size=2.5)
    drawing.commit()
    drawing.current_layer = "Plate"
    drawing.add_polyline([(0, 0), (1200, 0), (1200, 800), (0, 800)], closed=True)
    for x, y in HOLES:
        drawing.add_circle((x, y), 30.0)
        drawing.add_line((x - 50, y), (x + 50, y), layer="Centre")
        drawing.add_line((x, y - 50), (x, y + 50), layer="Centre")
    drawing.add_linear_dim((0, 0), (1200, 0), (600, -80), dim_style="PLATE-10", layer="Dims")
    drawing.add_linear_dim((0, 0), (0, 800), (-80, 400), dim_style="PLATE-10", layer="Dims")
    drawing.add_text("2 HOLES D60", (950.0, 470.0), 25.0, layer="Notes")
    drawing.commit()


def title_block(drawing: Drawing) -> None:
    """Defines the block TITLE, a box 160 by 35 with the attributes DRAWING, NUMBER and SCALE, and puts it on the sheet
    with their words in the same commit."""
    parts: list[DxfLine | DxfAttributeDefinition] = [*box(160.0, 35.0)]
    parts.append(DxfLine(GeoPoint3(0.0, 17.5, 0.0), GeoPoint3(160.0, 17.5, 0.0)))
    style = drawing.text_styles["Standard"]
    for tag, default, (x, y) in FIELDS:
        definition = DxfAttributeDefinition(GeoPoint3(x, y, 0.0), default, tag, tag.title(), style)
        definition.Height = 5.0
        parts.append(definition)
    drawing.blocks.add("TITLE", parts)
    drawing.add_insert("TITLE", TITLE_AT, layout=SHEET, attributes=VALUES)
    drawing.commit()


def lay_out(drawing: Drawing) -> None:
    """The layout on an A3 sheet in millimetres with a border, the title block and two viewports: the plate at 1:10 with
    the layer Notes frozen in it, and a detail of the second hole at 1:5 with the layer Dims frozen."""
    sheet = drawing.layouts.add(SHEET, paper="ISO_A3")
    for side in box(400.0, 277.0, (10.0, 10.0)):
        drawing.add(side, layout=sheet)
    title_block(drawing)
    sheet.add_viewport((20, 55, 250, 277), "1:10", center=(600, 400), frozen_layers=["Notes"])
    sheet.add_viewport((260, 55, 400, 277), 0.2, center=(900, 400), frozen_layers=["Dims"])  # 0.2 mm to a unit is 1:5


def main(argv: list[str]) -> int:
    if len(argv) != 1:
        print("usage: python sheet_from_code.py OUT_FOLDER", file=sys.stderr)
        return 2
    folder = Path(argv[0])
    folder.mkdir(parents=True, exist_ok=True)
    drawing = new_file()
    draw_plate(drawing)
    lay_out(drawing)
    sheet = drawing.layouts[SHEET]
    drawing.save_as(str(folder / "plate.dxf"))
    plot = sheet.plot_pdf(folder / "plate.pdf")
    print(f"{sheet.name}: {sheet.paper}, {sheet.viewports} viewports, title block {VALUES['NUMBER']}")
    print(f"plate.pdf: sheet {plot.sheet[0]:g} by {plot.sheet[1]:g}, scale {plot.scale}, written to {folder.name}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Tools of the app

The three tools that ship with the app, DrawingInfo (PYINFO), DrawRandom (PYRANDOM) and HelloWorld (PYHELLOWORLD), are not among the nineteen: they are in the app's Pythons folder and in examples\Pythons of the repository, and Python commands and tools shows what they write. Each tool below is run in a python.exe of its own, with a venv of its own that its requirements.txt fills (these need no package, so their files are empty).

These are folders, each a Python tool with no main: the app loads one (PYLOAD of its requirements.txt, or the Pythons folder), shows the commands its plugin.json names, and starts its process at the first command typed. They use opencad2d.cad for the prompts and the Drawing API, and each command is one undo step, so one U takes back all it drew. A test of the repository (PythonToolExampleTests) loads each folder and types its commands in a window's model, answering the prompts, so what the page says is what the tools do.

Number the points you pick

number_points, run with its command NUMBERPOINTS, asks First number <1>: and then Specify point: until Enter, and adds a text of height 2.5 at each point with add_text, the numbers counting up; the texts are applied when the run ends. After a first number of 1 and three points it writes

3 points numbered, 1 to 3.

The three texts read 1, 2 and 3 at the points picked. Enter at the first question and at the first point writes No point picked. and draws nothing.

"""Numbers the points you pick: a text of height 2.5 with the next number at each point, until Enter.

A Python tool: type NUMBERPOINTS in OpenCAD2D. It asks for the first number (1 on Enter), then for points.
The texts are added to the drawing when the command ends, as one undo step, so one U takes every number back.
"""

from opencad2d.cad import active_drawing, command, get_integer, get_point, write
from GeometryHelper.Geometry import GeoPoint2


@command("NUMBERPOINTS")
def number_points() -> None:
    first = get_integer("First number", default=1)
    if not isinstance(first, int):
        return
    drawing = active_drawing()
    number = first
    while True:
        point = get_point("Specify point")
        if not isinstance(point, GeoPoint2):  # Enter: no more points
            break
        drawing.add_text(str(number), point, 2.5)
        number += 1
    count = number - first
    if count == 0:
        write("No point picked.")
    else:
        write(f"{count} point{'s' if count != 1 else ''} numbered, {first} to {number - 1}.")

Commands of your own

drawing_tools, loaded with PYLOAD, defines two commands. RECTC (alias RC) asks for a centre, a width (<1000>) and a height (<500>) and draws a closed polyline rectangle about the centre; LAYERCOUNT writes the number of objects on each layer that has any, sorted by name. PYLOAD writes

drawing_tools loaded: LAYERCOUNT, RECTC.

RECTC with the centre 0,0, a width of 200 and a height of 100 draws a rectangle from -100,-50 to 100,50; with Enter at both questions it is 1 000 by 500 about the centre. RECTC adds the rectangle with add_polyline(..., closed=True) and writes nothing itself, except for a width or a height of 0 or less, which it refuses with The width and the height must be more than 0. and draws nothing (a rectangle of no width is a polyline with nothing inside it). On a drawing with one rectangle on layer 0, LAYERCOUNT writes 0: 1; an object on walls counts with the layer the table calls Walls.

"""Two commands of your own for OpenCAD2D: RECTC (alias RC) and LAYERCOUNT.

A Python tool: PYLOAD its requirements.txt, or put the folder in Pythons; its process starts at the first command typed.
RECTC draws a rectangle about a centre you pick, of a width and a height you give; LAYERCOUNT counts the objects on
each layer.
"""

from collections import Counter

from opencad2d.cad import active_drawing, command, get_distance, get_point, write
from GeometryHelper.Geometry import GeoPoint2


@command("RECTC", alias="RC")
def rectangle_by_centre() -> None:
    centre = get_point("Specify centre")
    if not isinstance(centre, GeoPoint2):
        return
    width = get_distance("Width", base=centre, default="1000")
    height = get_distance("Height", base=centre, default="500")
    if not isinstance(width, float) or not isinstance(height, float):
        return
    if width <= 0 or height <= 0:
        write("The width and the height must be more than 0.")
        return
    left, right = centre.X - width / 2, centre.X + width / 2
    bottom, top = centre.Y - height / 2, centre.Y + height / 2
    active_drawing().add_polyline([(left, bottom), (right, bottom), (right, top), (left, top)], closed=True)


@command("LAYERCOUNT")
def layer_count() -> None:
    drawing = active_drawing()
    # Counted under the layer table's spelling: an object on "walls" is on the layer the table calls "Walls".
    counts = Counter(
        drawing.layers[entity.layer].name if entity.layer in drawing.layers else entity.layer
        for entity in drawing.entities(layout="Model")
    )
    for name in sorted(counts, key=lambda name: (name.casefold(), name)):
        write(f"{name}: {counts[name]}")

The length of a selection

selection_lengths, run with its command SELECTIONLENGTHS, asks Select objects: and adds up the length of the lines, arcs, circles (their circumference) and polylines, and the area of the circles and closed polylines. Anything else is counted as skipped. On a line from 0,0 to 300,400, a circle of radius 120, a closed polyline rectangle 100 by 50 and a text, all selected, it writes

4 objects: length 1553.982, closed area 50238.934, 1 skipped

The length is the line's 500, the circle's 753.982 and the rectangle's 300; the area the circle's 45 238.934 and the rectangle's 5 000. With nothing selected it writes Nothing selected.

"""Totals the length and the closed area of the objects you select.

A Python tool: type SELECTIONLENGTHS in OpenCAD2D; it asks "Select objects:" as a command does.
Lines, arcs, circles (their circumference) and polylines add to the length; circles and closed polylines to the area.
"""

from opencad2d.cad import command, get_selection, write
from GeometryHelper.Dxf import DxfArc, DxfCircle, DxfLine, DxfPolyline


@command("SELECTIONLENGTHS")
def selection_lengths() -> None:
    entities = get_selection()
    if not entities:
        write("Nothing selected.")
        return
    length = 0.0
    area = 0.0
    skipped = 0
    for item in entities:
        entity = item.net
        if isinstance(entity, DxfCircle):
            length += entity.Circumference
            area += entity.Area
        elif isinstance(entity, (DxfLine, DxfArc)):
            length += entity.Length
        elif isinstance(entity, DxfPolyline):
            length += entity.Length
            area += entity.Area if entity.Closed else 0.0
        else:
            skipped += 1
    write(f"{len(entities)} objects: length {length:.3f}, closed area {area:.3f}, {skipped} skipped")

A snap, a setting and a button for circles

circle_marks is the one tool here that adds to the window, with the three files of a tool and what its plugin.json says besides its command. Its snap CTOP is the top of a circle: @snap("CTOP") is bound to the "snaps" entry with that keyword, which names it "Circle top", limits it to CIRCLE and gives it the marker of the quadrant snap, and the app asks the tool about a circle the cursor comes near once, until the drawing changes. For a circle of radius 25 about (100, 50) the point is (100, 75). Its setting textHeight (2.5, from 0.1 to 1000) is shown in Load/Unload Applications, Settings..., and the command MARKTOPS, which asks Select objects: (or takes the objects selected), writes a text R25 of that height at the top of each selected circle: 2.5 high until the user changes it. A ribbon tab Circles holds one large button, Mark tops, that starts MARKTOPS. With one circle selected it writes

Marks written: 1, 2.5 high.

Anything but a circle in the selection is passed over, and with no circle selected it writes No circle selected. and draws nothing. The snap and the setting need the app and its plugin.json; a test of the repository starts the tool's process, asks the snap as the app does and runs the command.

"""A snap, a setting, a command and a ribbon button for circles: CTOP, textHeight, MARKTOPS.

A Python tool: PYLOAD its requirements.txt, then snap to the top of a circle with CTOP, or select circles and press Mark
tops (or type MARKTOPS). A mark is a text of the height set in Load/Unload Applications, Settings.
"""

from opencad2d.cad import SnapRequest, active_drawing, command, get_selection, setting, snap, write
from GeometryHelper.Dxf import DxfCircle
from GeometryHelper.Geometry import GeoPoint2


@snap("CTOP")
def circle_top(request: SnapRequest) -> list[GeoPoint2]:
    circle = request.entity
    if not isinstance(circle, DxfCircle):
        return []
    return [GeoPoint2(circle.Center.X, circle.Center.Y + circle.Radius)]  # r=25 at (100, 50) gives (100, 75)


@command("MARKTOPS", uses_selection=True)
def mark_tops() -> None:
    height = setting("textHeight")
    circles = [entity for entity in get_selection() if isinstance(entity.net, DxfCircle)]
    if not circles or not isinstance(height, float):
        write("No circle selected.")
        return
    drawing = active_drawing()
    for entity in circles:
        circle = entity.net
        assert isinstance(circle, DxfCircle)
        drawing.add_text(f"R{circle.Radius:g}", (circle.Center.X, circle.Center.Y + circle.Radius), height)
    write(f"Marks written: {len(circles)}, {height:g} high.")

Driving a running app

These files connect to OpenCAD2D from another process with connect() (Driving the app from another program), so the app has to be running with "Allow other programs to connect" on (the setting). Each has a main that works on the App it is given, the Drawing API over the connection, and a __main__ block that makes the connection with with connect() as cad:, which closes it at the end. From Python tells how the .NET calls look in Python. The numbers below come from the test server of the repository, an app with no window.

Draw a grid and read it back

draw_and_read.py [OUT] starts a new drawing, adds a layer Grid and 11 vertical and 11 horizontal lines over a square of 1 000 at a spacing of 100, commits them as one undo step, reads them back with drawing.entities(DxfLine, layer="Grid") and, when OUT is given, saves the drawing.

22 lines on Grid, total length 22000.000
saved grid.dxf
"""Draws a grid in a running OpenCAD2D, reads it back, and saves it when you name a file.

Run outside the app, with "Allow other programs to connect" on in its Global settings: python draw_and_read.py [OUT]
A new drawing gets a layer Grid and 22 lines, 11 each way over 1000 by 1000 at 100 spacing, as one undo step; the
lines are read back by layer and kind, and the drawing is saved as OUT (.dxf or .dwg) when it is given.
"""

import sys
from pathlib import Path

from opencad2d.cad import App, connect
from GeometryHelper.Dxf import DxfLine

LAYER = "Grid"


def main(cad: App, out: str | None) -> None:
    drawing = cad.new()
    drawing.layers.add(LAYER)
    for step in range(0, 1001, 100):
        drawing.add_line((step, 0), (step, 1000), layer=LAYER)  # a vertical line
        drawing.add_line((0, step), (1000, step), layer=LAYER)  # a horizontal one
    drawing.commit()  # the layer first, then the lines: one undo step

    lines = drawing.entities(DxfLine, layer=LAYER)
    print(f"{len(lines)} lines on {LAYER}, total length {sum(line.net.Length for line in lines):.3f}")
    if out is not None:
        drawing.save_as(out)
        print(f"saved {Path(out).name}")


if __name__ == "__main__":
    with connect() as cad:
        main(cad, sys.argv[1] if len(sys.argv) > 1 else None)

Pick a point and mark it

pick_and_mark.py asks the user for a point (Pick the centre) and waits up to 60 seconds, then draws a circle of radius 50 there and zooms to the extents. The pick is made on drawing.net, the CadRemoteDocument, because PickPoint there takes the time limit that drawing.pick_point does not. A point of 120,80, clicked or typed on the app's command line, prints

circle at 120.000,80.000

and the script returns 0. Esc in the app throws a CadRemoteException whose IsCancelled is true; the script prints Cancelled. and returns 1. Any other exception, a timeout among them, is raised again. The time limit is there because Ctrl+C does not end a call into .NET that waits for the user (From Python).

"""Asks you to pick a point in a running OpenCAD2D, and draws a circle of radius 50 there.

Run outside the app, with "Allow other programs to connect" on in its Global settings: python pick_and_mark.py
It waits up to a minute for you to click on the canvas or type a point, then zooms to the extents. Esc in the app
cancels the pick: the script says so and returns 1.
"""

import sys

from System import TimeSpan

from opencad2d.cad import App, connect
from OpenCAD2D.Remote import CadRemoteException

PICK_TIMEOUT = TimeSpan.FromSeconds(60)  # a pick with no time limit would wait for ever, and Ctrl+C cannot end it


def main(cad: App) -> int:
    drawing = cad.active_drawing
    if drawing is None:  # the app has no drawing open
        drawing = cad.new()
    try:
        # drawing.net is the CadRemoteDocument: its PickPoint takes the time limit that drawing.pick_point does not.
        centre = drawing.net.PickPoint("Pick the centre", timeout=PICK_TIMEOUT)
    except CadRemoteException as error:
        if not error.IsCancelled:
            raise
        print("Cancelled.")
        return 1
    drawing.add_circle(centre, 50)
    drawing.commit()
    cad.run_command(drawing, "ZOOM E\n")  # "\n" is Enter
    print(f"circle at {centre.X:.3f},{centre.Y:.3f}")
    return 0


if __name__ == "__main__":
    with connect() as cad:
        sys.exit(main(cad))

The open drawings

open_documents.py lists the drawings the app has open, in the app's order: the name, with * after it for the drawing the user is working in, the number of objects in model space, and the count of each class of object, the classes sorted by name. With a drawing of two lines and a circle and a new, empty one shown on top it prints, tab-separated,

Drawing1.dxf	3	DxfCircle:1, DxfLine:2
Drawing2.dxf *	0	
"""Lists the drawings a running OpenCAD2D has open, with what is in their model space.

Run outside the app, with "Allow other programs to connect" on in its Global settings: python open_documents.py
One line for each drawing, in the app's order: its name (then " *" for the one shown), the number of objects in model
space, and the count of each class of object.
"""

from collections import Counter

from opencad2d.cad import App, connect


def main(cad: App) -> None:
    for drawing in cad.documents:
        objects = drawing.entities(layout="Model")
        classes = Counter(type(entity.net).__name__ for entity in objects)
        mark = " *" if drawing.is_active else ""
        per_class = ", ".join(f"{name}:{classes[name]}" for name in sorted(classes))
        print(f"{drawing.name}{mark}\t{len(objects)}\t{per_class}")


if __name__ == "__main__":
    with connect() as cad:
        main(cad)