Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

Repository for a workshop on Bayesian statistics

1430 views


'j�Z�N�@s�dZddlmZddlZddlZddljZddlZ	ddl
Z
ddlZGdd�de�Z
dd�Zddddd	�Zddd
d�Zdd
�Zdd�Zdd�Zdddd�Zdd�Zdd�Zdddd�Zdd�Zddd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Z d-d.�Z!d/dd0d1�Z"d/dd2d3�Z#d/d4d/d5d6�Z$d4d/d7d8�Z%d9d:�Z&d4a'da(d;d<�Z)d=d>�Z*d?d@�Z+dddAdB�Z,dCdDdE�Z-eZ.eZ/eZ0eZ1eZ2eZ3eZ4eZ5e&Z6eZ7eZ8e Z9eZ:eZ;e!Z<e"Z=e#Z>e$Z?e%Z@e)ZAe*ZBe,ZCdFdG�ZDeEdHkr�eD�dS)Iz�This file contains code for use with "Think Stats",
by Allen B. Downey, available from greenteapress.com

Copyright 2014 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
�)�print_functionNc@sUeZdZdZdZddddddd	d
dg	ddd�Zgdgdd
gdddgddddgddd
ddgddd
dddgdddd
dddgdddd
ddddgdddd
dddddg	g
ZdZedd��Z	edd��Z
edd��Zedd��Zedd��Z
dS) �_Brewerz�Encapsulates a nice sequence of colors.

    Shades of blue that look good in color and can be distinguished
    in grayscale (up to a point).
    
    Borrowed from http://colorbrewer2.org/
    Nz#f7fbffz#deebf7z#c6dbefz#9ecae1z#6baed6z#4292c6z#2171b5z#08519cz#08306b��r������cCs|jS)z$Returns the list of colors.
        )�colors)�cls�r�'/home/user/BayesMadeSimple/thinkplot.py�Colors=sz_Brewer.Colorsccs4x!|j|D]}|j|VqWtd��dS)zWReturns an iterator of color strings.

        n: how many colors will be used
        zRan out of colors in _Brewer.N)�which_colorsr�
StopIteration)r
�num�irrr�ColorGeneratorCsz_Brewer.ColorGeneratorcCs+|j|�|_tj�}||_dS)z?Initializes the color iterator with the given number of colors.N)r�
color_iter�plt�gcf�current_figure)r
r�figrrr�InitIterMsz_Brewer.InitItercCsd|_d|_dS)z Sets the color iterator to None.N)rr)r
rrr�	ClearIterTs	z_Brewer.ClearItercCsTtj�}||jkr1|j|�||_|jdkrM|j|�|jS)zGets the color iterator.N)rrrrr)r
rrrrr�GetIterZs
	
z_Brewer.GetIter�����)�__name__�
__module__�__qualname__�__doc__rrrr�classmethodrrrrrrrrrr s*			$
rcCsmd|kr|Stjd�}yt|�|d<Wn3tk
rhtjd�tj�t|�YnX|S)z5If color is not in the options, chooses a color.
    �colorr	z"Ran out of colors.  Starting over.)rr�nextr�warnings�warnr�_UnderrideColor)�optionsrrrrr(hs


r(cCs(|rtj|�|dkr/|dkr/dS|dk	rM|dkrMd}|dk	rk|dkrkd}dd
ddddddddddddddddi	}||f|kr�tj�}|j|||f�|dks�|dkrtj||d�}|a|antj�}|S)z�Takes hints about what's coming.

    num: number of lines that will be plotted
    rows: number of rows of subplots
    cols: number of columns of subplots
    Nrrrr�rrr	�
�)rr)rr)rr)r*r)rr)r*r)rr)r*r	)rr	)r*r)rr)r+r+)rr)r,r+)rr)rr+)rr)rr*)	rrrr�set_size_inches�subplot�SUBPLOT_ROWS�SUBPLOT_COLS�gca)r�rows�colsZsize_mapr�axrrr�PrePlot}s4
	r5cKs.|p	t}|pt}tj||||�S)z�Configures the number of subplots and changes the current plot.

    rows: int
    cols: int
    plot_number: int
    options: passed to subplot
    )r/r0rr.)Zplot_numberr2r3r)rrr�SubPlot�sr6cKsC|dkri}x*|j�D]\}}|j||�qW|S)z�Add key-value pairs to d only if key is not in d.

    If d is None, create a new dictionary.

    d: dictionary
    options: keyword args to add to d
    N)�items�
setdefault)�dr)�key�valrrr�
_Underride�s
r<cCs:datj�tj�tj�}|jdd�dS)z3Clears the figure and any hints that have been set.Nrr)�LOCrrr�clfrr-)rrrr�Clf�s


r?cKs!t|dd�tj|�dS)z$Sets options for the current figure.�figsizerrN)rr)r<r�figure)r)rrr�Figure�srB�cKs�t|�}t|dd�}t|ddddd|�}|}|dkr�t|d�ro|j�\}}t|tj�r�|j}|j	}|dkr�t
j|||�nt
j||||�dS)	z�Plots a line.

    Args:
      obj: sequence of x values, or Series, or anything with Render()
      ys: sequence of y values
      style: style string passed along to plt.plot
      options: keyword args passed to plt.plot
    �label�
_nolegend_�	linewidthr�alphagffffff�?N�Render)r(�getattrr<�hasattrrH�
isinstance�pandas�Series�values�indexr�plot)�obj�ys�styler)rD�xsrrr�Plot�s			rUcKs>t|�}t|dddd�}tj||||�dS)z�Plots a set of vertical lines.

    Args:
      xs: sequence of x values
      y1: sequence of y values
      y2: sequence of y values
      options: keyword args passed to plt.vlines
    rFrrGg�?N)r(r<r�vlines)rT�y1�y2r)rrr�Vlines�s	rYcKs>t|�}t|dddd�}tj||||�dS)z�Plots a set of horizontal lines.

    Args:
      ys: sequence of y values
      x1: sequence of x values
      x2: sequence of x values
      options: keyword args passed to plt.vlines
    rFrrGg�?N)r(r<r�hlines)rR�x1�x2r)rrr�Hliness	r]cKsAt|�}t|dddd�}tj|||||�dS)z�Fills the space between two lines.

    Args:
      xs: sequence of x values
      y1: sequence of y values
      y2: sequence of y values
      where: sequence of boolean
      options: keyword args passed to plt.fill_between
    rFrrGg�?N)r(r<r�fill_between)rTrWrX�wherer)rrr�FillBetweens
r`cKs;t|�}t|dddd�}tj|||�dS)z�Plots a line.

    Args:
      xs: sequence of x values
      ys: sequence of y values
      options: keyword args passed to plt.bar
    rFrrGg333333�?N)r(r<r�bar)rTrRr)rrr�Barsrbc
Kskt|dddddddd�}|d	krTt|tj�rT|j}|j}tj|||�d	S)
zhMakes a scatter plot.

    xs: x values
    ys: y values
    options: options passed to plt.scatter
    r$�bluerGg�������?�s��
edgecolors�noneN)r<rKrLrMrNrOr�scatter)rTrRr)rrr�Scatter,s		ricKs/t|dtjj�}tj|||�dS)zhMakes a scatter plot.

    xs: x values
    ys: y values
    options: options passed to plt.scatter
    �cmapN)r<�
matplotlib�cm�Bluesr�hexbin)rTrRr)rrr�HexBin=srocKs�|jdd�|jdd�}}|jdd�}|jd|d|d|�\}}t|d|j�}t|||�dS)z�Plots a Pdf, Pmf, or Hist as a line.

    Args:
      pdf: Pdf, Pmf, or Hist object
      options: keyword args passed to plt.plot
    �lowN�high�n�erD)�poprHr<rDrU)�pdfr)rprqrrrT�psrrr�PdfHs
%$rwcKs"x|D]}t||�qWdS)z�Plots a sequence of PDFs.

    Options are passed along for all PDFs.  If you want different
    options for each pdf, make multiple calls to Pdf.
    
    Args:
      pdfs: sequence of PDF objects
      options: keyword args passed to plt.plot
    N)rw)Zpdfsr)rurrr�PdfsVs

rxcKsF|j�\}}y|d|dWnNtk
rvdd�|D�}tjt|��}tj|d|�YnXd|kr�y!dtj|�j�|d<Wntk
r�t	j
d�YnXt|d|j�}t|d	d
�}|d	dkr
d|d	<n(|d	d
kr2d|d	<|dd9<t
|||�dS)aaPlots a Pmf or Hist with a bar plot.

    The default width of the bars is based on the minimum difference
    between values in the Hist.  If that's too small, you can override
    it by providing a width keyword argument, in the same units
    as the values.

    Args:
      hist: Hist or Pmf object
      options: keyword args passed to plt.bar
    rcSsg|]}t|��qSr)�str)�.0�xrrr�
<listcomp>xs	zHist.<locals>.<listcomp>g�?�widthg�������?znHist: Can't compute bar width automatically.Check for non-numeric types in Hist.Or try providing width option.rD�align�center�left�edge�rightrNr)rH�	TypeError�np�arange�lenr�xticks�diff�minr&r'r<rDrb)�histr)rTrR�labelsrrr�Histds(

!


r�cKs"x|D]}t||�qWdS)aPlots two histograms as interleaved bar plots.

    Options are passed along for all PMFs.  If you want different
    options for each pmf, make multiple calls to Pmf.

    Args:
      hists: list of two Hist or Pmf objects
      options: keyword args passed to plt.plot
    N)r�)�histsr)r�rrr�Hists�s

r�cKs�|j�\}}t|�t|�}}|jdd�}|dkr�ytj|�j�}Wntk
r�tjd�YnXg}tj	}d}	x�t
||�D]�\}
}|
|dkr�|j|df�|j|
df�|j|
|	f�|j|
|f�|j|
||f�|
|}|}	q�W|j|df�t
|�\}}
|jdd�}|dkr�tj|�|d}|d	kr�tj|�|}t
|d
|j�}t||
|�dS)z{Plots a Pmf or Hist as a line.

    Args:
      pmf: Hist or Pmf object
      options: keyword args passed to plt.plot
    r}NzlPmf: Can't compute bar width automatically.Check for non-numeric types in Pmf.Or try providing width option.rg�h㈵��>r~rg@r�rD)rHr��maxrtr�r�r�r&r'�nan�zip�append�arrayr<rDrU)�pmfr)rTrRrprqr}�points�lastx�lastyr{�yZpxs�pysr~rrr�Pmf�s:
	

r�cKs"x|D]}t||�qWdS)z�Plots a sequence of PMFs.

    Options are passed along for all PMFs.  If you want different
    options for each pmf, make multiple calls to Pmf.
    
    Args:
      pmfs: sequence of PMF objects
      options: keyword args passed to plt.plot
    N)r�)�pmfsr)r�rrr�Pmfs�s

r�cs-�fdd�tt��d�D�}|S)z�Compute the differences between adjacent elements in a sequence.

    Args:
        t: sequence of number

    Returns:
        sequence of differences (length one less than t)
    cs&g|]}�|d�|�qS)rr)rzr)�trrr|�s	zDiff.<locals>.<listcomp>r)�ranger�)r��diffsr)r�r�Diff�s	)r�FcKs�|j�\}}tj|�}tj|�}tdddd�}x3ddgD]%}||krR|j|�||<qRW|dkr�d}d|d<|dkr�d}d|d<d|d<|r�dd	�|D�}|d
kr-tj|d�}tj|d�}dd	�|D�}d|d<d|d<|d
krztj|d�}tj|d�}dd	�|D�}d|d<t|d|j�}t	|||�|S)adPlots a CDF as a line.

    Args:
      cdf: Cdf object
      complement: boolean, whether to plot the complementary CDF
      transform: string, one of 'exponential', 'pareto', 'weibull', 'gumbel'
      options: keyword args passed to plt.plot

    Returns:
      dictionary with the scale options that should be passed to
      Config, Show or Save.
    �xscale�linear�yscale�exponentialT�log�paretocSsg|]}d|�qS)g�?r)rz�prrrr|s	zCdf.<locals>.<listcomp>�weibullrcSs$g|]}tjd|��qS)g�?)�mathr�)rzr�rrrr|
s	�gumbelrcSs g|]}tj|��qSr)r�r�)rzr�rrrr|s	rDrr)
rHr��asarray�dictrt�delete�xpr<rDrU)�cdf�
complement�	transformr)rTrv�scalerdrrr�Cdf�s<






r�cKs(x!|D]}t||||�qWdS)z�Plots a sequence of CDFs.
    
    cdfs: sequence of CDF objects
    complement: boolean, whether to plot the complementary CDF
    transform: string, one of 'exponential', 'pareto', 'weibull', 'gumbel'
    options: keyword args passed to plt.plot
    N)r�)�cdfsr�r�r)r�rrr�Cdfss
r�Tcs�y|j��Wntk
r*|�YnXt|dddtjj�t�j��\}}tt	|��}tt	|��}t
j||�\}}�fdd�}	t
j|	�}	|	||�}
tj
jdd�}tj�}|jj|�|rtj|||
|�|rOtj|||
|�}
tj|
dd	d
d�|r�|d|d|d|df}tj|
d
||�dS)a:Makes a contour plot.
    
    d: map from (x, y) to z, or object that provides GetDict
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    imshow: boolean, whether to use plt.imshow
    options: keyword args passed to plt.pcolor and/or plt.contour
    rFrrjcs�j||fd�S)Nr)�get)r{r�)r9rr�<lambda>=szContour.<locals>.<lambda>�	useOffsetF�inliner�fontsizer+r�extentNrr)�GetDict�AttributeErrorr<rkrlrmr��keys�sorted�setr��meshgrid�	vectorize�ticker�ScalarFormatterrr1�xaxis�set_major_formatter�
pcolormesh�contour�clabel�imshow)rQ�pcolorr�r�r)rTrR�X�Y�func�Z�x_formatter�axes�csr�r)r9r�Contour(s.	
"r�cKs�t|dddtjj�tj||�\}}|}tjjdd�}	tj	�}
|
j
j|	�|r�tj||||�|r�tj
||||�}tj|dddd	�d
S)z�Makes a pseudocolor plot.
    
    xs:
    ys:
    zs:
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    options: keyword args passed to plt.pcolor and/or plt.contour
    rFrrjr�Fr�rr�r+N)r<rkrlrmr�r�r�r�rr1r�r�r�r�r�)rTrR�zsr�r�r)r�r�r�r�r�r�rrr�PcolorOs
r�cKs8t|dddddd�}tj||||�dS)zsPuts text in a figure.

    x: number
    y: number
    s: string
    options: keyword args passed to plt.text
    r�r,�verticalalignment�top�horizontalalignmentr�N)r<r�text)r{r�rdr)rrr�Textjs
		r�cKs�ddddddddd	d
g
}x1|D])}||kr+tt|�||�q+W|jdt�atr�|jdt�a|jd
d�}tjddt�ytjdtd
|�Wntk
r�YnXtjddt�|jdd�}|dk	r>|dkr>tj	�}|j
�}tj|dd�|jdd�}|dk	r�|dkr�tj	�}|j�}tj|dd�dS)z�Configures the plot.

    Pulls options out of the option dictionary and passes them to
    the corresponding plt functions.
    �title�xlabel�ylabelr�r�r��yticks�axis�xlim�ylim�legend�loc�frameonT�error�category�defaultZxticklabelsNZ	invisible�visibleFZyticklabels)
rIrr��LEGENDr=r&�filterwarnings�UserWarningr�r1�get_xticklabels�setp�get_yticklabels)r)�names�namer�r;r4r�rrr�Config|s6

r�cKs7|jdd�}t|�tj�|r3t�dS)zrShows the plot.

    For options, see Config.

    options: keyword args used to invoke various plt functions
    r>TN)rtr�r�showr?)r)r>rrr�Show�s


r�cKsQ|jdd�}t|�ddlj}|jtj��}|rMt�|S)zrShows the plot.

    For options, see Config.

    options: keyword args used to invoke various plt functions
    r>TrN)rtr�Z
plotly.plotly�plotlyZplot_mplrrr?)r)r>r��urlrrr�Plotly�s
r�c
Ks�|jdd�}i}x3ddgD]%}||kr%|j|�||<q%Wt|�|dkrpddg}y|jd�tdd	�Wntk
r�YnX|r�x|D]}t|||�q�W|r�t�dS)
z�Saves the plot in the given formats and clears the figure.

    For options, see Config.

    Args:
      root: string filename root
      formats: list of string formats
      options: keyword args used to invoke various plt functions
    r>T�bbox_inches�
pad_inchesNru�epsr�F)rtr��remover��
ValueError�
SaveFormatr?)�root�formatsr)r>Zsave_options�option�fmtrrr�Save�s$




rr�cKsGt|dd�d||f}td|�tj|d||�dS)z�Writes the current figure to a file in the given format.

    Args:
      root: string filename root
      fmt: string format
    �dpii,z%s.%sZWriting�formatN)r<�printr�savefig)r�rr)�filenamerrrr��s
r�cCs.tjd�}x|D]}t|�qWdS)Nr
)rrr)rr$rrr�mains
r�__main__)Fr"�
__future__rr�rk�matplotlib.pyplot�pyplotr�numpyr�rLr&�objectrr(r5r6r<r?rBrUrYr]r`rbrirorwrxr�r�r�r�r�r�r�r�r�r�r�r=r�r�r�rr�Zpreplotr.r>rArPrVrZr^r�rhr�r�r�r�r�r�r�r�r��configr��saverrrrrr�<module>s�H.


,.
5',#