Determination of Concentrations of Unknown Samples
Stephen Lukacs (2) iquanta.org/instruct/python
"""
reference: https://iquanta.org/instruct/python ::: Chemistry 12: Analytic Spectroscopy ::: Stephen Lukacs, Ph.D. ©2022-12-06
"""
from py4web import URL, request
from ombott.request_pkg.helpers import FileUpload
from yatl.helpers import *
from iquanta.mcp import request_to_boolean, is_str_float, is_str_int, str_to_float, str_to_int, extra_x
from numpy import array, mean, std, polyfit, diag, sqrt
from scipy import optimize
import plotly.graph_objects as go
BR, B = TAG['br/'], TAG['b']
M1 = 0.0557/58.44277/0.05
demo_data = f"{M1:.3e}, 2363\n{M1/5:.3e}, 539\n{M1/5**2:.3e}, 117\n{M1/5**3:.3e}, 28\n{M1/5**4:.3e}, 9\n{M1/5**5:.3e}, 7\n{M1/5**6:.3e}, 4\n"
rtn = FORM(_action=None, _method="post")
if ('txtfile' in request.forms):
txtfile = request.forms['txtfile']
if (txtfile.count('\t') > 0):
txtfile = '\n'.join([l.strip().replace('\t', ', ') for l in txtfile.replace('\r','').split('\n')])
rtn.append(CAT("Converted.. .", PRE(r"{}".format(txtfile.encode('utf-8'))), BR()))
txt = txtfile
data = [ ]
for l in txt.split('\n'):
if (l.find(',') > -1) and is_str_float(l.split(',')[0]):
data.append(tuple([str_to_float(d.strip()) for d in l.strip().split(',')]))
#rtn.append(CAT(data, BR()))
rtn.append(STYLE("input[type=text] { width: 70px; text-align: center; border-radius: 7px; } textarea { margin: 0px; width: 295px; height: 200px; border-radius: 5px; } p { margin: 2px 0px; padding: 8px; border-radius: 10px; border: 2px solid silver; }"))
rtn.append(CAT(DIV("Enter a calibration curve below...", BR(), "(C (M), A) Data Entry.. .", BR(), TEXTAREA(txtfile if ('txtfile' in locals()) else demo_data, _name="txtfile"), _style="float:left;"), DIV(*[BR()]*2, INPUT(_type="submit", _value="Upload"), ", or, just Upload to run the demonstration.", _style="float:left; margin: 5px;"), DIV(_style="float:none;clear:both;")))
extra_x = lambda dset, extra: linspace(dset[0], dset[-1], num=(extra*(len(dset)-1)+len(dset)))
linear = lambda x, m, b: m*x + b
if ('data' in locals()):
x, y = [d[0] for d in data], [d[1] for d in data]
mb = polyfit(x, y, 1, full=True)[0]
rtn.append(SPAN(XML(f'linear fit: L = {mb[0]:,.2f} C + {mb[1]:,.2f}'), BR(), _style="font-size:24pt;"))
#
fig = go.Figure()
#xss = extra_x(x, 1)
fig.add_trace(go.Scatter(x=x, y=[linear(d, *mb) for d in x], mode="lines", name="linear fit"))
fig.add_trace(go.Scatter(x=x, y=y, mode='markers', name="data", marker=go.scatter.Marker(color="Black")))
fig.update_layout(xaxis=go.XAxis(title="Concentration, C (M)"), yaxis=go.YAxis(title="Absorbance, A (dimensionless)", anchor='x', side='left'))
fig.update_layout(title_text="Spectroscopic Calibration Curve", height=750)
html = fig.to_html()
rtn.append(XML(html[html.find('<div>'):html.rfind('</div>')+6].replace('<div>', '<div id="plotly">')))
rtn.append(CAT("lecture by Stephen Lukacs, Ph.D., ©2011 - 2023; updated: March 7, 2023. all data confirmed via ", A("lecture_data_analysis.nb", _href=URL('static', "pdf/lecture_data_analysis8.pdf"), _target="data_analysis"), "."))