 ✅ Put your name here

# Pre-Class Assignment: Practice

In todays pre-class assignment you are going to practice what we have learned.

# Goals for today's pre-class assignment

1. topic
1. Assignment Wrap-up

```python
# Read data for this assignment
%matplotlib inline
import matplotlib.pyplot as plt
from scipy.misc import imread, imsave
from urllib.request import urlopen

url1 = 'http://res.cloudinary.com/miles-extranet-dev/image/upload/ar_16:9,c_fill,w_1000,g_face,q_50/Michigan/migration_photos/G21696/G21696-msubeaumonttower01.jpg'
with urlopen(url1) as file:
    im1 = imread(file, mode='RGB')
url2 = 'http://msutoday.msu.edu/_/img/assets/2013/beaumont-spring-1.jpg'
with urlopen(url2) as file:
    im2 = imread(file, mode='RGB')

f, (ax1, ax2) = plt.subplots(1, 2,figsize=(20,10))
ax1.imshow(im1)
ax2.imshow(im2)
```

----
# 1. Point Seleciton

```python
# The following command will install mpld3 - Uncomment and run once.

!pip install -t ./packages mpld3
```

    Collecting mpld3
      Downloading mpld3-0.5.5.tar.gz (1.0 MB)
    Collecting jinja2
      Downloading Jinja2-3.0.2-py3-none-any.whl (133 kB)
    Collecting matplotlib
      Downloading matplotlib-3.4.3-cp39-cp39-win_amd64.whl (7.1 MB)
    Collecting MarkupSafe>=2.0
      Downloading MarkupSafe-2.0.1-cp39-cp39-win_amd64.whl (14 kB)
    Collecting python-dateutil>=2.7
      Downloading python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
    Collecting pyparsing>=2.2.1
      Downloading pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)
    Collecting pillow>=6.2.0
      Downloading Pillow-8.4.0-cp39-cp39-win_amd64.whl (3.2 MB)
    Collecting cycler>=0.10
      Downloading cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)
    Collecting kiwisolver>=1.0.1
      Downloading kiwisolver-1.3.2-cp39-cp39-win_amd64.whl (52 kB)
    Collecting numpy>=1.16
      Downloading numpy-1.21.3-cp39-cp39-win_amd64.whl (14.0 MB)
    Collecting six
      Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
    Building wheels for collected packages: mpld3
      Building wheel for mpld3 (setup.py): started
      Building wheel for mpld3 (setup.py): finished with status 'done'
      Created wheel for mpld3: filename=mpld3-0.5.5-py3-none-any.whl size=200886 sha256=92ce84322a8357effb323059fc276b9df28bb02b05463dc5731527cbdc4ccc16
      Stored in directory: c:\users\owner\appdata\local\pip\cache\wheels\d9\ed\51\ac5c5c9f2f8105b101482c066a31f9e71a9eef9c2fd6379bdd
    Successfully built mpld3
    Installing collected packages: six, python-dateutil, pyparsing, pillow, numpy, MarkupSafe, kiwisolver, cycler, matplotlib, jinja2, mpld3
    Successfully installed MarkupSafe-2.0.1 cycler-0.10.0 jinja2-3.0.2 kiwisolver-1.3.2 matplotlib-3.4.3 mpld3-0.5.5 numpy-1.21.3 pillow-8.4.0 pyparsing-2.4.7 python-dateutil-2.8.2 six-1.16.0

```python
#Add Packages folder to path (Do only once per run of notebook:
from sys import path
package_folder = './packages'
if not package_folder in path:
    print('adding packages')
    path.append(package_folder)
else:
    print('found packages folder')
```

    adding packages

```python
# Code snipit to make point seleciton function (REQUIRES mpld3 installed)
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as img
import sys

import mpld3
from mpld3 import plugins
mpld3.enable_notebook()

# PLOTS THE IMAGE IN THE NOTEBOOK
def plot(imgname):
    fig, ax = plt.subplots()
    im = img.imread(imgname)
    plt.imshow(im, origin='lower')
    return fig

# FUNCTION CALLED IN THE NOTEBOOK
def pickpoints(fig='', radius=4, color="white", x = 'x', y = 'y'):
    if not fig:
        fig = plt.gcf()
    plugins.connect(fig, Annotate(radius, color, x, y)) # color='htmlcolorname', radius=int
    plugins.connect(fig, plugins.MousePosition())

# FORMATS x AND y LISTS INTO SHORTER DECIMALS, SO THEY'RE NOT TOO LENGTHY
def cleanformat(var):
    varlist = []
    if type(var) == float:
        varlist = '{:05.2f}'.format(var)
    else:
        for i in range(len(var)):
            varlist.append('{:05.2f}'.format(var[i]))
    return varlist

# MAIN CLASS THAT CONTAINS JAVASCRIPT CODE TO CREATE CIRCLES AND DRAG CIRCLES
class Annotate(plugins.PluginBase):
    """A plugin that creates points in a figure by clicking the mouse"""

    JAVASCRIPT = r"""
    mpld3.register_plugin("annotate", Annotate);
    Annotate.prototype = Object.create(mpld3.Plugin.prototype);
    Annotate.prototype.constructor = Annotate;
    Annotate.prototype.requiredProps = [];
    Annotate.prototype.defaultProps = {radius: 4, color: "white", x: 'x', y: 'y'};
    function Annotate(fig, props){
        mpld3.Plugin.call(this, fig, props);
    };

    Annotate.prototype.draw = function(){

        /// NECESSARY STARTUP VARIABLES ///

        var fig = this.fig;
        var ax = fig.axes;
        var dataset = [];
        var svg = d3.select(".mpld3-figure");   // existing svg element
        var radius = this.props.radius;
        var color = this.props.color;
        var x = this.props.x;
        var y = this.props.y;
        var ax = fig.axes[0];

        /// INDEXES HTML DOC TO PULL VALUES FOR x,y CALIBRATION ///
        var xcal = this.parent.axes[0].position[0];
        var ycal = this.parent.axes[0].position[1];
        console.log('x calibration: ' + xcal);
        console.log('y calibration: ' + ycal);

        var xcommand = x+" = []";
        IPython.notebook.kernel.execute(xcommand);
        var ycommand = y+" = []";
        IPython.notebook.kernel.execute(ycommand);

        ////////// CREATE POINT COMPONENT //////////

        var update_coords = function() {

            return function() {
                var pos = d3.mouse(this),
                    xpos = ax.x.invert(pos[0]),
                    ypos = ax.y.invert(pos[1]);

                var newpoint = {
                    cx: pos[0] + xcal,
                    cy: pos[1] + ycal,
                    r: radius,
                    fill: color
                };
                dataset.push(newpoint);

                var circles = svg.selectAll("circle")
                    .data(dataset)
                    .enter()
                    .append("circle")
                    .attr(newpoint)
                    .call(drag);

                var xcommand = x+".append("+xpos+")";
                IPython.notebook.kernel.execute(xcommand);
                console.log(xcommand);
                var ycommand = y+".append("+ypos+")";
                IPython.notebook.kernel.execute(ycommand);
                console.log(ycommand);

            };
        }();
        ax.baseaxes
            .on("mousedown", update_coords);

        ////////// DRAG POINT COMPONENT //////////

        var drag = d3.behavior.drag()
            .on("dragstart", dragstarted)
            .on("drag", dragged)
            .on("dragend", dragended);

        function dragstarted(d) {
             d3.event.sourceEvent.stopPropagation();
             d3.select(this).classed("dragging", true);
        }

        function dragged(d) {
             d3.select(this).attr("cx", d3.event.x)
                            .attr("cy", d3.event.y);
        }

        function dragended(d, i) {
             d3.event.sourceEvent.stopPropagation();
             d3.select(this).classed("dragging", false);
             var calib_cx = d3.select(this)[0][0].cx.animVal.value - xcal;
             var calib_cy = d3.select(this)[0][0].cy.animVal.value - ycal;
             var xcommand = x+"["+i+"] = "+ax.x.invert(calib_cx);
             var ycommand = y+"["+i+"] = "+ax.y.invert(calib_cy);
             IPython.notebook.kernel.execute(xcommand);
             IPython.notebook.kernel.execute(ycommand);
             console.log(xcommand);
             console.log(ycommand);
        }

    };"""

    def __init__(self, radius=4, color="white", x ='x', y ='y'):
        self.dict_ = {"type": "annotate",
                      "radius": radius,
                      "color": color,
                      "x": x,
                      "y": y};
```

```python
fig = plt.figure(figsize=(9,6))
plt.imshow(im1)
pickpoints(color='cyan', radius=2, x='x1', y='y1')
```

```python
fig = plt.figure(figsize=(9,6))
plt.imshow(im2)
pickpoints(color='cyan', radius=2, x='x2', y='y2')
```

----
# 1. Topic one

==TOPIC DESCRIPTION==

```python
%matplotlib inline
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
import scipy.misc as misc

from skimage import transform

# Here are some libraries you may need to use
%matplotlib inline
import matplotlib.pylab as plt

import sympy as sp
sp.init_printing()

import numpy as np

from ipywidgets import interact
import math

```

```python
plt.imshow(im2)
```

```python
im = im1
def affine_image(a1=0,s=1,tx=0,ty=0, alpha=1):
    theta = -a1/180  * math.pi

    dx = tx*im.shape[1]
    dy = ty*im.shape[0]
    S = np.matrix([[1/s,0,0], [0,1/s,0], [0,0,1]])
    T2 = np.matrix([[1,0,im.shape[1]/2], [0,1,im.shape[0]/2], [0,0,1]])
    T1 = np.matrix([[1,0,-im.shape[1]/2-dx], [0,1,-im.shape[0]/2-dy], [0,0,1]])
    R = np.matrix([[math.cos(theta),-math.sin(theta),0],[math.sin(theta), math.cos(theta),0],[0,0,1]])
    img = transform.warp(im, T2*S*R*T1);
    plt.imshow(im2);
    plt.imshow(img, alpha=alpha);

    plt.show();
```

```python
interact(affine_image, a1=(-180,180), s=(0.001,5), tx=(-1.0,1.0), ty=(-1,1,0.1),alpha=(0.0,1.0)); ##TODO: Modify this line of code
```

```python

```

```python

```

```python
# Here are some libraries you may need to use
%matplotlib inline
import matplotlib.pylab as plt

import sympy as sp
sp.init_printing()

import numpy as np

from ipywidgets import interact
import math

```

```python
from urllib.request import urlopen
from scipy.misc import imread, imsave

url = 'http://res.cloudinary.com/miles-extranet-dev/image/upload/ar_16:9,c_fill,w_1000,g_face,q_50/Michigan/migration_photos/G21696/G21696-msubeaumonttower01.jpg'

with urlopen(url) as file:
    im = imread(file, mode='RGB')

#Show the image
plt.imshow(im);
```

```python
##Put your function here
from skimage import transform

def affine_image(a1=0,s=0.5,tx=0,ty=0,shx=0, shy=0):
    T = np.matrix([[1,0,0],[0,1,0],[0,0,1]])
    #Your transformations go here.

    img = transform.warp(im, T);
    plt.imshow(img);
    plt.show();
```

```python

##ANSWER##

def affine_image(a1=0,s=0.5,tx=0,ty=0, shx=0, shy=0):
    theta = -a1/180  * math.pi

    dx = tx*im.shape[1]
    dy = ty*im.shape[0]
    S = np.matrix([[1/s,0,0], [0,1/s,0], [0,0,1]])
    SH = np.matrix([[1,shx,0], [shy,1,0], [0,0,1]])
    T2 = np.matrix([[1,0,im.shape[1]/2], [0,1,im.shape[0]/2], [0,0,1]])
    T1 = np.matrix([[1,0,-im.shape[1]/2-dx], [0,1,-im.shape[0]/2-dy], [0,0,1]])
    R = np.matrix([[math.cos(theta),-math.sin(theta),0],[math.sin(theta), math.cos(theta),0],[0,0,1]])
    img = transform.warp(im, T2*S*R*SH*T1);
    plt.imshow(img);

    plt.show();
##ANSWER##
```

```python

interact(affine_image, a1=(-180,180), s=(0.001,5), tx=(-1,1,0.1), ty=(-1,1,0.1), shx = (-1,1,0.1), shy = (-1,1,0.1)); ##TODO: Modify this line of code
```

```python
from IPython.display import YouTubeVideo
YouTubeVideo("NzysdpexqsM",width=640,height=360)
```

**Quesiton:** Ask a question that requires a written answer?

✎ Do This - Erase the contents of this cell and replace it with your answer to the above question!  (double-click on this text to edit this cell, and hit shift+enter to save the text)

 ✅ **To Do:** Task to be completed by student.

```python
%matplotlib inline
import matplotlib.pylab as plt
import numpy as np
import sympy as sp
sp.init_printing(use_unicode=True)
```

```python
#Example matrix in sympy
sp.Matrix([[1,0], [0,1]])
```

```python
#Example equation in sympy
#First define all of the symples to use in our equation
x,y,z,om = sp.symbols('x, y, z, \omega', negative=False)
pa = om*x**2+om*y**2+om*z**2
pa
```

```python
#Put your code here
```

Example matrix notation:

$$
\left[
\begin{matrix}
    1   & 0 & 4  \\
    0   & 2 & -2  \\
    0   & 1 & 2
 \end{matrix}
\, \middle\vert \,
\begin{matrix}
-10 \\ 3 \\ 1
\end{matrix}
\right]
$$

----
# 2. Assignment wrap-up

Please fill out the form that appears when you run the code below.  **You must completely fill this out in order to receive credit for the assignment!**

Direct Link: https://goo.gl/YcjHHB

```python
from IPython.display import HTML
HTML(
"""

"""
)
```

---------
### Congratulations, you're done with your pre-class assignment!

© Copyright 2018,  Michigan State University Board of Trustees


---

# Flamespeed

---

## What is Flamespeed?

Flamespeed is an open-source Python library with object-orientated methods for chemical kinetics with the following core functionality:

* API to import a database of elementary reactions in XML-format
* Efficiently calculate reaction rates for systems of irreversible elementary chemical reactions
* Output provided in format suitable for further analysis

Potential **applications** for Flamespeed includes:

* Validation of chemical phase input files
* Input for solving ODEs for system of reactions
* Input for machine learning methods (e.g. neural networks) that predict reaction types

## Installation

There are two ways to install Flamespeed:

**Install Flamespeed from PyPI (recommended)**

```bash
pip install flamespeed
```

**Alternatively: Install Flamespeed form Github source**

First, clone Flamespeed using `git`:

```sh
git clone https://github.com/bkleyn/flamespeed.git
```
Then, `cd` to the root folder and run the install command:
```sh
python setup.py install
```

The package **test suite** can be run as follows:

First, `cd` to the flamespeed folder and then run pytest:
```sh
cd flamespeed
pytest
```

**Requirements:**
* Python (>= 3.3)
* NumPy (>= 1.8.2)
* SciPy (>= 0.13.3)

## Getting started

Import the `chemkin` module in flamespeed, which is the main module to evaluate chemical reaction rates.

```python
from flamespeed import chemkin
```
Instantiate the reaction rates class and import reaction database in XML format. Example reaction files can be found in the `./data` directory within `flamespeed`.

```python
a = chemkin.ReactionRate()
a.read_XML('./flamespeed/data/rxns_reversible.xml')
print(a)
```
Next, set the initial concentrations for each of the species included in the reaction and the temperature.

```python
a.set_temp(750)
x = [2.0, 1.0, 0.5, 1.0, 1.0, 1.5, 0.5, 1]
```
Now that all the input parameters have been specified the reaction rates for each of the species in the system can be determined as follows:

```python
r = a.get_reaction_rate(x)
print(r)
```

---

## Technical detail

#### Irreversible Elementary Reactions

The mathematical and physical underpinnings of this chemical kinetics library is to solve for the reaction rates of a system consisting of $N$ species undergoing $M$ **irreversible**, **elementary** reactions of the form:

\begin{align}
  \sum_{i=1}^{N}{\nu_{ij}^{\prime}\mathcal{S}_{i}} \longrightarrow
  \sum_{i=1}^{N}{\nu_{ij}^{\prime\prime}\mathcal{S}_{i}}, \qquad j = 1, \ldots, M
\end{align}

An example system of reactions for which the reaction rates can be determined by this library is:

$$ H_{2} + O_{2} \longrightarrow H_{2}O + O$$
$$ H_{2}O + O \longrightarrow 2OH $$
$$ OH + H_{2} \longrightarrow 2H + OH $$

More specifically, the **reaction rate** of specie $i$ can be written as:

\begin{align}
  f_{i} = \sum_{j=1}^{M}{\nu_{ij}\omega_{j}}, \qquad i = 1, \ldots, N
\end{align}

where the **progress rate** for each reaction is denoted by:

\begin{align}
  \omega_{j} = k_{j}\prod_{i=1}^{N}{x_{i}^{\nu_{ij}^{\prime}}}, \qquad j = 1, \ldots, M
\end{align}

Please refer to the table below for an overview of used symbols. Note that $k_{j}$ is the forward reaction rate coefficient, and is a direct input to a reaction's progress rate. Specifically, this library is capable of handling and calculating three different types of reaction rate coefficients:

$$ Constant: k_j = c $$
$$ Arrhenius: k_j = Ae^{(-\dfrac{E}{RT})}$$
$$ Modified \hspace{0.25em} Arrhenius: k_j = AT^{b}e^{(-\dfrac{E}{RT})}$$

The library assigns each elementary reaction its own reaction rate coefficient. When loading an XML-file with data, the rate coefficient type needs to be specified. In case of a Arrhenius reaction rate coefficient, additional values need to be provided for $A$, $E$, $R$, $T$. In case of Modified Arrhenius reaction rate coefficient, additional values need to be provided for $A$, $b$, $E$, $R$, $T$.

---

#### Reversible Elementary Reactions

Although the above derivations hold for **irreversible** elementary reactions, oftentimes **reversible** elementary reactions occur in nature instead (i.e., the products can react and produce the reactants and so forth). Generally, a reversible reaction will have the form:

$$\sum_{i=1}^{N}{\nu_{ij}^{\prime}\mathcal{S}_{i}}  \rightleftharpoons \sum_{i=1}^{N}{\nu_{ij}^{\prime\prime}\mathcal{S}_{i}} \qquad j = 1, \ldots, M$$

where $\rightleftharpoons$ indicts that the foward and backward reactions occur. Note this sign is technically the only difference with the above derive reaction forms.

The total progress rate is then given by:

$$\omega_{j} = k_{j}^{\left(f\right)}\prod_{i=1}^{N}{x_{i}^{\nu_{ij}^{\prime}}} - k_{j}^{\left(b\right)}\prod_{i=1}^{N}{x_{i}^{\nu_{ij}^{\prime\prime}}}, \qquad j = 1,\ldots, M.$$

If, and only if, the reaction is elementary, the **backward reaction coefficient** can be defined as:

$$k_{j}^{\left(b\right)} = \frac{k_{j}^{\left(f\right)}}{k_{j}^{e}}, \qquad j =1, \ldots, M$$

where $k_{j}^{e}$ is the **equilibrium coefficient** for reaction $j$.

The final expression for the equilibrium coefficient is

$$k_{j}^{e} = \left(\frac{p_{0}}{RT}\right)^{\gamma_{j}}\exp\left(\frac{\Delta S_{j}}{R} - \frac{\Delta H_{j}}{RT}\right), \qquad j =1, \ldots, M$$

where $\gamma_{j} = \sum_{i=1}^{N}{\nu_{ij}}$ and $p_{0}$ is the pressure of the reactor (take it to be $10^{5}$ Pa).

The entropy and enthalpy change of reaction $j$ can be defined in terms of the entropy and enthalpy of the species participating in reaction $j$.  We have:

$$\Delta S_{j} = \sum_{i=1}^{N}{\nu_{ij}S_{i}} \quad \textrm{and} \quad \Delta H_{j} = \sum_{i=1}^{N}{\nu_{ij}H_{i}}, , \qquad j =1, \ldots, M.$$

The **specific heat** at constant pressure ($C_{p,i}$), **enthalpy** ($H_{i}$) and **entropy** ($S_{i}$) are related via

$$H_{i} = \int_{T_{0}}^{T}{C_{p,i}\left(T\right) \ \mathrm{d}T}, \qquad i = 1, \ldots, N$$

and

$$S_{i} = \int_{T_{0}}^{T}{\frac{C_{p,i}\left(T\right)}{T} \ \mathrm{d}T}, \qquad i = 1, \ldots, N$$

where $C_{p,i}$ is given by a polynomial in $T$ (called the **NASA polynomial**),

$$C_{p,i} = \left(\sum_{k=1}^{5}{a_{ik}T^{k-1}}\right)R, \qquad i = 1, \ldots, N.$$

The $7$th order NASA polynomials are given by

$$\frac{C_{p,i}}{R} = a_{i1} + a_{i2}T + a_{i3}T^{2} + a_{i4}T^{3} + a_{i5}T^{4}$$

$$\frac{H_{i}}{RT} = a_{i1} + \frac{1}{2}a_{i2}T + \frac{1}{3}a_{i3}T^{2} + \frac{1}{4}a_{i4}T^{3} + \frac{1}{5}a_{i5}T^{4} + \frac{a_{i6}}{T}$$

$$\frac{S_{i}}{R} = a_{i1}\ln\left(T\right) + a_{i2}T + \frac{1}{2}a_{i3}T^{2} + \frac{1}{3}a_{i4}T^{3} + \frac{1}{4}a_{i5}T^{4} + a_{i7}$$

for $i = 1,\dots, N$.

---

A few notes on symbols used:

| Symbol | Meaning |
|:--------:|:-------:|
| $\mathcal{S}_{i}$ | Chemical symbol of specie $i$ |
| $\nu_{ij}^{\prime}$ | Stoichiometric coefficients of reactants |
| $\nu_{ij}^{\prime\prime}$ | Stoichiometric coefficients of products |
| $N$                       | Number of species in system |
| $M$                       | Number of elementary reactions |
| $R$                       | Ideal gas constant |
| $T$                       | Temperature of reaction |
| $S_i$                     | Entropy of specie $i$ |
| $H_i$                     | Enthalpy of specie $i$ |
| $C_{p,i}$                 | Specific heat at constant pressure of specie $i$ |
| $f_{i}$                   | Rate of consumption or formation of specie $i$ (reaction rate) |
| $\omega_{j}$              | Progress rate of reaction $j$ |
| $x_{i}$                   | Concentration of specie $i$ |
| $k^f_{j}$                 | (Forward) Reaction rate coefficient for reaction $j$ |
| $k^b_{j}$                 | Backward reaction rate coefficient for reaction $j$ |
| $k^e_{j}$                 | Equilibrium reaction rate coefficient for reaction $j$ |
| $a_{i}$                   | NASA polynomial coefficients |

---

## Chemkin module

### ReactionCoefficients Class

**Methods:**
    1. k_const(k=1.0) - Simply returns a constant reaction rate coefficient
    2. k_arrhenius(A, E, T, R=8.314) - Arrhenius reaction rate coefficient
    3. k_arrhenius_mod(A, b, E, T, R=8.314) - Modified Arrhenius reaction rate coefficient

**k_const(k=1.0)**

    Parameters:
    k: float, default value = 1.0 - Constant reaction rate coefficient

    Returns:
    k: Constant reaction rate coefficient

**k_arrhenius(A, E, T, R=8.314)**

    Parameters:
    A: float, positive - Arrhenius prefactor
    E: float - Activation energy
    T: float, positive - Temperature in Kelvin
    R: float, positive, default value = 8.314 - Ideal gas constant

    Returns:
    k: Arrhenius reaction rate coefficient

**k_arrhenius_mod(A, b, E, T, R=8.314)**

    Parameters:
    A: float, positive - Arrhenius prefactor
    b: float - Modified Arrhenius parameter
    E: float - Activation energy
    T: float, positive - Temperature in Kelvin
    R: float, positive, default value = 8.314 - Ideal gas constant

    Returns:
    k: Modified Arrhenius reaction rate coefficient

### ReactionRate Class

**Methods:**
    1. __init__ - Initialize ReactionRate class
    2. __str__ - Return summary of XML file contents
    3. __repr__ - Return class type
    4. __len__ - Returns number of reactions
    5. read_XML(path) - Reads XML from file path and extracts reaction information
    6. set_temp(T) - Calculate reaction rate coefficients at specified temperature
    7. get_progress_rate(concs) - Progress rate for a system of elementary reactions
    8. get_reaction_rate(concs) - Reaction rate for a system of elementary reactions

**\__init__**

    Sets class-wide parameters

**\__str__**

    Returns: Returns summary of reaction phase, including species and number of reactions

**\__repr__**

    Returns: Class type

**\__len__**

    Returns: Number of reactions

**read_XML(path)**

    Parameters:
    path: string, path to the XML file

    Returns:
    ReactionRate class instance

**set_temp(T)**

    Parameters:
    T: Float, positive - Temperature in Kelvin

    Returns:
    k: float - Reaction rate coefficients for each reaction

**get_progress_rate(concs)**

    Parameters:
    concs: numpy array of floats (size: num_species) - Concentration of species

    Returns:
    w: numpy array of floats (size: num_reactions) - Progress rate for each reaction

**get_progress_rate(concs)**

    Parameters:
    concs: numpy array of floats (size: num_species) - Concentration of species

    Returns:
    f: numpy array of floats (size: num_species) - Reaction rate for each specie

---

## Thermo module

**Methods:**

    1. __init__(species, nu_coef) - Initialize ReactionRate class
    2. read_nasa_coeffs(T) - Read thermo.sqlite database to obtain NASA coefficients
    3. Cp_over_R(T) - Computes specific heat over ideal gas constant (R) at specified temperature
    4. H_over_RT(T) - Computes enthalpy change (delta H) over (R*T) at specified temperature
    5. S_over_R(T) - Computes entropy change (delta S) over (R) at specified temperature
    6. backward_coeffs(kf, T) - Calculate the backward coefficents given forward rate coefficients

**\__init__**

    Sets class-wide parameters

**read_nasa_coeffs(T)**

    Parameters:
    T: Temperature (in Kelvin)

    Returns:
    NASA Coefficients

**Cp_over_R(T)**

    Parameters:
    T: Temperature (in Kelvin)

    Returns:
    Specific Heat at constant pressure over Ideal Gas Constant (C/R)

**H_over_RT(T)**

    Parameters:
    T: Temperature (in Kelvin)

    Returns:
    Enthalpy Change (Delta S) over Ideal Gas Constant times Temperature (RT)

**S_over_R(T)**

    Parameters:
    T: Temperature (in Kelvin)

    Returns:
    Entropy Change (Delta S) over Ideal Gas Constant (R)

**S_over_R(T)**

    Parameters:
    kf: Forward Reaction Rate Coefficient
    T: Temperature (in Kelvin)

    Returns:
    Backward coefficient kf / ke where ke is the equilibrium coefficient

---

## Parser module

### ReactionParser Class

**Methods:**

    1.  __init__(supported, hook) - Initialize ReactionRate class
    2.  parse_species(rxns) - Return list of species in reaction data
    3.  check_keys()
    4.  check_structure()
    5.  check_reaction_types()
    6.  check_reaction_consistency()
    7.  check_species_eq_consistency()
    8.  check_species_stoich_consistency()
    9.  check_species_in_db()
    10. check_input_file(rxns)
    11. parse_reaction_rate_params(reaction, convert_units) - Parse reaction coefficient params
    12. parse_stoich_coefs(string, species) - Parse stoichiometric coefficients
    13. get_weight(string, species) - Return total molecular weight for reactants/products of reactions

**\__init__**

    Sets class-wide parameters

**parse_species(rxns)**

    Parameters:
    rxns: XML File

    Returns:
    species: List of species

**check_keys()**

    Parameters:
    None

    Returns:
    ValueError if missing tags in XML file

**check_structure()**

    Parameters:
    None

    Returns:
    ValueError if structure of XML file not self-consistent

**check_reaction_types()**

    Parameters:
    None

    Returns:
    ValueError if reaction type not implemented in parser

**check_reaction_consistency()**

    Parameters:
    None

    Returns:
    ValueError if reaction type tag inconsistent with equation

**check_species_eq_consistency()**

    Parameters:
    None

    Returns:
    ValueError if species in phase array inconsistent with equations

**check_species_stoich_consistency()**

    Parameters:
    None

    Returns:
    None

**check_species_in_db()**

    Parameters:
    None

    Returns:
    ValueError if species in phase array inconsistent with reactants/products

**check_input_file(rxns, check_mass)**

    Parameters:
    rxns: XML File
    check_mass: Boolean

    Returns:
    ValueError if any of check_ methods fail

**parse_reaction_rate_params(reaction, convert_units)**

    Parameters:
    reaction: Input reaction
    convert_units: Boolean

    Returns:
    output: A list of parsed dictionaries for each reaction

**parse_stoich_coefs(string, species)**

    Parameters:
    string:
    species:

    Returns:
    coef_out:

**get_weight(string, species)**

    Parameters:
    string:
    species:

    Returns:
    total_weight:

---

## API Input Format
* Elementary reactions in XML-format
    * Currently, the following input format is accepted:

```xml
<ctml>
    <reactionData id="test_mechanism">
        <!-- reaction 01  -->
        <reaction reversible="yes" type="Elementary" id="reaction01">
            <equation>H + O2 [=] OH + O</equation>
            <rateCoeff>
                <Kooij>
                    <A units="cm3/mol/s">3.52e+16</A>
                    <b>-0.7</b>
                    <E units="kJ/mol">71.4</E>
                </Kooij>
            </rateCoeff>
            <reactants>H:1 O2:1</reactants>
            <products>OH:1 O:1</products>
        </reaction>
    </reactionData>
</ctml>
```

---

## Basic usage and examples

**Example 1:**

```python
# Import numpy and relevant flamespeed modules
import os
import numpy as np
from flamespeed import chemkin
from flamespeed.thermo import thermochem
from flamespeed.test import test_reaction_rate

# Set specie concentration vector
x = np.array([2.0, 1.0, 0.5, 1.0, 1.0])

# Initialize chemkin module with XML file
a = fs.ReactionRate()
a.read_XML('./flamespeed/data/rxns_hw5.xml')
print(a)

# Set temperature and get reaction rates
a.set_temp(750)
f = a.get_reaction_rate(x)
print(f)

--
Output:

Number_of_reactions:3
Number_of_species:5
Number_of_reversible_reactions:0
Reversible:False
Reaction_type:Elementary
Species_list:['H2', 'O2', 'OH', 'HO2', 'H2O']

Reaction rate:

[-3607077.87280406 -5613545.18362079  9220623.05642485  2006467.31081673
 -2006467.31081673]

```

**Example 2:**

```python
# Import numpy and relevant flamespeed modules
from flamespeed import chemkin

# Set specie concentration vector
x = [1.0, 1.0, 1.0, 1.0, 1.0]

# Initialize chemkin module with XML file
a = chemkin.ReactionRate()
a.read_XML('./flamespeed/data/rxns_hw5.xml')

# Set temperature and get reaction rates
a.set_temp(2500)
f = a.get_reaction_rate(x)
print(f)

--
Output:

Reaction rate:

[ -4.51065356e+08  -4.57236287e+08   9.08301644e+08   6.17093098e+06
  -6.17093098e+06]
```

**Example 3:**

```python
# Import numpy and relevant flamespeed modules
from flamespeed import chemkin

# Set specie concentration vector
x = [2.0, 1.0, 0.5, 1.0, 1.0, 1.5, 0.5, 1]

# Initialize chemkin module with XML file
a = chemkin.ReactionRate()
a.read_XML('./flamespeed/data/rxns_reversible_mixed.xml')
print(a)

# Set temperature and get reaction rates
a.set_temp(750)
f = a.get_reaction_rate(x)
print(f)

--
Output:

Number_of_reactions:11
Number_of_species:8
Number_of_reversible_reactions:7
Reversible:Some
Reaction_type:Elementary
Species_list:['H', 'O', 'OH', 'H2', 'H2O', 'O2', 'HO2', 'H2O2']

Reaction rate:

[-1.84263836e+14   3.18111565e+13   2.20832161e+14   4.07078985e+13
   3.44685565e+13  -1.19150183e+13  -7.63606019e+13  -5.52803168e+13]
```

**Example 4: Verify Integrity & Convert Units**

```python
# Import numpy and relevant flamespeed modules
from flamespeed import chemkin

# Set specie concentration vector
x = [0.5, 0, 0, 2, 0, 1]

# Initialize chemkin module with XML file
a = chemkin.ReactionRate()
a.read_XML('./flamespeed/data/rxns_units.xml', verify_integrity=True, convert_units=True)
print(a)

# Set temperature and get reaction rates
a.set_temp(900)
f = a.get_reaction_rate(x)
print(f)

--
Output:

Number_of_reactions:3
Number_of_species:6
Number_of_reversible_reactions:0
Reversible:No
Reaction_type:Elementary
Species_list:['H', 'O', 'OH', 'H2', 'H2O', 'O2']

Reaction rate:
[ -8.08297505e-14   8.08297505e-14   8.08297505e-14   0.00000000e+00
   0.00000000e+00  -8.08297505e-14]
```

**Example 5: (Parsing Hooked Reactions - ThreeBody, TroeThreeBody, Duplicate)**

```python
x = [0.5, 0, 0, 2, 0, 1]

# Import reaction data
a = chemkin.ReactionRate()
print ("[Three Body Parsed]")
a.read_XML('./flamespeed/data/rxn_ThreeBody.xml', verify_integrity=True, convert_units=True)
for idx, item in enumerate(a.k_params_nonelementary):
	print ("Reaction {}".format(str(idx)))
	for rxn in item:
		print (rxn)

print ("\n[Troe Three Body Parsed]")
a = chemkin.ReactionRate()
a.read_XML('./flamespeed/data/rxn_TroeFalloffThreeBody.xml', verify_integrity=True, convert_units=True)
for idx, item in enumerate(a.k_params_nonelementary):
	print ("Reaction {}".format(str(idx)))
	for rxn in item:
		print (rxn)

print ("\n[Duplicate Parsed]")
a = chemkin.ReactionRate()
a.read_XML('./flamespeed/data/rxn_Duplicate.xml', verify_integrity=True, convert_units=True)
for idx, item in enumerate(a.k_params_nonelementary):
	print ("Reaction {}".format(str(idx)))
	for rxn in item:
		print (rxn)

--
Output:

[Three Body Parsed]
Reaction 0
{'Type': 'Kooij', 'A': 38000000000.0, 'b': -2.0, 'E': 0.0, 'name': None}
{'Type': 'efficiencies', 'H2': '2.5', 'H2O': '12.0', 'default': '1.0'}
Reaction 1
{'Type': 'Kooij', 'A': 48000000000.0, 'b': -5.0, 'E': 4.1840000000000002, 'name': None}
{'Type': 'efficiencies', 'H2': '2.5', 'H2O': '12.0', 'default': '1.0'}

[Troe Three Body Parsed]
Reaction 0
{'Type': 'Kooij', 'A': 636600000.0, 'b': -1.72, 'E': 2195.7631999999999, 'name': 'k0'}
{'Type': 'Kooij', 'A': 1475000.0, 'b': 0.6, 'E': 0.0, 'name': None}
{'Type': 'Troe', 'alpha': 0.8, 't1': 1e+30, 't2': 1e+30, 't3': 1e+30}
{'Type': 'efficiencies', 'H2': '2.0', 'H2O': '11.0', 'O2': '0.78', 'default': '1.0'}

[Duplicate Parsed]
Reaction 0
{'Type': 'Arrhenius', 'A': 420000000.0, 'E': 50132.688000000002}
{'Type': 'Arrhenius', 'A': 130000.0, 'E': -6816.9912000000004}
```

---

## New Feature

#### 1. Motivation and feature description

The new features for the Flamespeed library adds flexibility by converting user inputs with relevant warnings if incomplete or non-standard input is provided. An array of validation checks are performed on the input data to ensure the input data is self-consistent, improving the robustness of the package.

**Flexibility**

* Additional usage flexibility is allowed for in several areas:

* Unit conversion:

         a. Parsed reaction coefficient data is converted to metric units before any
           computations for a finite set of common conversions that might be required

* Incomplete Reaction Rate Parameters:

         a. Calling Arrhenius yet providing factor b in the XML file
            results in flamespeed applying Modified Arrhenius

* Three-Body Reactions:

         a. Parser extended to import parameters for three-body reactions
         b. Implemented hooks in code for further future development of three-body reactions

**Robustness and consistency**

* Additional robustness will be achieved following a two-pronged approach; namely checking user input consistency (i.e., in the form of XML files) as well as enforcing internal consistency throughout.

* User Input:

        a. Parsed chemical reaction equations are checked for conservation of mass
        b. Validation performed to ensure required data exists in thermo database for
           input species

* Self-consistent reaction data in XML file, by performing the following integrity checks:

         a. XML file contains all the required tags and is self-consistent
         b. Reaction type tags are consistent with reaction type implied by equations
         c. Species in reaction equations correspond to the "species array" in XML file
         d. Species in product/reactant arrays correspond to "species array" in XML file

The primary goal of the flamespeed chemical kinetics library is for users to use the package for real-life chemical kinetics computations. As such, providing potential users with additional measures to assure both user input consistency and internal library consistency is deemed highly relevant and practical. Added flexibility in terms of reaction rate specification and three-body reaction hooks only add to the relevance of this library to practicioners.

#### 2. Implementation details

Another module (parser.py) that contains most of the features described above, was added to the library. Given the scope of the additional features it made sense to create a separate module, rather than including this in the main chemkin module. Changes were also made to the main module (chemkin.py) to integrate the new features.

An overview of the additional features added to each of the modules is included below. See Parser Module section above for a more detailed specification of the classes and methods included in the module.

**Module descriptions**

*parser.py*

* Contains all of the methods to check / validate self-consistency of the input data
* Includes methods to extract the list of species, reaction rate coefficient parameters and stoichiometric coefficients
* Checks reactions for conservation of mass and performs unit conversions if required

*chemkin.py*

* Contains the main method to read reaction data from the XML file (read_XML)
* Performing validation checks on the input file and converting units have been added as optional parameters to ensure consistency with other projects and previous versions of this project

**Unit Conversion**

A central part to the proposed feature is the possibility to convert a random set of units inherited from an `xml` input file into a set of consistent SI-units. A few points are worth highlighting below.

Where do the units occur:
* Arrhenius prefactor "A"
    * Found in the `xml` input file
* Activation energy "E"
    * Found in the `xml` input file

What SI base units do conversions lead to:
* Meter (and its derivatives such as $m^3$, $m^6$, etc.)
* Joule
* Mol
* Seconds

What units are accounted for?
* A number of basic units are available as standard in the flamespeed package:
    * Length: ft, yd, cm, mm, etc.
    * Energy: cal, kcal, kJ, etc.
    * Time: minutes, etc.
* Users can expand the list of allowed units by simply expanding the `./data/units.csv` file with as many units as desired
    * In `./data/units.csv` users can also easily change the base units (i.e., it need not necessarily be those specified above)

**Conservation of mass**

The read_XML method that reads the reaction data from an XML file has an option to check conservation of mass for each of the reactions. In order to do this, the molecular weight of each specie inlcuded in the system is read from the `thermo` SQL database to compare the total mass of the reactants and products in each reaction. If conservation of mass is vioated for any reaction in the system an appropriate error message is displayed. This option can be turned off if there are valid species included in the reaction data, which is not included in the database.

```python

```


---
Project for the course in Microeconometrics | Summer 2020, M.Sc. Economics, Bonn University | [Ying-Xuan Wu](https://github.com/amanda8412383)

# Replication of Duflo E, Dupas P, Ginn T, Barasa GM, Baraza M, Pouliquen V, et al. (2019)
---

This notebook contains my replication of the results from the following paper:

> Duflo E, Dupas P, Ginn T, Barasa GM, Baraza M, Pouliquen V, et al. (2019) HIV prevention among youth: A randomized controlled trial of voluntary counseling and testing for HIV and male condom distribution in rural Kenya

Table of Contents

1. Introduction

2. Study Design

3. Identification Problems

4. Empirical Strategy

5. Replication of Duflo et al. (2019)

5.1. Data and Primary cleaning

5.2. Tables

            5.2.1. Table 1: Summary statistics at basline

5.2.2. Table 2: Intention to treat analysis

5.2.3. Table 3: Effects of Intervention on other outcomes

5.2.4. Table 4: Heterogenetiy test

6. Discussion

7. Debug: HSV-2 at baseline

7.1 Searching dataset and verifying

7.2 Others

8. References

```python
from auxiliary import *
from IPython.display import display
from IPython.display import Image
pd.options.display.max_rows = None
```

---
# 1. Introduction
---

Duflo et al. (2019) examine the effects of Voluntary Counseling and Testing for HIV (VCT) and increasing access to male condoms compared to standard available HIV prevention services, using biological and behavioral outcomes, among youth in Western Kenya. VCT, serving as the entry to HIV treatment and care, is a test of accessing one’s HIV serostatus, in addition to receiving individualized risk-reduction counseling. VCT is supposed to help individuals reduce risky sexual behaviors and prevent themselves and their partners from HIV and other sexually transmitted infections such as Herpes Simplex Type 2 (HSV-2). Even though some of the previous studies show the reduction of risky sexual behavior in testing-positive individuals, other studies bring about the concern of disinhibition among those testing negative (Sherr et al. 2007).

Through a four-arm, unblinded, individually randomized controlled trial implemented between 2009 and 2012 in four districts of Kenya’s Western Province, including samples of 10,245 youth aged 17 to 24 randomly assigned to receive community-based VCT, 150 male condoms, both VCT and condoms, or neither program, Duflo et al. (2019) examine the effect of these two interventions among the youth. The result suggests there are no statistically significant effects on the risk of HIV, or other behavioral or knowledge outcomes including self-reported pregnancy rates.

**Main variables**

| **Interventions**      | **Main outcomes**       |
|------------------------|-------------------------|
| community-based VCT    | HIV                     |
| 150 male condoms       | HSV-2                   |
| both                   |                         |
| neither                |                         |

In this notebook, I attempt to replicate the results presented in the paper by Duflo et al. (2019) but only acquire similar result and failed to find one of the most important outcome variable.In section 2, the methodology adopted by Duflo et al. (2019) is presented, regarding how sampling, treatment, randomizing and tracking are conducted. In Section 3, possible identification is brought out from 3 different aspects, containing selection bias, measure error from self report, and externality. Section 4 briefly discusses the methodology used by the authors. Section 5 shows my replication of the results in the paper and discussion thereof.  Section 6 offers  discussion on insignificant results. Section 7 reveals my failing attemps on finding HSV-2 testing result at baseline.

---
# 2. Study Design
---

#### **Sample**

The samples are from a previous study of the authors ( Duflo, Dupas, and Krewer 2015) which is clustered randomized controlled trial regarding teacher HIV training program and distribution of free uniform, consisting of 19289 enrolled students in grade 6 of 328 schools in 2003. 55% of them, 10245 individuals are trackable during the first round tracking between March 2009 to July 2010. In total, they represent 85% of aged 17 - 24 in 2009 western Kenya.

According to the criteria, the participants must :
1. Participated in the previous study, which implied at least attended grade 6
2. Residency in the study district
3. Provided informed consent

#### **Randomizing**
Stratification by gender, primary school, matriculation of secondary school in as from July 2007, ever pregnant as of 2007, randomly assigned to four arms, 25% each.

#### **Treatment**
There are standard VCT available to everyone at local health facilities, however, the intervention provided in the trial within community lowering travel time and cost, and social cost of visiting a HIV testing center. For the condom intervention arm, participants were provided 150 male condoms, they could take all or only of these condoms.

#### **Tracking**
Followed up survey is conducted from April 2011 to May 2013, if the respondent did not show up, field officers would track down the person. 25% of those whose acquittances providing contact information and 10% of those who can’t be contacted at all are randomly selected for further intensive tracking. Intensive tracking weight is included in the estimation.

---
# 3. Identification Problems
---
Considering Duflo et al. (2019) do not obtain any significant result, it might be more suitable to discuss possible identification problems in this section instead of identification. I am not trying to suggest obtaining significant result means problem-free, it just doesn’t seem meaningful to discuss how their identifications work in this case.

#### **casaul graph**
For a randomized control trial, it is expected to block all the back door part of unobservables and other controlled variable and obtain a clean casal effect. However, in this paper it's either fail to block backdoor path successfully or the treatments have no effect to it. I'll discuss some of the possible non-blocked backdoor part at later part of this section. In discussion, the possible correlations suggest by authors are listed.

```python
Image(filename='causal graph.jpg')
```

#### **Selection bias**
As a randomized control trial, this estimation is supposed to be free from selection bias. Nevertheless, in study design, Duflo et al. (2019) mention that the sample is based on its previous study which restricts the participants of this study to those who have attended at least 6 grade and accepting HIV related knowledges. Considering the following model from Greene (2006):
\begin{equation}
yi = xi' \beta + ei\\
zi^* = wi' \gamma + ui\\
zi = 1(zi^* > c)
\end{equation}
Where $yi$ is our outcome variable. $xi$ is the treatment group. $zi$ is attending grade 6 or not. wi is are exogenous factors decided to attend 6 grade or not. $ei, ui$ are error terms.
Then we can rewrite the function into:
\begin{equation}
E(yi|wi, ui) = xi' \beta + E(ei|wi, ui)\\
 = xi' \beta + E(ei|ui)
\end{equation}
For $E(ei|ui)$ not equals to zero, we might obtain a biased estimator. And such an example is easily thinking of, for example, children from poverty background may be more likely to drop out, and higher chance to become sex worker, can't afford to buy condoms, missing sex education in class are all factors that could increase their chance of getting STI.

In the latter discussion, the authors do not bring about this issue, but do admit lower external validity, while stressing as HIV prevention scaled up, increasing population would have access to prevention information.

#### **Measure error from self report**
Because of the behavioral outcomes are acquired through surveys, one common problem from self-reported is the imprecision of the data, possibly resulting from causes such as forgetfulness or deception.
considering models from Hansen (2020):
\begin{equation}
yi = \beta xi^* + ui\\
\textrm{where} \quad E[ui|xi^*] = 0\\
xi = xi^* + vi
\end{equation}
Where $yi$ is one of our outcome variables, $xi$ is reported behavior, $ui$ is the error term, and vi are deviation originated from forgetfulness or deception.
rewritten the function as:
\begin{equation}
yi = \beta xi^* + ui\\
\textrm{where} \quad ei = -\beta vi + ui\\
\end{equation}
Then we can get the covariance of our treatment and residual is the variance of this reporting mistake. As we need $xi$ and residual to be independent.

But I would say measurement error has limited influence in this case. Only a few behavior problems serving as independent variables, for example ever pregnant and school enrollment in 2007 and is theoretically possible to do fact checks on these two variables. Most of the behavioral outcomes are serving as dependent variables in the logistic regression stated at section 4, in which case affect our estimation much lesser.

#### **Externalty**
One intriguing question to ask is whether these treatments induce externality, Miguel, Edward, and Kremer (2004) finds out in a randomized trial on 75 Kenya primary schools that medical treatment for intestinal helminths in the treatment group also reducing the transmission within the control group, even their randomized trial is taking place across schools. Using male condoms would undoubtedly reduce the possibility of infecting sex partners and thus contaminate the obtaining result. If the subject having any behavioral change after receiving VCT, it’ll also affect their sexual partners. Such an externality exists hinder us to detach treatment effects from the treatment group. I haven’t found any paper having empirical evidence on how would externality affecting HIV research, but some of the papers point this out and try to discuss the possible influence, such as Canning D. (2006).

---
**NOTE**: the  model used in this paper is logistic regression while I use linear notations in section 3 for simplicity. For nonlinear model, endogeneity and externality are still problems that affect large sample property of estimators which have an in-depth discussion in _A Logit Model With Endogenous Explanatory Variables and Network Externalities_ ( de Grange et al. 2015)

---
# 4. Empirical Strategy
---
the following listed methods are statistic analysis used In Duflo et al. (2019).

#### **Descriptive statistic**
For both baseline and phase 2, descriptive data is shown. Estimation in stage 2 takes into account of weighted follow-up rate. The share of the total sample and comparison among males and females is shown and a second analysis to test for heterogeneity in the result by gender, childbearing experience at baseline, and baseline belief of HIV infection likelihood.

#### **Incidence rate**
HSV-2 incidence was calculated by dividing respondents who were negative at baseline to new HSV-2 cases in each treatment arm by the total person-years of exposure. If the person remained negative, person-years of exposure is calculated as the total time from the baseline test to the follow-up. For the newly infected cases, it’s calculated as half the time between the baseline test and the positive test.

#### **Weighted logistic regression**
For estimating the effect of interventions on outcomes, the following logistic regression weighted by survey tracking strategy is run to compare outcomes in each treatment arm to the control, and the adjusted odds ratio and confidence interval are reported. Regressors are listed as follow:

|**regressors**          |
|------------------------|
| age group              |
| months between 2 surveys             |
| gender                               |
| secondary school enrollment in 2007  |
| ever pregnant by 2007  |
| treatment arm          |

---
# 5. Replication of Duflo et al. (2019)
---

## 5.1. Data and Primary cleaning

Duflo et al. (2019) use a data set with 2374 variables and 19293 participants. The following list concluding main sources of these variable. I prune the dataset because of even lft can't afford to upload original data set.

- answers, remarks of baseline questionnaire
- answers, remarks of phase 2 questionnaire
- school properties such as location, average scores of all students in KCPE
- testing results, both HSV-2 and HIV require multiple time of testing
- poorly naming variable that might be created for analysis

Even though the problem set has 19293 respondents, the number of total participants in this project is supposed to yield 7565, the rest are participants of the authors’ previous study. An important question would be how the authors filtering the data and ruling out problematic entries. Since neither the rules of excluding an entry nor how did they clean the data is mentioned in the essay. Besides, because of the majority data are from surveys, 92 variables are naming with "comments" describing the situation in the data collecting process. For example, in Log_comment there are entries describing as "mentally ill" or "duplicate" even though they are surveyed.  After trying all the combinations that seems reasonable to me, I filtered the data by
1. having assigned to a treatment group
2. labeled as surveyed
3. labeled as tracked
4. discarded all the entries that have LOG_comments
Through this, I gaining an approximate participation number. Unfortunately, this means all my statistics would be different in various degrees with the paper.

```python
ind = df_filter.group.value_counts()
total = ind.sum()
print(ind)
print(f'total participant {total}')
```

    Control           1889
    VCT only          1866
    Condom only       1855
    Condom and VCT    1848
    Name: group, dtype: int64
    total participant 7458

##  5.2. Tables

### 5.2.1. Table 1: Summary statistics at basline

Table 1 shows baseline characteristics of man and woman across 4 trial arm. This table only includes individuals that have been surveyed at follow up. Because of lacking the original code, these variables are recreating myself. The below list describes the method I choose. This is the only table I forgo recreate percentage. As previously mentioned, the baseline HSV-2 result is nowhere to find, thus, second phase HSV-2 is used here.

| **Variables**          | **Method**              |
|------------------------|-------------------------|
| Number of individuals  | counting unique pupilid in each group   |
| Age                    | create dummy through variable "age2009" |
| Total year of schooling| create dummy through answer to "Q_b1_13_school_years"|
| HSV-2 positive         | using HSV-2 result of phase 2 instead   |
| Currently married      | people who have  "an_spouse_age"        |
| Ever or partner ever pregnant|people who have "evpreg07v2" (womwn only) or "Track_children_number" > 0 (both gender)|
| Ever had sex           | using "an_everhadsex"                   |
| Last sex used condom   | using answer of "Q_b4_127_last_sex_use_condom" |
| Ever had multiple partners| using "an_multiplepartners"          |
| Ever tested for HIV    | using "an_everHIVtested"                |
| Believed current HIV infection| using answer to "Q_b3_99"        |
| Believed future HIV infection | using answer to "Q_b3_100"       |
| Named 3 prevention      | from Dummies "an_Q_b3_80_how_prevent_hiv_1" to 19 has at least 3 of them being 1                         |
| Answered 3 questions    |"an_Q_b3_83", "an_Q_b3_84" negative & "an_Q_b3_88" being positive |
| Showed positive attitude|"an_Q_b3_112_agree_with_statement" is 1 & for question number 109 to 111 is 0|

3 HIV knowledge question is defined as follow by the author:
1. Can HIV be transmitted to a baby in the womb? (Q_b3_83)
2. Can HIV be transmitted to a baby during breastfeeding? (Q_b3_84)
3. Can HIV spread through mosquito bites? (Q_b3_88)

positive attitude is defined as follow by the author:
1. Agreed that people with HIV/AIDS should be treated the same as people without HIV/AIDS (an_Q_b3_112_agree_with_statement)
2. Disagreed that prostitutes or promiscuous men are responsible for spreading HIV("(an_Q_b3_110_agree_with_statement, an_Q_b3_111_agree_with_statement)
3. Disagreed that HIV was punishment for bad behavior (an_Q_b3_109_agree_with_statement)

```python
#variables in table 1
varlist = ['Number of individuals', 'Age at baseline_<19', 'Age at baseline_19-20', 'Age at baseline_21-22', 'Age at baseline_>22',
          'Not enrolled in school',
          'Total year of schooling_<10', 'Total year of schooling_10-11', 'Total year of schooling_12-13', 'Total year of schooling_>13',
          'HSV-2 positive', 'Currently married', 'Ever or partner ever pregnant', 'Ever had sex', 'Last sex used condom', 'Ever had multiple partners', 'Ever tested for HIV',
          'Believed current HIV infection', 'Believed future HIV infection',
          'Named 3 prevention', 'Answered 3 questions', 'Showed positive attitude']
table1(df_merge, varlist)
```

      all
      woman
      man

      group
      Condom and VCT
      Condom only
      Control
      VCT only
      Condom and VCT
      Condom only
      Control
      VCT only
      Condom and VCT
      Condom only
      Control
      VCT only

      Number of individuals
      1848
      1855
      1889
      1866
      823
      814
      864
      838
      1025
      1041
      1025
      1028

      Age at baseline_<19
      484
      515
      490
      497
      249
      282
      294
      295
      235
      233
      196
      202

      Age at baseline_19-20
      933
      915
      957
      920
      449
      424
      446
      410
      484
      491
      511
      510

      Age at baseline_21-22
      370
      376
      383
      389
      110
      97
      109
      113
      260
      279
      274
      276

      Age at baseline_>22
      61
      49
      59
      59
      15
      11
      15
      20
      46
      38
      44
      39

      Not enrolled in school
      927
      921
      954
      927
      462
      423
      452
      444
      465
      498
      502
      483

      Total year of schooling_<10
      501
      455
      491
      499
      257
      230
      281
      266
      244
      225
      210
      233

      Total year of schooling_10-11
      409
      483
      477
      457
      202
      209
      203
      210
      207
      274
      274
      247

      Total year of schooling_12-13
      810
      805
      808
      786
      333
      338
      354
      322
      477
      467
      454
      464

      Total year of schooling_>13
      95
      87
      90
      97
      18
      25
      16
      24
      77
      62
      74
      73

      HSV-2 positive
      164
      141
      146
      146
      85
      76
      81
      78
      79
      65
      65
      68

      Currently married
      367
      369
      387
      389
      223
      217
      241
      239
      144
      152
      146
      150

      Ever or partner ever pregnant
      397
      363
      385
      395
      292
      271
      290
      291
      105
      92
      95
      104

      Ever had sex
      1239
      1217
      1256
      1269
      508
      502
      526
      547
      731
      715
      730
      722

      Last sex used condom
      503
      468
      519
      505
      156
      146
      170
      164
      347
      322
      349
      341

      Ever had multiple partners
      578
      545
      579
      571
      184
      144
      183
      176
      394
      401
      396
      395

      Ever tested for HIV
      781
      819
      850
      803
      421
      433
      455
      451
      360
      386
      395
      352

      Believed current HIV infection
      429
      439
      401
      452
      174
      166
      165
      172
      255
      273
      236
      280

      Believed future HIV infection
      602
      618
      608
      648
      279
      261
      285
      286
      323
      357
      323
      362

      Named 3 prevention
      554
      561
      548
      569
      234
      232
      243
      247
      320
      329
      305
      322

      Answered 3 questions
      634
      617
      640
      639
      302
      285
      322
      303
      332
      332
      318
      336

      Showed positive attitude
      334
      352
      330
      312
      114
      152
      140
      108
      220
      200
      190
      204

### 5.2.2. Table 2: Intention to treat analysis
This table shows HSV-2 and HIV outcomes across males and females. None of the intervention turns out to reduce the infection rate of any of these diseases significantly. Either adjusted odd ratio or weighted prevalence appears similar across interventions.

For recreation, query & key was passed into the function to create panels for all and both gender. And also variables are passed in as a pair of (consonant, denominator) to calculate weighted percent.due to these variables are all recorded in different forms and hidden in the variable sea. Hence it requires searching it out, transforming, and passing it in manually. The replication does not contain HSV-2 at baseline, hence the incidence rate is also not in this table. Although HIV cases can be found in both stages, the infection case is too low to have a valid estimation.

| **Variables**          | **Method**              |
|------------------------|-------------------------|
| HSV-2                  | using "hsv2_positive"   |
| HIV                    | using answer of "p2_c2_233_hiv_result" |

```python
query = ['', 'sex == "2 Female"', 'sex == "1 Male"']
keys=['all', 'female', 'male']
varlist2 = [('HSV-2 positive', 'hsv2_accept'), ('HIV', 'p2_c2_233_hiv_result')]

Table(df_merge, query, keys, varlist2, option = 'T2')
```

      group
      Condom and VCT
      Condom only
      Control
      VCT only

      all
      HSV-2 positive
      Weighted cases
      191
      162
      164
      179

      N = 7440
      1840
      1854
      1885
      1861

      Weighted%
      10.38
      8.74
      8.7
      9.62

      Addjusted odds ratio
      1.14
      0.95
      NaN
      0.96

      95% CI
      (0.94 - 1.39)
      (0.77 - 1.16)
      None
      (0.79 - 1.18)

      HIV
      Weighted cases
      20
      11
      14
      11

      N = 5676
      1420
      1384
      1396
      1476

      Weighted%
      1.41
      0.79
      1
      0.75

      Addjusted odds ratio
      1.34
      1.09
      NaN
      0.58

      95% CI
      (0.70 - 2.59)
      (0.55 - 2.18)
      None
      (0.26 - 1.32)

      female
      HSV-2 positive
      Weighted cases
      91
      88
      96
      96

      N = 3331
      818
      814
      862
      837

      Weighted%
      11.12
      10.81
      11.14
      11.47

      Addjusted odds ratio
      1.07
      0.99
      NaN
      0.95

      95% CI
      (0.81 - 1.40)
      (0.75 - 1.32)
      None
      (0.72 - 1.26)

      HIV
      Weighted cases
      14
      6
      6
      11

      N = 2681
      669
      638
      686
      688

      Weighted%
      2.09
      0.94
      0.87
      1.6

      Addjusted odds ratio
      1.6
      0.8
      NaN
      0.94

      95% CI
      (nan - nan)
      (0.33 - 1.98)
      None
      (0.40 - 2.22)

      male
      HSV-2 positive
      Weighted cases
      100
      74
      68
      83

      N = 4109
      1022
      1040
      1023
      1024

      Weighted%
      9.78
      7.12
      6.65
      8.11

      Addjusted odds ratio
      1.23
      0.91
      NaN
      0.97

      95% CI
      (0.93 - 1.62)
      (0.68 - 1.22)
      None
      (0.72 - 1.30)

      HIV
      Weighted cases
      6
      5
      8
      0

      N = 2995
      751
      746
      710
      788

      Weighted%
      0.8
      0.67
      1.13
      0

      Addjusted odds ratio
      0.97
      1.89
      NaN
      0

      95% CI
      (0.27 - 3.56)
      (0.61 - 5.84)
      None
      (0.00 - inf)

 ### 5.2.3. Table 3: Effects of Intervention on other outcomes
In this table, some other behavioral outcome at phase 2 is analyzed across 4 treatment groups and by gender. For the treatment groups receiving condoms, "Ever received free condoms" and "Ever used the free condoms" are statistically significant comparing to the control or VCT treatment group. Similarly in the outcome "Ever had VCT", groups that have receive VCT are more significant comparing to the rest. While other variables, including childbearing, remains statistically insignificant.

| **Variables**               | **Method**              |
|-----------------------------|-------------------------|
| Ever received free condoms  | answer yes to "p2_b8_200_condomsfree_ever"    |
| Ever used the free condems  | answer 1 or 2 to "p2_b8_202_condfree_use"     |
| Ever sold/gave condoms      | answer 3 or 4  to "p2_b8_202_condfree_use"    |
| Ever had VCT                | answer yes to "p2_b9_204_evervct" |
| VCT more than once          | answer "p2_b9_205_timesvct" > 1   |
| VCT more than twice         | answer "p2_b9_205_timesvct" > 2   |
| Currently married p2        | answer currently married to "p2_b5_115_married"|
| Sex in last 6 months        | using "p2_b5_118_sexpartners_6mos" > 0 |
| Partner number last 6 months| using answer to "p2_b5_118_sexpartners_6mos"   |
| Partner number lifetime     | using answer of "p2_b5_119_sexpartners_life"   |
| Ever used condoms           | answer yes to "p2_b8_182_everusedcondom"       |
| Used condoms last time      | answer yes to "p2_b8_186_condom_lasttime"      |
| Unprotected sex non-monogamous| "p2_b5_119_sexpartners_life" > 1 & answer never to all of p2_b5_141 (using condoms with 3 most recent partner respectively)           |
| Self reported STI           | answer yes to "p2_b10_214_sti"       |
| Ever or partner ever pregnant p2| answer to "p2_b7_148_pregnancies_number" > 0|
| Named 3 prevention p2       | having more at least 3 answer in "p2_b4_72_protecthiv"|
| Answered 3 questions p2     | answer 1 to "p2_b4_74_hivinwomb", "p2_b4_75_hivbreastfeed" 2 to "p2_b4_76_hivmosquitoes" |
| Showed positive attitude p2 | answer 4 or 5 to "p2_b4_111_hivpunishment", "p2_b4_112_hivprostitutes", "p2_b4_113_hivpromiscuousmen" and 1 or 2 to "p2_b4_114_hivtreatedsame"|
| Child number p2             | using "p2_b7_148_pregnancies_number" |

```python
varlist3 = [
            ("Ever received free condoms", "everfreecondoms_base"),
            ("Ever used the free condems", "everfreecondoms_base"),
            ('Ever sold/gave condoms', 'Ever received free condoms'),
            ('Ever had VCT', 'evervct_base'),
            ('VCT more than once', 'evervct_base'),
            ('VCT more than twice', 'evervct_base'),
            ('Currently married p2', 'currentmarried_base'),
            ('Sex in last 6 months', 'sexpartners6mon_base'),
            ('Partner number last 6 months', None),
            ('Partner number lifetime', None),
            ('Ever used condoms', 'everusedcondom_base'),
            ('Used condoms last time', 'lasttimecondom_base'),
            ('Unprotected sex non-monogamous', 'polynocondom_base'),
            ('Self reported STI', 'sti_base'),
            ('Ever or partner ever pregnant p2', 'pregnant_base'),
            ('Named 3 prevention p2', 'named3prev_base'),
            ('Answered 3 questions p2', 'ans3q_base'),
            ('Showed positive attitude p2', 'posplhiv_base'),
            ('Child number', None)]

Table(df_t3, query, keys, varlist3)
```

      group
      Condom and VCT
      Condom only
      Control
      VCT only

      all
      Ever received free condoms
      Weighted cases
      1354
      1274
      857
      900

      Weighted base
      1931
      1776
      1740
      1814

      Weighted%
      70.12
      71.73
      49.25
      49.61

      Addjusted odds ratio
      1.56
      1.83
      NaN
      0.6

      95% CI
      (1.39 - 1.75)
      (1.63 - 2.06)
      None
      (0.53 - 0.67)

      Ever used the free condems
      Weighted cases
      773
      673
      488
      485

      Weighted base
      1931
      1776
      1740
      1814

      Weighted%
      40.03
      37.89
      28.05
      26.74

      Addjusted odds ratio
      1.37
      1.47
      NaN
      0.7

      95% CI
      (1.20 - 1.56)
      (1.29 - 1.67)
      None
      (0.61 - 0.81)

      Ever sold/gave condoms
      Weighted cases
      958
      804
      400
      425

      Weighted base
      1354
      1274
      857
      900

      Weighted%
      70.75
      63.11
      46.67
      47.22

      Addjusted odds ratio
      1.97
      1.95
      NaN
      0.47

      95% CI
      (1.74 - 2.23)
      (1.72 - 2.20)
      None
      (0.41 - 0.55)

      Ever had VCT
      Weighted cases
      1751
      1337
      1367
      1610

      Weighted base
      1811
      1650
      1637
      1711

      Weighted%
      96.69
      81.03
      83.51
      94.1

      Addjusted odds ratio
      1.39
      0.76
      NaN
      1.35

      95% CI
      (1.23 - 1.57)
      (0.67 - 0.85)
      None
      (1.20 - 1.53)

      VCT more than once
      Weighted cases
      1437
      1049
      1085
      1320

      Weighted base
      1811
      1650
      1637
      1711

      Weighted%
      79.35
      63.58
      66.28
      77.15

      Addjusted odds ratio
      1.34
      0.77
      NaN
      1.29

      95% CI
      (1.19 - 1.50)
      (0.69 - 0.87)
      None
      (1.15 - 1.45)

      VCT more than twice
      Weighted cases
      1006
      725
      742
      922

      Weighted base
      1811
      1650
      1637
      1711

      Weighted%
      55.55
      43.94
      45.33
      53.89

      Addjusted odds ratio
      1.26
      0.8
      NaN
      1.3

      95% CI
      (1.12 - 1.42)
      (0.71 - 0.90)
      None
      (1.16 - 1.47)

      Currently married p2
      Weighted cases
      848
      757
      843
      816

      Weighted base
      2411
      2231
      2261
      2306

      Weighted%
      35.17
      33.93
      37.28
      35.39

      Addjusted odds ratio
      0.88
      1.03
      NaN
      1.05

      95% CI
      (0.76 - 1.01)
      (0.89 - 1.18)
      None
      (0.92 - 1.21)

      Sex in last 6 months
      Weighted cases
      1577
      1448
      1538
      1564

      Weighted base
      2406
      2232
      2261
      2304

      Weighted%
      65.54
      64.87
      68.02
      67.88

      Addjusted odds ratio
      0.87
      0.96
      NaN
      1.19

      95% CI
      (0.77 - 0.98)
      (0.85 - 1.09)
      None
      (1.05 - 1.35)

      Partner number last 6 months
      Weighted cases
      0.86
      0.86
      0.9
      0.89

      Addjusted odds ratio
      0.87
      0.96
      NaN
      1.19

      95% CI
      (0.77 - 0.98)
      (0.85 - 1.09)
      None
      (1.05 - 1.35)

      Partner number lifetime
      Weighted cases
      3.57
      2.99
      3.13
      3.06

      Addjusted odds ratio
      0.87
      1.16
      NaN
      1.09

      95% CI
      (0.74 - 1.02)
      (0.99 - 1.37)
      None
      (0.92 - 1.27)

      Ever used condoms
      Weighted cases
      1578
      1459
      1432
      1460

      Weighted base
      2067
      1917
      1934
      1967

      Weighted%
      76.34
      76.11
      74.04
      74.22

      Addjusted odds ratio
      1.02
      1.07
      NaN
      0.97

      95% CI
      (0.91 - 1.14)
      (0.96 - 1.20)
      None
      (0.87 - 1.09)

      Used condoms last time
      Weighted cases
      819
      784
      794
      782

      Weighted base
      1587
      1476
      1444
      1483

      Weighted%
      51.61
      53.12
      54.99
      52.73

      Addjusted odds ratio
      0.96
      1.04
      NaN
      1.01

      95% CI
      (0.85 - 1.08)
      (0.92 - 1.17)
      None
      (0.90 - 1.13)

      Unprotected sex non-monogamous
      Weighted cases
      686
      572
      646
      590

      Weighted base
      2402
      2231
      2261
      2303

      Weighted%
      28.56
      25.64
      28.57
      25.62

      Addjusted odds ratio
      1.05
      0.96
      NaN
      0.99

      95% CI
      (0.93 - 1.19)
      (0.84 - 1.08)
      None
      (0.87 - 1.12)

      Self reported STI
      Weighted cases
      59
      30
      45
      49

      Weighted base
      2406
      2230
      2260
      2305

      Weighted%
      2.45
      1.35
      1.99
      2.13

      Addjusted odds ratio
      0.95
      0.78
      NaN
      1.18

      95% CI
      (0.64 - 1.40)
      (0.51 - 1.17)
      None
      (0.81 - 1.71)

      Ever or partner ever pregnant p2
      Weighted cases
      1100
      999
      1028
      1072

      Weighted base
      2404
      2231
      2259
      2302

      Weighted%
      45.76
      44.78
      45.51
      46.57

      Addjusted odds ratio
      0.95
      1.13
      NaN
      1.06

      95% CI
      (0.82 - 1.09)
      (0.98 - 1.30)
      None
      (0.92 - 1.22)

      Named 3 prevention p2
      Weighted cases
      1016
      953
      975
      913

      Weighted base
      2412
      2232
      2261
      2308

      Weighted%
      42.12
      42.7
      43.12
      39.56

      Addjusted odds ratio
      0.94
      1.04
      NaN
      1

      95% CI
      (0.84 - 1.05)
      (0.93 - 1.16)
      None
      (0.90 - 1.12)

      Answered 3 questions p2
      Weighted cases
      759
      711
      691
      652

      Weighted base
      2411
      2230
      2247
      2307

      Weighted%
      31.48
      31.88
      30.75
      28.26

      Addjusted odds ratio
      0.95
      1.06
      NaN
      0.92

      95% CI
      (0.85 - 1.07)
      (0.95 - 1.20)
      None
      (0.82 - 1.04)

      Showed positive attitude p2
      Weighted cases
      433
      378
      389
      470

      Weighted base
      2411
      2230
      2250
      2296

      Weighted%
      17.96
      16.95
      17.29
      20.47

      Addjusted odds ratio
      1
      1
      NaN
      1.04

      95% CI
      (0.87 - 1.16)
      (0.87 - 1.16)
      None
      (0.90 - 1.19)

      Child number
      Weighted cases
      0.81
      0.75
      0.8
      0.85

      Addjusted odds ratio
      0.95
      1.13
      NaN
      1.06

      95% CI
      (0.82 - 1.09)
      (0.98 - 1.30)
      None
      (0.92 - 1.22)

      female
      Ever received free condoms
      Weighted cases
      432
      436
      224
      297

      Weighted base
      845
      786
      779
      849

      Weighted%
      51.12
      55.47
      28.75
      34.98

      Addjusted odds ratio
      1.57
      1.84
      NaN
      0.63

      95% CI
      (1.32 - 1.86)
      (1.55 - 2.19)
      None
      (0.53 - 0.76)

      Ever used the free condems
      Weighted cases
      145
      134
      63
      100

      Weighted base
      845
      786
      779
      849

      Weighted%
      17.16
      17.05
      8.09
      11.78

      Addjusted odds ratio
      1.43
      1.51
      NaN
      0.76

      95% CI
      (1.11 - 1.84)
      (1.17 - 1.96)
      None
      (0.57 - 1.01)

      Ever sold/gave condoms
      Weighted cases
      251
      229
      72
      94

      Weighted base
      432
      436
      224
      297

      Weighted%
      58.1
      52.52
      32.14
      31.65

      Addjusted odds ratio
      1.99
      2.06
      NaN
      0.43

      95% CI
      (1.61 - 2.47)
      (1.66 - 2.55)
      None
      (0.33 - 0.57)

      Ever had VCT
      Weighted cases
      731
      587
      625
      749

      Weighted base
      743
      680
      697
      764

      Weighted%
      98.38
      86.32
      89.67
      98.04

      Addjusted odds ratio
      1.15
      0.83
      NaN
      1.36

      95% CI
      (0.95 - 1.39)
      (0.69 - 1.01)
      None
      (1.13 - 1.65)

      VCT more than once
      Weighted cases
      634
      494
      508
      670

      Weighted base
      743
      680
      697
      764

      Weighted%
      85.33
      72.65
      72.88
      87.7

      Addjusted odds ratio
      1.18
      0.83
      NaN
      1.4

      95% CI
      (0.98 - 1.42)
      (0.69 - 0.99)
      None
      (1.17 - 1.68)

      VCT more than twice
      Weighted cases
      468
      359
      370
      490

      Weighted base
      743
      680
      697
      764

      Weighted%
      62.99
      52.79
      53.08
      64.14

      Addjusted odds ratio
      1.11
      0.86
      NaN
      1.49

      95% CI
      (0.92 - 1.33)
      (0.72 - 1.04)
      None
      (1.24 - 1.78)

      Currently married p2
      Weighted cases
      480
      423
      488
      430

      Weighted base
      1060
      984
      1038
      1066

      Weighted%
      45.28
      42.99
      47.01
      40.34

      Addjusted odds ratio
      0.88
      1.11
      NaN
      0.99

      95% CI
      (0.72 - 1.08)
      (0.91 - 1.37)
      None
      (0.81 - 1.22)

      Sex in last 6 months
      Weighted cases
      703
      660
      694
      702

      Weighted base
      1060
      984
      1038
      1064

      Weighted%
      66.32
      67.07
      66.86
      65.98

      Addjusted odds ratio
      0.92
      1.04
      NaN
      1.16

      95% CI
      (0.76 - 1.12)
      (0.85 - 1.26)
      None
      (0.96 - 1.41)

      Partner number last 6 months
      Weighted cases
      0.71
      0.72
      0.69
      0.7

      Addjusted odds ratio
      0.92
      1.04
      NaN
      1.16

      95% CI
      (0.76 - 1.12)
      (0.85 - 1.26)
      None
      (0.96 - 1.41)

      Partner number lifetime
      Weighted cases
      1.65
      1.49
      1.49
      1.53

      Addjusted odds ratio
      0.88
      1.25
      NaN
      1.23

      95% CI
      (0.70 - 1.11)
      (0.98 - 1.58)
      None
      (0.97 - 1.56)

      Ever used condoms
      Weighted cases
      616
      568
      545
      598

      Weighted base
      878
      826
      846
      878

      Weighted%
      70.16
      68.77
      64.42
      68.11

      Addjusted odds ratio
      1.08
      1.02
      NaN
      1.06

      95% CI
      (0.92 - 1.27)
      (0.86 - 1.20)
      None
      (0.90 - 1.25)

      Used condoms last time
      Weighted cases
      216
      235
      229
      292

      Weighted base
      623
      579
      555
      615

      Weighted%
      34.67
      40.59
      41.26
      47.48

      Addjusted odds ratio
      0.94
      0.93
      NaN
      1.3

      95% CI
      (0.78 - 1.15)
      (0.77 - 1.13)
      None
      (1.07 - 1.56)

      Unprotected sex non-monogamous
      Weighted cases
      272
      215
      244
      201

      Weighted base
      1056
      983
      1038
      1063

      Weighted%
      25.76
      21.87
      23.51
      18.91

      Addjusted odds ratio
      1.18
      0.98
      NaN
      0.94

      95% CI
      (0.96 - 1.44)
      (0.79 - 1.20)
      None
      (0.77 - 1.16)

      Self reported STI
      Weighted cases
      20
      14
      24
      31

      Weighted base
      1060
      983
      1037
      1065

      Weighted%
      1.89
      1.42
      2.31
      2.91

      Addjusted odds ratio
      0.88
      0.71
      NaN
      1.36

      95% CI
      (0.50 - 1.54)
      (0.39 - 1.31)
      None
      (0.82 - 2.28)

      Ever or partner ever pregnant p2
      Weighted cases
      671
      590
      616
      607

      Weighted base
      1060
      983
      1037
      1065

      Weighted%
      63.3
      60.02
      59.4
      57

      Addjusted odds ratio
      0.98
      1.24
      NaN
      1.02

      95% CI
      (0.79 - 1.21)
      (1.00 - 1.53)
      None
      (0.83 - 1.27)

      Named 3 prevention p2
      Weighted cases
      395
      358
      388
      384

      Weighted base
      1060
      984
      1038
      1066

      Weighted%
      37.26
      36.38
      37.38
      36.02

      Addjusted odds ratio
      1.04
      1.02
      NaN
      0.98

      95% CI
      (0.87 - 1.24)
      (0.86 - 1.22)
      None
      (0.82 - 1.16)

      Answered 3 questions p2
      Weighted cases
      344
      323
      329
      311

      Weighted base
      1060
      983
      1024
      1066

      Weighted%
      32.45
      32.86
      32.13
      29.17

      Addjusted odds ratio
      0.91
      1.09
      NaN
      0.91

      95% CI
      (0.76 - 1.08)
      (0.92 - 1.30)
      None
      (0.76 - 1.08)

      Showed positive attitude p2
      Weighted cases
      171
      166
      156
      241

      Weighted base
      1060
      983
      1027
      1065

      Weighted%
      16.13
      16.89
      15.19
      22.63

      Addjusted odds ratio
      1.06
      1.03
      NaN
      1.04

      95% CI
      (0.85 - 1.32)
      (0.83 - 1.28)
      None
      (0.84 - 1.30)

      Child number
      Weighted cases
      1.17
      1.08
      1.11
      1.12

      Addjusted odds ratio
      0.98
      1.24
      NaN
      1.02

      95% CI
      (0.79 - 1.21)
      (1.00 - 1.53)
      None
      (0.83 - 1.27)

      male
      Ever received free condoms
      Weighted cases
      922
      838
      633
      603

      Weighted base
      1086
      990
      961
      965

      Weighted%
      84.9
      84.65
      65.87
      62.49

      Addjusted odds ratio
      1.56
      1.85
      NaN
      0.57

      95% CI
      (1.33 - 1.82)
      (1.58 - 2.16)
      None
      (0.49 - 0.66)

      Ever used the free condems
      Weighted cases
      628
      539
      425
      385

      Weighted base
      1086
      990
      961
      965

      Weighted%
      57.83
      54.44
      44.22
      39.9

      Addjusted odds ratio
      1.35
      1.46
      NaN
      0.69

      95% CI
      (1.16 - 1.57)
      (1.26 - 1.70)
      None
      (0.59 - 0.81)

      Ever sold/gave condoms
      Weighted cases
      707
      575
      328
      331

      Weighted base
      922
      838
      633
      603

      Weighted%
      76.68
      68.62
      51.82
      54.89

      Addjusted odds ratio
      1.96
      1.91
      NaN
      0.49

      95% CI
      (1.68 - 2.28)
      (1.64 - 2.22)
      None
      (0.41 - 0.58)

      Ever had VCT
      Weighted cases
      1020
      750
      742
      861

      Weighted base
      1068
      970
      940
      947

      Weighted%
      95.51
      77.32
      78.94
      90.92

      Addjusted odds ratio
      1.6
      0.71
      NaN
      1.34

      95% CI
      (1.35 - 1.88)
      (0.61 - 0.83)
      None
      (1.14 - 1.58)

      VCT more than once
      Weighted cases
      803
      555
      577
      650

      Weighted base
      1068
      970
      940
      947

      Weighted%
      75.19
      57.22
      61.38
      68.64

      Addjusted odds ratio
      1.46
      0.73
      NaN
      1.22

      95% CI
      (1.25 - 1.70)
      (0.63 - 0.85)
      None
      (1.05 - 1.42)

      VCT more than twice
      Weighted cases
      538
      366
      372
      432

      Weighted base
      1068
      970
      940
      947

      Weighted%
      50.37
      37.73
      39.57
      45.62

      Addjusted odds ratio
      1.4
      0.75
      NaN
      1.17

      95% CI
      (1.19 - 1.64)
      (0.63 - 0.89)
      None
      (1.00 - 1.38)

      Currently married p2
      Weighted cases
      368
      334
      355
      386

      Weighted base
      1351
      1247
      1223
      1240

      Weighted%
      27.24
      26.78
      29.03
      31.13

      Addjusted odds ratio
      0.88
      0.96
      NaN
      1.12

      95% CI
      (0.72 - 1.07)
      (0.79 - 1.16)
      None
      (0.92 - 1.36)

      Sex in last 6 months
      Weighted cases
      874
      788
      844
      862

      Weighted base
      1346
      1248
      1223
      1240

      Weighted%
      64.93
      63.14
      69.01
      69.52

      Addjusted odds ratio
      0.83
      0.92
      NaN
      1.21

      95% CI
      (0.71 - 0.98)
      (0.78 - 1.08)
      None
      (1.03 - 1.43)

      Partner number last 6 months
      Weighted cases
      0.98
      0.98
      1.09
      1.05

      Addjusted odds ratio
      0.83
      0.92
      NaN
      1.21

      95% CI
      (0.71 - 0.98)
      (0.78 - 1.08)
      None
      (1.03 - 1.43)

      Partner number lifetime
      Weighted cases
      5.08
      4.17
      4.52
      4.37

      Addjusted odds ratio
      0.86
      1.09
      NaN
      0.96

      95% CI
      (0.70 - 1.07)
      (0.87 - 1.36)
      None
      (0.77 - 1.20)

      Ever used condoms
      Weighted cases
      962
      891
      887
      862

      Weighted base
      1189
      1091
      1088
      1089

      Weighted%
      80.91
      81.67
      81.53
      79.16

      Addjusted odds ratio
      0.97
      1.12
      NaN
      0.89

      95% CI
      (0.83 - 1.14)
      (0.96 - 1.31)
      None
      (0.76 - 1.04)

      Used condoms last time
      Weighted cases
      603
      549
      565
      490

      Weighted base
      964
      897
      889
      868

      Weighted%
      62.55
      61.2
      63.55
      56.45

      Addjusted odds ratio
      0.97
      1.11
      NaN
      0.86

      95% CI
      (0.83 - 1.12)
      (0.95 - 1.28)
      None
      (0.74 - 1.00)

      Unprotected sex non-monogamous
      Weighted cases
      414
      357
      402
      389

      Weighted base
      1346
      1248
      1223
      1240

      Weighted%
      30.76
      28.61
      32.87
      31.37

      Addjusted odds ratio
      0.97
      0.95
      NaN
      1.02

      95% CI
      (0.83 - 1.14)
      (0.81 - 1.11)
      None
      (0.87 - 1.19)

      Self reported STI
      Weighted cases
      39
      16
      21
      18

      Weighted base
      1346
      1247
      1223
      1240

      Weighted%
      2.9
      1.28
      1.72
      1.45

      Addjusted odds ratio
      1.02
      0.78
      NaN
      1.05

      95% CI
      (0.59 - 1.74)
      (0.44 - 1.38)
      None
      (0.62 - 1.79)

      Ever or partner ever pregnant p2
      Weighted cases
      429
      409
      412
      465

      Weighted base
      1344
      1248
      1222
      1237

      Weighted%
      31.92
      32.77
      33.72
      37.59

      Addjusted odds ratio
      0.93
      1.06
      NaN
      1.08

      95% CI
      (0.77 - 1.12)
      (0.88 - 1.27)
      None
      (0.90 - 1.30)

      Named 3 prevention p2
      Weighted cases
      621
      595
      587
      529

      Weighted base
      1352
      1248
      1223
      1242

      Weighted%
      45.93
      47.68
      48
      42.59

      Addjusted odds ratio
      0.88
      1.06
      NaN
      1.01

      95% CI
      (0.75 - 1.02)
      (0.91 - 1.22)
      None
      (0.87 - 1.18)

      Answered 3 questions p2
      Weighted cases
      415
      388
      362
      341

      Weighted base
      1351
      1247
      1223
      1241

      Weighted%
      30.72
      31.11
      29.6
      27.48

      Addjusted odds ratio
      0.98
      1.03
      NaN
      0.95

      95% CI
      (0.84 - 1.15)
      (0.88 - 1.21)
      None
      (0.81 - 1.12)

      Showed positive attitude p2
      Weighted cases
      262
      212
      233
      229

      Weighted base
      1351
      1247
      1223
      1231

      Weighted%
      19.39
      17
      19.05
      18.6

      Addjusted odds ratio
      0.96
      0.99
      NaN
      1.02

      95% CI
      (0.79 - 1.17)
      (0.81 - 1.19)
      None
      (0.85 - 1.24)

      Child number
      Weighted cases
      0.53
      0.5
      0.54
      0.61

      Addjusted odds ratio
      0.93
      1.06
      NaN
      1.08

      95% CI
      (0.77 - 1.12)
      (0.88 - 1.27)
      None
      (0.90 - 1.30)

### 5.2.4. Table 4: Heterogenetiy test
Table 4 presents heterogeneity tests on those who had started childbearing and those who hadn’t in the first 2 panels, and comparing those respondents believed they have been infected at baseline to those who don’t in the last 2 panels, to show the effect of interventions which yield no significant result as well.

| **Panels**                        | **Method**              |
|-----------------------------------|-------------------------|
| Started child bearing             | using "started_childbearing"          |
| Not started child bearing         | using "started_childbearing"   |
| Believed current HIV infection > 0| using  "Q_b3_99" (what is the likelihood (chance) that you are infected with HIV/AIDS now)|
| Believed current HIV infection = 0| using  "Q_b3_99" (what is the likelihood (chance) that you are infected with HIV/AIDS now)|

```python
query4 = ['started_childbearing == 1', 'started_childbearing == 0', 'Q_b3_99 > 1', 'Q_b3_99 == 1']
keys4=['Started child bearing', 'Not started child bearing', 'Believed current HIV infection > 0', 'Believed current HIV infection = 0']
varlist4 = [('HSV-2 positive', 'hsv2_accept'), ('HSV-2 female', 'hsv2_accept_f'), ('HSV-2 male', 'hsv2_accept_m')]

Table(df_t3, query4, keys4, varlist4)
```

      group
      Condom and VCT
      Condom only
      Control
      VCT only

      Started child bearing
      HSV-2 positive
      Weighted cases
      76
      74
      75
      83

      Weighted base
      582
      501
      551
      596

      Weighted%
      13.06
      14.77
      13.61
      13.93

      Addjusted odds ratio
      1.09
      1.09
      NaN
      0.91

      95% CI
      (0.80 - 1.48)
      (0.80 - 1.49)
      None
      (0.67 - 1.24)

      HSV-2 female
      Weighted cases
      59
      56
      58
      55

      Weighted base
      416
      353
      380
      397

      Weighted%
      14.18
      15.86
      15.26
      13.85

      Addjusted odds ratio
      1.1
      1.03
      NaN
      0.91

      95% CI
      (0.77 - 1.57)
      (0.71 - 1.49)
      None
      (0.63 - 1.30)

      HSV-2 male
      Weighted cases
      17
      18
      17
      28

      Weighted base
      166
      148
      171
      199

      Weighted%
      10.24
      12.16
      9.94
      14.07

      Addjusted odds ratio
      1.08
      1.24
      NaN
      0.91

      95% CI
      (0.59 - 1.98)
      (0.69 - 2.22)
      None
      (0.50 - 1.65)

      Not started child bearing
      HSV-2 positive
      Weighted cases
      115
      88
      89
      96

      Weighted base
      1773
      1692
      1658
      1657

      Weighted%
      6.49
      5.2
      5.37
      5.79

      Addjusted odds ratio
      1.19
      0.86
      NaN
      0.98

      95% CI
      (0.92 - 1.54)
      (0.66 - 1.13)
      None
      (0.75 - 1.29)

      HSV-2 female
      Weighted cases
      32
      32
      38
      41

      Weighted base
      623
      617
      641
      639

      Weighted%
      5.14
      5.19
      5.93
      6.42

      Addjusted odds ratio
      1.05
      0.96
      NaN
      1.03

      95% CI
      (0.68 - 1.63)
      (0.61 - 1.50)
      None
      (0.66 - 1.61)

      HSV-2 male
      Weighted cases
      83
      56
      51
      55

      Weighted base
      1150
      1075
      1017
      1018

      Weighted%
      7.22
      5.21
      5.01
      5.4

      Addjusted odds ratio
      1.28
      0.83
      NaN
      0.97

      95% CI
      (0.93 - 1.76)
      (0.59 - 1.17)
      None
      (0.69 - 1.36)

      Believed current HIV infection > 0
      HSV-2 positive
      Weighted cases
      37
      36
      45
      45

      Weighted base
      519
      525
      467
      539

      Weighted%
      7.13
      6.86
      9.64
      8.35

      Addjusted odds ratio
      1.05
      0.94
      NaN
      0.75

      95% CI
      (0.70 - 1.57)
      (0.63 - 1.42)
      None
      (0.49 - 1.15)

      HSV-2 female
      Weighted cases
      20
      19
      27
      19

      Weighted base
      212
      203
      199
      205

      Weighted%
      9.43
      9.36
      13.57
      9.27

      Addjusted odds ratio
      0.99
      0.95
      NaN
      0.71

      95% CI
      (0.57 - 1.71)
      (0.54 - 1.66)
      None
      (0.39 - 1.29)

      HSV-2 male
      Weighted cases
      17
      17
      18
      26

      Weighted base
      307
      322
      268
      334

      Weighted%
      5.54
      5.28
      6.72
      7.78

      Addjusted odds ratio
      1.12
      0.94
      NaN
      0.79

      95% CI
      (0.62 - 2.04)
      (0.52 - 1.69)
      None
      (0.43 - 1.47)

      Believed current HIV infection = 0
      HSV-2 positive
      Weighted cases
      154
      126
      119
      134

      Weighted base
      1834
      1668
      1741
      1712

      Weighted%
      8.4
      7.55
      6.84
      7.83

      Addjusted odds ratio
      1.17
      0.95
      NaN
      1.05

      95% CI
      (0.94 - 1.47)
      (0.75 - 1.20)
      None
      (0.83 - 1.32)

      HSV-2 female
      Weighted cases
      71
      69
      69
      77

      Weighted base
      827
      767
      822
      830

      Weighted%
      8.59
      9
      8.39
      9.28

      Addjusted odds ratio
      1.1
      1.01
      NaN
      1.04

      95% CI
      (0.80 - 1.51)
      (0.73 - 1.41)
      None
      (0.76 - 1.43)

      HSV-2 male
      Weighted cases
      83
      57
      50
      57

      Weighted base
      1007
      901
      919
      882

      Weighted%
      8.24
      6.33
      5.44
      6.46

      Addjusted odds ratio
      1.25
      0.89
      NaN
      1.05

      95% CI
      (0.91 - 1.72)
      (0.64 - 1.26)
      None
      (0.75 - 1.46)

---
# 6. Discussion
---
Overall the analysis does not yield any significant result except for the condom related behavioral outcomes to groups receiving condoms and VCT related behavioral outcomes to groups having VCT.

Duflo et al. (2019) providing two possible explanations from previous studies for the non-significant result.
1.	Most of the past research only find behavioral changes in people testing positive of HIV. In a meta-analysis (Fonner 2012 et al.) summing up 17 studies, it appears that no significant changes in STI or HIV prevalence rate of those receiving VCT. However, to who being test positive for HIV, there is a reduction in sex partners and an increase in condom use. This cannot be assessed in our data due to overly low HIV prevalence.

2.	The age group. Another multi-component HIV prevention program conducted in Africa and Thailand suggests there is a significant reduction among older women, but no effect among ages 18 to 24 (Coates 2014 et al.). In this study, the subjects are between 17 to 24, which is consistent with their finding.
3.	There were several large scale HIV testing events in the area. At baseline, 44% of the control group had been tested for HIV, while 82.4% had been tested at follow up. The high participation rate is likely to interfere and weaken the effect of treatments.

I have considered changing paper because my replication process doesn’t feel like having closed connections to the course contents and the fact I failed to find HSV-2 at baseline. But I didn’t, subjecting to sunk cost fallacy.

---
# 7. Debug: HSV-2 at baseline
---
This section document all my failing attempts on searching for variable represent HSV-2 testing result at baseline.

## 7.1. Searching dataset and verifying

```python
hsv = df_filter.filter(regex='.*(?i)hsv.*',axis=1)
hsv.head()
```

      hsv2id
      merge_HSVcode
      HSV_result1
      HSV_od1
      HSV_result2
      HSV_od2
      HSV_result3
      HSV_od3
      HSV_result4
      HSV_od4
      HSV_finalresult
      HSV_batch
      merge_HSVresults
      hsv2_positive
      HSV2_blood_sample
      hsv2_decline
      hsv2_accept
      HSV-2 positive

      0
      546864.0
      3.0
      Negative
      NaN

      NaN

      NaN

      NaN
      Negative
      1.0
      3.0
      0.0
      1.0
      0.0
      1.0
      0

      1
      378855.0
      3.0
      Negative
      NaN

      NaN

      NaN

      NaN
      Negative
      1.0
      3.0
      0.0
      1.0
      0.0
      1.0
      0

      2
      579082.0
      3.0
      Negative
      NaN

      NaN

      NaN

      NaN
      Negative
      1.0
      3.0
      0.0
      1.0
      0.0
      1.0
      0

      3
      775833.0
      3.0
      Positive
      NaN
      Positive
      2.533

      NaN

      NaN
      Positive
      1.0
      3.0
      1.0
      1.0
      0.0
      1.0
      1

      4
      696069.0
      3.0
      Negative
      NaN

      NaN

      NaN

      NaN
      Negative
      1.0
      3.0
      0.0
      1.0
      0.0
      1.0
      0

First, rule out variables that are obviously irrelevant.
- **hsv2id** is assigned to almost all individuals in the data set 19202 out of 19293 regardless of having HSV-2 result at stage 2 or not. Here, in the filtered data frame total number equals 7458 as the surveyed individuals that are filtered out previously.
- **merge_HSVcode** seems to be some sort of merging key generated in data processing process of the authors, having only value 3.
- **HSV_od1** to **HSV_od4** are supposed to be the numerical value records of some special cases in the testing process. It takes values that range from 0 to about 5, only have value if HSV_result is not null.
- **HSV_batch** something takes value from 1 to 8, I assume it relates to testing branches.
- **merge_HSVresults** taking value 1 & 3 with 144 & 7313 entries each, it supposed to be something related to merge_HSVcode
- **HSV2_blood_sample**, **hsv2_decline**, **hsv2_accept** could be gauged by the number of entries and name that denoted taking hsv2 blood sample or not, accepting testing or not, declining test or not.
- **HSV-2 positive** is variable I created for table 2 based on hsv-positive

As for HSV_result1 to HSV_result4, HSV_finalresult, hsv2_positive, it can be seemn from below, HSV_finalresult is the same thing as hsv-positive.

```python
pd.crosstab(hsv['hsv2_positive'], hsv['HSV_finalresult'])
```

      HSV_finalresult
      Equivocal
      Negative
      Positive

      hsv2_positive

      0.0
      31
      6674
      0

      1.0
      0
      0
      597

As for the 4 HSV_result, if counting how many non-null values in each column, it will appear to be declined sharply.

```python
hsv_results = hsv.filter(regex='HSV_result.',axis=1)
hsv_results[hsv_results != ''].count()
```

    HSV_result1    7314
    HSV_result2     763
    HSV_result3     145
    HSV_result4      14
    dtype: int64

If comparing the only one testing that is covered almost the whole sample with the final result, it’ll show those who have been testing negative in HSV_result1 are all considered as negative in the final result. This explains that it can’t be testing at baseline because it suggests there is no new infections and is inconsistent with the number in Duflo et al. (2019). Combing these two characteristics and existence of HSV_od1 to 4, I’ll say these are just variables recording repeated testing results for the follow-up test.

```python
pd.crosstab(hsv['HSV_result1'], hsv['HSV_finalresult'])
```

      HSV_finalresult

      Equivocal
      Negative
      Positive

      HSV_result1

      144
      0
      0
      0

      Equivocal
      0
      21
      54
      27

      Negative
      0
      0
      6555
      0

      Positive
      0
      22
      65
      570

## 7.2. Others

Here is a list of the rest of my attempts because showing them all would look tedious.
- Using self-reported STI, an_STI_Q205 to compose the HSV-2 prevalence at baseline, sadly, it doesn’t yield anything closed to the value reported in Duflo et al. (2019) and is not the same as how the paper described as well. In the paper, it mentioned about blood testing, instead of self-reporting as the source of HSV-2 infection.
- Doing the searching and verifying process in 7.1 on keywords: ‘bd’, ‘blood’, ‘test’, ‘result’  etc.
- Checking both questionnaires about whether they have HSV results
- Poring over the whole dataset and testing any variable that having a name can possibly be it.

The only possible solution that’s left is writing to the author and ask about it. Considering of time they’ll take to reply might exceed project deadline and inappropriateness, I didn’t give this thought a shot.

---
# 8. References
---

* **Canning D. (2006)** _The economics of HIV/AIDS in low-income countries: the case for prevention. J Econ Perspect._ 20(3):121-142. doi:10.1257/jep.20.3.121

* **Coates TJ, Kulich M, Celentano DD, Zelaya CE, Chariyalertsak S, Chingono A, et al. (2014)** _Effect of community-based voluntary counselling and testing on HIV incidence and social and behavioural outcomes (NIMH Project Accept; HPTN 043): a cluster-randomised trial._ Lancet Global Health. 2(5): E267–77. https://doi.org/10.1016/S2214-109X(14)70032-4 PMID: 25103167

* **de Grange, L., González, F., Vargas, I. et al. (2015)** _A Logit Model With Endogenous Explanatory Variables and Network Externalities._ Netw Spat Econ 15, 89–116. https://doi.org/10.1007/s11067-014-9271-5

* **Duflo E, Dupas P, Ginn T, Barasa GM, Baraza M, Pouliquen V, et al. (2019)** _HIV prevention among youth: A randomized controlled trial of voluntary counseling and testing for HIV and male condom distribution in rural Kenya._ PLoS ONE 14(7): e0219535. https://doi.org/10.1371/journal.pone.0219535

* **Duflo E, Dupas P, Kremer M. (2015)** _Education, HIV, and Early Fertility: Experimental Evidence from Kenya. American Economic Review._ 105(9):2257–97.

* **Fonner VA, Denison J, Kennedy CE, O’Reilly K, Sweat M. (2012)** _Voluntary counseling and testing (VCT) for changing HIV-related risk behavior in developing countries._ The Cochrane Library. https://doi.org/10.1002/14651858.CD010274

* **Greene (2006)** _Econometric Analysis_

* **Hansen B. (2020)** _Econometrics_

* **Miguel, Edward, and Michael Kremer. (2004)** _Worms: Identifying Impacts on Education and Health in the Presence of Treatment Externalities._ Econometrica 72 (1): 159-217.

* **Sherr L, Lopman B, Kakowa M, Dube S, Chawira G, Nyamukapa C, et al. (2007)** _Voluntary counselling and testing: uptake, impact on sexual behaviour, and HIV incidence in a rural Zimbabwean cohort. AIDS._ 21(7):851–86 https://doi.org/10.1097/QAD.0b013e32805e8711 PMID: 17415040

-------
Notebook by Amanda Wu | Find me on GitHub at https://github.com/amanda8412383

---