Open Source C# Physics Library

In summary, an open source C# physics library called University Physics has been started with the aim of creating a comprehensive library for performing various physics calculations in C#. The library will cover topics such as mechanics, electromagnetism, thermodynamics, and quantum mechanics. The developer plans to start with the classic University Physics textbook and then move on to more advanced subjects. The project is open for contributions and the developer is also seeking inspiration from other resources such as the Openstax University Physics book. While C# may not be as widely used as other languages, it is still popular and considered to be better than Java by many professional programmers.
  • #1
sa1988
222
23
TL;DR 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 :oldbiggrin:
 
  • Like
Likes JD_PM and jedishrfu
Technology news on Phys.org
  • #2
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 there's 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.
 
  • #3
Also you should check out the Openstax University Physics book. Its free and is comparable to University Physics that you mentioned.

Openstax.org
 
  • Like
Likes sa1988
  • #4
jedishrfu said:
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 :smile:
 
  • #5
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.
 
  • Like
Likes sa1988
  • #6
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.
 
  • Like
Likes sa1988
  • #7
sa1988 said:
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".
 
  • Like
Likes jedishrfu
  • #8
aaroman said:
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.
 
  • #9
phinds said:
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.
 
  • Like
  • Informative
Likes DavidSnider and phinds
  • #10
  • #11
  • #12
Okay let's 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.
 
  • #13
jedishrfu said:
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 🧐
 
  • #14
Project Update

Started work on some https://github.com/Stuart88/University-Physics/tree/master/Thermodynamics.

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.
 
  • #15
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);
    
    myParticles.Add(p);
}

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.
 
  • #16
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 :)
 
  • Like
Likes sa1988
  • #19
sa1988 said:
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 :oldbiggrin:

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:
  • Like
Likes sa1988 and jedishrfu
  • #20
Just realized 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?
 
  • #21
pbuk said:
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 realized 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.
 
  • #22
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.
 
  • Like
Likes pbuk and sa1988
  • #23
jedishrfu said:
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.
 
  • #24
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
 
  • #26
I've added a disclaimer in the github project page warning folk that it's still in the very early development phase.

I can now wash my hands of all complaints if I decide to shuffle things around at will :oldlaugh:
 
  • #27
sa1988 said:
My method of comparison seems to be the accepted thing to do,
It is now, but it wasn't when I was looking at the code before commit dd51f03 yesterday :rolleyes:.

A tolerance of 0.5% is way too high - I would go for something like ## 16 \epsilon = 2^{-52+4} ## which allows for roundoff error in the two numbers to be compared plus some propagation within the routine (there is probably a standard but I can't find one at the moment) - back this up with some testing, you want 1/100 * 10 * 10 == 1 to be true but probably not if you iterate this 10 times. Be careful with your tests that the compiler is not optimizing away the inaccuracy (e.g. approx = 1 / 100 * 10 * 10 will be optimized to approx = 1).

You could overload the method with
Code:
public static bool WithinTolerance(double result, double expected, double tolerance)
where a more generous allowance is required.
 
  • #28
pbuk said:
It is now, but it wasn't when I was looking at the code before commit dd51f03 yesterday :rolleyes:.

Indeed. Not sure what point you're trying to make there.

A tolerance of 0.5% is way too high - I would go for something like 16ϵ=2−52+4 which allows for roundoff error in the two numbers to be compared plus some propagation within the routine (there is probably a standard but I can't find one at the moment) - back this up with some testing, you want 1/100 * 10 * 10 == 1 to be true but probably not if you iterate this 10 times. Be careful with your tests that the compiler is not optimizing away the inaccuracy (e.g. approx = 1 / 100 * 10 * 10 will be optimized to approx = 1).

You could overload the method with
Code:
public static bool WithinTolerance(double result, double expected, double tolerance)
where a more generous allowance is required.

Yeah the 0.5% tolerance thing was a mistake. It's because I was primarily thinking of very small numbers, where floating point errors can easily cause a difference of 0.5%.

To be honest the project only started out as a hacky thing for "doing physics with some code". Getting correct numbers from bog standard physics equations was the main aim; the true scale of floating point comparison concerns did not even register at that time. What can I say, I'm not a computer scientist!

I'll have a look into your suggestions later, thanks.
 
  • #29
sa1988 said:
Getting correct numbers from bog standard physics equations was the main aim; the true scale of floating point comparison concerns did not even register at that time.
You are not alone, this is a common pitfall for those without a formal training in numerical methods. From your profile I see that you are "considering taking a masters or postgraduate diploma in computational fluid dynamics in the near future" - you have just covered the first lecture!
 
  • Like
Likes sa1988
  • #30
pbuk said:
You are not alone, this is a common pitfall for those without a formal training in numerical methods. From your profile I see that you are "considering taking a masters or postgraduate diploma in computational fluid dynamics in the near future" - you have just covered the first lecture!

Ha, I should probably change that. Several years have passed since then, and my academic path stopped after BSc.

I ended up going into software development... (but not the kind for which floating point errors are an issue!).
 

1. What is an open source C# physics library?

An open source C# physics library is a collection of code and algorithms that allow developers to simulate and model physical phenomena using the C# programming language. It is free and available for anyone to use, modify, and distribute.

2. What are the benefits of using an open source C# physics library?

There are several benefits to using an open source C# physics library, including:

  • Cost-effective: Since it is free to use, developers can save money on licensing fees.
  • Customizable: Developers can modify the code to suit their specific needs and requirements.
  • Collaborative: Open source projects encourage collaboration and knowledge sharing among developers.
  • Community support: There is often a community of developers who can provide support and assistance with using the library.

3. How does an open source C# physics library work?

An open source C# physics library typically works by utilizing mathematical equations and algorithms to simulate and model physical phenomena. It may also include pre-built functions and classes for common physics calculations, making it easier for developers to incorporate physics into their projects.

4. Can an open source C# physics library be used for commercial purposes?

Yes, most open source C# physics libraries are released under permissive licenses, which allow for commercial use. However, it is important to carefully read the license terms and conditions before using the library for commercial purposes.

5. Are there any popular open source C# physics libraries available?

Yes, there are several popular open source C# physics libraries, including:

  • Box2DSharp: A 2D physics engine for C#.
  • SharpPhysics: A 3D physics engine for C#.
  • Jitter: A 3D physics engine for C# and .NET.
  • Farseer Physics: A 2D physics engine for C# and XNA.

Similar threads

  • Programming and Computer Science
Replies
10
Views
2K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
7
Views
1K
  • Programming and Computer Science
Replies
5
Views
959
  • Programming and Computer Science
Replies
17
Views
3K
  • Programming and Computer Science
Replies
4
Views
5K
  • Programming and Computer Science
Replies
1
Views
377
  • STEM Academic Advising
Replies
8
Views
827
  • Programming and Computer Science
Replies
1
Views
2K
Back
Top