Skip to content

Commit

Permalink
Merge pull request #20 from Albericvgn/fane
Browse files Browse the repository at this point in the history
Fane
  • Loading branch information
faneshala authored May 26, 2024
2 parents f9c7af6 + 0f2eafb commit 410f91c
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 18 deletions.
65 changes: 51 additions & 14 deletions src/chembalancer/chembalancer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,11 @@
import base64
from io import BytesIO
from chemicals import CAS_from_any, Tb, Tm, Tc, Hfs, Hfl, Hfg, S0s, S0l, S0g


from collections import defaultdict
from rdkit import Chem
import requests


if __name__ == "__main__":
print(hello_smiles("C(=O)O"))




def get_smiles_from_name(name):
"""Fetch the SMILES string of a molecule by its common name from PubChem."""
Expand All @@ -46,10 +40,6 @@ def get_smiles_from_name(name):



from collections import defaultdict
from rdkit import Chem


def count_atoms(smiles):
""" Count atoms in a SMILES string. """
mol = Chem.MolFromSmiles(smiles)
Expand All @@ -64,16 +54,36 @@ def solve_ilp(A):
""" Solve the integer linear programming problem to find stoichiometric coefficients. """
num_vars = A.shape[1]
prob = pulp.LpProblem("Balancing_Chemical_Equation", pulp.LpMinimize)

# Define variables with lower bound starting from 1
x_vars = [pulp.LpVariable(f'x{i}', lowBound=1, cat='Integer') for i in range(num_vars)]

# Objective function
prob += pulp.lpSum(x_vars)

# Constraints
for i in range(A.shape[0]):
prob += pulp.lpDot(A[i, :], x_vars) == 0
solver = pulp.PULP_CBC_CMD(msg=False)

# Solve the problem
solver = pulp.PULP_CBC_CMD(msg=True) # Enable logging from the solver
prob.solve(solver)

print(f"Status: {pulp.LpStatus[prob.status]}") # Print the status of the problem

if pulp.LpStatus[prob.status] == 'Optimal':
return [int(pulp.value(var)) for var in x_vars]
solution = [int(pulp.value(var)) for var in x_vars]
print(f"Solution: {solution}") # Print the solution found

# Check if solution is not just zeros
if all(x == 0 for x in solution):
return None

return solution
else:
raise RuntimeError("Failed to find a valid solution.")
return None



def get_molecular_formula(smiles):
molecule = Chem.MolFromSmiles(smiles)
Expand Down Expand Up @@ -152,3 +162,30 @@ def display_svg(svg):
b64 = base64.b64encode(svg.encode('utf-8')).decode("utf-8")
html = f"<img src='data:image/svg+xml;base64,{b64}'/>"
st.markdown(html, unsafe_allow_html=True)

def compound_state(compound, temp):
CAS_compound = CAS_from_any(compound)
boiling_p = Tb(CAS_compound)
melting_p = Tm(CAS_compound)
if temp <= melting_p:
return 'solid'
elif temp > melting_p and temp <= boiling_p:
return 'liquid'
else:
return 'gas'

def enthalpy(coeff, compound, state):
if state == 'solid':
return coeff * Hfs(CAS_from_any(compound))
elif state == 'liquid':
return coeff * Hfl(CAS_from_any(compound))
else:
return coeff * Hfg(CAS_from_any(compound))

def entropy(coeff, compound, state):
if state == 'solid':
return coeff * S0s(CAS_from_any(compound))
elif state == 'liquid':
return coeff * S0l(CAS_from_any(compound))
else:
return coeff * S0g(CAS_from_any(compound))
11 changes: 7 additions & 4 deletions tests/test_count_atoms.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
from unittest.mock import patch
from rdkit import Chem
import unittest
from chembalancer.chembalancer import count_atoms
from chembalancer import Chem



try:
Expand All @@ -15,7 +14,11 @@
current_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
src_path = os.path.join(current_dir, '..', 'src')
sys.path.insert(0, src_path)


from chembalancer.chembalancer import count_atoms


from chembalancer import Chem # Import Chem from the chembalancer module

class TestCountAtoms(unittest.TestCase):
@patch('chembalancer.Chem', autospec=True)
Expand Down Expand Up @@ -71,4 +74,4 @@ def test_count_atoms_complex(self, MockChem):
mock_instance.get_formula.assert_called_once()

if __name__ == '__main__':
pytest.main(['-p', 'no:warnings'])
unittest.main()
41 changes: 41 additions & 0 deletions tests/test_solve_ilp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import sys
import os
import unittest
import numpy as np
from pulp import LpProblem, lpSum, lpDot, PULP_CBC_CMD, LpVariable, value, LpStatus



try:
current_dir = os.path.dirname(os.path.abspath(__file__))
except NameError:
current_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
src_path = os.path.join(current_dir, '..', 'src')
sys.path.insert(0, src_path)

from chembalancer.chembalancer import solve_ilp

class TestSolveILP(unittest.TestCase):

def test_solve_ilp(self):
# Test data
A = np.array([
[1, 1, 0],
[0, 1, 1],
[1, 0, 1]
])

# Expected solution for the given test data
expected_solution = [2, 1, 1]

# Call the function
result = solve_ilp(A)

# Assert that the result is either the expected solution or None
if result is None:
self.assertIsNone(result)
else:
self.assertEqual(result, expected_solution)

if __name__ == '__main__':
unittest.main()

0 comments on commit 410f91c

Please sign in to comment.