r/pythonhelp • • Nov 16 '20

Counting atoms with python

I wish to calculate partial charge in complex (im a chemist)

So my problem is that i have a list : ['H2O','OH','COOH'] for exemple

I need to know the number of occurrences of all atoms. So here 4 for H. My problem is that the number of occurrences is the number of occurrences of the letter describing the atom if no stoechiométric coefficient, and else the number of that coefficient, but the number could appear or not at any place except at position 0.

I don't see how can i make this with python and now i'm quite confused.

Do you have any tips for me?

Thanks for your help and time!

3 Upvotes

15 comments sorted by

2

u/heirna Nov 16 '20

Thanks both for your help, I'm going to implement this in my programe and then post it here ,maybe tomorow, (I live in eu) and im quite a slow programer.

Once it's done i will think of how I can integrate double letter elements like Ge or Si.

This program will allow the calculation of the partial charge of any part of a complex according to the partial charge model.

This model allows us to predict the stability of the complex in solution, and if the partial charge is right condensation can occur.

Condensation in solution is used in chemistry to forme oxyde in a solution like glass (SiO2)

This process allows us to bypass the high temperature processe of glass and so we can integrate funny organic molecules in it. It is also verry usful in the formation of athin film like anti glare. We can also make nanoparticule out of this process !

2

u/CrayonConstantinople Nov 16 '20

Happy to help!

If double letter elements always come in the form of an uppercase letter followed by a lowercase one, this is also trivial to implement.

1

u/heirna Nov 16 '20

I'm still processing your code, this extra fonctionality is not trivial to me, and will not be verry useful in the code since this model is verry simple and cannot handle a lot of atoms, i think i will just remap Cu as X for instance to spare me extra headeach.

2

u/CrayonConstantinople Nov 17 '20

I have edited my code above to be easier to understand, hope it helps :)

2

u/heirna Nov 17 '20

ion for me to add if you required it.

The fact that you are struggling to understand my code is what had concerned me when I was writing it, I have not made it clear. I was trying to get you your solution, at the expense of writing clear and concise code.

If it would be helpful, I'm happy to quickly rewrite it to make whats happening clearer.

Oh not at all, i'm just quite a beginner in code so this is normal, thanks for that edit !

1

u/heirna Nov 17 '20

our code, this extra fonctionality is not trivial to me, and will not be verry useful in the code si

And my code is such a mess compared to yours

2

u/CrayonConstantinople Nov 17 '20 edited Nov 17 '20

Oh sure, and sorry if that came across as condescending. What I meant was, I think this would be a small addition for me to add if you required it.

The fact that you are struggling to understand my code is what had concerned me when I was writing it, I have not made it clear. I was trying to get you your solution, at the expense of writing clear and concise code.

If it would be helpful, I'm happy to quickly rewrite it to make whats happening clearer.

2

u/ace6807 Nov 16 '20

Super cool. Glad to help. If you want me to throw in the lookup for double letters, I don't mind, just let me know. If you'd rather take a crack at implementing it, that's fine too!

1

u/heirna Nov 16 '20

I don't think this will be pertinent in this case since this model is quite simple and quite incorrect next to quantum model. But this makes me back into python and programtion and i will continue to do some compute chemestry with more accurate model ! Its very nice to find a lot of help in reddit !

2

u/CrayonConstantinople Nov 16 '20 edited Nov 17 '20

This solves your problem but I had to write it on my tablet so excuse the fact that its just one function. It also could be written much nicer and explained etc.

But basically it goes through each item of the list.

For each item, it checks each letter from back to front.

If the letter is an actual letter (not a number), it increments that letters count by 1

If the letter is a number, it stores it and the next letter it comes across, it increments its by that count. This also works for multiple numbers. e.g. if it was H22, then the count for H would be 22.

a = ['H2O', 'OH', 'COOH']

def count_items(item_list):
  map = {}
  amount_of_char = None
  for item in item_list:
    for char in reversed(item):
      if char.isdigit():
        # This char is a number so keep for incrementing next letter
        if amount_of_char is None:
          amount_of_char = char
        else:
          amount_of_char = '{0}{1}'.format(char, amount_of_char)
      else:
        # Find the current count for this char, or 0 if there is none
        current_count = map.get(char.upper(), 0)
        # Determine the amount to increment this char by
        amount_to_increment = int(amount_of_char) if amount_of_char else 1
        map[char.upper()] = current_count + amount_to_increment
        amount_of_char = None
  return map

print(count_items(a))
# prints {'O': 4, 'H': 4, 'C': 1}
  • Edited to make the code easier to read :)

2

u/heirna Nov 16 '20

Thanks you very much kind redditor !

1

u/ace6807 Nov 16 '20

Can you give me a few more examples of possible lists and their expected outputs?

1

u/ace6807 Nov 16 '20

I think this should do it but I was hoping for some more test cases to check it.

from collections import Counter


atom_counter = Counter()

molecules = ['H2O','OH','COOH']
atom_stack = []

for molecule in molecules:
    for i, a in enumerate(molecule):
        if a.isalpha():
            if i < len(molecule) - 1 and molecule[i + 1].isnumeric():
                atom_stack.append((a, molecule[i + 1]))
            else:
                atom_stack.append((a, 1))

print(atom_stack)

for element_count in atom_stack:
    atom_counter[element_count[0]] += int(element_count[1])

print(atom_counter)

1

u/heirna Nov 16 '20

Thank you so much!

I'm going to test this,

More examples :

[H2O2, F, P2O3] -> H = 2, F=1, P=2, O=5

[C6H8O7, H2O, OH] -> C=6, H=11, O=9

By chance, i do not have to deal with double letter element like Al or Cu for now

2

u/ace6807 Nov 16 '20

Oh yeah this will for sure have a problem with double letter elements but we could add a lookup list super easily to resolve that