# Выражения

This page is a translated version of the page Expressions and the translation is 10% complete.
Outdated translations are marked like this.
Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎italiano • ‎polski • ‎português do Brasil • ‎русский

## Обзор

Свойства можно определять с помощью математических выражений. В графическом интерфейсе счетчики или поля ввода, привязанные к свойствам, содержат синий значок . Щелчок по значку или ввод знака равенства = вызывает редактор выражения для этого конкретного свойства.

Выражение FreeCAD - это математическое выражение, следующее за обозначениями стандартных математических операторов и функций, как описано ниже. Кроме того, выражение может ссылаться на другие свойства, а также использовать условные выражения. К числам в выражении может быть добавлена необязательная единица измерения.

В числах, для отделение целых цифр от десятичных, можно использовать запятую ',' или десятичную точку '.'. Когда используется десятичный маркер, за ним должна следовать хотя бы одна цифра. Таким образом, выражения 1.+2. и 1,+2, недопустимы, но 1.0 + 2.0 и 1,0 + 2,0 действительны.

Операторы и функции зависят от единиц измерения и требуют допустимых комбинаций единиц, если таковые имеются. Например, 2mm + 4mm является допустимым выражением, а 2mm + 4 - нет (причина в том, что выражение типа 1in + 4 люди обычно интерпретируют как 1 дюйм + 4 дюйма, но все единицы внутренне преобразуются в систему СИ, и система не может это угадать). В настоящее время распознаются такие единицы.

Вы можете использовать предопределенные константы и функции.

### Function arguments

Multiple arguments to a function may be separated by either a semicolon `;` or a comma followed by a space `, `. In the latter case, the comma is converted to a semicolon after entry. When a semicolon is used, no trailing space is necessary.

Arguments may include references to cells in a spreadsheet. A cell reference consists of the cell's uppercase row letter followed by its column number, for example `A1`. A cell may also be referenced by using the cell's alias instead, for example `Spreadsheet.MyPartWidth`.

### Referencing objects

You can reference an object by its ДанныеName or by its ДанныеLabel. In the case of a ДанныеLabel, it must be enclosed in double `<<` and `>>` symbols, such as `<<Label>>`.

You can reference any numerical property of an object. For example, to reference a Cylinder's height, you may use `Cylinder.Height` or `<<Long_name_of_cylinder>>.Height`.

To reference list objects, use `<<object_label>>.list[list_index]` or `object_name.list[list_index]`. If you want for example to reference a constraint in a sketch, use `<<MySketch>>.Constraints`. If you are in the same sketch you may omit its name and just use `Constraints`.
Note: The index starts with 0, therefore constraint 17 has the index 16.

## Поддерживаемые константы

The following constants are supported:

Constant Description
e Euler's number
pi Pi

## Поддерживаемые операторы

The following operators are supported:

Operator Description
- Subtraction
* Multiplication
/ Floating point Division
% Remainder
^ Exponentiation

## Поддерживаемые функции

### Основные математические функции

The mathematical functions listed below are available.

Trigonometric functions use degree as their default unit. For radian measure, add `rad` following the first value in an expression. So e.g. `cos(45)` is the same as `cos(pi rad / 4)`. Expressions in degrees can use either `deg` or `°`, e.g. `360deg - atan2(3; 4)` or `360° - atan2(3; 4)`. If an expression is without units and needs to be converted to degrees or radians for compatibility, multiply by `1 deg`, `1 °` or `1 rad` as appropriate, e.g. `(360 - X) * 1deg`; `(360 - X) * 1°`; `(0.5 + pi / 2) * 1rad`.
These trigonometric functions are supported:

Function Description Value range
acos(x) Arc cosine -1 <= x <= 1
asin(x) Arc sine -1 <= x <= 1
atan(x) Arc tangent all
atan2(x; y) Arc tangent of x/y all, except y = 0
cos(x) Cosine all
cosh(x) Hyperbolic cosine all
sin(x) Sine all
sinh(x) Hyperbolic sine all
tan(x) Tangent all, except x = n*90 with n = uneven integer
tanh(x) Hyperbolic tangent all
hypot(x; y) Pythagorean addition (hypotenuse). E.g. hypot(4; 3) = 5. x and y > 0
cath(x; y) Given hypotenuse, and one side, returns other side of triangle. E.g. cath(5; 3) = 4. x and y > 0, x >= y

These functions for exponentiation and logarithmization are supported:

Function Description Value range
exp(x) Exponential function all
log(x) Natural logarithm x > 0
log10(x) Common logarithm x > 0
pow(x; y) Exponentiation all
sqrt(x) Square root x >= 0

These functions for rounding, truncation and remainder are supported:

Function Description Value range
abs(x) Absolute value all
ceil(x) Ceiling function, smallest integer value greater than or equal to x all
floor(x) Floor function, largest integer value less than or equal to x all
mod(x; y) Remainder after dividing x by y all, except y = 0
round(x) Rounding to the nearest integer all
trunc(x) Truncation to the nearest integer in the direction of zero all

### Statistical / aggregate functions

Aggregate functions take one or more arguments.

Individual arguments to aggregate functions may consist of ranges of cells. A range of cells is expressed as two cell references separated by a colon `:`, for example `average(B1:B8)` or `sum(A1:A4; B1:B4)`. The cell references may also use cell aliases, for example `average(StartTemp:EndTemp)`.

These aggregate functions are supported:

Function Description Value range
average(a; b; c; ...) Average value of the arguments; same as sum(a; b; c; ...) / count(a; b; c; ...) all
count(a; b; c; ...) Count of the arguments; typically used for cell ranges all
max(a; b; c; ...) Maximum value of the arguments all
min(a; b; c; ...) Minimum value of the arguments all
stddev(a; b; c; ...) Standard deviation of the values of the arguments all
sum(a; b; c; ...) Sum of the values of the arguments; typically used for cell ranges all

### Операции со строками

#### Идентификация строк

Strings are identified in expressions by surrounding them with opening/closing double chevrons (as are labels).

In following example, "TEXT" is recognized as a string : `<<TEXT>>`

#### Объединение строк

Strings can be concatenated using the '+' sign.

Following example `<<MY>> + <<TEXT>>` will be concatenated to "MYTEXT".

#### Форматирование строк

String formatting is supported using the (old) %-style Python way.

All %-specifiers as defined in Python documentation.

As an example, supposing you have a default 10mm-side cube named 'Box' --default FreeCAD naming--, following expression `<<Cube length : %s>> % Box.Length` will expand to "Cube length : 10.0 mm"

A limitation is that only one %-specifier is allowed in string, thus you have to use string concatenation if more than one is needed. With same above situation, expression `<<Cube length is %s>> % Box.Length + << and width is %s>> % Box.Width` will expand to "Cube length is 10.0 mm and width is 10.0 mm".

A FreeCAD sample file using string formatting is available in the forum

### Create function

The following objects may be created in expressions via the `create` function:

• Vector
• Matrix
• Rotation
• Placement

The `create` function passes subsequent arguments to the underlying Python constructor when creating the object.

Various mathematical operations such as multiplication, addition, and subtraction are supported via standard mathematical operators (e.g. `*`, `+`, `-`).

#### Vector

When `create` is passed `<<vector>>` as the 1st argument, the next 3 arguments are the X, Y, and Z coordinates for the `Vector` respectively.

Example:

`create(<<vector>>; 2; 1; 2)`

#### Matrix

When `create` is passed `<<matrix>>` as the 1st argument, the next 16 arguments are the elements for the `Matrix` in row-major order.

Example:

`create(<<matrix>>; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16)`

#### Rotation

When `create` is passed `<<rotation>>` as the 1st argument, there are two ways to create a `Rotation`:

1. Specify an axis vector and a rotation angle.

Example:

`create(<<rotation>>; create(<<vector>>; 0; 1; 0); 45)`

2. Specify 3 rotations about the X, Y, and Z axes as Euler angles.

Example:

`create(<<rotation>>; 30; 30; 30)`

#### Placement

When `create` is passed `<<placement>>` as the 1st argument, there are five ways to create a `Placement`.

These possible combinations are documented in the below table and are based on the Placement API page.

Number of arguments Description
2 `create(<<placement>>; Placement)`
2 `create(<<placement>>; Matrix)`
3 `create(<<placement>>; Base; Rotation)`
4 `create(<<placement>>; Base; Rotation; Center)`
4 `create(<<placement>>; Base; Axis; Angle)`

The following example shows the syntax for creating a `Placement` from a `Base` (vector) and a `Rotation`:

`create(<<placement>>; create(<<vector>>; 2; 1; 2); create(<<rotation>>; create(<<vector>>; 0; 1; 0); 45))`

For readability, you can define vectors and rotations in separate cells, and then reference the cells in your expression.

### Matrix functions

#### mscale

Scale a `Matrix` with a given `Vector`.

`mscale(Matrix; Vector)`

`mscale(Matrix; x; y; z)`

#### minvert

Invert the given `Matrix`, `Rotation`, or `Placement`.

`minvert(Matrix)`

`minvert(Rotation)`

`minvert(Placement)`

### Tuple & list

You can create Python `tuple` or `list` objects via their respective functions.

`tuple(2; 1; 2)`

`list(2; 1; 2)`

## Условные выражения

Conditional expressions are of the form `condition ? resultTrue : resultFalse`. The condition is defined as an expression that evaluates to either `0` (false) or non-zero (true). Note that enclosing the conditional expression in parentheses is currently considered an error.

The following relational operators are defined:

Unit Description
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

## Единицы измерений

Units can be used directly in expressions. The parser connects them to the previous value. So `2mm` or `2 mm` is valid while `mm` is invalid because there is no preceding value.

All values must have a unit. Therefore you must in general use a unit for values in spreadsheets.
In some cases it works even without a unit, for example if you have e.g. in spreadsheet cell B1 just the number `1.5` and refer to it for a pad height. This only works because the pad height predefines the unit `mm` that is used if no unit is given. It will nevertheless fail if you use for the pad height e.g. `Sketch1.Constraints.Width - Spreadsheet.B1` because `Sketch1.Constraints.Width` has a unit and `Spreadsheet.B1` has not.

Units with exponents can directly be entered. So e.g. `mm^3` will be recognized as mm³ and `m^3` will be recognized as m³.

If you have a variable whose name is that of a unit you must put the variable between `<< >>` to prevent it from being recognized as a unit. For example if you have the dimension `Sketch.Constraints.A` it would be recognized as the unit ampere. Therefore you must write it in the expression as `Sketch.Constraints.<<A>>`.

The following units are recognized by the expression parser:

Amount of substance:

Unit Description
mol Mole

Угол:

Единица измерения Описание
° Градус; тоже самое, что и deg
deg Градус; тоже самое, что и °
gon Град
S Угловая секунда
Угловая секунда; тоже самое, что и S
M Минута дуги
Минута дуги; тоже самое, что и M

Current:

Unit Description
mA Milliampere
A Ampere
kA Kiloampere
MA Megaampere

Energy/work:

Unit Description
J Joule
Ws Watt second; alternative to the unit Joule
VAs Volt-ampere-second; alternative to the unit Joule
CV Coulomb-volt; alternative to the unit Joule

Сила:

Единица измерения Описание
mN Миллиньютон
N Ньютон
kN Килоньютон
MN Меганьютон
lbf Фунт-сила(Английская единица)

Length:

Unit Description
nm Nanometer
um Micrometer; alternative to the unit µm
µm Micrometer; alternative to the unit um
mm Millimeter
cm Centimeter
dm Decimeter
m Meter
km Kilometer
mil Thousandth of an inch; alternative to the unit thou
thou Thousandth of an inch; alternative to the unit mil
in Inch; alternative to the unit "
" Inch; alternative to the unit in
ft Foot; alternative to the unit '
' Foot; alternative to the unit ft
yd Yard
mi Mile

Luminous intensity:

Unit Description
cd Candela

Mass:

Unit Description
ug Microgram; alternative to the unit µg
µg Microgram; alternative to the unit ug
mg Milligram
g Gram
kg Kilogram
t Tonne
oz Ounce
lb Pound; alternative to the unit lbm
lbm Pound; alternative to the unit lb
st Stone
cwt Hundredweight

Power:

Unit Description
W Watt
VA Volt-ampere

Pressure:

Unit Description
Pa Pascal
kPa Kilopascal
MPa Megapascal
GPa Gigapascal
uTorr Microtorr; alternative to the unit µTorr
µTorr Microtorr; alternative to the unit uTorr
mTorr Millitorr
Torr Torr; 1 Torr = 133.32 Pa
psi Pound-force per square inch; 1 psi = 6.895 kPa
ksi Kilopound-force per square inch

Temperature:

Unit Description
uK Microkelvin; alternative to the unit µK
µK Microkelvin; alternative to the unit uK
mK Millikelvin
K Kelvin

Time:

Unit Description
s Second
min Minute
h Hour

Volume:

Unit Description
l Liter

The following commonly used units are not yet supported:

Unit Description Alternative
°C Celsius [°C] + 273.15 K
°F Fahrenheit; ([°F] + 459.67) × ​5/9
u Atomic mass unit; alternative to the unit Da 1.66053906660e-27 kg
Da Dalton; alternative to the unit u 1.66053906660e-27 kg
lm Lumen not directly
lx Lux not directly
px Pixel not directly

## Invalid characters and names

The expression feature is very powerful but to achieve this power it has some limitations concerning some characters. To overcome this, FreeCAD offers to use labels and reference them instead of the object names. In labels you can use almost all special characters.

In cases where you cannot use a label, such as the name of a sketch's constraints, you must be aware what characters are not allowed.

### Labels

For labels there are no invalid characters, however some characters need to be escaped:

Characters Description
`'`, `\`, `"` Need to be escaped by adding `\` in front of them.

For example, the label `Sketch\002` must be referenced as `<<Sketch\\002>>`.

### Names

Names of objects like dimensions, sketches, etc. may not have the characters or character sequences listed below, otherwise the name is invalid:

Characters / Character sequences Description
+, -, *, /, ^, _, <, >, (, ), {, }, [, ], ., ,, = Characters that are math operators or part of mathematical constructs
A, kA, mA, MA, C, G, F, uF, µF, J, K, ' , ft , °, and many more! Characters and character sequences that are units
#, !, ?, §, \$, %, &, :, ;, \, |, ~, , ¿, and many more! Characters used as placeholder or to trigger special operations
pi, e Mathematical constants
´, `, ' , " Characters used for accents
space A space defines the end of a name and can therefore not be used

For example, the following name is valid: `<<Sketch>>.Constraints.T2üßµ@`. While these are invalid names: `<<Sketch>>.Constraints.test\result_2` (\r means "carriage return") or `<<Sketch>>.Constraints.mol` (mol is a unit).

Since shorter names (especially if they have only one or two characters) can easily result in invalid names, consider using longer names and/or establishing a suitable naming convention.

### Cell aliases

For spreadsheet cell aliases only alphanumeric characters and underscores (`A` to `Z`, `a` to `z`, `0` to `9` and `_`) are allowed.

It is possible to use data from the model itself in an expression. To reference a property use`object.property`. If the property is a compound of fields, the individual fields can be accessed as `object.property.field`.

The following table shows some examples:

CAD data Call in expression Result
Parametric Length of a Part-Workbench Cube `Cube.Length` Length with units mm
Volume of the Cube `Cube.Shape.Volume` Volume in mm³ without units
Type of the Cube-shape `Cube.Shape.ShapeType` String: Solid
Label of the Cube `Cube.Label` String: Label
x-coordinate of center of mass of the Cube `Cube.Shape.CenterOfMass.x` x-coordinate in mm without units
Value of constraint in a sketch `Constraints.Width` Numeric value of the named constraint `Width` in the sketch, if the expression is used in the sketch itself.
Value of constraint in a sketch `MySketch.Constraints.Width` Numeric value of the named constraint `Width` in the sketch, if the expression is used outside of the sketch.
Value of a spreadsheet alias `Spreadsheet.Depth` Value of the alias `Depth` in the spreadsheet `Spreadsheet`
Value of a local property `Length` Value of the ДанныеLength property in e.g a Pad object, if the expression is used in e.g ДанныеLength2 in the same object.

## Document-wide global variables

There is no concept of global variables in FreeCAD at the moment. Instead, arbitrary variables can be defined as cells in a spreadsheet using the Spreadsheet workbench, and then be given a name using the alias property for the cell (right-click on cell). Then they can be accessed from any expression just as any other object property.

It is possible (with limitations) to define a Property of an object in your current document (".FCstd" file) by using an Expression to reference a Property of an object contained in a different document (".FCstd" file). For example, a cell in a spreadsheet or the ДанныеLength of a Part Cube, etc. in one document can be defined by an Expression that references the X Placement value or another Property of an object contained in a different document.

A document's name is used to reference it from other documents. When saving a document the first time, you choose a file name; this is usually different from the initial default "Unnamed1" (or its translated equivalent). To prevent links being lost when the master document is renamed upon saving, it is recommended that you first create the master document, create a spreadsheet inside it, and save it. Subsequently, you can still make changes to the file and its spreadsheet but you should not rename it.

Once the master document with the spreadsheet is created and saved (named), it is safe to create dependent documents. For example, assuming you name the master document `master`, the spreadsheet `modelConstants`, and give a cell an alias-name `Length`, you can then access the value as:

````master#modelConstants.Length`
```

Note: that the master document must be loaded for the values in the master to be available to the dependent document.

Unfortunately, the integrated checker sometimes claims that a valid name doesn't exist. Continue typing anyway. When you have completed the full reference, the OK button will become active.

Of course, it's up to you to load the corresponding documents later when you want to change anything.

## Known issues / remaining tasks

• The dependency graph is based on the relationship between document objects, not properties. This means that you cannot provide data to an object and query that same object for results. For example, even though there are no cyclic dependencies when the properties themselves are considered, you may not have an object which gets its dimensions from a spreadsheet and then display the volume of that object in the same spreadsheet. As a work-around use multiple spreadsheets, one to drive your model and the other for reporting.
• The expression parser does not handle parentheses well, and is unable to properly parse some expressions. For example: `= (A1 > A2) ? 1 : 0` results in an error, while `= A1 > A2 ? 1 : 0` is accepted. The expression `= 5 + ((A1>A2) ? 1 : 0)` cannot be entered in any form.
• As stated above, unfortunately, the integrated checker sometimes claims that a valid name doesn't exist. Continue typing anyway. When you have completed the full reference, the OK button will become active.
• FreeCAD does not yet have a built-in expression manager where all expressions in a document are listed, and can be created, deleted, queried, etc. But an addon is available: fcxref expression manager.
• Open bugs/tickets for Expressions can be found in the FreeCAD Bugtracker Expressions category