"""
### Computational Guided Inquiry for PChem (Mifflin, Neshyba & Guasco, 2019)

# Gibbs energy of an ideal reacting system

## Objective: Plot the Gibbs energy of an ideal reacting system, including enthalpic and entropic contributions
"""
"""
## Pre-class activities:
1. Read the Introduction below.  
2. Copy down all the equations in the introduction.
3. Define the terms _reaction extent_, _reaction quotient_, and _equilibrium constant_.  
4. Using the appropriate equation in the Introduction, calculate equilibrium constant, $K$, when the standard Gibbs energy of a reaction, $\Delta G_{rxn}^o$, equals negative two kilojoules.
"""
"""
## Introduction

You are familiar with the idea of using changes in the Gibbs energy as a condition for spontaneity at a given temperature and pressure, 

<p style='text-align: right;'>
$\Delta G_{rxn}<0 $ (spontaneous processes, fixed T and P)
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad (1) $
</p>

Since $G=H-TS$, this means that a system will tend to evolve toward the lowest enthalpy and the highest entropy possible; when the lowest Gibbs energy is reached, we say the system is in equilibrium. It turns out that when a system approaches equilibrium via a chemical reaction, this approach is constrained by the stoichiometry of the reaction. That's good because it gives a handle on how to think about how chemical systems react. That in turn provides some powerful analytical tools for predicting the position of equilibrium -- as you'll see in this exercise. 


"""
"""
Let’s say you are interested in the Gibbs energy associated with an aqueous reaction

<p style='text-align: right;'>
$A → B$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (2) $
</p>

where A and B are solutes. For starters, you need a way to keep track of the reaction progress as A is converted into B. To do so, it’s convenient to define a _reaction extent variable_, $ε$. The bounds of this variable are ε=0 (all A) up to ε=1 (all B). In between, the moles of A and B are given by

<p style='text-align: right;'>
$n_A=1-ε$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (3a) $
</p>

and

<p style='text-align: right;'>
$n_B=ε $
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (3b) $
</p>


"""
"""
Now suppose you want to calculate the Gibbs energy of this mixture as a function of ε. To do so, it’s helpful to imagine you have hypthothetical stock solutions of A and B, with concentrations $C_{A,stock}$ and $C_{B,stock}$ (usually assumed to be 1 <u>M</u>, if A and B are solutes). You take a sample of each solution, enough so that each has the moles of A and B indicated by Eq. 3, i.e., 

<p style='text-align: right;'>
$V_A=n_A/C_{A,stock}$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (4a) $
</p>

and 

<p style='text-align: right;'>
$V_B=n_B/C_{B,stock}$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (4b) $
</p>


"""
"""
The Gibbs energies of these two pure samples add up to

<p style='text-align: right;'>
$G^o=n_A  \Delta G ^o_{f,A} + n_B  \Delta G ^o_{f,B}$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (5) $
</p>

where $\Delta G ^o_{f,A}$ and $\Delta G ^o_{f,B}$ are the molar Gibbs energies of formation of A and B, typically obtained from a thermodynamic table. Of course, this is the _unmixed_ Gibbs energy. The real reaction is a mixture of A and B; physically, you would have to combine the two samples and stir them up. Such mixing would result in an entropy of mixing,


"""
"""
<p style='text-align: right;'>
$\Delta S_{mix}=-n_{tot}R[\chi _A ln\chi _A + \chi _B ln\chi _B]$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (6) $
</p>

where $n_{tot}$ is the sum of $n_A$ and $n_B$, and the mole fractions are given by the usual formulas, e.g., $\chi _A=n_A/n_{tot}$, etc. Now you can calculate the Gibbs energy of the reaction (as a function of reaction extent) according to 

<p style='text-align: right;'>
$G_{rxn}(ε)=G^o-T \Delta S_{mix}(ε)$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (7) $
</p>

where we have written $\Delta S_{mix}$ as a function of ε to stress that it depends on the reaction extent.
"""
"""
Now, what about those powerful analytical tools? Thermodynamics provides an interesting connection between $G$ and the equilibrium constant of a reaction, $K$. To make this connection, you’ll need to calculate concentrations of A and B _in the reaction mixture_ (i.e., not the stock concentrations). These values are given by

<p style='text-align: right;'>
$C_A = n_A/V_{tot}$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (8a) $
</p>

and 

<p style='text-align: right;'>
$C_B = n_B/V_{tot}$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (8b) $
</p>

where $V_{tot}=V_A+V_B$. Having obtained the concentrations, we can define a reaction quotient according to 

<p style='text-align: right;'>
$Q = C_B / C_A $
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (9) $
</p>

The reaction quotient is a function of ε; when the reaction is at equilibrium, we say that Q=K, where K is the equilibrium constant for the reaction. But Eq. 1 implies that this same equilibrium point must occur at the lowest point on a graph of G(ε). So this provides a way to find $K$. 



"""
"""
Thermodynamics provides one more interesting (and perhaps surprising) connection. You are probably familiar with the standard Gibbs energy of reaction, which for the reaction A → B is given by

<p style='text-align: right;'>
$\Delta G_{rxn}^o = \Delta G_{f,B}^o - \Delta G_{f,A}^o$
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (10) $
</p>

It can be shown that the equilibrium constant is related to $\Delta G_{rxn}^o$ according to 

<p style='text-align: right;'>
$K = exp(-\Delta G_{rxn}^o /RT) $
$\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad  (11) $
</p>

So this is yet one more way to find a value for $K$.
"""
"""
In this activity we’ll explore how these ideas of entropy of mixing, the Gibbs energy of reaction, and equilibrium constants play out in the context of the simple aqueous reaction $A → B$.
"""
"""
## In-class activities  
<br>
Import various libraries.
"""
from numpy import *
from matplotlib.pyplot import *
from mpl_toolkits.mplot3d import axes3d
%matplotlib notebook
"""
Define some constants
"""
# Constants
R = 8.314
T = 298

# Assume 1 M stock solutions 
CA0 = 1
CB0 = 1

# These are Gibbs energies of formation for A and B
G0A = 3.0e3 # In J/mol
G0B = 1.0e3

"""
Lay out the reaction progress parameter. It’s best if you start a little above zero, say at 0.01, and end a little shy of 1, say at 0.99. 
"""
#Define and print the reaction progress parameter

"""
Get the moles of the reactants and products as the reaction proceeds, and the mole fractions.
"""
# Calculate amounts of A and B at each point along the reaction (Eqs. 3a & 3b). Print your results for each to confirm they are reasonable.


# Get the mole fractions as a function of reaction progress

"""
Calculate volumes of the stock solutions needed to make the right concentrations.
"""
# Calculate the volumes (Eqs. 4a & 4b)

"""
Make a graph of the volumes over the course of a reaction.
"""
# Open a new plot window


# Plot VA(eps), VB(eps), and Vtot(eps)... change the variables to match with your definitions
plot(eps,VA,label='VA')
plot(eps,VB,label='VB')
plot(eps,Vtot,label='Vtot')
ylim(0, 1.1*Vtot.max()) # This gives a little extra space at the top of the graph
xlabel('eps')
ylabel('Volumes of stock solutions')
legend()
"""
The unmixed contribution to G 
"""
# Open a new plot window


# Calculate the unmixed contribution to Gibbs (Eq. 5)


# Plot G0(eps) (in kJ/mol, labeling x- and y-coordinates)




"""
The entropy of mixing
"""
# Open a new plot window


# Calculate the entropy of mixing (Eq. 6)


# Plot the entropy of mixing as a function of eps (in J/mol-K, labeling x- and y-coordinates)





"""
#### Pause For Analysis #1: Make a note of where along the extent of reaction the entropy of mixing is greatest. Using this information, determine the relative mole fractions of A and B that correspond to the maximum entropy of mixing. What is the cause of the increase in entropy as the components mix?
"""
"""
Calculate the Gibbs energy including mixing (Eq. 7). For this, it’s handy to create a variable Gmix, where Gmix = -T\*Smix. Then calculate the total Gibbs energy, including mixing, as G = G0 + Gmix. Finally, plot both unmixed and mixed:

plot(eps,G0/1e3,label='G0')
plot(eps,G/1e3,label='G')
legend()

where dividing by 1e3 converts to kJ/mole
"""
# Open a new plot window

# Calculate the Gibbs energy of mixing (Eq. 7)

# Calculate the total Gibbs energy

# Plot G(eps) and G0(eps) together (in kJ/mol, labeling x- and y-coordinates, with a legend)


"""
#### Pause For Analysis #2: What does the minimum point of the Gibbs energy of mixing represent? In which direction (i.e., increasing or decreasing epsilon) does the reaction proceed spontaneously when epsilon is less than the value corresponding to the minimum point? 
"""
"""
A little python interlude ... 
"""
"""
It will be handy to use python to find the minimum of $G(ε)$, and the value of eps at which that minimum occurs. Here's an example showing how to find the minimun of a simple function. 
"""
# Lay out a simple function, f=x^2+10
x = linspace(-1,1,5) # This makes five values of x, from -1 to 1
f = x**2+10

# Use "argmin" to get the minimum of f
ifmin = f.argmin()
print('f = ', f)
print('x = ', x)
print('The minimum of f occurs at index', ifmin)
print('The minimum value of f is', f[ifmin])
print('x at at the minimum value of f is', x[ifmin])
"""
... and now back to the Gibbs energy
"""
"""
Now use the same technique to find the minimum of $G$, and the value of eps at which it occurs.
"""
# You can find the index to the minimum value of G with argmin, as follows.
iGmin = G.argmin()
print('G = ', G)
print('eps', eps)
print('The minimum of G occurs at index', iGmin)
print('The minimum value of G is', G[iGmin])
print('eps at at the minimum value of G is', eps[iGmin])

"""
#### Pause For Analysis #3: Do your calculated values appear to match up with what you observe in your plot of G vs $\varepsilon$ above? What is the index to the value of eps where the minimum G occurs? What is the name of the corresponding variable.
"""
"""
The reaction quotient, $Q$
"""
# Concentrations of reactant and product in the reaction mixture (Eqs. 8a & 8b)



# Calculate the reaction quotient (Eq. 9)


# Plot Q(eps)





"""
#### Pause For Analysis #4: Why does Q increase with increasing $\varepsilon$? 
"""
"""
Print the value of $Q$ at the minimum eps, and see whether that is close to the prediction based on $\Delta G_{rxn}^o$
"""
# Calculate and print Q at equilibrium (i.e., at the value of eps for which G is a minimum)



# Get delta-G0 (Eq. 10)




# Get K (Eq. 11)




"""
#### Pause For Analysis #5: How do the values of K you calculated compare to each other? How do they compare the value you calculated in the pre-CGI activity?
"""
"""
## Post-CGI activities:   
In your lab notebook, enter the following:

1.	Of the terms you defined in the pre-lab, choose one (or more) whose definition you would want to revise after doing this exercise.  
3.  Explain the difference between the _Gibbs energy of a reaction mixture_ and the _Standard Gibbs energy of reaction_.  
2.	Sketch $\Delta S_{mix}(\varepsilon)$, $G_{rxn}(\varepsilon)$, and $Q(\varepsilon)$ (i.e. all as functions of reaction extent).  
4.	On your sketch of $Q(\varepsilon)$, show where the equilibrium constant computed from Eq. 11 is located.
5. Change the values of G0A and G0B so that $\Delta G_{rxn}^o$ has a different value than -2 kJ/mol. How do your minimum values, K, etc. change?

#### Complete the Canvas "Post-CGI Activity" quiz for this CGI after class to receive credit. Your answers to the Post-class activity should now be recorded in both your physical CGI notebook (for reference after class) and on Canvas (to receive points).

I will also look at your python notebook (the .ipynb file) on the CGI server. I will be looking for evidence of your mastery of the computational methods embedded in the exercise: whether the notebook is complete and your results accurate. Please don't hesistate to contact me if you encounter any difficulty in executing a programming task or answering a Pause for Analysis item.
"""