vpype

This module contains vpype core and its API.

Functions

_get_version

rtype

str

arc

Build an elliptical arc path.

as_vector

Return a view of a complex line array that behaves as an Nx2 real array

block_processor

Create an instance of the block processor class.

circle

Build a circular path.

convert_angle

Convert an angle optionally expressed as a string with unit to degrees.

convert_length

Convert a length optionally expressed as a string with unit to px value.

convert_page_size

Converts a string with page size to dimension in pixels.

crop

Crop a polyline to a rectangular area.

crop_half_plane

Crop a path at a axis-aligned location.

ellipse

Build an elliptical path.

generator

Helper decorator to define generator-type commands.

global_processor

Helper decorator to define a global processor command.

interpolate

Compute a linearly interpolated version of line with segments of step length or less.

is_closed

Check if a line is closed.

layer_processor

Helper decorator to define a layer processor command.

line

Build a line from two points

line_length

Compute the length of a line.

multiple_to_layer_ids

Convert multiple-layer CLI argument to list of layer IDs.

pass_state

Marks a command as wanting to receive the current state.

read_multilayer_svg

Read a multilayer SVG file and return its content as a Document instance retaining the SVG’s layer structure and its dimension.

read_svg

Read a SVG file an return its content as a LineCollection instance.

rect

Build a rectangular path, with optional rounded angles.

reloop

Change the seam of a closed path.

single_to_layer_id

Convert single-layer CLI argument to layer ID, accounting for the existence of a current a current target layer and dealing with default behavior.

union

Returns True if every callables in keys return True (similar to all().

write_hpgl

Create a HPGL file from the Document instance.

write_svg

Create a SVG from a Document instance.

Classes

AngleType()

click.ParamType sub-class to automatically converts a user-provided angle string (which may contain units) into a value in degrees.

ConfigManager()

Helper class to handle vpype’s TOML configuration files.

Document([line_collection, page_size])

This class is the core data model of vpype and represent the data that is passed from one command to the other.

LayerType([accept_multiple, accept_new])

Interpret value of --layer options.

LengthType()

click.ParamType sub-class to automatically converts a user-provided length string (which may contain units) into a value in CSS pixel units.

LineCollection([lines])

LineCollection encapsulate a list of piecewise linear lines (or paths).

LineIndex(lines[, reverse])

Wrapper to scipy.spatial.cKDTree to facilitate systematic processing of a line collection.

PageSizeType()

click.ParamType sub-class to automatically converts a user-provided page size string into a tuple of float in CSS pixel units.

PaperConfig(name, y_axis_up, origin_location)

Data class containing configuration for a give plotter type/paper size combinations.

PlotterConfig(name, paper_configs, …[, info])

Data class containing configuration for a given plotter type.

VpypeState([doc])

Functions

_get_version()
Return type

str

arc(x, y, rw, rh, start, stop, quantization=0.1)

Build an elliptical arc path. Zero angles refer to east of unit circle and positive values extend counter-clockwise.

Parameters
  • x (float) -- center X coordinate

  • y (float) -- center Y coordinate

  • rw (float) -- ellipse half-width

  • rh (float) -- ellipse half-height (use the same value as rw for a circular arc)

  • start (float) -- start angle (degree)

  • stop (float) -- stop angle (degree)

  • quantization (float) -- maximum length of linear segment

Return type

ndarray

Returns

arc path

as_vector(a)

Return a view of a complex line array that behaves as an Nx2 real array

block_processor(c)

Create an instance of the block processor class.

circle(x, y, radius, quantization=0.1)

Build a circular path.

Parameters
  • x (float) -- center X coordinate

  • y (float) -- center Y coordinate

  • radius (float) -- circle radius

  • quantization (float) -- maximum length of linear segment

Return type

ndarray

Returns

circular path

convert_angle(value)

Convert an angle optionally expressed as a string with unit to degrees.

Parameters

value (Union[str, float]) -- angle to convert

Return type

float

Returns

converted angle in degree

Raises

ValueError --

convert_length(value)

Convert a length optionally expressed as a string with unit to px value.

Parameters

value (Union[str, float]) -- value to convert

Return type

float

Returns

converted value

Raises

ValueError --

convert_page_size(value)

Converts a string with page size to dimension in pixels.

The input can be either a known page size (see vpype write --help for a list) or a page size descriptor in the form of “WxH” where both W and H can have units.

Examples

Using a know page size:

>>> import vpype
>>> vpype.convert_page_size("a3")
(1122.5196850393702, 1587.4015748031497)

Using page size descriptor (no units, pixels are assumed):

>>> vpype.convert_page_size("100x200")
(100.0, 200.0)

Using page size descriptor (explicit units):

>>> vpype.convert_page_size("1inx2in")
(96.0, 192.0)
Parameters

value (str) -- page size descriptor

Return type

Tuple[float, float]

Returns

the page size in CSS pixels

crop(line, x1, y1, x2, y2)

Crop a polyline to a rectangular area.

Parameters
  • x1 (float) -- left coordinate of the crop area

  • y1 (float) -- bottom coordinate of the crop area

  • x2 (float) -- right coordinate of the crop area

  • y2 (float) -- top coordinate of the crop area

Return type

List[array]

Returns

list of lines resulting of the crop (emtpy if x1 > x2 or y1 > y2)

crop_half_plane(line, loc, axis, keep_smaller)

Crop a path at a axis-aligned location.

The path is cut at location x=loc for axis=0, and y=loc for axis=1. The argument keep_smaller controls which part of the path is discarded.

Parameters
  • line (ndarray) -- path to crop

  • loc (float) -- coordinate at which the cut is made

  • axis (int) -- 0 for a cut along x axis, 1 for y axis

  • keep_smaller (bool) -- if True, parts of line with coordinates smaller or equal than loc are kept, and the reverse otherwise

Return type

List[ndarray]

Returns

list of paths

ellipse(x, y, w, h, quantization=0.1)

Build an elliptical path.

Parameters
  • x (float) -- center X coordinate

  • y (float) -- center Y coordinate

  • w (float) -- half width of the ellipse

  • h (float) -- half height of the ellipse

  • quantization (float) -- maximum length of linear segment

Return type

ndarray

Returns

elliptical path

generator(f)

Helper decorator to define generator-type commands.

Generator do not have input, have automatically a “-l, --layer” option added to them, and must return a LineCollection structure, which will be added to a new layer or an existing one depending the option.

global_processor(f)

Helper decorator to define a global processor command.

This type of command implement a global, multi-layer processing and should be used for processors which cannot be applied layer-by-layer independently (in which case, using a layer_processor() is advised.

No option is automatically added to global processors. In cases where the user should be able to control on which layer(s) the processing must be applied, it is advised to add a --layer option (with type LayerType) and use the multiple_to_layer_ids() companion function (see example below)

A global processor receives a Document as input and must return one.

Example:

@click.command()
@click.option(
    "-l",
    "--layer",
    type=vpype.LayerType(accept_multiple=True),
    default="all",
    help="Target layer(s).",
)
@vpype.global_processor
def my_global_processor(
    document: vpype.Document, layer: Union[int, List[int]]
) -> vpype.Document:
    '''Example global processor'''

    layer_ids = multiple_to_layer_ids(layer, document)
    for lines in document.layers_from_ids(layer_ids):
        # [apply some modification to lines]

    return document


my_global_processor.help_group = "My Plugins"
interpolate(line, step)

Compute a linearly interpolated version of line with segments of step length or less.

Parameters
  • line (ndarray) -- 1D array of complex

  • step (float) -- maximum length of interpolated segment

Return type

ndarray

Returns

interpolated 1D array of complex

is_closed(line, tolerance)

Check if a line is closed.

Parameters
  • line (ndarray) -- the line to test

  • tolerance (float) -- max distance between starting and ending point to consider a path is_closed

Return type

bool

Returns

True if line is is_closed

layer_processor(f)

Helper decorator to define a layer processor command.

Layer processors implements “intra-layer” processing, i.e. they are independently called for every layer in the pipeline. A --layer option is automatically appended to the option to let the user control on which layer(s) the processor should be applied (by default, all is used).

Layer processors receive a LineCollection as input and must return one.

Example:

@click.command()
@vpype.layer_processor
def my_processor(lines: vpype.LineCollection) -> vpype.LineCollection:
    '''Example layer processor'''

    new_lines = vpype.LineCollection()

    for line in lines:
        # [do something with line]
        new_lines.append(line)

    return lines

my_processor.help_group = "My Plugins"
line(x0, y0, x1, y1)

Build a line from two points

Parameters
  • x0 (float) -- line start X coordinate

  • y0 (float) -- line start Y coordinate

  • x1 (float) -- line end X coordinate

  • y1 (float) -- line end Y coordinate

Return type

ndarray

Returns

line path

line_length(line)

Compute the length of a line.

Return type

float

multiple_to_layer_ids(layers, document)

Convert multiple-layer CLI argument to list of layer IDs.

Parameters
Return type

List[int]

Returns

List of layer IDs

pass_state(f)

Marks a command as wanting to receive the current state.

read_multilayer_svg(filename, quantization, crop=True, simplify=False, parallel=False, default_width=1000, default_height=1000)

Read a multilayer SVG file and return its content as a Document instance retaining the SVG’s layer structure and its dimension.

Each top-level group is considered a layer. All non-group, top-level elements are imported in layer 1.

Groups are matched to layer ID according their inkscape:label attribute, their id attribute or their appearing order, in that order of priority. Labels are stripped of non-numeric characters and the remaining is used as layer ID. Lacking numeric characters, the appearing order is used. If the label is 0, its changed to 1.

All curved geometries are chopped in segments no longer than the value of quantization. Optionally, the geometries are simplified using Shapely, using the value of quantization as tolerance.

Parameters
  • filename (str) -- path of the SVG file

  • quantization (float) -- maximum size of segment used to approximate curved geometries

  • crop (bool) -- crop the geometries to the SVG boundaries

  • simplify (bool) -- run Shapely’s simplify on loaded geometry

  • parallel (bool) -- enable multiprocessing (only recommended for simplify=True and SVG with many curves)

  • default_width (float) -- default width if not provided by SVG or if a percent width is provided

  • default_height (float) -- default height if not provided by SVG or if a percent height is provided

Return type

Document

Returns

Document instance with the imported geometries and its page size set the the SVG dimensions

read_svg(filename, quantization, crop=True, simplify=False, parallel=False, default_width=1000, default_height=1000)

Read a SVG file an return its content as a LineCollection instance.

All curved geometries are chopped in segments no longer than the value of quantization. Optionally, the geometries are simplified using Shapely, using the value of quantization as tolerance.

Parameters
  • filename (str) -- path of the SVG file

  • quantization (float) -- maximum size of segment used to approximate curved geometries

  • crop (bool) -- crop the geometries to the SVG boundaries

  • simplify (bool) -- run Shapely’s simplify on loaded geometry

  • parallel (bool) -- enable multiprocessing (only recommended for simplify=True and SVG with many curves)

  • default_width (float) -- default width if not provided by SVG or if a percent width is provided

  • default_height (float) -- default height if not provided by SVG or if a percent height is provided

Return type

Tuple[LineCollection, float, float]

Returns

tuple containing a LineCollection with the imported geometries as well as the width and height of the SVG

rect(x, y, width, height, tl=0, tr=0, br=0, bl=0, quantization=0.1)

Build a rectangular path, with optional rounded angles.

Parameters
  • x (float) -- top-left corner X coordinate

  • y (float) -- top-left corner Y coordinate

  • width (float) -- rectangle width

  • height (float) -- rectangle height

  • tl (float) -- top-left corner radius (0 if not provided)

  • tr (float) -- top-right corner radius (0 if not provided)

  • br (float) -- bottom-right corner radius (0 if not provided)

  • bl (float) -- bottom-left corner radius (0 if not provided)

  • quantization (float) -- maximum size of segments approximating round corners

Return type

ndarray

Returns

rectangular path

reloop(line, loc=None)

Change the seam of a closed path. Closed-ness is not checked. Beginning and end points are averaged to compute a new point. A new seam location can be provided or will be chosen randomly.

Parameters
  • line (ndarray) -- path to reloop

  • loc (Optional[int]) -- new seam location

Return type

ndarray

Returns

re-seamed path

single_to_layer_id(layer, document)

Convert single-layer CLI argument to layer ID, accounting for the existence of a current a current target layer and dealing with default behavior.

Arg:

layer: value from a LayerType argument document: target Document instance (for new layer ID)

Return type

int

Returns

Target layer ID

union(line, keys)

Returns True if every callables in keys return True (similar to all(). This function is typically used with LineCollection.filter().

Parameters
  • line (ndarray) -- line to test

  • keys (List[Callable[[ndarray], bool]]) -- list of callables

Return type

bool

Returns

True if every callables return True

write_hpgl(output, document, page_size, landscape, center, device, velocity, quiet=False)

Create a HPGL file from the Document instance.

The device/page_size combination must be defined in the built-in or user-provided config files or an exception will be raised.

By default, no translation is applied on the geometry. If center=True, geometries are moved to the center of the page.

No scaling or rotation is applied to geometries.

Parameters
  • output (TextIO) -- text-mode IO stream where SVG code will be written

  • document (Document) -- geometries to be written

  • page_size (str) -- page size string (it must be configured for the selected device)

  • landscape (bool) -- if True, the geometries are generated in landscape orientation

  • center (bool) -- center geometries on page before export

  • device (Optional[str]) -- name of the device to use (the corresponding config must exists). If not provided, a default device must be configured, which will be used.

  • velocity (Optional[float]) -- if provided, a VS command will be generated with the corresponding value

  • quiet (bool) -- if True, do not print the plotter/paper info strings

Return type

None

write_svg(output, document, page_size=None, center=False, source_string='', layer_label_format='%d', show_pen_up=False, color_mode='none')

Create a SVG from a Document instance.

If no page size is provided (or (0, 0) is passed), the SVG generated has bounds tightly fitted around the geometries. Otherwise the provided size (in pixel) is used. The width and height is capped to a minimum of 1 pixel.

By default, no translation is applied on the geometry. If center=True, geometries are moved to the center of the page.

No scaling or rotation is applied to geometries.

Layers are named after layer_label_format, which may contain a C-style format specifier such as %d which will be replaced by the layer number.

For previsualisation purposes, pen-up trajectories can be added to the SVG and path can be colored individually (color_mode="path") or layer-by-layer (color_mode="layer").

Parameters
  • output (TextIO) -- text-mode IO stream where SVG code will be written

  • document (Document) -- geometries to be written

  • page_size (Optional[Tuple[float, float]]) -- if provided, overrides document.page_size

  • center (bool) -- center geometries on page before export

  • source_string (str) -- value of the source metadata

  • layer_label_format (str) -- format string for layer label naming

  • show_pen_up (bool) -- add paths for the pen-up trajectories

  • color_mode (str) -- “none” (no formatting), “layer” (one color per layer), “path” (one color per path)

Return type

None