Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
leooooo
  • Loading branch information
Albericvgn authored May 29, 2024
1 parent a8095fa commit 64e212b
Showing 1 changed file with 82 additions and 26 deletions.
108 changes: 82 additions & 26 deletions notebooks/notebook.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,21 @@
" Returns:\n",
" str: The SMILES string of the molecule, or an error message if not found.\n",
" \"\"\"\n",
" url = f\"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{name}/property/CanonicalSMILES/JSON\"\n",
" response = requests.get(url)\n",
" if response.status_code == 200:\n",
" url = f\"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{name}/property/CanonicalSMILES/JSON\"\n",
" try:\n",
" response = requests.get(url)\n",
" response.raise_for_status() # Raise HTTPError for bad responses\n",
" data = response.json()\n",
" smiles = data['PropertyTable']['Properties'][0]['CanonicalSMILES']\n",
" return smiles\n",
" else:\n",
" except requests.exceptions.HTTPError as errh:\n",
" # Handle HTTPError\n",
" return f\"HTTP Error: {errh}\"\n",
" except requests.exceptions.RequestException as err:\n",
" # Handle other RequestExceptions\n",
" return f\"Request Exception: {err}\"\n",
" except (KeyError, IndexError):\n",
" # Handle missing data or incorrect JSON format\n",
" return \"No data found or error occurred.\"\n"
]
},
Expand Down Expand Up @@ -125,7 +133,6 @@
" mol = Chem.MolFromSmiles(smiles)\n",
" atom_counts = defaultdict(int)\n",
" if mol:\n",
" # Add explicit hydrogens to the molecule\n",
" mol = Chem.AddHs(mol)\n",
" for atom in mol.GetAtoms():\n",
" atom_counts[atom.GetSymbol()] += 1\n",
Expand Down Expand Up @@ -171,16 +178,34 @@
" \"\"\"\n",
" num_vars = A.shape[1]\n",
" prob = pulp.LpProblem(\"Balancing_Chemical_Equation\", pulp.LpMinimize)\n",
" \n",
" # Define variables with lower bound starting from 1\n",
" x_vars = [pulp.LpVariable(f'x{i}', lowBound=1, cat='Integer') for i in range(num_vars)]\n",
" \n",
" # Objective function\n",
" prob += pulp.lpSum(x_vars)\n",
" \n",
" # Constraints\n",
" for i in range(A.shape[0]):\n",
" prob += pulp.lpDot(A[i, :], x_vars) == 0\n",
" solver = pulp.PULP_CBC_CMD(msg=False)\n",
" \n",
" # Solve the problem\n",
" solver = pulp.PULP_CBC_CMD(msg=True) # Enable logging from the solver\n",
" prob.solve(solver)\n",
" \n",
" print(f\"Status: {pulp.LpStatus[prob.status]}\") # Print the status of the problem\n",
" \n",
" if pulp.LpStatus[prob.status] == 'Optimal':\n",
" return [int(pulp.value(var)) for var in x_vars]\n",
" solution = [int(pulp.value(var)) for var in x_vars]\n",
" print(f\"Solution: {solution}\") # Print the solution found\n",
" \n",
" # Check if solution is not just zeros\n",
" if all(x == 0 for x in solution):\n",
" return None\n",
" \n",
" return solution\n",
" else:\n",
" raise RuntimeError(\"Failed to find a valid solution.\")\n"
" return None\n"
]
},
{
Expand Down Expand Up @@ -267,7 +292,7 @@
" \"\"\"\n",
" reactant_counts = [count_atoms(smiles) for smiles in reactant_smiles]\n",
" product_counts = [count_atoms(smiles) for smiles in product_smiles]\n",
" \n",
"\n",
" reactant_elements = set(sum([list(counts.keys()) for counts in reactant_counts], []))\n",
" product_elements = set(sum([list(counts.keys()) for counts in product_counts], []))\n",
"\n",
Expand All @@ -285,11 +310,14 @@
" A_reactants = setup_matrix(elements, reactant_counts)\n",
" A_products = setup_matrix(elements, product_counts)\n",
" A = np.concatenate([A_reactants, -A_products], axis=1)\n",
" \n",
"\n",
" integer_coefficients = solve_ilp(A)\n",
" if integer_coefficients is None or not integer_coefficients:\n",
" raise ValueError(\"Failed to solve the balance equation. The system may be underdetermined or inconsistent.\")\n",
"\n",
" reactant_coeffs = integer_coefficients[:len(reactant_smiles)]\n",
" product_coeffs = integer_coefficients[len(reactant_smiles):]\n",
" \n",
"\n",
" reactant_data = [(coeff, get_molecular_formula(smiles)) for coeff, smiles in zip(reactant_coeffs, reactant_smiles)]\n",
" product_data = [(coeff, get_molecular_formula(smiles)) for coeff, smiles in zip(product_coeffs, product_smiles)]\n",
"\n",
Expand Down Expand Up @@ -334,10 +362,16 @@
" numpy.ndarray: The stoichiometry matrix.\n",
" \"\"\"\n",
" matrix = []\n",
" for element in elements:\n",
" row = [compound.get(element, 0) for compound in compounds]\n",
" for count in counts:\n",
" row = [count.get(element, 0) for element in elements]\n",
" matrix.append(row)\n",
" return np.array(matrix, dtype=int)\n",
" \n",
" # Ensure matrix is 2D\n",
" matrix = np.array(matrix)\n",
" if matrix.ndim == 1:\n",
" matrix = matrix.reshape(1, -1) # Reshape to 2D if it's inadvertently 1D\n",
"\n",
" return matrix\n",
"\n"
]
},
Expand Down Expand Up @@ -437,7 +471,7 @@
" \"\"\"\n",
" reactants_str = '.'.join(reactants)\n",
" products_str = '.'.join(products)\n",
" return f\"{reactants_str}>>{products_str}\"\n"
" return f\"{reactants_str}>>{products_str}\""
]
},
{
Expand Down Expand Up @@ -478,7 +512,7 @@
" \"\"\"\n",
" b64 = base64.b64encode(svg.encode('utf-8')).decode(\"utf-8\")\n",
" html = f\"<img src='data:image/svg+xml;base64,{b64}'/>\"\n",
" st.markdown(html, unsafe_allow_html=True)"
" return html"
]
},
{
Expand Down Expand Up @@ -520,12 +554,13 @@
" CAS_compound = CAS_from_any(compound)\n",
" boiling_p = Tb(CAS_compound)\n",
" melting_p = Tm(CAS_compound)\n",
" if temp <= melting_p:\n",
"\n",
" if float(temp) <= float(melting_p):\n",
" return 'solid'\n",
" elif temp > melting_p and temp <= boiling_p:\n",
" return 'liquid'\n",
" elif float(temp) >= float(boiling_p):\n",
" return 'gas'\n",
" else:\n",
" return 'gas'"
" return 'liquid'"
]
},
{
Expand Down Expand Up @@ -564,12 +599,22 @@
" Returns:\n",
" float: The enthalpy of the compound.\n",
" \"\"\"\n",
" Cas_compound=CAS_from_any(compound)\n",
" if state == 'solid': \n",
" return coeff * Hfs(CAS_from_any(compound))\n",
" if Hfs(Cas_compound)== None:\n",
" return 0\n",
" else: \n",
" return float(coeff) * Hfs(Cas_compound)\n",
" elif state == 'liquid':\n",
" return coeff * Hfl(CAS_from_any(compound))\n",
" if Hfl(CAS_from_any(compound))== None:\n",
" return 0\n",
" else:\n",
" return float(coeff) * Hfl(Cas_compound)\n",
" else: \n",
" return coeff * Hfg(CAS_from_any(compound))\n"
" if Hfg(CAS_from_any(compound))== None:\n",
" return 0\n",
" else:\n",
" return float(coeff) * Hfg(Cas_compound)"
]
},
{
Expand Down Expand Up @@ -609,11 +654,22 @@
" Returns:\n",
" float: The entropy of the compound.\n",
" \"\"\"\n",
" Cas_compound=CAS_from_any(compound)\n",
" if state == 'solid': \n",
" return coeff * S0s(CAS_from_any(compound))\n",
" if S0s(Cas_compound)== None:\n",
" return 0\n",
" else: \n",
" return float(coeff) * S0s(Cas_compound)\n",
" elif state == 'liquid':\n",
" return coeff * S0l(CAS_from_any(compound))\n",
" else: "
" if S0l(CAS_from_any(compound))== None:\n",
" return 0\n",
" else:\n",
" return float(coeff) * S0l(Cas_compound)\n",
" else: \n",
" if S0g(CAS_from_any(compound))== None:\n",
" return 0\n",
" else:\n",
" return float(coeff) * S0g(Cas_compound)\n"
]
}
],
Expand Down

0 comments on commit 64e212b

Please sign in to comment.