Spaces:
Runtime error
Runtime error
File size: 1,418 Bytes
6028a2b fd5bb51 6028a2b fd5bb51 6028a2b fd5bb51 6028a2b fd5bb51 6028a2b fd5bb51 6028a2b fd5bb51 6028a2b fd5bb51 6028a2b fd5bb51 6028a2b fd5bb51 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | 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 |