Navigation Menu

Skip to content

Commit

Permalink
Fix codacy issues
Browse files Browse the repository at this point in the history
Fixed 29 trailing whitespace errors and converted three assert
statements into exceptions.
  • Loading branch information
goldmanm committed Jun 28, 2018
1 parent 500c95d commit 3f90465
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 53 deletions.
48 changes: 25 additions & 23 deletions rmgpy/tools/isotopes.py
Expand Up @@ -62,12 +62,11 @@ def initialize_isotope_model(rmg, isotopes):
"""
Initialize the RMG object by using the parameter species list
as initial species instead of the species from the RMG input file.
"""
# Read input file
rmg.loadInput(rmg.inputFile)

# Check input file
# Check input file
rmg.checkInput()

# Load databases
Expand Down Expand Up @@ -163,13 +162,15 @@ def generate_isotope_reactions(isotopeless_reactions, isotopes):
reaction.
uses the reactSpecies method to find reactions with proper degeneracies and
then filters out those that don't match products. the proper reactions are
then filters out those that don't match products. the proper reactions are
given kinetics of the previous reaction modified for the degeneracy difference.
"""
# make sure all isotopeless reactions have templates and are TemplateReaction objects
for rxn in isotopeless_reactions:
assert isinstance(rxn,TemplateReaction)
assert rxn.template is not None, 'isotope reaction {0} does not have a template attribute. Full details :\n\n{1}'.format(str(rxn),repr(rxn))
if not isinstance(rxn,TemplateReaction):
raise TypeError('reactions sent to generate_isotope_reactions must be a TemplateReaction object')
if rxn.template is None:
raise AttributeError('isotope reaction {0} does not have a template attribute. The object is:\n\n{1}'.format(str(rxn),repr(rxn)))

from rmgpy.reaction import _isomorphicSpeciesList

Expand Down Expand Up @@ -302,7 +303,7 @@ def add_isotope(i, N, mol, mols, element):

def cluster(objList):
"""
Creates subcollections of isotopomers/reactions that
Creates subcollections of isotopomers/reactions that
only differ in their isotopic labeling.
This method works for either species or reactions.
Expand All @@ -329,10 +330,10 @@ def cluster(objList):
def remove_isotope(labeledObj, inplace = False):
"""
Create a deep copy of the first molecule of the species object and replace
non-normal Element objects (of special isotopes) by the
non-normal Element objects (of special isotopes) by the
expected isotope.
If the boolean `inplace` is True, the method remove the isotopic atoms of
If the boolean `inplace` is True, the method remove the isotopic atoms of
the Species/Reaction
inplace and returns a list of atom objects & element pairs for adding back
to the oritinal object. This should significantly improve speed of this method.
Expand All @@ -351,7 +352,7 @@ def remove_isotope(labeledObj, inplace = False):
return modifiedAtoms
else:
stripped = labeledObj.copy(deep=True)

for atom in stripped.molecule[0].atoms:
if atom.element.isotope != -1:
atom.element = getElement(atom.element.symbol)
Expand Down Expand Up @@ -413,7 +414,7 @@ def remove_isotope(labeledObj, inplace = False):
def ensure_reaction_direction(isotopomerRxns):
"""
given a list of reactions with varying isotope labels but identical structure,
obtained from the `cluster` method, this method remakes the kinetics so that
obtained from the `cluster` method, this method remakes the kinetics so that
they all face the same direction.
"""

Expand Down Expand Up @@ -446,7 +447,7 @@ def ensure_reaction_direction(isotopomerRxns):

def redo_isotope(atomList):
"""
This takes a list of zipped atoms with their isotopes removed, from
This takes a list of zipped atoms with their isotopes removed, from
and elements.
"""
for atom, element in atomList:
Expand Down Expand Up @@ -584,7 +585,8 @@ def get_labeled_reactants(reaction, family):
Used for KIE method 'simple'
"""
assert reaction.family == family.name, "{0} != {1}".format(reaction.family, family.name)
if reaction.family != family.name:
raise AttributeError("The reaction must come from the family specified: {0} != {1}".format(reaction.family, family.name))
# save the reactants and products to replace in the reaction object
reactants = list(reaction.reactants)
products = list(reaction.products)
Expand Down Expand Up @@ -657,7 +659,7 @@ def ensure_correct_symmetry(isotopmoper_list, isotopic_element = 'C'):
returns True if the correct symmetry is detected. False if not detected
This uses the observation that if there are less than 2^n isotopomors, where n is the number of
isotopic elements, then there should be an 2^n - m isotopomers where
isotopic elements, then there should be an 2^n - m isotopomers where
m is related to the amount of entropy increased by some isotopomers since they
lost symmetry.
"""
Expand All @@ -677,12 +679,12 @@ def ensure_correct_symmetry(isotopmoper_list, isotopic_element = 'C'):

def ensure_correct_degeneracies(reaction_isotopomer_list, print_data = False, r_tol_small_flux=1e-5, r_tol_deviation = 0.0001):
"""
given a list of isotopomers (reaction objects), returns True if the correct
degeneracy values are detected. False if incorrect degeneracy values
exist.
given a list of isotopomers (reaction objects), returns True if the correct
degeneracy values are detected. False if incorrect degeneracy values
exist.
This method assuumes an equilibrium distribution of compounds and finds
the fluxes created by the set of reactions (both forward and
This method assuumes an equilibrium distribution of compounds and finds
the fluxes created by the set of reactions (both forward and
reverse). It then checks that the fluxes of each compounds are proportional to their
symmetry numbers (since lower symmetry numbers have higher entropy and should have a
larger concentration.)
Expand All @@ -707,7 +709,7 @@ def store_flux_info(species, flux, product_list, product_structures):
species - The desired species that you'd like to modify the flux value of
flux - the amount to modify the flux of the species
product_list - a list of current flux and symmetry values
product_structures - a list of unlabled structures un the reaction class
product_structures - a list of unlabled structures un the reaction class
modifies the product list by either adding on new row with the species' structure, flux
symmetry ratio, etc. or adds the flux to the species' current row in `product_list`
Expand All @@ -718,7 +720,7 @@ def store_flux_info(species, flux, product_list, product_structures):
for struc_index, product_structure in enumerate(product_structures):
if compare_isotopomers(product_structure, species):
structure_index = struc_index
break
break
# store product flux and symmetry info
for index in product_list.index:
spec = product_list.at[index,'product']
Expand All @@ -729,7 +731,7 @@ def store_flux_info(species, flux, product_list, product_structures):
return product_list
# add product to list
symmetry_ratio = product_structures[structure_index].getSymmetryNumber() / float(species.getSymmetryNumber())
return product_list.append({'product': species,
return product_list.append({'product': species,
'flux': flux,
'product_struc_index': structure_index,
'symmetry_ratio': symmetry_ratio},
Expand Down Expand Up @@ -776,7 +778,7 @@ def store_flux_info(species, flux, product_list, product_structures):
for rxn_reactant in rxn.reactants:
product_list = store_flux_info(rxn_reactant,-product_flux, product_list, product_structures)

# now find characteristic flux of reverse direction.
# now find characteristic flux of reverse direction.
if isinstance(rxn.kinetics, MultiArrhenius):
reverse_A_factor = 0
for arr in rxn.kinetics.arrhenius:
Expand Down Expand Up @@ -819,7 +821,7 @@ def run(inputFile, outputDir, original=None, maximumIsotopicAtoms = 1,
Firstly, generates the RMG model for the first input file. Takes the core species of that mechanism
and generates all isotopomers of those core species. Next, generates all reactions between the
generated pool of isotopomers, and writes it to file.
generated pool of isotopomers, and writes it to file.
"""
logging.info("isotope: Starting the RMG isotope generation method 'run'")
if not original:
Expand Down
52 changes: 27 additions & 25 deletions rmgpy/tools/isotopesTest.py
Expand Up @@ -34,14 +34,20 @@

from rmgpy.species import Species
from rmgpy.molecule import Molecule
from rmgpy.tools.isotopes import *
from rmgpy.tools.isotopes import correct_entropy,apply_kinetic_isotope_effect_simple,\
generate_isotope_reactions,get_reduced_mass,get_labeled_reactants,\
is_enriched,generate_isotopomers,cluster,remove_isotope,\
redo_isotope,ensure_reaction_direction,compare_isotopomers

from rmgpy import settings
from rmgpy.reaction import Reaction
from rmgpy.data.kinetics.family import TemplateReaction
from rmgpy.kinetics.arrhenius import Arrhenius

from rmgpy.data.rmg import RMGDatabase

database=None

def setUpModule():
"""A function that is run ONCE before all unit tests in this module."""
global database
Expand Down Expand Up @@ -177,14 +183,13 @@ def testClusterWithReactions(self):
rxn3 = Reaction(reactants=[eth,meth], products=[eth,meth])
rxn4 = Reaction(reactants=[meth], products=[meth])
rxn5 = Reaction(reactants=[ethi], products=[eth])



sameClusterList = [rxn0,rxn1]

clusters = cluster(sameClusterList)
self.assertEquals(len(clusters), 1)
self.assertEquals(len(clusters[0]), 2)

sameClusterList = [rxn2,rxn3]

clusters = cluster(sameClusterList)
Expand All @@ -197,7 +202,6 @@ def testClusterWithReactions(self):
self.assertEquals(len(clusters), 4)
self.assertEquals(len(clusters[0]), 1)


def testRemoveIsotopeForReactions(self):
"""
Test that remove isotope algorithm works with Reaction objects.
Expand Down Expand Up @@ -231,7 +235,7 @@ def testRemoveIsotopeForReactions(self):
unlabeledRxn = Reaction(reactants=[eth], products = [eth])
labeledRxn = Reaction(reactants=[ethi], products = [ethi])
stripped = remove_isotope(labeledRxn)

self.assertTrue(unlabeledRxn.isIsomorphic(stripped))

def testRemoveIsotopeForSpecies(self):
Expand Down Expand Up @@ -316,7 +320,7 @@ def testEnsureReactionDirection(self):
"""

# get reactions

methyl = Species().fromSMILES('[CH3]')
methyli = Species().fromAdjacencyList(
"""
Expand All @@ -335,7 +339,7 @@ def testEnsureReactionDirection(self):
4 H u0 p0 c0 {1,S}
5 H u0 p0 c0 {1,S}
""")

dipropyl = Species().fromSMILES('[CH2]C[CH2]')
dipropyli = Species().fromAdjacencyList("""
multiplicity 3
Expand All @@ -349,7 +353,7 @@ def testEnsureReactionDirection(self):
8 H u0 p0 c0 {4,S}
9 H u0 p0 c0 {4,S}
""")

propyl = Species().fromSMILES('CC[CH2]')
propyli = Species().fromAdjacencyList("""
multiplicity 2
Expand Down Expand Up @@ -406,11 +410,11 @@ def testEnsureReactionDirection(self):

# call method
ensure_reaction_direction(rxns)

for rxn in rxns:
# ensure there is a methane in reactants for each reaction
self.assertTrue(any([compare_isotopomers(methane, reactant) for reactant in rxn.reactants]),msg='ensureReactionDirection didnt flip the proper reactants and products')

# ensure kinetics is correct
if any([dipropyli.isIsomorphic(reactant) for reactant in rxn.reactants]):
self.assertAlmostEqual(rxn.kinetics.A.value, 0.5, msg= 'The A value returned, {0}, is incorrect. Check the reactions degeneracy and how A.value is obtained. The reaction is:{1}'.format(rxn.kinetics.A.value, rxn))
Expand Down Expand Up @@ -472,7 +476,7 @@ def testCompareIsotopomersDoesNotAlterSpecies(self):
8 H u0 p0 c0 {2,S}
""")
compare_isotopomers(ethii,ethi)

# ensure species still have labels
for atom in ethii.molecule[0].atoms:
if atom.element.symbol == 'C':
Expand Down Expand Up @@ -582,7 +586,7 @@ def testCompareIsotopomersWorksOnReactions(self):
products = [h2,npropyl],
family = 'H_Abstraction')
self.assertTrue(compare_isotopomers(reaction2,reaction3))

def testCompareIsotopomersFailsOnReactions(self):
"""
Test that compareIsotomers fails on different reaction objects
Expand Down Expand Up @@ -643,7 +647,7 @@ def testCompareIsotopomersFailsOnReactions(self):
reaction2 = TemplateReaction(reactants = [propanei,h],
products = [npropyli,h2],
family = 'H_Abstraction')

magicReaction = TemplateReaction(reactants = [propane,h],
products = [propanei,h],
family = 'H_Abstraction')
Expand All @@ -655,7 +659,7 @@ def testCorrectEntropy(self):
thermo as isotopeless with the change in entropy corresponding to the
symmetry difference.
This example compares propane to a asymmetrically labeled propane.
This example compares propane to a asymmetrically labeled propane.
"""
from rmgpy.thermo.nasa import NASA, NASAPolynomial
from copy import deepcopy
Expand Down Expand Up @@ -691,9 +695,9 @@ def testCorrectEntropy(self):

# get thermo of propane
original_thermo = NASA(polynomials=[NASAPolynomial(
coeffs=[1.10564,0.0315339,-1.48274e-05,3.39621e-09,-2.97953e-13,-14351.9,18.775],
coeffs=[1.10564,0.0315339,-1.48274e-05,3.39621e-09,-2.97953e-13,-14351.9,18.775],
Tmin=(100,'K'), Tmax=(3370.6,'K')), NASAPolynomial(
coeffs=[-1.45473,0.0241202,-6.87667e-06,9.03634e-10,-4.48389e-14,-6688.59,43.0459],
coeffs=[-1.45473,0.0241202,-6.87667e-06,9.03634e-10,-4.48389e-14,-6688.59,43.0459],
Tmin=(3370.6,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'),
comment="""Thermo group additivity estimation: group(Cs-CsCsHH) + gauche(Cs(CsCsRR)) + other(R) + group(Cs-CsHHH) + gauche(Cs(Cs(CsRR)RRR)) + other(R) + group(Cs-CsHHH) + gauche(Cs(Cs(CsRR)RRR)) + other(R)""")
propane.thermo = deepcopy(original_thermo)
Expand All @@ -715,7 +719,7 @@ def testGenerateIsotopomers(self):
polynomial = NASAPolynomial(coeffs=[1.,1.,1.,1.,1.,1.,1.],
Tmin=(200,'K'),Tmax=(1600,'K'),E0=(1.,'kJ/mol'),
comment='made up thermo')

spc.thermo = NASA(polynomials=[polynomial],Tmin=(200,'K'),
Tmax=(1600,'K'),E0=(1.,'kJ/mol'),
comment='made up thermo')
Expand Down Expand Up @@ -750,7 +754,6 @@ def testIsEnriched(self):
9 H u0 p0 c0 {2,S}
10 H u0 p0 c0 {2,S}
""")

npropyli = Species().fromAdjacencyList(
"""
multiplicity 2
Expand All @@ -765,20 +768,19 @@ def testIsEnriched(self):
9 H u0 p0 c0 {2,S}
10 H u0 p0 c0 {2,S}
""")

self.assertTrue(is_enriched(npropyli))

self.assertFalse(is_enriched(npropyl))

enrichedReaction = TemplateReaction(reactants = [npropyl],
products = [npropyli],
family = 'H_Abstraction')
self.assertTrue(is_enriched(enrichedReaction))

bareReaction = TemplateReaction(reactants = [npropyl],
products = [npropyl],
family = 'H_Abstraction')

self.assertFalse(is_enriched(bareReaction))

def testGetLabeledReactants(self):
Expand Down Expand Up @@ -911,7 +913,7 @@ def testGenerateIsotopeReactions(self):
isotope_list = [[methyl,methyli],
[methane,methanei],
[craigie,craigiei]]

new_reactions = generate_isotope_reactions([reaction], isotope_list)

self.assertEqual(len(new_reactions), 4)
Expand Down
10 changes: 5 additions & 5 deletions scripts/isotopes.py
Expand Up @@ -2,8 +2,8 @@
# -*- coding: utf-8 -*-

"""
This script accepts one input file (e.g. input.py) with the RMG-Py model to generate,
optional parameters `--original [folder of original rmg model] ` can allow using
This script accepts one input file (e.g. input.py) with the RMG-Py model to generate,
optional parameters `--original [folder of original rmg model] ` can allow using
a starting RMG model. A special path can be added with the argument `--output` for the
path to output the final files.
"""
Expand All @@ -29,7 +29,7 @@ def parseCommandLineArguments():
parser = argparse.ArgumentParser()
parser.add_argument('input', help='RMG input file')
parser.add_argument('--output', type=str, nargs=1, default='',help='Output folder')
parser.add_argument('--original', type=str, nargs=1, default='',
parser.add_argument('--original', type=str, nargs=1, default='',
help='Location of the isotopeless mechanism')
parser.add_argument('--maximumIsotopicAtoms', type=int, nargs=1, default=[1000000],
help='The maxuminum number of isotopes you allow in a specific molecule')
Expand All @@ -38,7 +38,7 @@ def parseCommandLineArguments():
parser.add_argument('--kineticIsotopeEffect', type=str, nargs=1, default='',
help='Type of kinetic isotope effects to use, currently only "simple" supported.')
args = parser.parse_args()

return args

def main():
Expand All @@ -56,7 +56,7 @@ def main():
if kie not in supported_kie_methods and kie is not None:
raise InputError('The kie input, {0}, is not one of the currently supported methods, {1}'.format(kie,supported_kie_methods))
initializeLog(logging.INFO, os.path.join(os.getcwd(), 'RMG.log'))
run(inputFile, outputdir, original=original,
run(inputFile, outputdir, original=original,
maximumIsotopicAtoms=maximumIsotopicAtoms,
useOriginalReactions=useOriginalReactions,
kineticIsotopeEffect = kie)
Expand Down

0 comments on commit 3f90465

Please sign in to comment.