group

class Group(
id: str | None = None,
*,
extra_keys: dict[str, Any] | None = None,
entities: EntityList = NOTHING,
tiles: TileList = NOTHING,
groups: CollectionList = NOTHING,
schedules: ScheduleList = NOTHING,
wires=NOTHING,
parameters: list[IDParameter | NumberParameter] = NOTHING,
stock_connections: list[StockConnection] = NOTHING,
name: str = 'group',
type: str = 'group',
position=NOTHING,
collision_mask=NOTHING,
)

Bases: Transformable, Collection, EntityLike, Exportable

Group entities together, so you can manipulate them all as one unit.

Allows for the creation of “blocks” that can be added multiple times very easily to a blueprint. This allows you to create a complex portion of your desired blueprint only once, and then add that Group multiple times to the final blueprint.

Groups can also be used to organize Blueprints at the structure level. You can give entities the same name in a Blueprint as long as they exist in different groups. For example, the following is a perfectly valid structure for a Blueprint to have:

Blueprint().groups = [
    Group("1").entities = [Entity(id="A"), Entity(id="B"), Entity(id="C")],
    Group("2").entities = [Entity(id="A"), Entity(id="B"), Entity(id="C")],
]

This is particularly useful if each group has a similar function, but just exists as a different “part” of the overall blueprint.

EntityLike instances in a Group are considered to be in “group-space”; meaning their positions are offset by the position of the Group they reside in. If a Group is located at position (5, 5), and an entity inside of it is located at (5, 5), when the group is added to a parent Blueprint the contained entity will be located at the position (10, 10). This effect continues if Groups nest inside of other Groups, which is also perfectly legal.

property circuit_connectable : bool

Whether or not this EntityLike can be connected using circuit wires.

Example:

>>> from draftsman.entity import *
>>> Beacon().circuit_connectable
False
>>> Inserter().circuit_connectable
True
>>> DeciderCombinator().circuit_connectable
True
collision_mask : set[str]

The set of all collision layers that this group collides with, specified as strings. Defaults to an empty set.

property collision_set : CollisionSet | None

TODO: is this even a good idea to have in the first place? It seems like having this set be the union of all entities it contains would make the most sense, but that would be slow to compute instead of using a spatial map for that. The user could specify a custom collision set, but how is that supposed to interact with the hashmap? no idea

property double_grid_aligned : bool

Whether or not this EntityLike is “double-grid-aligned”, which applies to entities which need to align with the rail grid.

property dual_circuit_connectable : bool

Whether or not this EntityLike has two circuit connection points.

Example:

>>> from draftsman.entity import *
>>> Beacon().dual_circuit_connectable
False
>>> Inserter().dual_circuit_connectable
False
>>> DeciderCombinator().dual_circuit_connectable
True
property dual_power_connectable : bool

Whether or not this EntityLike has two power connection points.

Example:

>>> from draftsman.entity import *
>>> Beacon().dual_power_connectable
False
>>> ElectricPole().dual_power_connectable
False
>>> PowerSwitch().dual_power_connectable
True
entities : EntityList

Serialized

This attribute is imported/exported from blueprint strings.

The list containing this collection’s entities.

Supports inserting/appending new entities via a string name, as well as any keyword arguments to pass to that entity’s constructor:

blueprint.entities.append("wooden-chest", bar=10)
assert type(blueprint.entities[-1]) is Container
assert blueprint.entities[-1].name == "wooden-chest"
assert blueprint.entities[-1].bar == 10

In addition to indexing by integer location, EntityList also supports indexing via string, corresponding to the id of the entity:

blueprint.entities.insert(0, "wooden-chest", id="example")
assert blueprint.entities["example"] is blueprint.entities[0]
extra_keys : dict[str, Any] | None

Serialized

This attribute is imported/exported from blueprint strings.

Any additional keys that are not recognized by Draftsman when loading from a raw JSON dictionary end up as keys in this attribute. Under normal circumstances, this field should always remain None, indicating that all fields provided were properly translated into the internal Python format.

If there are any values in extra_keys after being imported from a raw JSON dictionary, then (left alone) these values will also be exported back into an output JSON dictionary in order to keep import-export cycles stable. A side effect of this is that users can use this attribute to add additional fields that will end up in the output string, primarily for custom metadata that can be read by other tools:

>>> input_dict = {
...    "name": "wooden-chest",
...    "position": {"x": 0.5, "y": 0.5},
...    "unknown_key": "blah"
... }
>>> container = Container.from_dict(input_dict)
>>> container.extra_keys
{"unknown_key": "blah"}
>>> container.extra_keys["custom"] = "data"
>>> container.to_dict()
{
    "name": "wooden-chest",
    "position": {"x": 0.5, "y": 0.5},
    "unknown_key": "blah",
    "custom": "data"
}

The structure of input keys are preserved, meaning you may have to recurse through keys to find the unknown data:

>>> input_dict = {
...     "name": "wooden-chest",
...     "position": {"x": 0.5, "y": 0.5},
...     "nested": {
...         "dictionary": "value"
...     }
... }
>>> container = Container.from_dict(input_dict)
>>> container.extra_keys
{"nested": {"dictionary": "value"}}

Note

While Draftsman makes an effort to preserve keys that it doesn’t recognize, Factorio itself makes no such effort - so if you create a blueprint string with custom metadata and then import it into the game, that additional data will be stripped and cannot be retrieved when exporting a new string from the game.

property flags : set[str]

The set of flags associated with this EntityLike. Returns None if the entitylike is not recognized by Draftsman.

property flippable : bool

Whether or not this collection can be flipped or not. This is determined by whether or not any of the entities contained can be flipped or not. Read only.

property global_position : Vector

The “global”, or root-most position of the Group. This value is always equivalent to position, unless the group exists inside another Collection. If it does, then it’s global position is equivalent to the sum of all parent positions plus it’s own position. Used when recursing the position of any sub-entity contained within the Group. Read only.

groups : CollectionList

A list of child Group objects that this collection contains.

Like EntityList, Groups added to this list with populated IDs can be accessed via those IDs:

>>> from draftsman.blueprintable import Blueprint, Group
>>> blueprint = Blueprint()
>>> new_group = Group(id="something")
>>> blueprint.groups.append(new_group)
Group(...)
>>> assert blueprint.groups["something"] == new_group

This attribute is not exported. Instead, all entities/tiles that are contained within it are “flattened” to the root-most entity/tile lists, with their positions and associations preserved.

Added in version 3.0.0.

id : str | None

The ID of the Group. The most local form of identification between Groups.

name : str

The name of the Group. Defaults to "group". Can be specified to any string to aid in organization and querying.

parameters : list[IDParameter | NumberParameter]

Serialized

This attribute is imported/exported from blueprint strings.

A list of all Parameter s that this blueprint implements.

Parameters are evaluated sequentially from the beginning of the list to the end.

Added in version 3.1.0: (Factorio 2.0)

property parent : Collection | None

The parent Collection object that contains the entity, or None if the entity does not currently exist within an Collection.

position : Vector

The position of the Group. Acts as the origin of all the entities contained within, and offsets them on export.

property power_connectable : bool

Whether or not this EntityLike can be connected using power wires.

Example:

>>> from draftsman.entity import *
>>> Beacon().power_connectable
False
>>> ElectricPole().power_connectable
True
>>> PowerSwitch().power_connectable
True
property rotatable : bool

Whether or not this collection can be rotated or not. Included for posterity; always returns True, even when containing entities that have no direction component. Read only.

schedules : ScheduleList

Serialized

This attribute is imported/exported from blueprint strings.

A list of the Collections’s Schedule s.

stock_connections : list[StockConnection]

Serialized

This attribute is imported/exported from blueprint strings.

A list of connections between train cars, documenting exactly which ones are connected to what. Prior to Factorio 2.0, train car connections were inferred and automatically generated on blueprint import; this field allows for manual control over this behavior.

Added in version 3.0.0: (Factorio 2.0)

tiles : TileList

Serialized

This attribute is imported/exported from blueprint strings.

The list containing this collection’s tiles.

Supports inserting/appending new tiles via a string name, as well as any keyword arguments to pass to that entity’s constructor:

blueprint.tiles.append("landfill")
assert type(blueprint.tiles[-1]) is Tile
assert blueprint.tiles[-1].name == "landfill"
type : str

The type of the Group. Defaults to "group". Can be specified to any string to aid in organization and querying.

wires : list[list[Association, WireConnectorID, Association, WireConnectorID]]

Serialized

This attribute is imported/exported from blueprint strings.

A list of all the wire connections in this blueprint.

Wires are specified as two pairs of Association and WireConnectorID; the first pair represents the first entity, and the second pair represents the second entity. The association points to the corresponding entity in this collection, and the wire type enum indicates what type of connection it is.

When exported to JSON, the associations and enums in each wire are resolved to integers corresponding to the given entity_number in the resulting entities list.

Added in version 3.0.0: (Factorio 2.0)

add_circuit_connection(
color: 'red' | 'green',
entity_1: EntityLike | int | str | Sequence[int | str],
entity_2: EntityLike | int | str | Sequence[int | str],
side_1: 'input' | 'output' = 'input',
side_2: 'input' | 'output' = 'input',
) None

Adds a circuit wire connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the entities list, or it’s string ID. Color specifies the color of the wire to make the connection with, and is either "red" or "green". side1 specifies which side of the first entity to connect to (if applicable), and side2 specifies which side of the second entity to connect to (if applicable). Does nothing if the connection already exists.

Raises ConnectionSideWarning if the side of either of the entities is 2 when the entity is not dual-circuit-connectable.

Raises ConnectionRangeWarning if the distance between the two entities exceeds the maximum wire distance between the two.

Parameters:
color: 'red' | 'green'

Color of the wire to make the connection with. Must be either "red" or "green".

entity_1: EntityLike | int | str | Sequence[int | str]

ID or index of the first entity to join.

entity_2: EntityLike | int | str | Sequence[int | str]

ID or index of the second entity to join.

side_1: 'input' | 'output' = 'input'

Which side of entity_1 to connect to. Only necessary to specify for entities that are Entity.dual_circuit_connectable.

side_2: 'input' | 'output' = 'input'

Which side of entity_2 to connect to. Only necessary to specify for entities that are Entity.dual_circuit_connectable.

Raises:
add_power_connection(
entity_1: EntityLike | int | str | Sequence[int | str],
entity_2: EntityLike | int | str | Sequence[int | str],
side_1: 'input' | 'output' = 'input',
side_2: 'input' | 'output' = 'input',
) None

Adds a copper wire power connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the entities list, or it’s string ID. Tuples of strings and ints mean to recursively search through the Collection ‘s groups for an entity at that tree “path”. For example:

blueprint.entities.append("small-electric-pole")
group = Group("group") # A type of `Collection`
group.entities.append("small-electric-pole", tile_position=(5, 0))
blueprint.groups.append(group)

# Add a connection between the first power pole and the first entity
# in the group
blueprint.add_power_connection(blueprint.entities[0], ("group", 0))

Side specifies which side to connect to when establishing a connection to a dual-power-connectable entity (usually a power-switch). Does nothing if the connection already exists.

Raises ConnectionRangeWarning if the distance between the two entities exceeds the maximum wire distance between the two.

Raises TooManyConnectionsWarning if either of the power poles exceed 5 connections when this connection is added.

Parameters:
entity_1: EntityLike | int | str | Sequence[int | str]

EntityLike, ID, or index of the first entity to join.

entity_2: EntityLike | int | str | Sequence[int | str]

EntityLike, ID or index of the second entity to join.

side_1: 'input' | 'output' = 'input'

Which side of entity_1 to connect power to. Only necessary to specify for entities that are Entity.dual_power_connectable.

side_2: 'input' | 'output' = 'input'

Which side of entity_2 to connect power to. Only necessary to specify for entities that are Entity.dual_power_connectable.

Raises:
  • KeyError, IndexError – If entity_1 and/or entity_2 are invalid ID’s or indices to the parent Collection.

  • InvalidAssociationError – If entity_1 and/or entity_2 are not inside the parent Collection.

  • EntityNotPowerConnectableError – If either entity_1 or entity_2 do not have the capability to be copper wire connected.

  • DraftsmanError – If both entity_1 and entity_2 are dual-power-connectable, of which a connection is forbidden.

add_train_at_position(
config: TrainConfiguration,
position: Vector | tuple[int | float, int | float],
direction: Direction,
schedule: Schedule | None = None,
) None

Adds a train with a specified configuration and schedule at a position facing a particular direction. Allows you to place a fully configured train in a single function call.

If schedule is specified, then it’s checked if that schedule already exists within the collection’s schedules. If found, all the locomotives in the added train are added to that schedule’s locomotives; if not, a new schedule is appended to the list and the locomotives are added to that entry instead.

Parameters:
config: TrainConfiguration

The TrainConfiguration to use as a template for the created train, or a str that will be converted into one.

position: Vector | tuple[int | float, int | float]

A Vector specifying the center of the starting wagon.

direction: Direction

A Direction enum or int specifying which direction the train is “facing”.

schedule: Schedule | None = None

A Schedule object specifying the schedule that the newly created train should inherit.

add_train_at_station(
config: TrainConfiguration,
station: EntityLike | str | int,
schedule: Schedule | None = None,
) None

Adds a train with a specified configuration and schedule behind a specified train stop.

If schedule is specified, then it’s checked if that schedule already exists within the collection’s schedules. If found, all the locomotives in the added train are added to that schedule’s locomotives; if not, a new schedule is appended to the list and the locomotives are added to that entry instead.

Parameters:
config: TrainConfiguration

The TrainConfiguration to use as a template for the created train, or a str that will be converted into one.

station: EntityLike | str | int

The ID or index of the train entity stop to spawn behind. Note that station names cannot be used; if you want to place a train behind a stop with a specific station name use find_entities_filtered() to find candidates and then pick ones from there.

schedule: Schedule | None = None

A Schedule object specifying the schedule that the newly created train should inherit.

find_entities(
aabb: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None = None,
) list[EntityLike]

Returns a list of all entities within the area aabb. Works similiarly to LuaSurface.find_entities. If no aabb is provided then the method simply returns all the entities in the blueprint.

Parameters:
aabb: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None = None

An AABB, or a Sequence of 4 floats, usually a list or tuple.

Returns:

A regular list of EntityLikes whose collision_box overlaps the queried AABB.

find_entities_filtered(
position: Vector | None = None,
radius: float | None = None,
area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None = None,
name: str | set[str] | None = None,
type: str | set[str] | None = None,
direction: Direction | None = None,
invert: bool = False,
limit: int | None = None,
) list[EntityLike]

Returns a filtered list of entities within the Collection. Works similarly to LuaSurface.find_entities_filtered.

Keywords are organized into two main categrories: region and criteria:

Region keywords

Name

Type

Description

position

Vector or PrimitiveVector

Grid position to search.

radius

float

Radius of the circle around position to search.

area

AABB or PrimitiveAABB

AABB to search in.

If none of the above are specified, then the search area becomes the entire Collection. If radius is specified but position is not, the search area also becomes the entire Collection.

Criteria keywords

Name

Type

Description

name

str or set{str}

The name(s) of the entities that you want to search for.

type

str or set{str}

The type(s) of the entities that you want to search for.

direction

Direction or set{Direction}

The direction(s) of the entities that you want to search for.
Excludes entities that have no direction.

limit

int

Limit the maximum size of the returned list to this amount.
Unlimited by default.

invert

bool

Whether or not to return the inverse of the search.
False by default.
Parameters:
position: Vector | None = None

The global position to search the source Collection. Can be used in conjunction with radius to search a circle instead of a single point. Takes precedence over area.

radius: float | None = None

The radius of the circle centered around position to search. Must be defined alongside position in order to search in a circular area.

area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None = None

The AABB or PrimitiveAABB to search in.

name: str | set[str] | None = None

Either a str, or a set[str] where each entry is a name of an entity to be returned.

type: str | set[str] | None = None

Either a str, or a set[str] where each entry is a type of an entity to be returned.

direction: Direction | None = None

Either a Direction enum (or corresponding int), or a set[Direction] where each entry is a valid direction for each returned entity to match. Excludes entities that have no direction attribute.

invert: bool = False

Whether or not to return the inversion of the search criteria.

limit: int | None = None

The total number of matching entities to return. Unlimited by default.

Returns:

A list of Entity references inside the searched collection that satisfy the search criteria.

find_entity(
name: str,
position: Vector | tuple[int | float, int | float],
) EntityLike

Finds an entity with name at a position position. If multiple entities exist at the queried position, the one that was first placed is returned.

Parameters:
name: str

The name of the entity to look for.

position: Vector | tuple[int | float, int | float]

The position to search, either a PrimitiveVector or a Vector.

Retuns:

The EntityLike at position, or None of none were found.

find_entity_at_position(
position: Vector | tuple[int | float, int | float],
) EntityLike

Finds any entity at the position position. If multiple entities exist at the queried position, the one that was first placed is returned.

Parameters:
position: Vector | tuple[int | float, int | float]

The position to search, either a PrimitiveVector or a Vector.

Retuns:

The EntityLike at position, or None of none were found.

find_tile(
position: Vector | tuple[int | float, int | float],
) list[Tile]

Returns a list containing all the tiles at the tile coordinate position. If there are no tiles at that position, an empty list is returned.

Parameters:
position: Vector | tuple[int | float, int | float]

The position to search, either a PrimitiveVector or a Vector.

Returns:

A list of all tiles at position.

find_tiles_filtered(
position: Vector | tuple[int | float, int | float] | None = None,
radius: float | None = None,
area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None = None,
name: str | None = None,
invert: bool = False,
limit: int | None = None,
) list[Tile]

Returns a filtered list of tiles within the blueprint. Works similarly to LuaSurface.find_tiles_filtered.

Keywords are organized into two main categrories: region and criteria:

Region keywords

Name

Type

Description

position

Vector or PrimitiveVector

Grid position to search.

radius

float

Radius of the circle around position to search.

area

AABB or PrimitiveAABB

AABB to search in.

Criteria keywords

Name

Type

Description

name

str or set{str}

The name(s) of the entities that you want to search for.

limit

int

Limit the maximum size of the returned list to this amount.
Unlimited by default.

invert

bool

Whether or not to return the inverse of the search. False
by default.
Parameters:
position: Vector | tuple[int | float, int | float] | None = None

The global position to search the source Collection. Can be used in conjunction with radius to search a circle instead of a single point. Takes precedence over area.

radius: float | None = None

The radius of the circle centered around position to search. Must be defined alongside position in order to search in a circular area.

area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None = None

The AABB or PrimitiveAABB to search in.

name: str | None = None

Either a str, or a set[str] where each entry is a name of an entity to be returned.

invert: bool = False

Whether or not to return the inversion of the search criteria.

limit: int | None = None

The total number of matching entities to return. Unlimited by default.

Returns:

A list of Tile references inside the searched collection that match the specified criteria.

find_train_from_wagon(
wagon: Locomotive | CargoWagon | FluidWagon | ArtilleryWagon,
) list[Locomotive | CargoWagon | FluidWagon | ArtilleryWagon]

Returns a list of rolling stock connected together. Allows you to grab all connected cars to a particular wagon if you know where one is, such as when iterating through the locomotives in a particular Schedule object, cargo wagons with a particular item filter returned from find_entities_filtered(), etc.

Note that this function may return a working train (rolling stock with at least one connected locomotive), but it also may not, since it’s only criteria is connection.

Warning

This function might also return false positives if rolling stock is located right next to each other in a fully-compresssed rail setups. PR’s to mitigate this are welcome.

Parameters:
wagon: Locomotive | CargoWagon | FluidWagon | ArtilleryWagon

The ID of the wagon or the wagon itself to search for neighbours.

Returns:

A list of references to all connected wagons in the Collection, including wagon itself. The order of wagons is listed from end to end, where the first entry in the list is the outermost car in the direction that wagon points.

find_trains_filtered(
train_length: int | tuple | None = None,
orientation: Orientation | None = None,
at_station: bool | set = False,
num_type: dict | None = None,
num_name: dict | None = None,
config: TrainConfiguration | None = None,
schedule: Schedule | None = None,
invert: bool = False,
limit: int | None = None,
) list[list[EntityLike]]

Finds a set of trains that match the passed in parameters. Formally, a “train” in this context is a connected set of wagons which may or may not contain a locomotive. This is done so that the user can search a blueprint for unconnected rolling stock if any exists, and can filter for regular trains more broadly.

Note

When using the config parameter, equality is strictly checked; which means that if a returned train doesn’t _exactly_ match the specified argument, the train is filtered from the result. This includes things like fuel requests and cargo wagon item filters, so check these values in the blueprints you’re searching and adjust config accordingly.

Parameters:
train_length: int | tuple | None = None

Can either be specified as an int representing the exact length of trains to return, or as a Sequence of 2 int``s representing the minimum and maximum length of trains to return (inclusive). Either the min or the max can also be set to ``None which indicates no minimum length and no maxiumum length respectively.

orientation: Orientation | None = None

A Orientation (or equivalent float) that describes the orientation that every car in the returned train list should have. Note that trains placed on curved rails will not be returned by this parameter, as _all_ train cars must equal orientation.

at_station: bool | set = False

Can be specified as a bool value which will return all trains at any station, a str value where it will return all trains at any station with that name, or as a set[str] where all of the trains behind any station with one of those names is returned.

num_type: dict | None = None

A dict of wagon types where each key is the str type of the wagon and the value is an int representing the desired number of those wagons in the returned train. Allows to search for trains of a particular composition without regards to contents, order, or orientation. Also supports swapping the int with a Sequence of 2 int``s representing the minimum and maximum tolerable value of a wagon of that type, along with ``None for no particular min or max.

num_name: dict | None = None

Identical to num_type, except that instead of wagon type it’s wagon name, in case there happen to be more than one Locomotive, CargoWagon, FluidWagon, or ArtilleryWagon. Useful for blueprints with modded trains, where you might want to distinguish between them.

config: TrainConfiguration | None = None

A TrainConfiguration object to filter against. Performs a equality check between each of the train configuration’s cars and the cars in the returned trains.

schedule: Schedule | None = None

A Schedule that the returned trains should match. Only trains who’s schedules match this one exactly will be returned.

invert: bool = False

Whether or not to return the inversion of the search criteria.

limit: int | None = None

A maximum number of unique trains to return.

Returns:

A list of list s, where each sub-list represents a contiguous train. Trains are ordered such that the first index is the “front” of the train, as chosen by the orientation of the first found wagon in that group.

flip(direction: 'horizontal' | 'vertical' = 'horizontal') None

Flip the blueprint across an axis, if possible. Flipping is done over the x or y axis, depeding on the input direction.

Parameters:
direction: 'horizontal' | 'vertical' = 'horizontal'

The direction to flip by; either "horizontal" or "vertical"

classmethod from_dict(
d: dict,
version: tuple[int, ...] | None = None,
) Self

Attempts to construct a new instance of this class from a Python dictionary in JSON format.

Parameters:
d: dict

The dictionary to interpret.

version: tuple[int, ...] | None = None

The Factorio version that the input data is compliant with.

The given version tuple will automatically attempt to grab the closest applicable converter - meaning that specifying a version of (1, 1, 96) will use the 1.0 converter, and a version of (2, 0, 32) will use the 2.0 converter.

If no version is provided, it will default to current environment’s Factorio version, or to draftsman.DEFAULT_FACTORIO_VERSION if unable to read the current environment.

classmethod from_string(string: str)

Creates a Group with the contents of a Blueprint string.

Raises UnknownKeywordWarning if there are any unrecognized keywords in the blueprint string for this particular blueprintable.

Parameters:
string: str

Factorio-encoded blueprint string.

Raises:
generate_power_connections(
prefer_axis: bool = True,
only_axis: bool = False,
) None

Automatically create power connections between all electric poles.

The algorithm used is similar to demi-pixel’s generateElectricalConnections() function, but with some slight differences. Power poles are still prioritized closest first, but can be selected to prefer to connect neighbours on the same axis, as well as only connect to neighbours on the same axis. This function will only connect power poles that have less than 5 power connections already made, preserving power connections that were manually specified. This function does not generate connections between power-switches.

Parameters:
prefer_axis: bool = True

Determines whether or not to rank power-poles on the same x or y coordinate higher than poles that are closer, but not on either axis. Used to prefer creating neat, regular grids when possible.

only_axis: bool = False

Removes any neighbour that does not lie on the same x or y axis from the candidate pool, preventing non-grid connections.

get() list[Entity]

Gets all the child-most Entity instances in this Group and returns them as a “flattened” 1-dimensional list. Offsets all of their positions by the position of the parent Group.

Returns:

A list of Entity instances associated with this Group.

get_world_bounding_box() AABB | None

Gets the world-space coordinates AABB that completely encompasses the collision_set of this SpatialLike. Returns None if the collision set of the target object is unknown.

get_world_collision_set() CollisionSet

Get’s the world-space coordinate CollisionSet of the object, AKA the collection of all shapes that this EntityLike interacts with.

Returns:

A copy of this objects CollisionSet with the correct world-space location.

mergable_with(other: EntityLike) bool

Checks to see if an entity is “mergable” with another entity. This means that if a certain set of criteria is met, the attributes of other will be combined to the attributes of this entity. This is useful for mimicking cases where entities of the same name and type are placed on top of each other, merging them together into a single entity with shared attributes.

For the full list of all merging rules, see (TODO).

Note

This function does not actually merge the two, it simply checks to see if such a merge is considered valid. To actually merge the two entities use merge().

Parameters:
other: EntityLike

The other EntityLike to check against.

Returns:

True if they can be merged, False otherwise.

merge(other: EntityLike)

Changes the attributes of the calling entity with the attributes of the passed in entity. The attributes of other take precedence over the attributes of the calling entity. They can be either copied or merged together, depending on the specific attribute being merged.

For the full list of all merging rules, see (TODO).

Parameters:
other: EntityLike

The other EntityLike to merge with.

remove_circuit_connection(
color: 'red' | 'green',
entity_1: EntityLike | int | str | Sequence[int | str],
entity_2: EntityLike | int | str | Sequence[int | str],
side_1: 'input' | 'output' = 'input',
side_2: 'input' | 'output' = 'input',
) None

Removes a circuit wire connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the entities list, or it’s string ID. side1 specifies which side of the first entity to remove the connection from (if applicable), and side2 specifies which side of the second entity to remove the connection from (if applicable). Does nothing if the specified connection doesn’t exist.

Parameters:
color: 'red' | 'green'

Color of the wire to remove. Either "red" or "green".

entity_1: EntityLike | int | str | Sequence[int | str]

ID or index of the first entity to remove the connection to.

entity_2: EntityLike | int | str | Sequence[int | str]

ID or index of the second entity to remove the connection to.

side_1: 'input' | 'output' = 'input'

Which side of entity_1 to remove the connection from. Only necessary to specify for entities that are Entity.dual_circuit_connectable.

side_2: 'input' | 'output' = 'input'

Which side of entity_2 to remove the connection from. Only necessary to specify for entities that are Entity.dual_circuit_connectable.

Raises:
  • KeyError, IndexError – If entity_1 and/or entity_2 are invalid ID’s or indices to the parent Collection.

  • InvalidAssociationError – If entity_1 and/or entity_2 are not inside the parent Collection.

remove_circuit_connections() None

Remove all circuit connections in the Collection. Recurses through all subgroups and removes circuit connections from them as well. Does nothing if there are no circuit connections in the Collection to remove.

remove_power_connection(
entity_1: EntityLike | int | str | Sequence[int | str],
entity_2: EntityLike | int | str | Sequence[int | str],
side_1: 'input' | 'output' = 'input',
side_2: 'input' | 'output' = 'input',
) None

Removes a copper wire power connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the entities list, or it’s string ID. side specifies which side to remove the connection from when removing a connection to a dual-power-connectable entity (usually a power-switch). Does nothing if the specified connection does not exist.

Parameters:
entity_1: EntityLike | int | str | Sequence[int | str]

EntityLike, ID or index of the first entity to remove the connection to.

entity_2: EntityLike | int | str | Sequence[int | str]

EntityLike, ID or index of the second entity to remove the connection to.

side_1: 'input' | 'output' = 'input'

Which side of entity_1 to remove a power connection from. Only necessary to specify for entities that are Entity.dual_power_connectable.

side_2: 'input' | 'output' = 'input'

Which side of entity_2 to remove a power connection from. Only necessary to specify for entities that are Entity.dual_power_connectable.

Raises:
  • KeyError, IndexError – If entity_1 and/or entity_2 are invalid ID’s or indices to the parent Collection.

  • InvalidAssociationError – If entity_1 and/or entity_2 are not inside the parent Collection.

remove_power_connections() None

Remove all power connections in the Collection, including any power connections between power switches. Recurses through any subgroups, and removes power connections from them as well. Does nothing if there are no power connections in the Collection.

remove_train(cars: list[EntityLike]) None

Removes all of the rolling stock specified as the list cars, and also takes care of removing any locomotive associations in any corresponding Schedule object(s). Does nothing if cars is empty.

Parameters:
cars: list[EntityLike]

A list of references to EntityLike s within the collection.

Raises:

KeyError – If the specified entities within the list do not exist within the collection being accessed.

rotate(angle: int)

Rotate the blueprint by angle, if possible. Operates the same as pressing ‘r’ with a blueprint selected.

angle is specified in terms of Direction enum, meaning that a rotation of 4 is 90 degrees clockwise.

Because eight-way rotatable entities exist in a weird gray area, this function behaves like the feature in-game and only rotates on 90 degree intervals. Attempting to rotate the blueprint an odd amount raises an RotationError.

Parameters:
angle: int

The angle to rotate the blueprint by.

Raises:

RotationError – If the rotation is attempted with an odd value.

set_train_schedule(
train_cars: Locomotive | list[Locomotive | CargoWagon | FluidWagon | ArtilleryWagon],
schedule: Schedule | None,
) None

Sets the schedule of a particular locomotive, or an entire list of RollingStock. The list of rolling stock can include non-locomotive cars, they will just be skipped when setting schedules. The list of rolling stock can also include locomotives across multiple trains; in this case all connected train cars from every touched train will be given the new schedule. If schedule is set to None, then any touched locomotive will have their schedule cleared instead of set.

Parameters:
train_cars: Locomotive | list[Locomotive | CargoWagon | FluidWagon | ArtilleryWagon]

The single Locomotive, or a list of RollingStock.

schedule: Schedule | None

The Schedule to give each connected train, or None to remove the schedule from each connected train.

to_dict(
version: tuple[int, ...] | None = None,
exclude_none: bool = True,
exclude_defaults: bool = True,
) dict

Export this object to a JSON dictionary, usually directly prior to encoding into the compressed blueprint string format.

Parameters:
version: tuple[int, ...] | None = None

Which Factorio version format this entity should be exported with. The same Draftsman object can be converted to many version-specific output dictionaries, each of which may have different structures.

The given version tuple will automatically attempt to grab the closest applicable converter - meaning that specifying a version of (1, 1, 96) will use the 1.0 converter, and a version of (2, 0, 32) will use the 2.0 converter.

If no version is provided, it will default to current environment’s Factorio version, or to draftsman.DEFAULT_FACTORIO_VERSION if unable to read the current environment.

exclude_none: bool = True

Whether or not None properties should be omitted from the output string. For certain properties this option has no effect, as they either must always be present or never be present if None.

exclude_defaults: bool = True

Whether or not to exclude properties that are equivalent to their default values. Including these values in the generated output is redundant as Factorio will populate them automatically, but it is useful to disable for debug/illustation purposes.

translate(x: int, y: int) None

Translates all entities and tiles in the blueprint by x and y. Raises RailAlignmentWarning if the parent class contains double-grid-aligned entities and the translation amount is an odd value on either x or y.

Parameters:
x: int

A number indicating how much to translate along x.

y: int

A number indicating how much to translate along y.

validate(
mode: ValidationMode = ValidationMode.STRICT,
) ValidationResult

Validates the called object against it’s known format.

Example:

>>> import draftsman
>>> from draftsman.constants import ValidationMode
>>> from draftsman.entity import Container
>>> from draftsman.error import DataFormatError
>>> c = Container("wooden-chest")
>>> with draftsman.validators.set_mode(ValidationMode.DISABLED):
...     c.bar = "incorrect"
>>> try:
...     c.validate().reissue_all()
... except DataFormatError as e:
...     print("wrong!")
wrong!
Parameters:
mode: ValidationMode = ValidationMode.STRICT

How strict to be when valiating the object, corresponding to the number and type of errors and warnings returned.

Returns:

A ValidationResult object, which contains all errors and warnings from the validation pass.