<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Chapter 7 :: Coding For Chemists</title>
    <link>https://codingforchemistsbook.com/book_material/chapter-7/index.html</link>
    <description>Data Download Data for Chapter 7&#xA;Alternatively, individual files can be found in the Data section.&#xA;Code from chapter &#39;&#39;&#39; A function that returns the pH response as equivalents of acid are added to a solution Written by: Ben Lear and Chris Johnson (authors@codechembook.com) v1.0.0 - 250210 - initial version &#39;&#39;&#39; import numpy as np from codechembook.quickPlots import quickScatter def pH_response (eqs, pKa = None, base_i = None): &#39;&#39;&#39; Calculates pH values based on equivalents of acid added, pKa, and starting concentration of base. REQUIRED PARAMETERS: qs (ndarray): equivalents of acid added pKa (float): the pKa of the base base_i (float): initialtial concentration of the base RETURNS: (ndarray of floats): the pHs at each point &#39;&#39;&#39; # Calculate the terms for the quadratic equation a = 1 b = -1 * (base_i + eqs*base_i + 10**(-pKa)) # eqs*base_i gives concentration of acid c = base_i*(eqs * base_i) # Calcalute the two roots of the equation x1 = (-1*b + np.sqrt(b**2 - 4*a*c))/(2*a) x2 = (-1*b - np.sqrt(b**2 - 4*a*c))/(2*a) # Make a list of the correct x-values x = [] # this is an empty list that will eventually hold the correct values for eq, e1, e2 in zip(eqs, x1, x2): # test each value if e1 &lt; 0: # can&#39;t have negative number of molecules x.append(e2) elif base_i &lt; e1 or eq*base_i &lt; e1: # can&#39;t be greater than qty. added x.append(e2) elif isinstance(e1, complex): # must be a real number x.append(e2) else: # if none of those, then it is the correct value x.append(e1) x = np.array(x) # convert our list to a numpy array return pKa + np.log10((base_i - x)/(x)) # return an array, converted to pH # Test that the function is working, by plotting an example if __name__ == &#39;__main__&#39;: # this only runs if the file is run directly # Make up some test numbers eqs = np.linspace(0.05, 0.95, 20) # Run the function and plot the result quickScatter(x = eqs, y = pH_response(eqs, pKa = 7, base_i = 1), mode = &#39;lines+markers&#39;, xlabel = &#39;equivalents added&#39;, ylabel = &#39;pH&#39;) &#39;&#39;&#39; A program to fit a titration to the Hendersson-Hassebalch equations Requires: pH_response from titration.py .csv files with col 1 as wavelength and col 2 as intensity Written by: Ben Lear and Chris Johnson (authors@codechembook.com) v1.0.0 - 250214 - initial version &#39;&#39;&#39; import numpy as np from pathlib import Path from lmfit import Model from codechembook.quickPlots import plotFit import codechembook.symbols as cs from codechembook.quickTools import quickOpenFilename, quickPopupMessage import os # Ask the user to specify a file with the data and read it quickPopupMessage(&#39;Select the file with the titration data to fit.&#39;) exp_eqs, exp_pHs = np.genfromtxt(quickOpenFilename(), delimiter = &#39;,&#39;, skip_header = 1, unpack = True) # Import the function we will want to use as our model try: # first, we attempt to import the pH_response function from TitrationModel import pH_response # import the function we want direct access to except ModuleNotFoundError: # if import fails, ask user to find the python script quickPopupMessage(&#39;titration.py not found. Please locate it using the file dialog. Click OK to open the file dialog.&#39;) script_path = quickOpenFilename(filetypes = &#39;*.py&#39;) # locate the .py file you want to use original_path = Path(&#39;.&#39;).resolve() # record the path you are currently using os.chdir(script_path.parent) # change directory to the one holding the .py file from TitrationModel import pH_response # import the .py file os.chdir(original_path) # change back to the working directory you started in # Define a new lmfit model using the pH_response function pH_model = Model(pH_response, independent_vars=[&#39;eqs&#39;]) # set up the model with eqs as the &#39;x&#39; axis # Set up the fit parameter and non-adjustable parameter for initial amount of acid pH_params = pH_model.make_params() # make a parameter object pH_params.add(&#39;pKa&#39;, value = np.mean(exp_pHs)) # specifications for the parameter base_i = 0.05 # the initial amount of acid # Fit the model to the data and store the results pH_fit = pH_model.fit(data = exp_pHs, eqs = exp_eqs, params = pH_params, base_i = base_i) # Create a figure for the fit result but don&#39;t show it yet fig = plotFit(pH_fit, residual = True, xlabel = &#39;equivalents added&#39;, ylabel = &#39;pH&#39;, output = None) # Add a horzontal line to highlight the pKa as determined by the fit fig.add_scatter(x = [min(exp_eqs), max(exp_eqs)], y = [pH_fit.params[&#39;pKa&#39;].value, pH_fit.params[&#39;pKa&#39;].value], mode = &#39;lines&#39;, showlegend=False, line = dict(color = &#39;gray&#39;)) # Add an annotation containing the best fitting pKa and its uncertainty fig.add_annotation(x = max(exp_eqs), y = pH_fit.params[&#39;pKa&#39;].value, xanchor = &#39;right&#39;, yanchor = &#39;bottom&#39;, text = f&#39;pKa = {pH_fit.params[&#34;pKa&#34;].value:.3f} {cs.math.plusminus} {pH_fit.params[&#34;pKa&#34;].stderr:.3f}&#39;, showarrow = False) fig.show(&#39;png&#39;) Solutions to Exercises Targeted exercises Automatically running different code under different conditions using if-then-else statements Exercise 0 Write three different functions that take as an argument a pH value and print a statement saying whether the value is ‘strongly acidic’, ‘acidic’, ’neutral’, ‘basic’, or ‘strongly basic’. One version can only use if statements, the second must use nested if-else statements, and the third must use if-elif-else. Prove that they work correctly by testing the values 1.0, 4.0, 7.0, 10.0, and 13.0.</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <managingEditor>authors@codingforchemistsbook.com (Benjamin Lear and Christopher Johnson)</managingEditor>
    <webMaster>authors@codingforchemistsbook.com (Benjamin Lear and Christopher Johnson)</webMaster>
    <atom:link href="https://codingforchemistsbook.com/book_material/chapter-7/index.xml" rel="self" type="application/rss+xml" />
  </channel>
</rss>