Expressions/ru

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

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

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

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

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

Аргументы функции
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. A cell may also be referenced by using the cell's alias instead, for example.

Ссылка на объект в выражении
You can reference an object by its or by its. In the case of a, it must be enclosed in double and  symbols, such as.

You can reference any property of an object. For example, to reference a Cylinder's height, you may use or. To reference the object itself use the pseudo property. For example, you may use or.

To reference list objects, use or. If you want for example to reference a constraint in a sketch, use. If you are in the same sketch you may omit its name and just use. Note: The index starts with 0, therefore constraint 17 has the index 16.

For more information about referencing objects, see Reference to CAD_data.

Поддерживаемые константы
Поддерживаются следующие константные значения:

Поддерживаемые операторы
Поддерживаются следующие операторы:

Основные математические функции
Поддерживаются следующие математические функции:

Функции тригонометрии
Trigonometric functions use degree as their default unit. For radian measure, add following the first value in an expression. So e.g. is the same as. Expressions in degrees can use either or, e.g.  or. If an expression is without units and needs to be converted to degrees or radians for compatibility, multiply by, or  as appropriate, e.g. ; ;.

Функции агрегирования и статистики
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 or. The cell references may also use cell aliases, for example.

Поддерживаются следующие функции агрегирования:

Идентификация строк
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 :

Объединение строк
Строки могут быть объединены с помощью символа "+".

Например строки будут объединены в "МОЙТЕКСТ".

Преобразование числа в строку
Числовые значения могут быть преобразованы в строки с помощью функции :

Форматирование строк
Форматирование строк поддерживается с использованием (старого) Python способа в стиле %.

Сведения о всех %-спецификаторах, можно узнать из документации Python.

As an example, supposing you have a default 10mm-side cube named 'Box' (default FreeCAD naming), the following expression will expand to "Cube length : 10.0 mm"

For more than one %-specifier use the following syntax:. Or use concatenation:. Both will expand to "Cube length is 10.0 mm and width is 10.0 mm".

Пример файла FreeCAD с применением форматирования строк доступен на форуме

Функция Create
С помощью функции в выражениях могут быть созданы следующие объекты :
 * Vector
 * Matrix
 * Rotation
 * Placement

The 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 is passed  as the 1st argument, the next 3 arguments are the X, Y, and Z coordinates for the  respectively.

Example:

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

Пример:

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

1. Specify an axis vector and a rotation angle.

Пример:

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

Пример:

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

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

The following example shows the syntax for creating a from a  (vector) and a :

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

mscale
Scale a with a given.

minvert
Invert the given, , or.

Кортежи и списки
Вы можете создавать Python объекты: кортежи или списки  с помощью соответствующих функций.

Условные выражения
Conditional expressions are of the form. The condition is defined as an expression that evaluates to either (false) or non-zero (true). Note that enclosing the conditional expression in parentheses is currently considered an error.

The following relational operators are defined:

Единицы измерений
Units can be used directly in expressions. The parser connects them to the previous value. So or  is valid while  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 and refer to it for a pad height. This only works because the pad height predefines the unit that is used if no unit is given. It will nevertheless fail if you use for the pad height e.g. because  has a unit and  has not.

Units with exponents can directly be entered. So e.g. will be recognized as mm³ and  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 it would be recognized as the unit ampere. Therefore you must write it in the expression as.

The following units are recognized by the expression parser:

Неподдерживаемые единицы измерения
The following commonly used units are not yet supported, for some an alternative is provided:

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:

For example, the label must be referenced as.

Названия
Names of objects like dimensions, sketches, etc. may not have the characters or character sequences listed below, otherwise the name is invalid:

For example, the following name is valid:. While these are invalid names: (\r means "carriage return") or  (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
See Spreadsheet SetAlias.

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

The following table shows some examples:

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.

Cross-document linking
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 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, the spreadsheet , and give a cell an alias-name , you can then access the value as:

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 button will become active.

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

Известные проблемы / нерешённые задачи

 * 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:   results in an error, while  is accepted.  The expression  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 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