Method for sorting atomic orbitals (slightly scientific)

[I wasn’t sure which forum to post this (Code or Science and Engineering) , so if it is found inadequate due to not being specifically about programming then I will understand completely]

As a personal side project, I have decided to create a python script that displays the electrons in each shell in an atom (when the number of electrons is inputted).

I know this isn’t the scientific category, and that’s not where I’m having an issue. I can do this on pen and paper - my issue is actually implementing this into code.

I briefly explain what I need to do:

As a general rule, the order of filling atomic orbitals is given as n + l, where n refers to the shell number and l represents the orbitals respectively (i.e 1 = s, 2 = p etc).
The lowest sum of n + l value is indicative of which orbital to fill (in ascending order).
(and yes I’m aware there is exceptions to this, such as group 11)

I hope this isn’t seen as spam, but this is what I’m on about:
1(n) + 1(l) = 2(the “1 s” orbital is filled first, as it has the lowest sum value)
2(n) + 1(l) = 3(the “2 s” orbital is filled second, as it has the next lowest sum value)
2(n) + 2(l) = 4(the “2 p” orbital is filled third)
3(n) + 1(l) = 4(the “3 s” orbital is filled next)
3(n) + 2(l) = 5(the “3 p” orbital is filled next)
[THIS IS WHERE THE PATTERN BREAKS]
4(n) + 1(l) = 5, where:
3(n) + 3(l) = 6

Here is a diagram of the above:
https://upload.wikimedia.org/wikipedia/commons/1/15/Aufbau_Principle.png

I was thinking along the lines of a bubble sort function, that essentially does the above, storing the resulting “1 s”, “2 s” etc in a list, which would be representative of the filling pattern.

Thank you so much to anyone who even takes the time to respond at all to this, as conveying this through speech is hard enough, let alone through a keyboard!

There are a couple of ways to do this. You can use a sort, cases statements, or recursion to achieve the task.

I would lean towards recursion the way that you laid out the rules. Once you get that working, then you can look at putting a sort with logic that performs equivalently.

Are you familiar with these algorithm concepts?

No I’m not please can you elaborate? Thank you

And that timing tho.

Recursion https://en.wikipedia.org/wiki/Recursion_(computer_science)
Case Statements https://en.wikipedia.org/wiki/Switch_statement
Sort Algorithms https://en.wikipedia.org/wiki/Sorting_algorithm
Factorials https://en.wikipedia.org/wiki/Factorial

So with recursion, you take all of the information and push it onto a stack. This is also known as a First In Last Out Queue. You feed the input to the function and it will keep breaking things down until it achieves a stopping case. Once that happens, the function then starts popping things off of the stack. by the nature of the algorithm, once you achieve the stopping case, you can design it so that the echo out to console or file the order of the orbitals based on finding the first to be filled, pop off stack, second to be filled, pop off stack, third … all the way to to the starting case.

Look at the following example for demonstration. I don’t know how to explain this using layman terms.
4! (Four Factorial)
4! = 24 But how.

Iterative thinking, 4! = 1234 or 4321. Both equal 24.

Recursively, 4! = 4 * 3!. But what is 3!? Well that is 3 * 2!. 2! = 2 * 1!. 1! is 1 * 1. this can all be rewritten as the following series.
4! = 4 * 3!
= 4 * (3 * (2 * (1)))
The inner most parenthesis is the stopping case. Using the first Inner - Outer principle, 1234 =24.
If you imagine that we were printing out at each stage once we get to out stopping case (1! always equals 1
1) we have let the basic rules of factorial create the solution of outputting the math starting with the most basic factor all the way to the starting factor.

I know that I make the assumption that you know what factorials are and the fact that you have to actually code this to work has been obscured. But do you see the concept.

If you were to do this with sorting, you would need put a lot of if statements and you would have to reduce everything down to the starting case anyway and work your way up using a reversed for loop at best.

Case statements are literally, if value at is X, then do , returned to case to evaluate.

I am doing this from a phone so I hope that I did not confuse you. If it helps. Look up factorial program examples to understand how to code the recursive function.

1 Like

Just a note, normal sorting algorithms work for anything that you can compare. All you need is to find a way of comparing orbitals that follow the aufbau principle.
And according to wikipedia

1. Electrons are assigned to orbitals in order of increasing value of (n+ℓ).
2. For subshells with the same value of (n+ℓ), electrons are assigned first to the sub shell with lower n. 

So it seems quite possible to create an object with a principal and orbital quantum number which compares according to these rules. If n+l is equal, compare n, otherwise compare n+l. Then you can sort these objects with whatever sorting algorithm you like.

As has been pointed out though, there are other options.
I think if you have a list of orbitals and need to order them, sorting is the right option.
But if you want to list all orbitals in order, or perhaps get an arbitrary one (like, which orbital is the 9th one) then some other way might be better. Because creating a list and sorting it is a lot of overhead if all you want to know is a single position in the list.

Well said compared to my ramblings.

Okay thank you all for your responses.

My reason for not responding quickly is because I have been attempting to try this out (to no prevail) - it just seems I can’t get my head around loops!

I’m not looking for an opportunity for a quick copy/paste, but I would be most grateful is someone could provide a practical example (preferably in Python) of a sorting algorithm that puts the orbitals in order “1s, 2s, 2p, 3s, 3d, 4s, 3p” etc, mostly for my own learning rather than anything else at this point.

Again thank you so much all.

Sure. This is how I might do it. I made a function that creates them orbitals in order, and also sort them using the build in sort using a function that makes them comparable.

import random


class Orbital:
    def __init__(self, n, l):
        self.n = n
        self.l = l

    def __repr__(self):
        return str(self.n) + ['s', 'p', 'd', 'f'][self.l - 1] # TODO extend list for higher l values if neccessary


def list_orbitals(N):
    # Make a list of the first N orbitals in order
    k = 1 # sum of n+l
    orbitals = []
    while (True):
        # outer loop of the sum of n+l. This makes sense as this always increases or stays the same
        for n in range(k//2, k):
            # inner loop going through all the options at one value of n+l.
            # Since l <= n, the number of possible n values are reduced.
            # So by looping from k//2 (integer division that rounds down) we can avoid these unallowed values
            orbitals.append(Orbital(n + 1, k-n))
            N -= 1
            if N == 0: # have we found as many as requested yet?
                return orbitals
        k += 1


if __name__ == "__main__":
    orbs = list_orbitals(15)
    print(orbs)

    # And let's demonstrate sorting because why not.
    # Shuffle
    random.shuffle(orbs)
    print(orbs)

    # sorting
    # I'm a little bit unfamiliar with implementing custom sorts in python, so this might not be the best way
    # The idea is that I convert an orbital object into a number, which python knows how to sort
    # And I think (n+l)^2 + n will sort in the right way. (i.e. n+l always most important, but n matters on n+l ties)
    # I'm more familiar with the c++ operator overloading or custom comparator way.
    orbs.sort(key=lambda orb: (orb.n + orb.l)**2 + orb.n)
    print(orbs)

Hopefully comments make it somewhat clear. And no promises my code is bug free :slight_smile:

1 Like

Cheers for that Sandalmoth, I’ve managed to get it working. If you don’t mind me asking do you have a degree of any kind in Computer Science/ Software Engineering?

Merry Christmas / Happy Holidays

Nope, I’ve got a chemistry degree. But I do computational chemistry/biology stuff now, so I get a fair bit of programming practice. Mostly self taught programmer though.

1 Like

I will try to take a stab at the recursive approach today. I don’t dabble with python much so… You have been warned.

Do you know what I think would be really cool? Instead of representing the shells using the 2d Bohr model, I could use an openGL library (I think python has one) and make a 3d model. Kinda like this:

How hard would that be? I’ve no idea has I have done nothing like this before.

Sorry that I have not delivered. I sat down to do this and then life happened.

Python is not my strong point. Simple graphics are not hard, just tedious. The biggest thing that gets me with python is the lack of punctuation. I guess that I am old. I also find the syntax lacking.

@Jack0572

So, I think what these images usually show is a probability isosurface.

Basically, from the wavefunction (squared) we get the probability of finding an electron as a function of 3d coordinates. like:

P(x, y, z) = (Psi)^2

Edit: I think you can also draw the unsquared wavefunction. Though it can be positive or negative, so two thresholds are needed (but you could color + and - regions differently).

Then every point (x, y, z) that is above a threshold (like 0.05 or something) we think of as solid, and part of the object. Whereas every point with less than the threshold is see-through space.

I can think of two ways to render isosurfaces (I’m sure there are more). One is the marching cubes algorithm, which creates a normal 3d model of the surface, which can then be rendered using opengl or whatever. Marching cubes seems rather tricky to implement, but I’ve never tried. Still though, since it creates a normal model it is probably good for performance, if you wanna rotate or animate or something.

The other way is to render with raytracing. I made a raytracer isosurface renderer, and it’s pretty straightforward to do. It’s gonna be pretty slow though, unless you try to use opencl or similar for it. I found http://www.geisswerks.com/ryan/BLOBS/blobs.html to be kinda helpful for that. It’s the same principle.

@Mastic_Warrior

Well, there are plenty of languages out there so I’m sure there’s something fitting. Personally I use mostly python and C++, C++ is definitely more strict and syntax heavy (but also generally faster). Adjusting to write one or the other can be a bit odd, I start writing curly braces and semicolons in my python, and try to use the print() function in C++ xD. But really, the general principles behind many programming languages tend to be pretty similar, and it’s mostly syntax changes.

There are ofc languages that are more different (for instance functional languages like haskell) too.

Graphics do have a tendency to be a bit tedious in my experience though.