Expressions/es

Resumen
Es posible definir propiedades utilizando expresiones matemáticas. En la interfaz gráfica de usuario, los cuadros de giro o campos de entrada que están vinculados a las propiedades contienen un icono azul. Haciendo clic en el icono o escribiendo el signo igual aparece el editor de expresiones para esa propiedad en particular.

Es una expresión matemática que sigue la notación de los operadores y funciones matemáticas estándar, como se describe a continuación. Además, la expresión puede hacer referencia a otras propiedades, y también utilizar condicionales. Los números en una expresión pueden tener una unidad opcional adjunta.

Los número pueden usar ya sea una coma o un punto decimal  para separar los dígitos enteros de los decimales. Cuando se usa el marcador decimal, "debe" ser seguido por al menos un dígito. Por lo tanto, las expresiones y  son inválidas, pero  y  son válidas.

Los operadores y las funciones son conscientes de la unidad y requieren combinaciones válidas de unidades, si se suministran. Por ejemplo, es una expresión válida, mientras que  no lo es (la razón es que una expresión como  probablemente será interpretada como  por los humanos, pero todas las unidades se convierten al sistema métrico internamente, y el sistema no puede adivinar esto). Estas unidades son reconocidas actualmente.

Puedes usar constantes predefinidas y funciones.



Argumentos de la función
Múltiples argumentos a una función pueden estar separados por un punto y coma o una coma seguida por un espacio. En el último caso, la coma se convierte a un punto y coma después de la entrada. Cuando se usa un punto y coma, no es necesario un espacio final.

Los argumentos pueden incluir referencias a las celdas en una hoja de cálculo. Una referencia de celda consiste en la letra mayúscula de fila de la celda seguida de su número de columna, por ejemplo. También se puede hacer referencia a una celda utilizando el alias de la celda, por ejemplo,.



Referencia de objetos
Puede hacer referencia a un objeto por su o por su. En el caso de un, debe estar encerrado en doble símbolos y , como.

Puede referenciar cualquier propiedad de un objeto. Por ejemplo, para referenciar la altura de un Cilindro puede usar o. Para referenciar al objeto mismo use la pseudo propiedad. Por ejemplo, puede usar o.

Para referenciar una lista de objetos use or. Si quiere por ejemplo referenciar una restricción de un croquis use. Si está en el mismo croquis puede omitir su nombre y solo usar. Nota: El índice inicia en 0, por lo que la restricción 17 tiene el índice 16.

Para más información de como referenciar objetos, vea Referencia a los datos CAD.



Constantes soportadas
Las siguientes constantes están soportadas.



Operadores soportados
Los siguientes operadores son soportados.



Funciones soportadas


Funciones matemáticas generales
Las siguientes funciones matemáticas son soportadas:



Funciones trigonométricas
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. ; ;.

Rounding, truncation and remainder functions


Funciones estadísticas/agregadas
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.

The following aggregate functions are supported:

String identification
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 :

String concatenation
Strings can be concatenated using the '+' sign.

Following example will be concatenated to "MYTEXT".

String conversion
Numerical values can be converted to strings with the function:

String formatting
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), 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".

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

Object creation functions
The following objects may be created in expressions using the following functions:

Matrix functions
and can each be represented by a. The following functions all take in a, , or as their first parameter denoted in the table below by. The type of the returned object is the same as the object supplied in the first argument except when using on a, in which case a  will be returned.



Expresiones condicionales
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:

Unidades
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:

Unsupported units
The following commonly used units are not yet supported, for some an alternative is provided:



Caracteres y nombres no válidos
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.

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

For example, the label must be referenced as.

Nombres
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.



Referencia a los datos CAD
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:



Variables globales de todo el documento
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.



Enlace entre documentos
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.



Problemas conocidos / tareas pendientes

 * 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