Working with units and physical quantities in the Wolfram Language

Eric Weisstein
Michael Trott

Wolfram Technology Conference
October 19, 2017

What's not new

Wolfram|Alpha and the Wolfram Language contain the world's most extensive collection of cuarted, computable units

The WL contains an ever-growing and increasingly powerful set of tools for working with units and dimensional quantities

What is new

QuantityVariable and QuantityVariableDimensions functionality improvements in V11.2

QuantityVariableCanonicalUnit improvements and NonDimensionalizationTransform coming in V11.3

new "PhysicalConstant" entity domain added in V11.1(1/2)

General overview of unit system in the WL

unit-ed values (Quantity)

custom Quantity functions (QuantityArray, QuantityDistribution)

physical quantities (QuantityVariable)

new physical constant entity domain ("PhysicalConstant")

Units

Mathematica unit system is based on curated unit tables built for Wolfram|Alpha

Mathematica "knows" > 25,000 units (including compound units in the total)

Examples: meters, feet, inches of mercury, US dollars, Russian vershoks, ...

"Knowledge" consists of:

numerical value with correct precision

relationships to other units

spellings, abbreviations, alternate names, disambiguation

associated physical quantities

formatting

region and date information of usage

Unit representation

In the WL, units are encoded by a numeric magnitude (QuantityMagnitude) together with a unit name represented as a string, product/ratio of strings, or MixedUnit expression (QuantityUnit)

unit strings are camelcased plural unit names for simple units ("Meters", "Miles", "Seconds", "Volts", "Dollars", "PureUnities") and camelcased singular unit names for constants ("SpeedOfLight", "PlanckConstant", "BohrRadius")

simple unit strings can be combined via *, /, and ^ to give compound units ("Meters"/"Seconds"^2, "Volts"/"Ohms", "Joules"/"SpeedOfLight"^2)

the expression and wrapper holding a combination of a numeric magnitude and (possibly compound) string unit specification is called a Quantity

Quantity expressions in which the magnitude is omitted autoevaluate to have magnitude 1

Unit representation

Quantity["SpeedOfLight"]

Quantity[1,"Ohms"]

QuantityMagnitude[%]//InputForm

QuantityUnit[%%]//InputForm

Quantity[1,"Meters"/"Seconds"]

Through[{Identity,QuantityMagnitude,QuantityUnit}[%]]//InputForm

Unit input methods

Quantity using input form (as above)

Quantity using autocompletion

free-form input via Wolfram|Alpha using Ctrl=

LinguisticAssistant

InputForm[%]

Another unit input method: QuantityUnit canonicalization

good for discovery; slow for production use (each canonicalization performs a server call)

caveat user: if you're not sure, use KnownUnitQ

Quantity[1,"m"]//InputForm

KnownUnitQ/@{"m","Meters"}

Quantity["MilesPerHour"]//InputForm

KnownUnitQ/@{"MilesPerHour","Miles"/"Hours"}

MixedMagnitude/MixedUnit representation

Quantity[MixedMagnitude[{5,10}],MixedUnit[{"Feet","Inches"}]]

UnitConvert[%,"SI"]

N[%]

Independent units

Quantity[1,IndependentUnit["WolframTechnologyConferences"]/"Years"]

Quantity[10,"Years"]*%

InputForm[%]

Example units: Pulsars

Union[QuantityUnit[Cases[EntityValue[(Entity["Crab Pulsar", Entity["Pulsar","PSRJ0534Plus2200"], "Entity[\"Pulsar\", \"PSRJ0534Plus2200\"]", "pulsar"]),"PropertyAssociation"],_Quantity,∞]]]

Popular units

By use in W|A

Common length units by magnitude

Unit conversion

UnitConvert[Quantity[26.2,"Miles"],"Kilometers"]

UnitConvert[Quantity[1,"Miles"],"SI"]

UnitConvert[Quantity[1,"Miles"],"SIBase"]

UnitConvert[Quantity[26.2,"Miles"]]

Unit conversion via QuantityMagnitude

QuantityMagnitude[Quantity[26.2,"Miles"],"Kilometers"]

QuantityMagnitude[Quantity[30,"Days"],"Seconds"]

Currency unit conversion

may require internet connectivity to query exchange rates

includes historical exchange information

UnitConvert[Quantity["Euros"],"USDollars"]

UnitConvert[Quantity["Euros"],DatedUnit["USDollars",2015]]

Historical currency conversion

DateListPlot[Table[{DateObject[{year}],
 UnitConvert[Quantity[1,DatedUnit["Euros",year]],DatedUnit["USDollars",year]]},
{year,2000,2017}],FrameLabel->{"year",Quantity[None, "USDollars"/"Euros"]}]

UnitConvert[Quantity[1,DatedUnit["USDollars",1800]],"USDollars"]

DateListPlot[Table[{DateObject[{year}],
 UnitConvert[Quantity[1,DatedUnit["USDollars",year]],"USDollars"]},
{year,1800, 2017}],FrameLabel->{None,Quantity[None, "USDollars"]}]

Date computations with units

Today+Quantity[100,"Days"]

Now+Quantity[20,"Minutes"]

Unit simplification

UnitSimplify allows units to be combined and rearranged to give "nicer" units

Quantity["Grams" "Meters"/"Seconds"^2]

UnitSimplify[%]

UnitSimplify[Quantity[1,"Joules"/"Seconds"]]

Unit dimensions

UnitConvert["Joule"]

UnitDimensions["Joule"]

InputForm[%]

UnitDimensions["Newton"]

UnitDimensions["PureUnities"]

Unit simplification with non-dimensionalization

UnitSimplify[Quantity[3,"Revolutions"/"Seconds"]]

UnitSimplify[Quantity[3,"Revolutions"/"Seconds"],UnityDimensions->{"AngleUnit"}]

UnitConvert[%]

UnitConvert[%,"SIBase"]

UnitConvert[%,"SI"]

Computing with units: Solve

Solve[Quantity[1,"Newtons"]==m Quantity["StandardAccelerationOfGravity"],m]

eqn=((94080 (G^3) (k^9) (π^4)((Zeta[(9/2)])^2) )/((c^18) (h^6)))(T^9)==((8 (k^3) π ((Zeta[3])^2))/((c^3) (h^3))) (T^3);

rules=Thread[{G,k,h,c}->Quantity/@{"GravitationalConstant","BoltzmannConstant","PlanckConstant","SpeedOfLight"}];

Solve[eqn&&T>0/.rules,T]

Computing with units: DSolve

sho=𝓍''[𝓉]+(ω^2)𝓍[𝓉]==0;

DSolve[{
sho,
𝓍[Quantity[0,"Seconds"]]==Quantity[1,"Meters"],𝓍'[Quantity[0,"Seconds"]]==Quantity[π,"Meters"/"Seconds"]},𝓍[𝓉],𝓉]

%/.{ω->Quantity[2Pi,"Hertz"],𝓉->Quantity[2.5,"Seconds"]}

QuantityArray

Provides an efficient representation for arrays of quantities

qa=QuantityArray[{2.3,1.5,9.0},"Meters"]

QuantityMagnitude[qa]

QuantityUnit[qa]

QuantityArray conversion/expansion

qa=QuantityArray[{{1,2},{3,4},{5,6}},{"Meters","Feet"}]

Normal[qa]

CommonUnits[qa]

Normal[%]

QuantityArray[%]

%["Summary"]

QuantityArray in GeoElevationData + friends

GeoElevationData, GeogravityModelData, GeomagneticModelData return QuantityArray's:

GeoElevationData[(Entity["Denver", Entity["City",{"Denver","Colorado","UnitedStates"}], "Entity[\"City\", {\"Denver\", \"Colorado\", \"UnitedStates\"}]", "city"])]

ReliefPlot[%,DataReversed->True]

data=GeoElevationData[GeoDisk[(Entity["Mount Everest", Entity["Mountain","MountEverest"], "Entity[\"Mountain\", \"MountEverest\"]", "mountain"]),(QuantityUnit[3])]]

ListPlot3D[Reverse[data],MeshFunctions->{#3&},Mesh->30]

QuantityDistribution

Allows construction and computation with distributions of quantity data

𝒟=NormalDistribution[(Quantity[120, "cm", centimeters, "Centimeters"]),(Quantity[16, "cm", centimeters, "Centimeters"])]

Probability[x>(Quantity[1.5, "yd", yards, "Yards"]),x\[Distributed]𝒟]

times=Quantity[{2.35,1.55,2.7,0.25,1.5,3.35,1.85,0.15,2.3,0.65,0.85,5.15},"Minutes"]

EstimatedDistribution[times,ExponentialDistribution[λ]]

EstimatedDistribution[QuantityArray[times],ExponentialDistribution[λ]]

AnotherQuantityDistribution example

The average speed of cars traveling from Champaign to Chicago is well described as a triangular random variable:

speed𝒟=TriangularDistribution[{(Quantity[55, "mi""/""h", miles per hour, (("Miles")/("Hours"))]),(Quantity[82, "mi""/""h", miles per hour, (("Miles")/("Hours"))])},(Quantity[72, "mi""/""h", miles per hour, (("Miles")/("Hours"))])]

Plot[PDF[speed𝒟,Quantity[s,"Miles"/"Hours"]],{s,55,82}]

Expectation[GeoDistance[(Entity["Champaign", Entity["City",{"Champaign","Illinois","UnitedStates"}], "Entity[\"City\", {\"Champaign\", \"Illinois\", \"UnitedStates\"}]", "city"]),(Entity["Chicago", Entity["City",{"Chicago","Illinois","UnitedStates"}], "Entity[\"City\", {\"Chicago\", \"Illinois\", \"UnitedStates\"}]", "city"])]/v,v\[Distributed]speed𝒟]

UnitConvert[%,MixedUnit[{"Hours","Minutes"}]]

Physical quantities

Mathematica knows >2,200 physical quantities

examples: length, speed, force, magnetic induction, coil sensitivity, ...

represented as a string of the camelcased physical quantity name ("Length", "Speed") wrapped in QuantityVariable

includes physical quantity "instances" ("BondLength", "CoherenceLength", "CharacteristicLength")

Entering physical quantities

QuantityVariable using input form

QuantityVariable["Mass"]

QuantityVariable string completion

free-form input

LinguisticAssistant

Physical quantity visualization

Physical quantities in formulas

RandomSample[FormulaData[],5]

FormulaData["Resistivity"]

InputForm[%]

FormulaData["OhmsLaw"]

InputForm[%]

Cases[%,qv_QuantityVariable:>QuantityVariableIdentifier[qv],∞]

FormulaData["OhmsLaw",{"V"->Quantity[2,"Volts"],"R"->Quantity[1,"Ohms"]}]

Physical quantities in PhysicalSystemData

ham=(Entity["double pendulum", Entity["PhysicalSystem","DoublePendulum"], "Entity[\"PhysicalSystem\", \"DoublePendulum\"]", "physical system"])["HamiltonianFunction"]

Cases[ham,QuantityVariable[_,pq_]:>pq,{0,∞},Heads->True]//Union

InputForm[ham]

QuantityVariableCanonicalUnit

The canonical unit for a given physical quantity:

QuantityVariableCanonicalUnit[QuantityVariable["Mass"]]

QuantityVariableCanonicalUnit[QuantityVariable["Energy"]]

QuantityVariableCanonicalUnit[QuantityVariable["TorsionalConstant"]]

QuantityVariableCanonicalUnit[QuantityVariable["ReynoldsNumber"]]

QuantityVariableDimensions

The dimensions of a given physical quantity:

QuantityVariableDimensions[QuantityVariable["Speed"]]

QuantityVariableDimensions[QuantityVariable["Mass"*"Acceleration"]]

QuantityVariableDimensions on expressions

Can be applied to QuantityVariable directly:

ψ=QuantityVariable["ψ","WavefunctionBoundState1DPositionRepresentation"];
x=QuantityVariable["x","Length"];
t=QuantityVariable["t","Time"];

QuantityVariableDimensions[ψ[x,t]]

Can be applied to expressions containing QuantityVariable:

QuantityVariableDimensions[Derivative[0,1][ψ][x,t]]

Dimensional combinations

Dimensionally equivalent to a force:

DimensionalCombinations[{"ElectricCharge","Distance","ElectricElastivity"},"Force"]

DimensionalCombinations[{"Mass","Distance","Time"},"Force"]

To an energy:

DimensionalCombinations[{"MassDensity","Radius","Time"},"Energy"]

"Discover" the Reynolds number using DimensionalCombinations

FormulaLookup["reynolds number"]

re=FormulaData[{"ReynoldsNumber","DynamicViscosity"}]

re//InputForm

pqs=Cases[re,QuantityVariable[_,u_]:>u,∞]

DimensionalCombinations[Rest[pqs]]

Find dimensionless combinations of constants

solns=DimensionalCombinations[{},IncludeQuantities->"PhysicalConstants"]

UnitConvert[%]

More generally:

physicalConstants=Quantity/@{"SpeedOfLight","PlanckConstant","GravitationalConstant","ElectricConstant","MagneticConstant","ElementaryCharge","ElectronMass"};

DimensionalCombinations[{}, IncludeQuantities->physicalConstants]//Column

Physical constants

"PhysicalConstant" entity domain released in August 2017

content still being added

196+ constants from physics, astronomy, chemistry, ...

helps provide computable content, entity access, and easy updating of constants in WL and W|A

contains detailed information on uncertainties, standards defining constants, etc.

inter-convertible with Quantity via ToEntity and FromEntity

deliberately lacks free-form parsing ("would you like the quantity or the entity form for c?")

Physical quantity entities

EntityList["PhysicalConstant"]//Length

RandomEntity["PhysicalConstant",5]

With[{ents=Take[EntityList["PhysicalConstant"],10]},Grid[EntityValue[ents,{"Entity","CanonicalName","Value"}],Dividers->All,Alignment->Left]]

Physical constant properties

EntityValue["PhysicalConstant","Properties"]

Entity["PhysicalConstant","SpeedOfLight"]["PrimarySource"]

Entity["PhysicalConstant","SpeedOfLight"]["ExternalLink"]

Entity["PhysicalConstant","SpeedOfLight"]["Quantity"]//InputForm

Entity["PhysicalConstant","SpeedOfLight"][{"Value","StandardUncertainty"}]

Physical constant classes

EntityClassList["PhysicalConstant"]

EntityList[(EntityClass["cosmological constants", EntityClass["PhysicalConstant","Cosmological"], "EntityClass[\"PhysicalConstant\", \"Cosmological\"]", "physical constants"])]

Physical constant values over time

Grid[{#,Column[#2]}&@@@Entity["PhysicalConstant","PlanckConstant"]["Values"],Dividers->All,Alignment->Left,BaseStyle->18]

Physical constant conjectured values

EntityValue[Entity["PhysicalConstant","InverseFineStructureConstant"],{"Value","StandardUncertainty"}]

(alphas=Entity["PhysicalConstant","FineStructureConstant"]["ConjecturedValues"])//Short[#,3]&

data={#,Short[v=UnitConvert[1/("Value"/.#2)/."ElectronProtonMassRatio"->1/"ProtonElectronMassRatio"]],N[v,20]}&@@@alphas//Quiet;

Grid[SortBy[Append[data,{Style["experiment",Red],"",UnitConvert[Quantity["InverseFineStructureConstant"]]}],Last],Alignment->Left,Dividers->All]

Physical quantity entity/quantity conversion

ToEntity[Quantity["BoltzmannConstant"]]

%//InputForm

FromEntity[(Entity["gravitational constant", Entity["PhysicalConstant","GravitationalConstant"], "Entity[\"PhysicalConstant\", \"GravitationalConstant\"]", "physical constant"])]

%//InputForm

Explicit uncertainty tagging

cons={"SpeedOfLight","ReducedPlanckConstant","GravitationalConstant","ElectricConstant","MagneticConstant","ElementaryCharge","ElectronMass"};

data=EntityValue[Entity["PhysicalConstant",#]&/@cons,{"Quantity","Value","StandardUncertainty"}];

Grid[Prepend[{#,#2,#3,NumberForm[rel=If[#3===Missing["Exact"],0,#3/#2],{2,1}],-Log10[2rel]}&@@@data,Style[#,Gray]&/@{"constant","value","uncertainty","relative uncertainty","precision"}],
Dividers ->All]

Future work

fill out "PhysicalConstant"

speed up parsing and operations involving units in WL

extend support for units in visualization and computation

NonDimensionalizationTransform to put equations into dimensionless form

NonDimensionalizationTransform[(QuantityVariable["ω", "Frequency"]) (QuantityVariable["x", "Length"])[(QuantityVariable["t", "Time"])]+a (QuantityVariable["x", "Length"])'[(QuantityVariable["t", "Time"])]==A (QuantityVariable["f", "Speed"])[(QuantityVariable["t", "Time"])],{(QuantityVariable["x", "Length"]),(QuantityVariable["t", "Time"]),(QuantityVariable["f", "Speed"])},{x,t,F}]

stronger typing for physical quantity dimensions

better support for "scale" units

Thanks

Jose Martín-García

Nick Lariviere

Jason Martinez

Bjorn Zimmerman