Expressions/it: Difference between revisions

From FreeCAD Documentation
(Replaced content with "==Unità==")
(Created page with "== Espressioni condizionali ==")
Line 210: Line 210:
</div>
</div>


== Conditional Expressions ==
== Espressioni condizionali ==


<div class="mw-translate-fuzzy">
<div class="mw-translate-fuzzy">

Revision as of 21:53, 11 October 2019

Descrizione

È possibile definire le proprietà utilizzando espressioni matematiche. Nella GUI, gli spin box o i campi di input che sono legati alle proprietà contengono un'icona blu File:Sketcher Expressions.png. Cliccando sull'icona, oppure digitando il segno di uguale (=), si porta in primo piano l'editor delle espressioni per quella particolare proprietà.

Una espressione di FreeCAD è un'espressione matematica che segue la notazione per gli operatori matematici standard e le funzioni come descritto in seguito. Inoltre, l'espressione può fare riferimento ad altre proprietà, e anche utilizzare le condizioni. I numeri di un'espressione possono opzionalmente essere collegati ad una unità di misura.

Numbers may use either a comma ',' or a decimal point '.' separating whole digits from decimals. When the decimal marker is used, it must be followed by at least one digit. Thus, the expressions 1.+2. and 1,+2, are invalid, but 1.0 + 2.0 and 1,0 + 2,0 are valid.

Gli operatori e le funzioni sono unit-aware (consapevoli delle unità), e richiedono combinazioni di unità valide, se sono fornite. Ad esempio, 2mm + 4mm è un'espressione valida, mentre 2mm + 4 non lo è (il motivo di questo è che un'espressione come 1in + 4 molto probabilmente viene interpretata come 1in + 4in da un umano, ma tutte le unità vengono convertite nel sistema SI interno, e il sistema non è in grado di indovinare questo). Queste unità sono attualmente riconosciute.

You can use predefined constants and functions.

Referencing objects

You can reference to 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 this object. For example, to refer to a Cylinder's height, you may use Cylinder.Height or <<Long_name_of_cylinder>>.Height.

To reference list objects, the syntax is object_name.list[list_index]. If you want for example reference a constraint in a sketch, hover with the mouse over this constraint and look in the footer of FreeCAD's main window. Assuming you see there Sketch_name.Constraint17, then you reference it this way: Sketch_name.Constraints[16] (The index starts with 0, therefore constraint 17 has the index 16.) If you are in the same sketch you can omit its name and just use Constraints[16].

For more info about referencing objects, see this section.

Supported Operators

The following operators are supported:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponentiation

Quando una funzione accetta più argomenti, questi possono essere separati da un punto e virgola (';') o da una virgola seguita da uno spazio (", "). In quest'ultimo caso, la virgola viene convertita in un punto e virgola dopo la voce. Quando si utilizza un punto e virgola, non è necessario terminare la riga con uno spazio.

abs(x)

Description: Absolute value

Returns: value >= 0

acos(x)

Description: Arc cosine; -1 <= x <= 1

Returns: acos(x)

asin(x)

Description: Arc sine; -1 <= x <= 1

Returns: asin(x)

atan(x)

Description: Arc tangent

Returns: atan(x)

atan2(y, x)

Description: Arc tangent of y / x;

Returns: atan2(y,x)

ceil(x)

Description: Ceiling

Returns: The smallest integer value greater than or equal to x introduced in version 0.16

cos(angle)

Description: Cosine; angle is in degrees (any value)

Returns: -1 <= cos(x) <= 1

cosh(x)

Description: Hyperbolic cosine of x

Returns: cosh(x)

exp(y)

Description: Natural exponent

Returns: e y

floor(x)

Description: Floor

Returns: The largest integer value less than or equal to x introduced in version 0.16

log(x)

Description: Natural logarithm

Returns: loge x

log10(x)

Description: Logarithm base 10

Returns: log10 x

mod(x, y)

Description: Remainder x/y

Returns: Remainder after dividing x by y

pow(x, y)

Description: Power function

Returns: x y

round(x)

Description:

Returns: x rounded to the nearest integer introduced in version 0.16

sin(angle)

Description: Cosine; angle in degrees (any value)

Returns: -1 <= sin(x) <= 1

sinh(x)

Description: Hyperbolic sine of x

Returns: sinh(x)

sqrt(x)

Description: Square root; x >= 0

Returns: Square root of x

tan(angle)

Description: Tangent; angle in degrees (any value)

Returns: tan(angle)

tanh(x)

Description: Hyperbolic tangent of x

Returns: tanh(x)

trunc(x)

Description: Truncate

Returns: x truncated to the nearest integer introduced in version 0.16

Funzioni Supportate

General Mathematical Functions

Le funzioni matematiche elencate di seguito sono disponibili.

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.

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).
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 of x = n·90 with n = integer
tanh(x) Hyperbolic tangent all

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 all

Statistica / Funzioni di aggregazione

Le funzioni di aggregazione elencate di seguito sono supportate. Le funzioni di aggregazione accettano uno o più argomenti, separati da un punto e virgola ';' o una virgola e uno spazio ", ". Gli argomenti possono includere riferimenti a celle di un foglio di calcolo; i riferimenti alla cella sono costituiti dalla lettera di riga (Maiuscola) seguita dal numero di colonna. Gli argomenti possono includere intervalli di celle (due riferimenti di cella separati da due punti). Esempio: average(B1:B8)

average(x y)

Description: Average of values in cells x through y

Returns: sum(x, y) / count(x, y)

count(x y)

Description: Number of cells from x through y

Returns: The number of cells from x through y, inclusive

max(x y)

Description: Maximum value in cells x through y

Returns: Maximum value

min(x y)

Description: Minimum value in cells x through y

Returns: Minimum value

stddev(x y)

Description: Standard deviation of values in cells x through y

Returns: Standard deviation

sum(x y)

Description: Sum of values in cells x through y

Returns: Sum

Espressioni condizionali

Le espressioni condizionali sono nella forma condition ? resultTrue : resultFalse

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

Unità

Units can directly be used 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³.

Le funzioni trigonometriche usano i gradi come unità predefinita. Per le misurazioni che utilizzano il radiante, aggiungere rad dopo il primo valore angolare nell'espressione. Esempio: cos(45) è equivalente a cos(pi rad/4).

The following units are recognized by the expression parser:

Amount of substance:

Unit Description
mol Mole

Angle:

Unit Description
° Degree; alternative to the unit deg
deg Degree; alternative to the unit °
rad Radian
gon Gradian
S Second of arc
Second of arc; alternative to the unit S
M Minute of arc
Minute of arc; alternative to the unit 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

Force:

Unit Description
mN Millinewton
N Newton
kN Kilonewton
MN Meganewton
lbf Pound of force

Length:

Unit Description
nm Nanometer
um Micrometer; alternative to the unit µm
µm Micrometer; alternative to the unit mu
mm Millimeter
cm Centimeter
mm Millimeter
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
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

Espressioni condizionali

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
psi Pound-force per square inch
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

Torque:

Unit Description
Nm Newton metre

Volume:

Unit Description
l Liter

The following commonly used units are not yet supported:

Unit Description Alternative
C Coulomb 1 A*s
Hz Hertz 1 /s
V Volt 1 W/A
eV Electronvolt 1.602176634e-19 J
kWh Kilowatt hour 3.6e6 J
bar Bar 100 kPa
T Tesla 1 kg/s^2/A
F Farad 1 s^4*A^2/m^2/kg
H Henry 1 kg*m^2/s^2/A^2
u Atomic mass unit; alternative to the unit 'Da' 1.66053906660e-27 kg
Da Dalton; alternative to the unit 'u' 1.66053906660e-27 kg
cal Calorie 4.184 J
sr Steradian not directly
lm Lumen not directly
lx Lux not directly
Mpsi Megapound-force per square inch 1000 ksi

Riferimento ai dati CAD

In un'espressione è possibile utilizzare i dati del modello stesso. Per fare riferimento a una proprietà usare object.property. Se la proprietà è un composto di campi, è possibile accedere ai singoli campi come object.property.field.

La tabella seguente mostra alcuni esempi:

Dati CAD Chiamata nell'espressione Risultato
Lunghezza parametrica di un Cubo di Parte Cube.Length Lunghezza con unità in mm
Volume del Cubo Cube.Shape.Volume Volume in mm³ senza unità
Tipo di forma del Cubo Cube.Shape.ShapeType Stringa: Solid
Etichetta del Cubo Cube.Label Stringa: Label
coordinata x del centro di massa del Cubo Cube.Shape.CenterOfMass.x coordinata x in mm senza unità
Valore di un vincolo in uno schizzo Constraints.Width Valore numerico del vincolo di nome 'Width' nello schizzo, se l'espressione è utilizzata nello schizzo stesso.
Valore di un vincolo in uno schizzo MySketch.Constraints.Width Valore numerico del vincolo di nome 'Width' nello schizzo, se l'espressione è usata al di fuori dello schizzo.
Valore di un alias in spreadsheet Spreadsheet.Depth Valore dell'alias "Depth" nel foglio "Spreadsheet"
Valore di una proprietà locale Length Valore della proprietà Length, ad es. di un oggetto Pad, oppure Length2 nello stesso oggetto se l'espressione è già usata.

Variabili globali nell'ambito del documento

Al momento in FreeCAD non esiste il concetto di variabili globali. Invece, utilizzando l'ambiente Spreadsheet, si possono definire delle variabili arbitrarie come celle in un foglio di calcolo, e poi assegnare loro un nome utilizzando la proprietà alias della cella (tasto destro del mouse sulla cella). Dopo si può accedere alla variabile da qualsiasi espressione, come per qualsiasi altra proprietà di un oggetto.

Riferimenti incrociati nel documento

In un documento è possibile fare riferimento a un foglio di calcolo contenuto in un altro documento.

È possibile utilizzare il nome di un documento per fare riferimento ad esso da altri documenti. Quando si salva un documento per la prima volta, si sceglie un nome per il file; questo di solito è diverso dal default iniziale "Unnamed1" (o il suo equivalente tradotto). Per evitare la perdita dei collegamenti quando il documento master viene rinominato al momento del salvataggio, si consiglia di creare prima il documento master, creare un foglio di calcolo al suo interno e salvarlo. Successivamente è ancora possibile apportare modifiche e salvare il file, ma non si deve rinominarlo.

Una volta creato e salvato (e denominato) il documento master con il foglio di calcolo, è possibile creare dei documenti dipendenti. Supponendo che il documento master sia stato denominato "master", il foglio di calcolo sia stato rinominato "modelConstants" e a una cella sia stato assegnato un nome alias "Length", il valore è accessibile come "master#modelConstants.Length". Notare che il documento master deve sempre essere caricato affinché i valori nel master siano disponibili per il documento dipendente.

    master#modelConstants.Length  

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

Purtroppo, il checker integrato a volte afferma che un nome valido non esiste. Continuare comunque a digitare. Quando il riferimento è completato, il pulsante OK diventa attivo.

Naturalmente, dopo spetta all'utente il compito di caricare i documenti corrispondenti, quando si desidera cambiare qualcosa.

Problemi noti / attività rimanenti

  • I grafici delle dipendenze si basano sul rapporto tra gli oggetti del documento, non sulle proprietà. Questo significa che non è possibile fornire i dati a un oggetto e interrogare lo stesso oggetto per i risultati. Ad esempio, anche se non ci sono dipendenze cicliche quando vengono considerate solo le proprietà, non si può avere un oggetto che ottiene le sue dimensioni da un foglio di calcolo e quindi visualizza il volume di tale oggetto nello stesso foglio di calcolo. Per aggirare il problema, utilizzare più fogli di calcolo, ad esempio uno per sviluppare il modello, e uno per i rapporti.
  • Il parser delle espressioni non gestisce bene le parentesi e non è in grado di analizzare correttamente alcune espressioni. Ad esempio: "= (A1 > A2) ? 1 : 0" restituisce un errore, mentre "= A1 > A2 ? 1 : 0" è accettato. L'espressione "= 5 + ((A1>A2) ? 1 : 0)" non può essere inserita in nessuna forma.
  • Non è implementato nessun gestore delle espressioni in cui siano elencate tutte le espressioni di un documento, e possano essere create, eliminate, interrogate, ecc.
  • I nomi dei vincoli di Sketcher non devono contenere spazi vuoti quando il valore è calcolato da un'espressione, vedere questa discussione nel forum.
  • I bug aperti per le espressioni si trovano in FreeCAD Bugtracker Expressions category