import re import pandas as pd from atomic_weights import atomic_weights def parse_formula(formula): pattern = r'([A-Z][a-z]?)(\d*)' matches = re.findall(pattern, formula) if not matches: raise ValueError("Invalid chemical formula.") composition = {} for element, count in matches: if element not in atomic_weights: raise ValueError(f"{element} not available in database.") count = int(count) if count else 1 composition[element] = composition.get(element, 0) + count return composition def molecular_weight(comp): total = 0 for element, count in comp.items(): total += atomic_weights[element] * count return round(total,3) def classify(formula): if formula.startswith("H"): return "Acid" elif formula.endswith("OH"): return "Base" elif formula.endswith("O"): return "Oxide" elif "C" in formula: return "Organic Compound" else: return "Salt" def analyze_compound(formula): comp = parse_formula(formula) mw = molecular_weight(comp) compound_type = classify(formula) df = pd.DataFrame({ "Element": list(comp.keys()), "Atoms": list(comp.values()) }) summary = f""" ### Analysis Report **Formula:** {formula} **Compound Type:** {compound_type} **Molecular Weight:** {mw} g/mol """ return summary, df