Skip to content

Metric Tensor in Quantity System

The best part in making the Quantity System, is that I am re-discovering mathematics with it. It gives me an immense pleasure to learn mathematics in a practical way and to try and make corrections on two levels, Programming and Mathematics.

This post will be a usage scenario for the quantity system. The scenario will be applicable for the latest source code (which can be downloaded from labeled by version [Qs 1.2.5])

In this post I will explain the mathematical foundation with my language/realization (so I am not tied to the formal way of books)

Coordinates Introduction

In studying geometry, we always encounter (x,y,z) coordinate system. This system simply is a way to describe the location of point.

And if we are talking with Vectors, then {x y z} is an arrow coming from {0 0 0} to {x y z} and we are calling it Vector.

Using {x1 x2 x3} labeling instead of {x y z} then we have indexes 1,2, and 3 usually referred as R3 Space.

What does that mean ??

R2: 2 dimensional coordinate system (2D Space)

R3: 3 dimensional coordinate system (3D Space)

R4: 4 dimensional coordinate system (4D Space) (yes it exists somehow refer to Hypersphere coordinate system )

Note: Using ‘R’ refer to the numbering system type we are using which is Real Numbers.

So in Rn the point/vector can be described by {x1 x2 x3 x4 .. xn} and to generalize the point location we end into defining xi

where i: 1,2, 3, .., n for number of coordinates

Cartesian Coordinates

They are simply {x y} or {x y z}, R2 or R3 which we all know and studied during school. (an important note here is that the angle between the unit vectors is 90 degree or Orthogonal)

Curvilinear Coordinates

In this type of coordinates the unit vectors that represent the coordinate system is not a straight forward lines, but on contrary they are making curves in some way.

When dealing with curvilinear coordinates every coordinate has a tangent vector (e) and orthogonal vector (E)

Without going into a lot of details these extra vectors are the foundation of covariant and contravariant vectors

The curse of Curvilinear coordinates is that the location of point can be represented by two vectors covariant or contravariant.

We label the two types of vectors by this

Contravariant vector: xi superscript index or simple {x1 x2 x3}

Covariant vector: xi subscript index {x1 x2 x3}

Best to be seen by the following figure

Note: we are obliged to use two types of vectors specially when we are beginning to use geometric properties of geometric objects (for example the line length in curvilinear coordinates is not the same as Cartesian coordinates, think about line over spherical object like big line on earth) line length = sqrt(x*x + y*y + z*z) however in curvilinear length = sqrt(x1*x1 + x2*x2 +x3*x3) or simply length = sqrt(xi*xi) Einstein summation notation.

Coordinates Transformation

We can transform the point from Cylindrical to Cartesian (here I mean changing the representation of point/vector from r,q,z to x,y,z )

x = r cos(q)

y = r sin(q)

z = z

a vice versa transformation exist but I will not write it here

for simplicity let us write that any {r q z} vector we can transform it by multiplying it with {r*cos(q) r*sin(q) z}

so for any two coordinate systems there is a transformation

Note: in mathematical books they are referring to Jacobian calculation to make sure that such transformation exist

How can we make this simple with quantity system?

  • Define a vector that contains a symbolic quantities
  • Get the function from this vector
  • Now you can get x, y, z vector from r q z vector by the function fc
  • Also using named parameters (so you don’t get ambiguous about parameters order)
  • And for fun you can pass Symbolic parameters (remember that quantity system blend the usage between numbers and symbols)


Note: Quantity system permits you to make calculations on symbols as if they were first citizen types in Qs to define symbol you can precede dollar sign before it like $x $y $myvariable and to define complex expression you can use ${expression} like ${x+y*r} or ${sqrt(sin(u*v^2))} please refer to the separate symbolic variable engine that also made by me in

Covariant and Contravariant vectors Dilemma

A question is raised here, how can I get covariant and contravariant components of vector with the guide of Transformation Equations and existing vector?

This dilemma is solved by the Metric Tensor. The metric tensor is a matrix like object that when multiplied by vector gets the corresponding vector

There are also two types of metric tensor (covariant metric tensor and contravariant metric tensor)

To calculate the metric tensor we get back to the definition of base vector

In the figure above the x1,x2,x3 represent a curvilinear coordinate system and g1,g2,g3 represent covariant base vectors (the base vectors has been defined by the differentiation of the location point transformation of curvilinear coordinate system)

Let us take the cylindrical transformation to Cartesian

x = r cos(q)

y = r sin(q)

z = z

g1 = g1x*i1+g1y*i2+g1z*i3

to get these components we differentiate each term of transformation vector with r

g1x = diff(r*cos(q), r)

g1y = diff(r*sin(q), r)

g1z = diff(z, r)

then we get the other

g2 also is the differentiation of all components with q

g3 is differentiating with z

Now to make the metric tensor we will use the dot product of vectors to get this 2nd order tensor which looks like matrix











I will not dive into details about characteristics of metric tensor but there are common rules about them

  1. contravariant * covariant metric tensors = Identity
  2. Covariant Metric Tensor * Covariant Vector = Contravariant Vector
  3. Contravariant Metric Tensor * Contravariant Vector = Covariant Vector.

So by getting the metric tensor for the curvilinear coordinate system (or any higher spaces if we want) then we can get the covariant and contravariant components of vector.

Metric Tensor with Quantity System

As my reader can see, you have to know many skills to get the metric tensor for specific coordinate system

  • Transformation equations
  • Differentiations
  • Dot Product
  • Matrix Algebra (for matrix inverse)

Without another mumbling let’s use the precious quantity system for this operation.

Continuing on the last transformation for cylindrical coordinates

  • Get g1
  • as it can be noticed differentiation has been made all over components of vector
  • Get g2
  • Get g3
  • Get the covariant metric tensor

You can notice that if you do Trigonometric simplification to the covariant metric tensor of cylindrical coordinates would be











Which is the right deduction for it (I didn’t implement simplification in symbolic algebra yet bear with me please J)

Calculating contravariant vector


  • Get a function from the metric tensor
  • Suppose that we have vector with r=3 theta=2 and z=10 as a covariant vector
  • Then to get contravariant vector we simply do the following



  • Quantity system make it easy to calculate the metric tensor
  • Quantity system make it easy to get covariant and contravariant vectors
  • I am very biased J
    J to the quantity system (I can’t help it actually)


Of course I am not claiming that my implementation is 100% error free (and you will see mistakes while playing with these calculations) however I am trying to say that the idea of blending symbolic calculations beside numerical calculations and getting the result easily and intuitively should enhance the global or macro view of mathematics and may increase the researcher ability to distinguish between these concepts and testing it easily while he is studying.

I also wish that I can reach a stable state that makes these calculations really reachable and easy for all of those interested beside being easy in using as an embedded language inside C# applications and .NET framework.


Thank you all for reading this so far.


Ahmed Sadek










Quantity System Types Architecture

Today I am going to talk about the types that the Quantity System contains in its runtime

I should make a distinction between two labels now:

  • Quantity System Framework: is the library responsible about Quantities and their units. It forms the required functionality that holds the necessary classes for embedding units and quantities in your application.
  • Quantity System: is the runtime that is built over the framework, that is evolving with time and its main concern is a new vision to apply the mathematics as a unit aware expressions.


I admit that I am learning mathematics again while programming this marvelous library, I learnt the compiler theory, parsing techniques, object oriented, and how can I apply it to physical applications.

I will try also to shorten my posts and increasing them to indicate the features that I’ve implemented so far. Also you (Dear reader) may encounter a lot of my thinking during the writings in this blog.

However let’s avoid my philosophy view of what I am doing and dive directly into the architecture.

Qs Types

There is a complex type that called QsScalar which serve the basic calculation type in Qs.

The architecture of types that is calculated is illustrated on the next diagram

Figure 1: Logical Relation between Qs Scalar and Tensor




The scalar in quantity is a single quantity that holds a defined set of fields beside the unit of that field.



The field is simply a Ring (Mathematical Point of View) or (Entity if I am talking from a programmer point of view)

Integer Numbers are a field, Real Numbers are a field, Rational Numbers are a field, Irrational Numbers are fields also.

But the concept of field goes beyond these samples also, because you can find Functions as Field.

The following diagram will illustrate the Scalar Object supported fields in Quantity System

Figure 2: Supported Mathematical Fields in QsScalar Type


Real Number


Rational Number

Which contains {Numerator, Denominator}


Complex Number

Which contains 2 components {Real Value, Imaginary Value}



Which contains 4 compnents {Real, i, j, k}


Symbolic variables that help in symbolic calculations



Referring to the function as a single quantity that can be added or subtracted


As I promised that’s all for now J

In the next posts, I will talk about the rest functionalities of Quantity System. So be tuned J

The New Release

you may wondering why is this long long version number

actually I don’t want to reach 1.2 soon, thats why I slow down in my releases counting

especially that I am still in ALPHA release

the new release is featuring  the new symbolic quantity concept which makes you do calculations with symbolics like mathematica and maxima BUT with my point of view of units

to declare a symbolic quantity you precede it with dollar sign ‘$’ and any number of charachters

$x+$y   is a valid expression for x plus y

lets have some fun

make a rank two matrix

h = [$x<in> $y<ft>; 4<fm> 3<mm>]

ofcourse <fm> is Femto Meter  ;)

get the determinant

Qs> |h| 

Area: 3*x-4.8E-11*y <>

What about 3 ranked matrix

Qs> m = [$x<in> $y<ft> $z<pm>; 4<fm> 3<mm> 2<yd>; $u<m> $v<ft> $w<rod>]

Qs> |m|

Volume: 3*x*w-110.836363636364*x*v+4363.63636363636*y*u-4.8E-11*y*w+9.54426151276544E-24*z*v-2.34848954546393E-11*z*u <>

This release also feature a tensor support

the tensor syntax will use ‘<|’  ‘|>’  which I don’t have a names for them now

as I understand (because I am not sure) I was reading the global relativity theory of Einstien (and I repeat I am not sure if  I got it right)  that Tensor is the ability to transfer your point of view from local co-ordinates into another reference co-ordinates

so that when you look into a matrix for example you see it as a square or rectangle

and to go into z-direction you have to use a tensor view like a cube (this is the 3rd order tensor)

however to go into more reference like 4th order tensor you need some sort of recursive representation for this problem

I found that I can use some sort of recursive magic in syntax

for tensor of matrix resemblance you can use the same matrix syntax

T2 = <| 3 4; 8 9 |> 

go into 3rd order tensor

T3 = <| 3 4; 8 9 | 8 7; 3 2|>

go into 4th order

T4 = <| <| 3 4; 8 9 | 8 7; 3 2|> | <| 3 4; 8 9 | 8 7; 3 2|> |>


T4 = <| T3 | T3 |>

and yes in storing this in memory I use a lot of inner objects (remember that I didn’t think about performance yet )

etc the 5th and 6th orders to the degree you want

BUT :(

all sources I read is only dealing with tensor of 2nd order

Needless to say how I get frustrated to understand what the heck is the tensor it really is (but it exists).

covariant, and contra variant vectors and tensors (some help needed here)
Another confusing thing (made my head spin)

If you make a vector, don’t safely consider it a first order tensor, also tensor of first order is NOT a vector

(I don’t know the validity of previous statement)

how is this differ in quantity system

make two vectors

v1 = {3 4 6}

v2 = {9 8 3}

multipy them tensorial ‘(*)

Qs> v1 (*) v2
       27 <1>        24 <1>         9 <1>
       36 <1>        32 <1>        12 <1>
       54 <1>        48 <1>        18 <1>

Great isn’t it

However what about tensor from the first order

Qs> tv1 = <|3 4 6|>
    QsTensor: 1st Order
        3 <1>         4 <1>         6 <1>

Qs> tv2 = <|9 8 3|>
    QsTensor: 1st Order
        9 <1>         8 <1>         3 <1>

Qs> tv1*tv2
    QsTensor: 2nd Order
       27 <1>        24 <1>         9 <1>
       36 <1>        32 <1>        12 <1>
       54 <1>        48 <1>        18 <1>

The difference is that ordinary tensor multiplication is different than the tensorial product of mathematical types other then the tensor.

The first one you have to use ‘(*)’ explicitly and the result was matrix

The second one you only used ‘*’ for multiplication and the result was a tensor from the 2nd order (and it called dyadic product)

another headache product called (kronecker product) for matrices

Try this

Qs> fm = [1 2; 3 4]
        1 <1>         2 <1>
        3 <1>         4 <1>

Qs> sm = [0 5; 6 7]
        0 <1>         5 <1>
        6 <1>         7 <1>

Qs> fm (*) sm
        0 <1>         5 <1>         0 <1>        10 <1>
        6 <1>         7 <1>        12 <1>        14 <1>
        0 <1>        15 <1>         0 <1>        20 <1>
       18 <1>        21 <1>        24 <1>        28 <1>

the result haven’t changed

Note: you may try two regular multiplication between 2nd order tensors but you will get an exception (because I didn’t implement it yet unless I understand)

About understanding all of these I didn’t imagine that I will go into all of this details (so I really walk into it as it appears to me)

I realized that (vectors, marices, and tensors) are another types of quantities

thats why their becomes a must if I would say.

what else ??

yep I tried to speed up things so I tweaked my parser and made a lot of improvements (but as an inner feeling something is not right, the speed is not satisfactory)

that was a long post as usual :)

good to write again :)  and see you safe and sound later :)

Symbolic Algebra Project

I have started Symbolic Algebra Project in CodePlex

WHY ??

Because I am a Silly Guy WHO really like to reinvent the WHEEL :D

I think this project will be the same concept of GiNaC

however being .NET natively should make my hear rest in peace this way

I am going to add derivatives also so wait for it to be released

(MAY be AfTeR long Time :) :) )

Work and Torque (Solution)

I am really sorry

I didn’t notice that I haven’t posted how did I solve the dilemma of Torque and Work Problem

however the solution was there in my discussion of quantity System

and also on this post of my personal blog

Problem Core: Length

Simply I defined TWO Length Types

Normal Length (NL)

This is the normal length that we refer to it in our daily life

Radial Length (RL)

This is the radius length that have an origin point in center of circle


Work:       Force * Normal Length

Torque:   Force * Radial Length

Angle:      Normal Length / Radial Length

In quantity system I made the L dimension as NL+RL


I made it explicitly a quantity that is NOT dimensionless

and THIS SOLVED ALL my problems of this Problem

I won’t argue much let us test :)

Torque * Angle = Work

F*RL * (NL/RL) =  F * NL    <== see what I mean

Torque * Angular Speed = Power

F*RL * (NL/RL*T) = F*NL/T   <== where T is the time.

so you may wonder about Angle and Solid Angle

in SI they are all dimensionless  but in Quantity System YOU CAN’T consider them like this

(By the way I’ve break the checking for these two quantities to be summable with dimensionless numbers – just to keep the fundamentals as it is although I am not convinced and I may remove it in future but damn it I need support from any physics guy)


Solid Angle:  NL^2/RL^2   because its area over area

Frequency =  1/T

Angular Velocity = (NL/RL)/T

do you remember the conversion between RPM to frequency

RPM (Revolution Per Minute) is a Angle / Time

lets test the law

Omega  = 2*pi*frequency

pi: radian value which is  NL/RL

Omega = (NL/RL) * 1/T = (NL/RL)/T   which  angular velocity


PI value

PI is ratio of any circle‘s circumference to its diameter    WHICH MEANS  (NL/RL)

this is the same value as the ratio of a circle’s area to the square of its radius     WHICH MEANS  (NL^2/RL^2)

which corresponds to radian unit and stradian unit for angle and solid angle quantities.

Reynolds Number

I am not holding back ( Reynolds number is a dimensionless number that measure inertial forces to viscous forces)

WHY we always differentiating between Flow in Pipes and Flow on Flat plate

let’s see with normal length in quantity system

Qs> rho = 3[Density]
Density: 3 <kg/m^3>
Qs> v=0.5<m/s>
Speed: 0.5 <m/s>
Qs> l=4<m>
Length: 4 m
Qs> mue = 2<Pa.s>
Viscosity: 2 <Pa.s>
Qs> rho*v*l/mue
DimensionlessQuantity: 3 <kg/m.s^2.Pa>

it shows it is a dimensionless quantity

ok let us force my theory about flow in pipes

the pipe have a diameter  and Reynolds number is calculated by rho*v*DIAMETER/viscosity

so let me add d as a diameter and solve again

Qs> d=0.5<m!>

RadiusLength: 0.5 m

Qs> rho*v*d/mue

DerivedQuantity: 0.375 <kg/m.s^2.Pa>

NOTE: Adding ‘!’ after the length unit will mark the quantity as Radial Length quantity.

ERROR  it shouldn’t be DerivedQuantity at all it should be Dimensionlesss

so there is another term that should be fixed. Do you know which term ???

lets try the velocity  with vr=0.5<m!/s>

Qs> vr=0.5<m!/s>

DerivedQuantity: 0.5 <m/s>

Qs> rho*vr*d/mue

DerivedQuantity: 0.375 <kg/m.s^2.Pa>


ok let us try the density

Qs> rhor = 3<kg/m!^3>

DerivedQuantity: 3 <kg/m^3>

Qs> rhor*v*d/mue

SolidAngle: 0.375 <kg/m.s^2.Pa>


do you remember the above argue about Solid Angle is dimensionless number

can I pretend now that reynolds number for pipes is CORRECT ???

the new density which is kg/m!^3

This is driving me nuts

Pump Affinity Laws

Also  pump equations led to the same SolidAngle Quantity not DimensionLess one


I’ve said what I’ve discovered till now about this problem I hope that may be someday someone explain to me or convince me that Angle is really a Dimensionless number   after all of this and that my assumption about Torque and Work is Wrong.

Catching Up


I want to catch up with what I’ve implemented so far.

This is not what’s new, but rather a glimpse on what I’ve done and still remembering it

I really need to organize my thoughts about what is happening in this project

the scattering thoughts are frightening me :S

Tensor Parsing:

I want to add Tensor badly in Qs because I wasn’t able to understand it I had to include it

however I’ve Added Tensor parsing

Qs> <|4 3;3 2| 4 5; 5 3 |>

Yes this is a 3rd rank tensor  or you may see it as a two matrices in the Z-Axis

what about 4th Tensor (You may ask) ??!!   Bear with me I am still thinking of a natural syntax to add it.

also I would like to remind my self that Stress tensor is a 2nd rank tensor (which looks like matrix but with special operations)

using <|…|>  syntax you can define also zero rank tensor up to 3rd rank tensor (what will I do with this?? I don’t KNOW)


yes I included the text at last (I was struggling against putting text in Qs, but it was necessary :S or let me say I couldn’t come up with another strategy.

Qs> ml = “c d e f g a b c>”;

Qs> Music:Play(ml + ” ” ml);     #Music:Play is an extension function that play midi and the music library is 100% implemented by me (I mean sequencer part and music DSL as it contains eastern tones also – another story indeed)

and yes you can add text to text, also imagine you can add text to number

Qs> 4 + “44″

DimensionlessQuantity: 48 <1>

but the opposite is will not act like this (because I am casting to the left type always – which is the first one in fact)

What is meant by adding text is to differentiate between sending text to functions and sending other types.

so Windows:MessageBox  function now accept Text

Windows:MessageBox(“Hello There”)  will result into messagebox ofcourse (just try it)

to escape quotation mark  use back slash “\”hello\””


I like it :) (do you ?!? :):))

Function Extensions

With C# or any .Net language frankly {put static class with static functions under Qs.Modules namespace}

the class name becomes namespace in Qs.

- I’ve enhanced the function binding so you can write your C# native function with native numerical type and I will cast it to you without you notice it ( no more QsValue as a parameter type), however this will add other processing lag (but who cares :D everything is cached after this)

also I can map vector to array of numbers so use ff(int[] ia)  declaration :) it will work

Why I was enhancing the extension functions {simply because I am planning to include OpenGL } asking me why :O :O :O ??

silly, every numerical system has a 3d device to render to it.

but frankly I am thinking of visualizing Scalars, vectors, and tensors into 3d conceptual drawings

however OpenGL  is  a very far idea


don’t forget the Graph:Plot(xvector, y1vector)  it really draws and I consumed a free opensource library to do it.

may be a freakin plot but hey it works and I can visualize some quick samples indeed.

Function Named Arguments

Quantity System Engine can consume different declaration to the function with the same name

however you must change the parameter names

that’s why you can call the function with named arguments (shhsh  argument==parameter so I use it interchangeably)

all the following are correct declarations

f(x) = x

f(y) = y^1.5

f(z) = z^2

f(er) = er/4

f(g) = g+9/g^2

Note:  the first function name declared is the (default function) the one you call it without specify named arguments

to call any of these functions use the ‘=’ equal sign


Function Variables

Now you can treat the functions as normal variables because they are inherited from QsValue (internal structure of Qs)

so that when declaring

u(x) = x^2

v(x) = x/2

w(x) = x*9

r = @u+@v+@w      #  <==   this sum all functions and generate new function in r

r(x) = x^2+x/2+x*9

and don’t worry about parameters, as they are merged for you with any number of them

all basic operations supported (simply I merge the function declaration text with the desired operator :))

HOWEVER this is going to change after I put the symbolic algebra library :) (another library I am making) :( :(

What about named argument functions??!! (clever question)

imagine you have a x-component speed in u function

u(x) = x

u(y) = y/2

u(z) = z^2.1

you can write

u = @u(x) + @u(y) +@u(z)

and yes

Qs> u(3,4,5)   #IT WILL Work

because you may not remember but I encode the functions in the memory based on their arguments number also

so u(x,y,z) now is the default function of u in 3 arguments ;)  (impressive for me I admit)


my beloved feature.

sequence now can return a function series

for example

e[n](x) ..> x^n/n!

e[1](1)  gives 1

however calling the sequence without specify argument (IN argument enables sequence)

e[1]  gives _(x) = x^1/1!

and you can assign it to a function also

let me make it fast

exp = e[0++20]


_(x) = (x^0/0!) + (x^1/1!) + (x^2/2!) + (x^3/3!) + (x^4/4!) + (x^5/5!) + (x^6/6!) + (x^7/7!) + (x^8/8!) + (x^9/9!) + (x^10/10!) + (x^11/11!) + (x^12/12!) + (x^13/13!) + (x^14/14!) + (x^15/15!) + (x^16/16!) + (x^17/17!) + (x^18/18!) + (x^19/19!) + (x^20/20!)

which when you can call your exp normally


Shifting Operators

I’ve added ‘>>‘ right shift as C family  and ‘<<‘ left shift

simply the operators is shifting vectors and matrices

not implemented yet for tensors

and also you will find these operators starting of Qs release  Changeset 39690

I hope I listed things that I remembered for now

and chaao :D

‘When-Otherwise’ Condition Expression

In Quantity System Calculator (DLR)  I’ve implemented a new way of conditional expression that can be written continuously and fits into one line.

I called it  ‘when-otherwise’ expression

‘[true result] when [test] otherwise [false result] when …’

let us define a simple function with it

f(x)  = x when x< 10 otherwise x^2 when x<20 otherwise x^5

I know that I am going against the famous ‘if-then’ statement, however ‘if-then’ statement is an imperative syntax, and I needed a functional statement that fits in one line.

when I was thinking about this new syntax I also didn’t ignore the question syntax of C,C++, C#

‘Test?True Part, False Part’ , but also this syntax is somehow complex to use, and give me a headache actually.

thats why I invented it this way. You can see that the result part precede the condition part and the syntax is truly easy to remember (hard to type) but easy to extend.


Get every new post delivered to your Inbox.