# Open Source C# Physics Library

• C/++/#
Summary:
I've started work on a physics library in C#. I work professionally as a programmer and have a physics degree, however the idea of turning physics into code never really occurred to me. So far it's been fun. Project is open source. Join!
TL:DR;

I've started an open source C# physics library: University Physics

The Long Version

So it turns out there's relatively little in the way of full physics libraries written in C# (the best I can find is bepuphysics which seems to be focused only on classical mechanics). With this discovery as motivation, I've decided to start work on a C# library for performing as much general physics calculation as possible, in all sub-topics of physics.

So that's mechanics, electromagnetism, thermodynamics, quantum mechanics, fluid dynamics... anything involving turning the real world into equations and numbers. The library will be useful in basic games, simulations and as a basic learning tool for people interested in physics and programming via C#.

The aim is to simplify the work that is required to turn a set of physical values or items into a useful result. A personal example is in a physics simulator I created several years ago, in which a load of particles floated around the screen and repelled each other on close proximity with other particles.

For that simulator, I needed to write the code for electrostatic force myself from scratch. Via this new physics library, it would be as simple as:

C#:
ParticleSet particles = new ParticleSet
{
Particles = new List<Particle>()
{
new Particle(mass: 1, position: new Vector(0,1,0), charge: 1),
new Particle(mass: 1, position: new Vector(0,2,0), charge: 1),
new Particle(mass: 1, position: new Vector(3,2,0), charge: 4),
new Particle(mass: 1, position: new Vector(1,0,0), charge: 1),
}
}

particleSet.Move(timeDelta: t);

So basically the user just creates what they want, sets it up and presses 'Go'.

At first I'm going to go through the classic University Physics textbook (Young & Freedman), turning as much of the content as possible into usable objects and classes. After that I'll move onto more advanced subjects, or just whatever takes my fancy as I go.

The primary aim at the moment is to just create a library of 'physics stuff'. Performance and optimisation will come later.

I'm setting up this thread for two purposes:

1. To provide updates on progress
2. To inform others about the project so they can join in if they wish

I've never worked on an open source project before, so this aspect is being entered with a mixture of interest and mild trepidation.

If you're interested in contributing to the project, reply to this thread or follow/fork the project on GitHub.

Project Repository is here: University Physics

Thanks

JD_PM and jedishrfu

jedishrfu
Mentor
Theres a couple of other libraries for Java:

- open source physics aka OSP at www.compadre.org
- processing IDE has several third party physical sim and particle systems libraries that are quite awesome

And theres the Gould Christian Tobochnik book with how to use OSP in a variety of situations.

You might get some inspiration and code ideas from them.

Have fun coding.

jedishrfu
Mentor
Also you should check out the Openstax University Physics book. Its free and is comparable to University Physics that you mentioned.

Openstax.org

sa1988
Also you should check out the Openstax University Physics book. Its free and is comparable to University Physics that you mentioned.

Openstax.org

Thanks, looks like a good resource.

I already saw OSP before I created this post. Looks like it could prove useful for some stuff, though I must admit I'm more keen to do my work 'from scratch', for the sake of my own learning. OSP is certainly good to have available anyway. I'll see how things go

jedishrfu
Mentor
There some things in sims that you will trip over when trying to over optimize your code and so it’s always good to see how others approached it.

sa1988
Check out Computational Physics by Jos Thijssen, it's the best book I could find on 'generic' computational physics. Others are either too simple or more complex but specialized on narrow subjects.

A lot of my projects on GitHub are started from ideas from that book: https://github.com/aromanro?tab=repositories They are described on my blog, here: https://compphys.go.ro/ The code is C++, though.

sa1988
phinds
Gold Member
So it turns out there's relatively little in the way of full physics libraries written in C#
Hardly surprising since it's a proprietary language and hardly used compared to the more popular languages.

from C#

C# ("C sharp") is Microsoft's attempt to create a C language that is purely object-oriented like Java. C# is proprietary to Microsoft and thus is not used on other platforms (Apple, Unix, etc). I don't know if it is still true, but an early comment about C# was "C# is sort of Java with reliability, productivity and security deleted".

jedishrfu
Check out Computational Physics by Jos Thijssen, it's the best book I could find on 'generic' computational physics. Others are either too simple or more complex but specialized on narrow subjects.

A lot of my projects on GitHub are started from ideas from that book: https://github.com/aromanro?tab=repositories They are described on my blog, here: https://compphys.go.ro/ The code is C++, though.

Nice, you've got some pretty cool stuff there. I intend make a load of graphical sims after I've got the library done.

Hardly surprising since it's a proprietary language and hardly used compared to the more popular languages.

from C#

A very out of date opinion.

C# is number 5 in the TIOBE Index (it used to be 3rd!).

I follow programming trends and chatter much more closely than I follow physics. Among professional programmers, C# is generally considered to be "not quite as widely used but generally better than Java". It's cross-platform and works on Linux too.

I know it was hated and seen as a corporate invasion by Microsoft when it was released. That was a long time ago.

DavidSnider and phinds
jedishrfu
Mentor
jedishrfu
Mentor
Okay lets get back to the thread topic.

Programmers choose languages based on the application development environment and for purposes of this thread the OP is filling a perceived need in the C# .Net world.

Hence C# is the language of choice.

Does anyone have some useful suggestions for important routines for this new library?

I know a convolution routine would be good and perhaps some interpolation routines for 1D and 2D arrays.

C#’s inability to run outside the windows ecosystem limits it for many cross platform applications though.

https://www.guru99.com/java-vs-c-sharp-key-difference.html

C# is cross-platform, open source and free. Windows, Linux, Apple, Android, you name it (but you're right, Kotlin is 'winning' for Android - and Swift is the thing for iOS now).

Admittedly Java is still king for cross-platform, but C# is at least technically better

Project Update

Started work on some Thermodynamics classes.

It's all very simple stuff for now.

An energy converter:

C#:
EnergyConverter e = new EnergyConverter(500, EnergyMeasure.Joules);

// e.Joules = 500;
// e.ElectronVolts = 3.1208E21;
// e.MegaElectronVolts  = 3.1208E15
// e.KilowattHours  = 0.00013889;

A Temperature class:

C#:
Temperature temp = new Temperature(100, TemperatureType.Kelvin);

// temp.Kelvin  = 100;
// temp.Celsius = -173.15;
// temp.Fahrenheit = -279.67;

//// Can be instantiated with implicit conversion from double value (in Kelvin)

Temperature temp2 = 100;

// temp2.Kelvin  = 100;
// temp2.Celsius = -173.15;
// temp2.Fahrenheit = -279.67;

And a simple class of methods for performing basic substance calculations

C#:
// BasicThermodynamics.SubstanceEquations

//Based on pV = nRT

double volume = 100; // m^3
double n_moles = 12; // moles
Temperature temp = 350; // Kelvin

double pressure = BasicThermodynamics.SubstanceEquations.Pressure(volume, n_moles, temp);

// pressure = 349.208

// Also contains method for:
//
// Volume()
// n_Moles()
// Temperature()
// MolarMass()
// TotalTranslationalEnergy ()
// EnergyPerMolecule()
// RMS_Speed()
// MeanFreePath()

I was never too keen on thermodynamics so I probably won't do much more advanced than this for now.

Project Update

Added VectorField class, especially useful for simulating motion in things like fluid dynamics.

Simply create a system of particles (or any class derived from PhysicsObjectBase)

C#:
List<Particle> myParticles = new List<Particle();

Random rand = new Random();

VelocityField vField = FluidDynamics.CommonVelocityFields.RankineVortex;

for(int i = 0; i< 500; i++){

int xPos = r.Next(0, 500);
int yPos = r.Next(0, 500);

Vector pos = new Vector(xPos, yPos);

Particle p = new Particle(mass: 5, position: pos);

p.ApplyVelocityField(vField);

}

Then, for example, the system can be set to evolve with time.

C#:
while(simulationRunning){

foreach(Particle p in myParticles){

p.Move(timeDelta: t);
//timeDelta would come from a timer/clock of some variety.
}

// Particles will move as dictated by their given velocity field.
}

I'm working on a visual representation of this now, to show how it can be used in graphical simulation.

This is awesome. I am currently learning C# for the purposes of modelling physics. I am an undergraduate about to graduate with a degree in physics who unfortunately didn't get much programming experience in school. So i'm a late bloomer but I am working through courses on C# at the moment and plan to use this library and hopefully contribute as well :)

sa1988
jedishrfu
Mentor
Thanks for sharing.

pbuk
Gold Member
Very late update but I've been busy changing countries and starting a new job...

Thanks to @BeyondBelief96 for the first outside contribution, the ComplexNumber class

https://github.com/Stuart88/University-Physics/wiki/Complex-Numbers

It does all basic complex number operations including addition, subtraction, multiplication, division, magnitude, phase and conjugation.
It's great that you are getting collaboration. I have a couple of observations on consistency within the new class:
• Why is ComplexNumber::getConjugate() implemented as a method whereas all other unary operations (magnitude, real part etc.) implemented as getters?
• ComplexNumber::Conjugate() is the only method that modifies a ComplexNumber which is otherwise immutable - oh also set RealPart and set ImaginaryPart. These should be removed (possibly into a new MutableComplexNumber class along with AddInPlace etc. methods).
And a suggestion: there are some methods 'missing' - ComplexNumber::pow is an obvious one. Oh I see your library uses PascalCase for method names so that should be ComplexNumber::Pow.

Hmmm, I see there are some tests but it doesn't look like nearly enough - what about edge cases? I'm also not sure about using a tolerance for the == override - wow, the tolerance is an absolute number so 1e-10 + 0i == 0 is true but 10000000.0000001 + 0i == 10000000 is false. A bit more work needed I think.

Last edited:
sa1988 and jedishrfu
pbuk
Gold Member
Just realised this is C# where you will usually have access to System.Numerics.Complex (and also System.Numerics.Vector). Is the more interesting and useful stuff you mentioned at the top of this thread ready for release yet?

It's great that you are getting collaboration. I have a couple of observations on consistency within the new class:
• Why is ComplexNumber::getConjugate() implemented as a method whereas all other unary operations (magnitude, real part etc.) implemented as getters?

For no reason at all :D

Fixed now.

ComplexNumber::Conjugate() is the only method that modifies a ComplexNumber which is otherwise immutable - oh also set RealPart and set ImaginaryPart. These should be removed (possibly into a new MutableComplexNumber class along with AddInPlace etc. methods)

You're probably right with this suggestion but it seems a bit of a rabbit hole to go down at the moment. I suspect every class will have issues like this. My aim was to first make classes that simply "do the maths/physics", then later go on an optimisation quest.

And a suggestion: there are some methods 'missing' - ComplexNumber::pow is an obvious one

'Tis a work in progress!

Hmmm, I see there are some tests but it doesn't look like nearly enough - what about edge cases? I'm also not sure about using a tolerance for the == override - wow, the tolerance is an absolute number so 1e-10 + 0i == 0 is true but 10000000.0000001 + 0i == 10000000 is false. A bit more work needed I think.

Ha! I forgot about this. I was actually using something a little bit better in my unit tests; going for a 0.5% acceptable tolerance between values. That unit test comparison code is now shifted over to the main library. (See : https://github.com/Stuart88/Univers.../University Physics/Maths/MathsHelpers.cs#L97)

My method of comparison seems to be the accepted thing to do, however... with this being a physics library, it needs to deal with comparison of very large and very small numbers, so that 0.5% can vary wildly and is simply not correct (e.g. 199.9 and 200 are considered equal!).

Next plan of action is to get this sorted. Probably need to have different comparison methods for large numbers and small numbers, with some sort of cut-off point to decide what defines 'large' or 'small'.

Just realised this is C# where you will usually have access to System.Numerics.Complex (and also System.Numerics.Vector)

Yeah, there are maths libraries for all sorts that I could have used (and perhaps I still will). I was just enjoying making some stuff for myself.

. Is the more interesting and useful stuff you mentioned at the top of this thread ready for release yet?

I'd like to say the other bits are good to go, but since the tolerance stuff isn't quite right for unit testing, I can't guarantee that things are perfect.

A while ago I used the fluid dynamics part of the library to create a working 2D fluid motion sim on Android, so I can at least confirm that the fluid dynamics part gives something of an 'expected' result.

jedishrfu
Mentor
Be careful of the notion of knocking out a version and then later going back to fix it.

As folks begin to use it, they will be rather upset if you remove functionality or break functionality in your quest to optimize and will dump your project for a better managed one.

the same goes for how you name functions and classes, a lot Of thought needs to be put into it so it doesn’t changes with future versions unless it’s done through deprecation.

you will want folks to always use your latest stable build which means changes that introduce errors into user apps will make those users reluctant to upgrade.

pbuk and sa1988
Be careful of the notion of knocking out a version and then later going back to fix it.

As folks begin to use it, they will be rather upset if you remove functionality or break functionality in your quest to optimize and will dump your project for a better managed one.

the same goes for how you name functions and classes, a lot Of thought needs to be put into it so it doesn’t changes with future versions unless it’s done through deprecation.

you will want folks to always use your latest stable build which means changes that introduce errors into user apps will make those users reluctant to upgrade.

Yeah that's a fair point, and one which I never really considered. This was only supposed to be a bit of fun, but I might as well try to do things properly.

As a programmer I've never really had the responsibility of doing proper devops for something like this, where new releases need to stay in line with old ones, so this is a perfect learning exercise.

Maybe my next step will be to formulate a large wire frame and/or road map to prevent any breaking changes or reshuffles later on.

Thanks for the pointer.

jedishrfu
Mentor
Also consider developing a parallel set of test cases covering edge cases that is run every time you change things. It will catch a lot of semantic typos in your code and verifynthat edgecases work too.

in particular, the floating pt comparisons need to be done with a changeable tolerance not precisely 0.0. This is why some programmers will develop code but use well known public math libraries over custom built ones.

The Julia programming language comes to mind where under the covers they defer to a BLAS compliant library for linear algebra support.

https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms