PhysicalValues/en: Unterschied zwischen den Versionen

Aus expecco Wiki (Version 2.x)
Zur Navigation springen Zur Suche springen
Zeile 1.007: Zeile 1.007:
|1 inch cubed || => || 16.387064 ml
|1 inch cubed || => || 16.387064 ml
|-
|-
|1 inch cubed asLiters || => || 1.0 cuin
|1 inch cubed asLiters || => || 0.016387064 l
|-
|-
|1 inch cubed asCubicInches || => || 1.0 cuin
|1 inch cubed asCubicInches || => || 1.0 cuin

Version vom 7. Mai 2021, 09:08 Uhr

Notice: the physical values package as described here is considered "work in progress" and provided as a preview feature. Please report any errors or inconveniences (or wishes) to exept.

Starting with version 19.2, expecco supports values with units, to represent physical values such as length, acceleration, area, volume, mass, temperature, electric current etc.

Physical values are useful for a nicer presentation of measurement values (eg. in a report) and to convert between unit systems (eg. metric vs. imperial vs. US). They can also make elementary code which computes physical values more readable.

Physical values are implemented by the underlying Smalltalk system and can be used both in Smalltalk and in JavaScript elementary blocks. Similar public domain packages are available for Node and Python actions - these have to be installed with "npm" or "pip".
There are currently no plans to support exchange of physical value objects transparently with Python, Node or Java actions. If required, these should be passed as { amount: unit: } objects and converted in the bridge as required.

The following document describes the programmer's API for elementary Smalltalk and JavaScript actions.

Inhaltsverzeichnis

Motivating Examples[Bearbeiten]

Example1: Time to Load a Cap[Bearbeiten]

You want to compute how long it takes to load a 100uF capacitor, given a 5V supply and a current limiting resistor with 100 kOhm?

The electric charge (in Coulomb) transported through a wire is:

I*t (I = current in Ampere; t in Seconds)

and the charge (in Coulomb) of a capacitor is:

C*U  (C = capacity in Farad; U = voltage)

We can immediately compute the electrical charge (in Coulomb) with the formula (C*U):

(5 volt * 100 micro farad)

and get the result:

(1/2000) C

We can also compute the current through the loading resistor as:

5 volt / 100 kilo ohm

and get the result:

50 µA

To compute the time, rearrange the above formula:

    (C * U)
t = -------
       I

with I = U / R, we get:

    (C * U)
t = -------
    (U / R)

in Smalltalk (*):

t := (5 volt * 100 micro farad ) / (5 volt / 100 kilo ohm)

and will get the time for t as:

10s

(*) obviously, we could have further simplified the formula;
or ask expecco to simplify it for us:
(Physic::Parser parse:'(U * C) / (U / R)') simplified
which gives the result:C * R

Example2: Bandpass Filter Frequency[Bearbeiten]

A filter's frequency is computed as:

         1  
f = ------------
      2*pi*R*C

What is the frequency, given 1 Megaohm and 0.1 Microfarad as values?
In Smalltalk:

|r c f| 
r := 1 mega ohm.
c := 0.1 micro farad.
f := 1 / (2*Float pi * r * c)

result:

f = 1.59154943091895 Hz

Programming Language API[Bearbeiten]

As you'll have noticed, Smalltalk has a convenient syntax, for this kind of framework: you can immediately write code like "1 kilo meter / 10 minutes" to compute a velocity.

Due to the fact that the builtin Javascript also allows for numbers to be treated like objects, the same code written in JavaScript still looks somewhat readable: "1.kilo().meter() / 10.minutes(), although the parentheses make the code somewhat ugly.

All code fragments in the following document are written in Smalltalk syntax.

Base Units[Bearbeiten]

All base units are measured in their corresponding SI standard units and print with an appropriate scaling prefix.

For example, a mass, which has a base unit of kilogram ("kg") will print itself as "kg', 'mg', 'µg' etc. depending on its magnitude. Explicit converters can be used to enforce a particular unit printing (eg. if you insist on printing a mass in pounds, in grams, etc.). See examples below on how those converters affect the printout of a value.

Base units are:

s	Second	    time
m	Metre	    length
kg	Kilogram    mass
A	Ampere	    electric current
K	Kelvin	    temperature
mol	Mole	    amount of substance
cd	Candela	    luminous intensity

Derived Units[Bearbeiten]

Additional derived units are:

V      Volt                voltage
Hz     Hertz               frequency
m/s    Meter per Second    speed, velocity
m/s²   m/s per Second      acceleration
m²     Square Meter        area
m³     Cubic Meter         volume
pa     Pascal              pressure
W      Watt                power
N      Newton              force
J      Joule               energy
Ω      Ohm                 electric resistance
C      Coulomb             electric charge
F      Farad               electric capacitance

Plus possibly more, by the time you read this.

SI Prefix[Bearbeiten]

Numbers (in Smalltalk and JavaScript) can be scaled by an SI prefix message. For example, without SI prefix:

1 gram -> '1 g'

whereas with a 'micro' prefix:

1 micro gram -> '1 µg'

and:

1 hecto liter -> '100 liter'

The corresponding JavaScript code is similar, but slightly less elegant looking:

1.gram()
1.micro().gram()
1.hecto().liter()

Possible scaling prefixes are:

yocto   1E-24   1 / 1000000000000000000000000 
zepto   1E-21   1 / 1000000000000000000000 
atto    1E-18   1 / 1000000000000000000
femto   1E-15   1 / 1000000000000000
pico    1E-12   1 / 1000000000000
nano    1E-9    1 / 1000000000
micro   1E-6    1 / 1000000
milli   1E-3    1 / 1000
centi   1E-2    1 / 100
deci    1E-1    1 / 10
deca    1E+1    10
hecto   1E+2    100
kilo    1E+3    1000
mega    1E+6    1000000
giga    1E+9    1000000000
tera    1E+12   1000000000000
peta    1E+15   1000000000000000
exa     1E+18   1000000000000000000
zetta   1E+21   1000000000000000000000
yotta   1E+24   1000000000000000000000000

Physic Package Loading[Bearbeiten]

Depending on your expecco version, the physic package (stx:goodies/physic/units) may or may not be already loaded. If not, either add it to the list of required packages of your test suite or evaluate

Smalltalk requirePackage:'stx:goodies/physics/units'

in either an elementary action or in the startup file ("expeccoStart.rc"). All physic classes will be found in the "Physic" namespace (i.e. classes are prefixed with "Physic::").

Unit API[Bearbeiten]

PhysicalValue instances can be created by sending the "unitAmount:" message to a Unit.
For example:

Physic::PhysicalUnit energy unitAmount:100

generates an energy instance of 100 joule.

The argument of the "unitAmount:" call is always given in units of the receiver unit, whereas the alternative constructor named "baseUnitAmount:" expects the argument to be in the underlying base unit (i.e. one of the SI units).

This makes no difference for the base SI units, but is relevant, if you deal with conversion units (eg. imperial units) as described later. Thus,

Physic::PhysicalUnit energy calories unitAmount:100

will create an energy instance of 100 calories (which will print itself as calories), whereas:

Physic::PhysicalUnit energy calories baseUnitAmount:100

will create an energy instance of 100 joule (which will print itself as calories).


Notice, that the "energy" message is a facade getter method of Physic::PhysicalUnit (i.e. the class named "PhysicalUnit" in the "Physic" namespace). It retrieves the Energy class, which is actually named "Physic::Energy" and is also located in the Physic namespace.

Base SI Units[Bearbeiten]

Getters for well known units are:

Physic::PhysicalUnit acceleration
Physic::PhysicalUnit amountOfSubstance
Physic::PhysicalUnit area
Physic::PhysicalUnit currentDensity
Physic::PhysicalUnit electricCapacitance
Physic::PhysicalUnit electricCharge
Physic::PhysicalUnit electricConductance
Physic::PhysicalUnit electricCurrent
Physic::PhysicalUnit electricResistance
Physic::PhysicalUnit energy
Physic::PhysicalUnit force
Physic::PhysicalUnit frequency
Physic::PhysicalUnit inductance
Physic::PhysicalUnit length
Physic::PhysicalUnit luminousIntensity
Physic::PhysicalUnit mass
Physic::PhysicalUnit massDensity
Physic::PhysicalUnit power
Physic::PhysicalUnit pressure
Physic::PhysicalUnit specificVolume
Physic::PhysicalUnit temperature
Physic::PhysicalUnit time
Physic::PhysicalUnit velocity
Physic::PhysicalUnit voltage
Physic::PhysicalUnit volume
 
Physic::PhysicalUnit knownUnits

The last returns a collection of all known units (there are actually more than listed above).

For the most common units, additional instance creation protocol is provided in the Number class (eg. "100 joules" will generate the same as

(Physic::PhysicalUnit energy) baseUnitAmount:100

The additional protocol is described below.

Printing Unit Values[Bearbeiten]

When printed, physical values will scale and use an SI prefix as appropriate.
For example, by default, a value of 100 millimeter will print as "100 mm" instead of "0.1 m" (remember: meter is the underlying SI base unit).

This print behavior can be changed by converting to an explicit unit via one of the "asXXX" messages listed below. However, the SI unit amount will be kept internally and used in arithmetic operations. Thus, eg. when adding a meter with inches, an SI meter value will be generated, and the result will be presented in the same unit as the receiver (first operand).
For example, "1 meter + 1 inch asInches" will print as meter, whereas "1 inch asInches + 1 meter" will print as inches.

Converting Units[Bearbeiten]

In addition to predefined converting units, as listed below, it is also possible to define custom units, with different (customizable) print behavior (more on that below).

Predefined Converting Units[Bearbeiten]

Some such custom units are already predefined; for example, to represent imperial units, conversion units derived from mass are found (among others) as:

Physic::PhysicalUnit mass ounces
Physic::PhysicalUnit mass pounds

and length units as:

Physic::PhysicalUnit length inches
Physic::PhysicalUnit length feet
Physic::PhysicalUnit length yards

Thus, you can create unit values which print themself (eg.) in imperial units:

yardsUnit := Physic::PhysicalUnit length yards.
distance := yardsUnit unitAmount:10

will give you 10 yards, which prints itself as such ("10 yd").

Whereas:

distance2 := yardsUnit baseUnitAmount:10

will create a distance of 10 meters (the underlying base unit), which prints itself in yards.

Be careful to not confuse unit amounts with base unit amounts, and be reminded that the internal storage representation of all units is always in SI base units. The conversion is only performed when such values are printed.


In general, you can ask most base units for common conversion units (which are the units used by the asXXX converters below). These can also be used to instantiate instances or for conversion. Eg.

Physic::PhysicalUnit mass ounces unitAmount:1 

returns 1 ounce (which prints itself as such), and:

1 kiloGram as:(Physic::PhysicalUnit mass ounces)

returns 32.27 ounces (which also prints itself as such).

Mass:[Bearbeiten]
  • Physic::PhysicalUnit mass ounces
    Returns the "Ounces" unit.
  • Physic::PhysicalUnit mass pounds
    Returns the "Pounds" unit.
  • Physic::PhysicalUnit mass troyOunces
    Returns the "TroyOunces" unit.
  • Physic::PhysicalUnit mass carat
    Returns the "Carat" unit.
  • Physic::PhysicalUnit mass atomicMassUnits
    Returns the "AtomicMassUnits" unit.
  • more mass units are returned by: daltons, grams, kiloGrams, kiloTonnes, megaTonnes, milliGrams, microGrams, nanoGrams, tonnes.

You may wonder what the kiloGrams sub unit is useful for, as the base unit's amount is already in kiloGram. The difference is that the base unit will print values with a prefix (milli, micro, kilo etc.) whereas the sub unit will always print kilograms.

AmountOfSubstance:[Bearbeiten]
  • Physic::PhysicalUnit amountOfSubstance particles
    Returns the "Particles" unit.
Area:[Bearbeiten]
  • converting units are returned by: acre, are, hectare, squareFoot, squareKiloMeters, squareMeter, squareMiles.
Electric Charge:[Bearbeiten]
  • converting units are returned by: ampereSeconds, ampereHours.
Energy:[Bearbeiten]
  • converting units are returned by: btu, calories, electronVolts, gigaWattHours, megaWattHours, kiloCalories, kiloJoules, kiloWattHours, megaWattHours.
Force:[Bearbeiten]
  • converting units are returned by: gramForce, newtons, poundForce, tonForce
Frequency:[Bearbeiten]
  • converting units are returned by: kiloHertz, megaHetz, gigahertz.
Length:[Bearbeiten]
  • converting units are returned by: feet, feetAndInches, inches, kiloMeters, landMiles, lightSeconds, lightYears, meters, micrometers, milliMeters, nanoMeters, nauticalMiles, yards.
Power:[Bearbeiten]
  • converting units are returned by: dBW, dBm, gigaWatt, kiloWatt, megaWatt, milliWatt
Pressure:[Bearbeiten]
  • converting units are returned by: bar, hectoPascal, pascal, psi
Temperature:[Bearbeiten]
  • converting units are returned by: celsius, fahrenheit, rankine
Velocity:[Bearbeiten]
  • converting units are returned by: kiloMetersPerHour, knots, metersPerHour, milesPerHour
Volume:[Bearbeiten]
  • converting units are returned by: centiLiters, cubicInches, cubicMeters, fluidOuncesGB, fluidOuncesUS, gallonsGB, gallonsUS, hectoLiters, liters, milliLiters

Per Unit Detailed API[Bearbeiten]

Mass[Bearbeiten]

Mass is measured in units of Kilogram, and the default printing is in "kg", "g", "mg", "ng" or whatever the print function considers appropriate.
The following operations return an instance of a mass (i.e. a value with a unit of "Mass") all of which will print themself as base units:

  • number kiloGram
    Generates a mass-value of n kilograms.
    Same as n kilo gram (using SI prefix).
  • number gram
    Generates a mass-value of n grams.
  • number milliGram
    Generates a mass-value of n milligrams.
    Same as n milli gram.
  • number microGram
    Generates a mass-value of n micrograms.
    Same as n micro gram.
  • number pounds
    Generates a mass-value of n pounds. A pound is defined as 453.59237 gram.
  • number ounces
    Generates a mass-value of n ounces. These are british (imperial) ounces (28.35 g)
  • number troyOunces
    Generates a mass-value of n troy ounces. These are used with metals (esp. gold) (31.1034768 g)

Unit Conversion[Bearbeiten]

  • aMass asGrams
    Returns the original mass in a converted unit which enforces explicit printing in grams (i.e. without any SI scaling prefix).
  • aMass asNanoGrams
    Same, but enforces explicit printing in nanograms ("ng").
  • aMass asMicroGrams
    Enforces explicit printing in micrograms ("µg").
  • aMass asMilliGrams
    Enforces explicit printing in milligrams ("mg").
  • aMass asKiloGrams
    Enforces explicit printing in kilograms ("kg").
  • aMass asTonnes
    Enforces explicit printing in (metric) tonnes ("t").
  • aMass asKiloTonnes
    Enforces explicit printing in (metric) kilotonnes ("kt").
  • aMass asMegaTonnes
    Enforces explicit printing in (metric) megatonnes ("Mt").
  • aMass asPounds
    Enforces explicit printing in pounds ("lb") One pound is 453.59237 g.
  • aMass asCarat
    Enforces explicit printing in carat ("ct"). 1 carat is 200mg.
  • aMass asOunces
    Enforces explicit printing in ounces ("oz"). These are british (imperial) ounces (28.35 g)
  • aMass asTroyOunces
    Enforces explicit printing in troy ounces ("oz t"). These are used with metals (31.103 g)
  • aMass asAtomicMassUnits
    Enforces explicit printing in atomic mass units ("amu"). One amu is 1.660539066605e-27Kg.

Length[Bearbeiten]

Length is measured in Meters, and the default printing is in "m", "km", "mm", "nm" or whatever the print function considers appropriate.

  • number meter
    Generates a length-value of n meters.
  • number centiMeter
    Generates a length-value of n centimeters.
    Same as n centi meter.
  • number milliMeter
    Generates a length-value of n millimeters.
    Same as n milli meter.
  • number microMeter
    Generates a length-value of n micrometers.
    Same as n micro meter.
  • number nanoMeter
    Generates a length-value of n nanometers.
    Same as n nano meter.
  • number kiloMeter
    Generates a length-value of n kilometers.
    Same as n kilo meter.
  • number inch
    Generates a length-value of n inches. An inch is 25.4 mm.
  • number inches
    Same as inch above (for readability)
  • number feet
    Generates a length-value of n feet. A foot is 12 inches or 0.3048 m.
  • number yards
    Generates a length-value of n yards. A yard is 36 inches or 0.9144 m.
  • number landMiles
    Generates a length-value of n landMiles. A landMile is 5280 feet or 1609.344 m.
  • number nauticalMiles
    Generates a length-value of n nauticalMiles. A nauticalMile is 1852 m.
  • number astronomicalUnits
    Generates a length-value of n astronomical units. An au is 149597870.7 km.
  • number lightSeconds
    Generates a length-value of n lightseconds. A ls is 299792.458 km.
  • number lightYears
    Generates a length-value of n lightyears. A ly is 9460730472580.8 km.
  • number angstrom
    Generates a length-value of n angstroms. 1 Å = 0,1 = 10E−10 m.

Unit Conversion[Bearbeiten]

  • aLength asMeters
    Returns the original length but enforces explicit printing in meters (i.e. prevents scaling prefix when printed).
  • aLength asMilliMeters
    Enforces explicit printing in millimeters ("mm").
  • aLength asMicroMeters
    Enforces explicit printing in micrometers ("µm").
  • aLength asNanoMeters
    Enforces explicit printing in nanometers ("nm").
  • aLength asKiloMeters
    Enforces explicit printing in kilometers ("km").
  • aLength asInches
    Enforces explicit printing in inches ("in").
  • aLength asFeet
    Enforces explicit printing in feet ("ft").
  • aLength asYards
    Enforces explicit printing in yards ("yd").
  • aLength asFeetAndInches
    Enforces explicit printing in feet and inches (inches rounded to 4 digits).
  • aLength asLandMiles
    Enforces explicit printing in land miles ("mi"). One land mile is 1.609344 km.
  • aLength asNauticalMiles
    Enforces explicit printing in nautical miles ("NM"). One nautical mile is 1.852 km.
  • aLength asLightYears
    Enforces explicit printing in lightyears ("ly"). A light year is 9460730472580.8 km.
  • aLength asLightSeconds
    Enforces explicit printing in lightseconds ("ls"). A light second is 299792.458 km.

Temperature[Bearbeiten]

Temperature is measured in Kelvin, and the default printing is in "K".

  • number kelvin
    Generates an temperature-value of n Kelvin.
  • number degreesCelcius
    Generates an temperature-value of n degrees Celsius.
  • number degreesFahrenheit
    Generates an temperature-value of n degrees Fahrenheit.
  • number rankine
    Generates an temperature-value of n degrees Rankine.

Unit Conversion[Bearbeiten]

  • aTemperature asFahrenheit
    Returns the original temperature but enforces explicit printing in Fahrenheit.
  • aTemperature asCelsius
    Enforces explicit printing in degrees celsius.
  • aTemperature asRankine
    Enforces explicit printing in rankine.

Frequency[Bearbeiten]

Frequency is measured in Hertz, and the default printing is in "Hz", "kHz", "MHz" or whatever the print function chooses.

  • number hertz
    Generates an frequency-value of n hertz.
  • number kiloHertz
    Generates an frequency-value of n kilohertz.
    Same as n kilo hertz.
  • number megaHertz
    Generates an frequency-value of n megahertz.
    Same as n mega hertz.
  • number gigaHertz
    Generates an frequency-value of n gigahertz.
    Same as n giga hertz.

Unit Conversion[Bearbeiten]

  • aFrequency asKiloHertz
    Returns the original frequency but enforces explicit printing in kilohertz ("kHz").
  • aFrequency asMegaHertz
    Enforces explicit printing in megahertz ("mHz").
  • aFrequency asGigaHertz
    Enforces explicit printing in gigahertz ("gHz").

Energy[Bearbeiten]

Energy is measured in Joule, and the default printing is in "J", "kJ" or whatever the print function chooses.
Many domains have their own preferred unit to use (atom physics use electron volts, energy industry uses wattHours and the oil industry uses btu).

  • number joule
    Generates an energy-value of n joule.
  • number kiloJoule
    Generates an energy-value of n kilojoule.
    Same as n kilo joule .
  • number megaJoule
    Generates an energy-value of n megajoule.
    Same as n mega joule .
  • number wattHours
    Generates an energy-value of n wattHours.
    Same as n watt * 1 hours.
  • number kiloWattHours
    Generates an energy-value of n kiloWattHours.
    Same as n kilo wattHours and also the same as n kilo watt * 1 hours.
  • number megaWattHours
    Generates an energy-value of n megaWattHours.
    Same as n mega wattHours and also the same as n mega watt * 1 hours.
  • number electronVolts
    Generates an energy-value of n electronVolts.
  • number btu
    Generates an energy-value of n BTUs (british thermal units).
  • number calories
    Generates an energy-value of n calories.
  • number kiloCalories
    Generates an energy-value of n kcal.
    Same as n kilo calories .

Unit Converting[Bearbeiten]

  • energy asElectronVolts
    Present as electronVolts ("eV")
  • energy asKiloWattHours
    Present as kiloWattHours ("kWh")
  • energy asMegaWattHours
    Present as megaWattHours ("mWh")
  • energy asGigaWattHours
    Present as gigaWattHours ("gWh")
  • energy asBTUs
    Present as BTUs (British Thermal Units)
  • energy asCalories
    Present as calories ("cal")
  • energy asKiloCalories
    Present as kilo calories ("kcal")

Power[Bearbeiten]

Power is measured in Watt, and the default printing is in "W", "kW" or whatever the print function chooses. Instances of "Power" are returned eg. when multiplying an electric current by a voltage.

  • number watt
    Generates a power-value of n watt.
  • number milliWatt
    Generates a power-value of n milliWatt.
    Same as "n milli watt ".
  • number kiloWatt
    Generates a power-value of n kiloWatt.
    Same as "n kilo watt ".
  • number megaWatt
    Generates a power-value of n megaWatt.
    Same as "n mega watt ".
  • number gigaWatt
    Generates a power-value of n gigaWatt.
    Same as "n giga watt ".

Unit Converting[Bearbeiten]

  • power asMilliWatt
    Presents itself as mW
  • power asKiloWatt
    Presents itself as kW
  • power asMegaWatt
    Presents itself as mW
  • power asGigaWatt
    Presents itself as gW
  • power asDBm
    Presents itself as decibel based on milliwatt (1 mW is 0.0 dBm; 1 W is 30.0 dBm)
  • power asDBW
    Presents itself as decibel based on watt (1 W is 0.0 dBW; 1 kW is 30.0 dBW)

Force[Bearbeiten]

Force is measured in Newton, and by default printed as such.

  • number newton
    Generates a force-value of n newton.

Unit Converting[Bearbeiten]

  • force asGramForce
    Presents itself as gf
  • force asTonForce
    Presents itself as tf (metric tons of force)
  • force asPoundsForce
    Presents itself as lbf

Area[Bearbeiten]

Area is a derived unit based on length in meters and measured in square meter. The default printing is in "m²". Instances of "Area" are created eg. when multiplying two length values or when dividing a volume by a length.

  • number squareMeter
    Generates an area-value of n square meters (m²).
  • number squareKiloMeter
    Generates an area-value of n square kilometers (1000*1000 m²).
  • number hectare
    Generates an area-value of n hectares. Same as n hecto are or 10000 m².
  • number are
    Generates an area-value of n ares. 1 are being 10 m².
  • number squareFeet
    Generates an area-value of n square feet. 1 sq ft being 0.0929 m².
  • number acres
    Generates an area-value of n acres. 1 acre being 4046.856 m².

Converting[Bearbeiten]

  • area asHectare
    Presents itself as hectare ("ha")
  • area asAre
    Presents itself as are (10 m²)
  • area asSquareFeet
    Presents itself as square feet ("m²")
  • area asAcres
    Presents itself as acres ("ac")
  • area asSquareMiles
    Presents itself as square miles ("sqm") (based on a land mile being 1609.344 m)

Volume[Bearbeiten]

Volume is a derived unit based on length in meters and measured in cubic meter. The default printing is in "m³", although the print function may choose to print in liters "l", or milli liters "ml" etc. Instances of "Volume" are created eg. when multiplying an area by a length or when cubing a length.

  • number cubicMeter
    Generates an volume-value of n cubic meters (1000 l).
  • number liter
    Generates an volume-value of n liters.
  • number milliLiter
    Generates a volume-value of n milliliters.
    Same as "n milli liter".
  • number hectoLiter
    Generates a volume-value of n hectoliters.
    Same as "n hecto liter".
  • number barrel
    Generates a volume of n barrels (oil volume measurement).
  • number flozGB
    Generates a volume of n imperial fluid ounces (0.02841 liter).
  • number flozUS
    Generates a volume of n US fluid ounces (0.02957 liter).
  • number pintGB
    Generates a volume of n imperial pints (568.26125 ml).
  • number pintUS
    Generates a volume of n US pints (473.176473 ml).
  • number quartGB
    Generates a volume of n imperial quarts (1.1365 liter).
  • number quartUS
    Generates a volume of n US quarts (946.353 ml).
  • number gallonGB
    Generates a volume of n imperial gallons (4.5461 liter).
  • number gallonUS
    Generates a volume of n US gallons (3.7854 liter).

Converting[Bearbeiten]

  • volume asCubicMeters
    Presents itself as cubic meters ("mˆ3") (not as "ml" or "l")
  • volume asLiters
    Presents itself as liters ("l"). (not as "ml" or "mˆ3")
  • volume asHectoLiters
    Presents itself as hectoliters ("hl") (not as "ml", "l" or "mˆ3")
  • volume asMilliLiters
    Presents itself as milliliters ("ml") (not as "l" or "mˆ3")
  • volume asCubicInches
    Presents itself as cubic inches ("cuin")
  • volume asFlozGB
    Presents itself as imperial fluid ounces ("imp fl oz")
  • volume asFlozUS
    Presents itself as US fluid ounces ("us fl oz")
  • volume asGallonsGB
    Presents itself as imperial gallons ("imp ga")
  • volume asGallonsUS
    Presents itself as US gallons ("us ga")

Velocity (Speed)[Bearbeiten]

Velocity is a derived unit based on length in meters and measured in meters per second. The default printing is in "m/s". Instances of "Velocity" are created eg. when dividing a length by a time duration.

  • number meterPerSecond
    Generates a velocity of n meters per second.
  • number kiloMeterPerHour
    Generates a velocity of n km per hour.
  • number milesPerHour
    Generates a velocity of n mph.
  • number knots
    Generates a velocity of n nautical miles per hour.

Converting[Bearbeiten]

  • volume asKiloMetersPerHour
    Presents itself as km/h
  • volume asMilesPerHour
    Presents itself as mph
  • volume asKnots
    Presents itself as nautical knots (kn). 1 knot being 0.514 m/s or 1.852 km/h ("1.0 knots asKiloMetersPerHour").

Acceleration[Bearbeiten]

Velocity is a derived unit based on length in meters and measured in meters per second per second. The default printing is in "m/s²". Instances of "Acceleration" are created eg. when dividing a velocity by a time duration.

  • number metersPerSecondPerSecond
    Generates an acceleration of n m/s².

Pressure[Bearbeiten]

Pressure is a derived unit measured in Pascal. The default printing is in "Pa". Instances of "Pressure" are created eg. when dividing a force by an area.

  • number pascal
    Generates a pressure value of n pascal.
  • number hectoPascal
    Generates a pressure value of n hectoPascal.
    Same as "n hecto pascal".

Converting[Bearbeiten]

  • volume asBar
    Presents itself as bar
  • volume asPSI
    Presents itself as psi

Voltage[Bearbeiten]

Voltage is a derived unit measured in Volt. The default printing is in "V", "mV", "kV" as appropriate.

  • number volts
    Generates an electrical voltage of n volts.
  • number milliVolt
    Generates a voltage of n millivolt.
  • number microVolt
    Generates an voltage of n microvolt.
  • number kiloVolt
    Generates an voltage of n kilovolt.

Electric Current[Bearbeiten]

A derived unit measured in Ampere. The default printing is in "A", "mA", "kA" as appropriate. Instances of "Current" are created eg. when dividing an electric charge by a time duration.

  • number ampere
    Generates an electric current of n ampere.
  • number milliAmpere
    Generates an electric current of n milliampere.
  • number microAmpere
    Generates an electric current of n microampere.

Electric Resistance[Bearbeiten]

A derived unit measured in Ohm. The default printing is in "Ω", "kΩ", "MΩ" as appropriate.

  • number ohm
    Generates an electric resistance of n ohm.
  • number kiloOhm
    Generates an electric current of n kiloOhm.
  • number megaOhm
    Generates an electric current of n megaOhm.

Electric Capacitance[Bearbeiten]

A derived unit measured in Farad. The default printing is in "F", "uF", "nF", "pF" as appropriate.

  • number farad
    Generates an electric capacitance of n farad.
  • number microFarad
    Generates an electric capacitance of n microfarad.
  • number nanoFarad
    Generates an electric capacitance of n nanofarad.
  • number picoFarad
    Generates an electric capacitance of n picofarad.

Electric Charge[Bearbeiten]

A unit measured in Coulomb. The default printing is in "C". Instances of "Charge" are created eg. when multiplying an electric current by a time duration.

  • number coulomb
    Generates an electric charge of n coulomb.

Converting[Bearbeiten]

  • aCharge asAmpereSeconds
    Presents itself as "As" (which is also a coulomb, but "As" might be preferred in some domains)
  • aCharge asAmpereHours
    Presents itself as "Ah"

Inductance[Bearbeiten]

A unit measured in Henry.

Mass Density[Bearbeiten]

A unit measured in kg/m³. Instances are created eg. when dividing a mass by a volume.

Converting[Bearbeiten]

  • massDensity asGramPerCubicCentimeter
    Presents itself as g/cm³

Defining Additional Unit Converters[Bearbeiten]

You can define additional unit converters as ConvertedUnit as follows:

myUnit := Physic::ConvertedUnit 
            name:name 
            baseUnit:baseUnit 
            unitString:unitString 
            unitValueBlock:unitValueBlock
            baseUnitValueBlock:baseUnitValueBlock

Where baseUnit is the underlying base (SI) unit, unitString is the string used when printing, unitValueBlock is a Smalltalk block to compute the unit value from a base unit value and baseUnitValueBlock is a Smalltalk block to compute the base unit value from the unit value.

For example, to get volumes printed as cubic inches, you could define (1):

cI := Physic::ConvertedUnit
            name:'cubicInches'
            baseUnit:(Physic::Volume) 
            unitString:'in³' 
            unitValueBlock:[:cubicMeters | cubicMeters * 61023.7440947323]
            baseUnitValueBlock:[:cubicInches| cubicInches / 61023.7440947323]

(where 61023.7440947323 is the number of cubic inches per cubic meter)

Then create a new physical value for your volume with:

cI amount:volumeInCubicMeters

Or, to present a mass in units of gummy-bears (assuming one bear weighs 1.1g (2)),

bearUnit := Physic::ConvertedUnit
            name:'Haribo-Bears'
            baseUnit:(Physic::Mass) 
            unitString:'bears' 
            unitValueBlock:[:kiloGram| kiloGram * 1000 / 1.1]
            baseUnitValueBlock:[:bears| bears * 1.1 / 1000]

and then take a 150g bag of bears and ask it to print itself on an output stream:

bagOfBears := bearUnit amount:0.150.
bagOfBears printOn:Transcript 

gives:

-> "136.363636363636 bears"

Notice, that bearUnit ("Haribo") is still a unit of mass; we can add another kilogram to those bears:

bagOfBears + 1 kilo gram

and get more bears:

-> 1045.45454545455 bears

You can also convert any mass into gummy-bears:

(1 kiloGram as:bearUnit) floor

gives:

909.0 bears

Notes:
1) this is only an example; you don't need that, as volumes already support conversion to cubicInches (see asCubicInches above)
2) the author does not know what the actual mass of a gummy bear is ;-)

Arithmetic[Bearbeiten]

Arithmetic on physical values will generate an appropriate physical value with its own unit. Eg., when multiplying a velocity by a time, you will get a distance, or when dividing a distance by a time, you will get a velocity.

The following lists some of the possible results.

Velocity[Bearbeiten]

distance = velocity * time

3 meterPerSecond -> 3 m/s  
1 meterPerSecond * 10 seconds -> 10 m  
10 kiloMetersPerHour * 30 minutes -> 5000 m
30 meter / 2 seconds -> 15 m/s
10 meter / 1 seconds * 20 seconds -> 20 m

Acceleration[Bearbeiten]

speed = acceleration * time

1 meterPerSecondPerSecond * 10 seconds -> 10 m/s  
(1 meterPerSecondPerSecond distanceAfter:1 hours) -> 6480.0 km
1 meterPerSecond / 10 seconds -> 0.1 m/s²

Mass[Bearbeiten]

force = mass * acceleration

1 kiloGram * 1 meterPerSecondPerSecond -> 1 N
1 newton / 2 kiloGram -> (1/2) m/s²

Electric[Bearbeiten]

10 volt / 220 ohm -> 45.45 mA
150 ohm * 20 milliAmpere -> 3 V 
0.5 ampere * 0.5 seconds -> 0.25 C
100.0 micro farad * 100 volt -> 0.01 C
10.0 micro farad * 100 ohm -> 1.0 ms (the RC time constant)

Energy[Bearbeiten]

10 kiloWatt * 10 hours -> 360.0 MJ 
(10 kiloWatt * 10 hours ) asKiloWattHours -> 100 kWh

Formula Evaluation[Bearbeiten]

Formula can be parsed and further processed by use of the Physic::Parser class.

  • Physic::Parser parse: aString
    generates a parse tree for further processing
  • Physic::Parser evaluate: aString
    parses and evaluates

Generated parse trees can be further processed with:

  • aParseTree value
    evaluates the tree
  • aParseTree simplify
    simplifies a parsed formula (if possible)
  • aParseTree derivate
    generates a derivate

Examples[Bearbeiten]

(Physic::Parser parse:'a*x^2 + b*x + c') derivate 
-> 2·a·x + b

(Physic::Parser parse:'sin(a*x) + cos(b*x)') derivate 
-> cos(a·x)·a - sin(b·x)·b

Nature Constants[Bearbeiten]

The following constants are known to the parser and can be used in formula/equations:

pi
e
mass[X], for X in {'earth', 'moon', 'mercure', 'venus', 'mars', 'jupiter'}
volume[X], for X in planets above
surface[X], for X in planets above
DISTANCE_SUN_EARTH
DISTANCE_EARTH_MOON

Equation Solving[Bearbeiten]

The solver can solve simple equations:

equation := Physic::Parser parse:'a = 5*b + c".
equation solveFor:'b' 
-> 'b = (a - c) / 5'.

For example, from the wellknown Formula "U = R * I",

equation := Physic::Parser parse:'U = R * I".

we can derive:

equation2 := equation solveFor:'R'.

and get "R = U/I".
Of which the right side:

formulaForR := equation2 rightSide 

is:

U/I

Applying this formulaForR to concrete values:

formulaForR valueIn:{ 'U' -> 5 volt . 'I' -> 20 milliAmpere }

we get the result:

250 Ω

Physical Values in Activity Diagrams[Bearbeiten]

Unfortunately, the arithmetic actions in the standard library were defined with pin types being "Number", instead of the more general "ArithmeticValue" (of which PhysicalValues inherit). Thus, they will not accept physical values if type checking is enabled on the pin values (although the underlying primitive code would handle those types).

We therefore provide a separate PhysicalValues library, with redefined arithmetic actions. Please use those when dealing with physical values (instead of "forcing" types or disabling type checks).

Freeze values can be given either using the above listed instance creation messages on number (eg. "10 meters" or "1 kilo joule") or by using a unit suffix, possibly with an appreciated SI prefix, as in "10 kV" or "10 mA".

Physical Values in Elementary Code[Bearbeiten]

See examples below.

Examples[Bearbeiten]

The following code snippets are plain Smalltalk code + the printed representation (as for example found in a report).
For JavaScript, write "n.X()" instead of "n X" (eg. "1.kilogram() + 10.0.gram()" instead of "1 kiloGram + 10.0 gram".

The following shows the printed output of typical Smalltalk expressions:

Length Examples:[Bearbeiten]

(1/4) inches => 6.25 mm
10 milliMeter asInches => 0.3937 in
10 milli meter asInches => 0.3937 in
10 feet => 3.048 m
1.8 meter asFeet => 5.905 ft
10 miles => 16.09 km
10 nauticalMiles => 18.52 km
1 parsec => 3.26156377716705 ly
10 kiloMeters asMeters => 10000 m
1 micro inch => 25.4 nm
1.80 meter asFeetAndInches => 5′10.866
1 yards => 0.9144 m

Mass Examples:[Bearbeiten]

1 kiloGram + 10.0 gram => 1.01 kg
(1 kiloGram + 10 gram) asGrams => 1010 g
10 gram => 10 g
10 gram asKiloGrams => (1/100) kg
10.0 gram asKiloGrams => 0.01 kg
10 gram asMilliGrams => 10000 mg
1 microGram => 1 µg
1 micro gram => 1 µg
10000 gram => 10 kg
1 pound => 453.59237 g
1 pound asKiloGrams => 0.45359237 kg
1 pound asPounds => 1.0 lb
1 kiloGram asPounds => 2.20462262184878 lb

Temperature Examples:[Bearbeiten]

0 degreesCelsius => 273.16 K
0 degreesCelsius asFahrenheit => 32.018 °F
40 degreesFahrenheit => 277.59 K
60 degreesFahrenheit asCelsius => 15.556 °C
40 degreesFahrenheit asKelvin => 277.59 K
10 kelvin => 10 K
100 rankine => 55.556 K
100 rankine asRankine => 100.0 °R

Energy Examples:[Bearbeiten]

1 joule asElectronVolts => 6.24150912550149E+18 eV
1 joule asCalories => 0.239005736137667 cal
1 joule asBTUs => 0.000947817 BTU
1.0 joule asKiloWattHours => 2.77777777777778E-07 kWh
10 electronVolts => 1.6021766208E-18 J
1000 joule asKiloWattHours => 0.000278 kWh
1000.0 kiloJoule asKiloWattHours => 0.2778 kWh

Electricity Examples:[Bearbeiten]

1 coulomb asAmpereHours => 0.000277 Ah
1.1 volt / 10 kilo ohm => 110.0 µA
100 micro farad * 10.0 volt => 0.001 C
100 ohm * 0.1 micro farad => 10.0 µs

Volume Examples:[Bearbeiten]

1000 liter => 1 m³
1000 liter asLiters => 1000 l
1000 liter asHectoLiters => 10 hl
1000 liter asCubicInches => 61023.7440947323 cuin
100.0 liter asCubicInches => 6102.37440947323 cuin
100.0 deci liter asCubicInches => 610.237440947323 cuin
1 liter asCubicInches => 61.0237440947323 cuin
1 deci liter asCubicInches => 6.10237440947323 cuin
1 milli liter asCubicInches => 0.0610237440947323 cuin
1 inch cubed => 16.387064 ml
1 inch cubed asLiters => 0.016387064 l
1 inch cubed asCubicInches => 1.0 cuin
1 inch cubed asCubicInches unitString => 'cuin'
1 inch cubed asCubicInches unitAmount => 1.0
1 inch cubed asCubicInches unitStringSI => 'm³'
1 inch cubed asCubicInches amount => 1.6387064E-05



Copyright © 2014-2024 eXept Software AG