<jupyter_start><jupyter_text>Copyright **<NAME> and <NAME>**, January 2021 Equilibrium problem \1Consider the Haber–Bosch process for the production of Ammonia\begin{equation}\mathrm{N_2 + 3H_2 \to NH_3}\end{equation}where the equilibrium constant can be written as\begin{equation}K_p = \dfrac{x^2(NH_3)}{x(N_2)x^3(H_2)}\bigg(\dfrac{p^\circ}{p}\bigg)\end{equation}where $x(i)$ is the mole fraction of species $i$ and $p$ is the pressure of the reactor.By determining the equilibrium constant at different temperatures, you can:- compute the enthalpy and entropy of the reaction- determine the maximum theoretical temperature below which the formation of ammonia is favourable Tips:Remember the integrated van't Hoff equation that you learnt in first year: \begin{equation*}\ln K_{eq} = -\dfrac{\Delta G}{RT} = -\dfrac{\Delta H}{RT} + \dfrac{\Delta S}{R}\end{equation*} Instructions:- Use the slide bar below to select temperature at which you perform the virtual experiment, - Click `Perform measurement` to run the virtual experiment and obtain the result of the experiment,- Click `Download CSV` to export the complete data set for all the experiments as a CSV file.<jupyter_code># define path to results.csv file
respath = os.path.join(os.getcwd(), "..", "results.csv")

# delete existing result file and setup rng
if os.path.exists(respath):
    os.remove(respath)

#random.seed(params["error"].get("seed", 0))
t = int( time.time() * 1000.0 )
random.seed( ((t & 0xff000000) >> 24) +
             ((t & 0x00ff0000) >>  8) +
             ((t & 0x0000ff00) <<  8) +
             ((t & 0x000000ff) << 24)   )

class system:
    def __init__(self, vol=0, conc=0, press=0):
        self.vol = vol
        self.conc = conc
        self.press = press

class data:
    def __init__(self, start=-1, error=0, label='none', units='pure', value=0,
                minval=-1, maxval=3):
        self.start = start
        self.minval = minval
        self.maxval = maxval
        self.error = error
        self.label = label
        self.units = units
        self.value = value
    
# Experiment setup (+ hidden paramters)
system = system()
def initialiseExperiment():
    global n
    global system 
    global columns_list
    global scatter
    
    scatter = 0.2


    n = []
    columns_list = []

    n.append(len(args)) # number of input adjustable parameters    
    n.append(len(result)) # number of results for the experiment

    for i in range(0, n[0]):
        columns_list.append(f"{args[i].label} [{args[i].units}]")
    for i in range(0, n[1]):
        columns_list.append(f"{result[i].label} [{result[i].units}]")

    # Random initial concentration
    system.conc = random.random()

# Adjustable input parameters
def initialiseVariables():
    global logScale
    logScale = False
    global args
    args = []
    args.append(
        data(
            label = "Temperature",
            minval = 273,
            maxval = 800,
            start = 300+273.15,
            units = "K",
            value = 0.
        )
    )

# Results
def initialiseResults():
    global result
    result = []
    result.append(
        data(
            label = "k$_{p}$",
            start = 0.,
            error = random.random() / 50.,
            units = "pure"
        )
    )

def measure():
    gasR = 8.3145 # J/mol/K
    temp = args[0].value.value
    lnK = -params["dH"] / gasR / temp + params["dS"] / gasR
    res = math.exp(lnK)
    return res

initialiseVariables()

out_P = ipw.Output()
out_L = ipw.Output()

with out_L:
    display(Markdown("[Download CSV](../results.csv)"))
    
def calc(btn):
    out_P.clear_output()
    
    # Measurement result
    result[0].value = measure()
    
    # Random error
    result[0].error = result[0].value * scatter * (0.5 - random.random()) * 2
    
    # Output result
    out_R[0].value = f"{result[0].value + result[0].error:.3e}"

    # Read previous lines
    res = pd.read_csv(respath) 
    
    var_list = []
    for i in range(0, n[0]):
        var_list.append(args[i].value.value)
    for i in range(0, n[1]):
        var_list.append(result[i].value + result[i].error)
    
    # Append result
    res.loc[len(res)] = var_list
    res.to_csv(respath, index=False)
    with out_P:
        display(res.tail(50))

def reset(btn):
    if os.path.exists(respath):
        os.remove(respath)

    initialiseResults()
    initialiseExperiment()
    
    res = pd.DataFrame(columns=columns_list)
    res.to_csv(respath, index=False)
    with out_P:
        out_P.clear_output()
        display(res.tail(50))

# interactive buttons ---
btn_reset = ipw.Button(description="Restart Laboratory", layout=ipw.Layout(width="150px"))
btn_reset.on_click(reset)

btn_calc = ipw.Button(description="Perform measurement", layout=ipw.Layout(width="150px"))
btn_calc.on_click(calc)
# ---

reset(btn_reset)

rows = []
for i in range(0, n[0]):
    if logScale:
        args[i].value = ipw.FloatLogSlider(value=args[i].start, min=args[i].minval, max=args[i].maxval)
    else:
        args[i].value = ipw.FloatSlider(value=args[i].start, min=args[i].minval, max=args[i].maxval)
        
    rows.append(ipw.HBox([ipw.Label(value=f"{args[i].label} [{args[i].units}]:",
                                    layout=ipw.Layout(width="250px")),
                          args[i].value]))

out_R = []
for i in range(0, n[1]):
    out_R.append(ipw.Label(value=""))
    rows.append(ipw.HBox([ipw.Label(value=f"Measured {result[i].label} [{result[i].units}]:",
                                    layout=ipw.Layout(width="250px")),
                            out_R[i]]))

rows.append(ipw.HBox([btn_reset, btn_calc, out_L]))
rows.append(ipw.HBox([out_P]))

ipw.VBox(rows)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.142657586869216, 'fraction_numerical': 0.022001047668936617, 'mean_word_length': 2.714656290531777, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '96464', 'license': 'MIT', 'n_tokens_mistral': 1982, 'n_tokens_neox': 1869, 'n_words': 452, 'path': 'CEK_problems/equilibrium_01.ipynb', 'repo_name': 'blake-armstrong/TeachingNotebook', 'size': '5740'}