partridgejiang / Kekule.js

A Javascript cheminformatics toolkit.
http://partridgejiang.github.io/Kekule.js
MIT License
250 stars 61 forks source link

[Question] Get molecule mass #64

Open erni93 opened 6 years ago

erni93 commented 6 years ago

Hi, first thanks for you time developing this library, i have a question, how can i obtain a molecule mass? In some objects i can use molecule methods how .getNodes() and take getAtomicMass(); but atoms object not always have this method.

I saw a datatable plugin example but this data is precalculated.

Thanks.

partridgejiang commented 6 years ago

Hi @erni93, sorry for the delay of replying. Since there are several possible node types in a molecule and some of them do not have a meaningful atomic mass (e.g., pseudoatom), so you have to check if getAtomicMass method is available in each node before accessing it. The following code may help you to calculate the total mass of a molecule:

var flattenMol = molecule.getFlattenedShadowFragment(true);  // expand all possible subgroups in molecule first
var totalMass = 0;
for (var i = 0, l = flattenMol.getNodeCount(); i <l; ++i)
{
  var node = flattenMol.getNodeAt(i);
  if (node.getAtomicMass)
    totalMass += node.getAtomicMass();
}
console.log(totalMass);
erni93 commented 6 years ago

Ok, thanks ;)

erni93 commented 6 years ago

Hi again @partridgejiang, i am saw that 'getNodeCount()' is ignoring hydrogen molecules, around 1.01 g/mol.

How can i take the number of hydrogen molecules?

Excuse me if the question is stupid, i am not a chemical. Thanks ;)

partridgejiang commented 6 years ago

@erni93, sorry that I had forgotten the implicit hydrogen atoms in last reply. So the correct code should be:

var flattenMol = molecule.getFlattenedShadowFragment(true);  // expand all possible subgroups in molecule first
var totalMass = 0;
for (var i = 0, l = flattenMol.getNodeCount(); i <l; ++i)
{
  var node = flattenMol.getNodeAt(i);
  if (node.getAtomicMass)
    totalMass += node.getAtomicMass();
  if (node.getImplicitHydrogenCount)
  {
    var hcount = node.getImplicitHydrogenCount() || 0;
    totalMass += hcount * 1.01;
  }
}
console.log(totalMass);
erni93 commented 6 years ago

Ok, thanks 👍