Skip to content

Commit

Permalink
Merge pull request #6 from n-elie/master
Browse files Browse the repository at this point in the history
Fix add/sub Formula objects
  • Loading branch information
deeenes authored Jan 15, 2023
2 parents 222e757 + e805dec commit 85d6fae
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
25 changes: 14 additions & 11 deletions src/lipyd/formula.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def __iadd__(self, other):

def __sub__(self, other):

new = copy.copy(self)
new = copy.deepcopy(self)
new.__isub__(other)
return new

Expand All @@ -203,6 +203,9 @@ def __isub__(self, other):
self.charge -= (other.charge if hasattr(other, 'charge') else 0)
self.isotope -= (other.isotope if hasattr(other, 'isotope') else 0)

self.calc_mass()
self.update_mz()

return self

def __imul__(self, other):
Expand All @@ -211,12 +214,12 @@ def __imul__(self, other):

return self

for elem, cnt in iteritems(self.atoms):
for elem, cnt in iteritems(self._atoms):

self.counts[elem] = cnt * other

self.calc_mass()
self.formula_from_dict(self.atoms)
self.formula_from_dict(self._atoms)
self.isotope = self.isotope * other

def __mul__(self, other):
Expand All @@ -227,7 +230,7 @@ def __mul__(self, other):

new_atoms = defaultdict(int)

for elem, cnt in iteritems(self.atoms):
for elem, cnt in iteritems(self._atoms):

new_atoms[elem] = cnt * other

Expand All @@ -254,7 +257,7 @@ def as_mass(self):
Returns this ``Formula`` instance as ``mass.MassBase`` object.
"""

return MassBase(self.formula, self.charge, self.isotope)
return mass.MassBase(self.formula, self.charge, self.isotope)


def add(self, formula):
Expand All @@ -268,7 +271,7 @@ def add(self, formula):
"""

for elem, cnt in mass._re_form.findall(formula):
self.atoms[elem] += int(cnt or '1')
self._atoms[elem] += int(cnt or '1')

self.update()

Expand All @@ -284,9 +287,9 @@ def sub(self, formula):
"""

for elem, cnt in mass._re_form.findall(formula):
self.atoms[elem] -= int(cnt or '1')
self._atoms[elem] -= int(cnt or '1')

if self.atoms[elem] < 0:
if self._atoms[elem] < 0:

raise ValueError('Can not remove %s from %s: '
'too few %s atoms!' % (formula, self.formula, elem))
Expand All @@ -300,10 +303,10 @@ def update(self):
re-calculates the mass.
"""

if len(self.atoms):
if len(self._atoms):

self.formula = ''.join('%s%u' % (elem, self.atoms[elem])
for elem in sorted(self.atoms.keys()))
self.formula = ''.join('%s%u' % (elem, self._atoms[elem])
for elem in sorted(self._atoms.keys()))
self.calc_mass()


Expand Down
2 changes: 1 addition & 1 deletion src/lipyd/mass.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@ def calc_mass(self):
)
m = 0.0
for element, count in atoms:
count = int(count or '1')
count = int('1' if count == '' else count)
m += self.exmass[element] * count

if self.isotope:
Expand Down

0 comments on commit 85d6fae

Please sign in to comment.