%matplotlib inline

import nsfg
from cumulative import *
import thinkstats2
import thinkplot
import random

preg = nsfg.ReadFemPreg()

"""
Explanation: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br>
Allen Downey
Read the pregnancy file.
End of explanation
"""


live = preg[preg.outcome == 1]
live_cdf = thinkstats2.Cdf(live.prglngth)
first_cdf = thinkstats2.Cdf(live[live.birthord == 1].totalwgt_lb, label = 'first')
other_cdf = thinkstats2.Cdf(live[live.birthord > 1].totalwgt_lb, label = 'other')

"""
Explanation: Select live births, then make a CDF of <tt>totalwgt_lb</tt>.
End of explanation
"""


thinkplot.PrePlot(2)
thinkplot.Cdfs([first_cdf, other_cdf])
thinkplot.Show(xlabel='weight (pounds)', ylabel='CDF')

"""
Explanation: Display the CDF.
End of explanation
"""


first_cdf.Percentile(50)

"""
Explanation: Find out how much you weighed at birth, if you can, and compute CDF(x).
End of explanation
"""


first_cdf.Percentile(50)

"""
Explanation: If you are a first child, look up your birthweight in the CDF of first children; otherwise use the CDF of other children.
Compute the percentile rank of your birthweight
End of explanation
"""


first_cdf.Percentile(25), first_cdf.Percentile(75)

"""
Explanation: Compute the median birth weight by looking up the value associated with p=0.5.
End of explanation
"""


first_cdf.Random()

"""
Explanation: Compute the interquartile range (IQR) by computing percentiles corresponding to 25 and 75. 
Make a random selection from <tt>cdf</tt>.
End of explanation
"""


first_cdf.Sample(10)

"""
Explanation: Draw a random sample from <tt>cdf</tt>.
End of explanation
"""


%time thinkplot.Pmf(thinkstats2.Pmf([random.random() for i in xrange(100)]))
%time thinkplot.Pmf(thinkstats2.Pmf([random.random() for i in xrange(100)]))

"""
Explanation: Draw a random sample from <tt>cdf</tt>, then compute the percentile rank for each value, and plot the distribution of the percentile ranks.
Generate 1000 random values using <tt>random.random()</tt> and plot their PMF.
End of explanation
"""


thinkplot.Cdf(thinkstats2.Cdf([random.random() for i in xrange(10000)]))

"""
Explanation: Assuming that the PMF doesn't work very well, try plotting the CDF instead.
End of explanation
"""


