Beispiel #1
0
    def __init__(self,
                 event_spec=None,
                 random_variable=None,
                 color="#0000aa",
                 alpha=0.5,
                 success='#00aa00',
                 failure='#aa0000'):

        if event_spec is not None and random_variable is not None:
            raise ValueError(
                'can only specify `event_spec` or `random_variable`')

        sample_space = [
            (i, j) for i, j in itertools.product(range(1, 7), range(1, 7))
        ]

        if event_spec is not None:
            self.model = BoxModel(sample_space).event(event_spec)
            self.model_type = 'event'
        elif random_variable is None:
            self.model = BoxModel(sample_space)
            self.model_type = 'pair of dice'
        else:
            self.model = RandomVariable(BoxModel(sample_space),
                                        random_variable)
            self.model_type = 'random variable'

        # all related to _repr_html_ output
        self.success = success
        self.failure = failure
        self.color = color
        self.alpha = alpha

        self.outcome = None
Beispiel #2
0
 def __init__(self, values, grid=(-1, 5), replace=True):
     values = copy(values)
     self.grid = grid
     np.random.shuffle(values)
     BoxModel.__init__(self, values, replace=replace)
     self._cached_html_ = _html_box(self.values, grid=self.grid)
     self._drawn = []
 def __init__(self, nblue, nred, ndraw, draw_fig=True):
     self.nblue, self.nred, self.ndraw = nblue, nred, ndraw
     self.box = BoxModel(['B']*nblue + ['R']*nred, replace=False)
     self.X = np.random.sample((nblue+nred, 2))
     self.draw_fig = draw_fig
     if draw_fig:
         self.draw()
Beispiel #4
0
 def __init__(self, values, grid=(-1,5), replace=True):
     values = copy(values)
     self.grid = grid
     np.random.shuffle(values)
     BoxModel.__init__(self, values, replace=replace)
     self._cached_html_ = _html_box(self.values, grid=self.grid)
     self._drawn = []
Beispiel #5
0
class Sample(ProbabilitySpace):

    figsize = (5.5, 5.5)
    alpha = 0.3
    ptsize = 5
    sample_ptsize = 60

    def __init__(self, nblue, nred, ndraw, draw_fig=True):
        self.nblue, self.nred, self.ndraw = nblue, nred, ndraw
        self.box = BoxModel(["B"] * nblue + ["R"] * nred, replace=False)
        self.X = np.random.sample((nblue + nred, 2))
        self.draw_fig = draw_fig
        if draw_fig:
            self.draw()

    def draw(self, color={"R": "red", "B": "blue"}):
        self.figure.clf()
        ax, X = self.axes, self.X
        ax.scatter(X[: self.nblue, 0], X[: self.nblue, 1], s=self.ptsize, color=color["B"], alpha=self.alpha)
        ax.scatter(X[self.nblue :, 0], X[self.nblue :, 1], s=self.ptsize, color=color["R"], alpha=self.alpha)
        ax.set_xticks([])
        ax.set_xlim([-0.01, 1.01])
        ax.set_yticks([])
        ax.set_ylim([-0.01, 1.01])

    @property
    def figure(self):
        if not hasattr(self, "_figure"):
            self._figure = plt.figure(figsize=self.figsize)
        self._axes = self._figure.gca()
        return self._figure

    @property
    def axes(self):
        self.figure
        return self._axes

    def draw_sample_pts(self, bgcolor={"R": "red", "B": "blue"}, color={"R": "red", "B": "blue"}):
        self.draw(color=bgcolor)
        ax, X = self.axes, self.X
        sample = self.box.sample(self.ndraw)
        nblue = np.sum([s == "B" for s in sample])
        nred = self.ndraw - nblue
        ax.scatter(
            X[:nblue, 0], X[:nblue, 1], s=self.sample_ptsize, color=color["B"], alpha=0.8, edgecolor="gray", linewidth=2
        )
        ax.scatter(
            X[-nred:, 0], X[-nred:, 1], s=self.sample_ptsize, color=color["R"], alpha=0.8, edgecolor="gray", linewidth=2
        )
        return self.figure

    def trial(self, bgcolor={"R": "red", "B": "blue"}, color={"R": "red", "B": "blue"}):
        sample = self.box.sample(self.ndraw)
        if self.draw_fig:
            self.draw_sample_pts(color=color, bgcolor=bgcolor)
        self.outcome = np.mean([s == "B" for s in sample])
        return self.outcome
class Sample(ProbabilitySpace):

    figsize = (5.5, 5.5)
    alpha = 0.3
    ptsize = 5
    sample_ptsize = 60

    def __init__(self, nblue, nred, ndraw, draw_fig=True):
        self.nblue, self.nred, self.ndraw = nblue, nred, ndraw
        self.box = BoxModel(['B']*nblue + ['R']*nred, replace=False)
        self.X = np.random.sample((nblue+nred, 2))
        self.draw_fig = draw_fig
        if draw_fig:
            self.draw()

    def draw(self, color={'R':'red','B':'blue'}):
        self.figure.clf()
        ax, X = self.axes, self.X
        ax.scatter(X[:self.nblue,0], X[:self.nblue,1], s=self.ptsize, color=color['B'], alpha=self.alpha)            
        ax.scatter(X[self.nblue:,0], X[self.nblue:,1], s=self.ptsize, color=color['R'], alpha=self.alpha)            
        ax.set_xticks([]);    ax.set_xlim([-0.01,1.01])            
        ax.set_yticks([]);    ax.set_ylim([-0.01,1.01])       

    @property
    def figure(self):
        if not hasattr(self, "_figure"):
            self._figure = plt.figure(figsize=self.figsize)
        self._axes = self._figure.gca()
        return self._figure
    
    @property
    def axes(self):
        self.figure
        return self._axes

    def draw_sample_pts(self, bgcolor={'R':'red','B':'blue'},
                        color={'R':'red','B':'blue'}):
        self.draw(color=bgcolor)
        ax, X = self.axes, self.X
        sample = self.box.sample(self.ndraw)
        nblue = np.sum([s == 'B' for s in sample])
        nred = self.ndraw - nblue
        ax.scatter(X[:nblue,0], X[:nblue,1], s=self.sample_ptsize, color=color['B'], alpha=.8, edgecolor='gray', linewidth=2)            
        ax.scatter(X[-nred:,0], X[-nred:,1], s=self.sample_ptsize, color=color['R'], alpha=.8, edgecolor='gray', linewidth=2)           
        return self.figure

    def trial(self, bgcolor={'R':'red','B':'blue'},
              color={'R':'red','B':'blue'}):
        sample = self.box.sample(self.ndraw)
        if self.draw_fig:
            self.draw_sample_pts(color=color, bgcolor=bgcolor)
        self.outcome = np.mean([s == 'B' for s in sample])
        return self.outcome
 def __init__(self, draw_fig=True):
     self.npop, self.ndraw = 5000, 50
     self.box = BoxModel(np.random.random_integers(-15,
                                                   0,
                                                   size=(self.npop, )),
                         replace=True)
     self.X = (np.mgrid[0:1:10j, 0:1:5j].reshape(
         (2, 50)) + np.random.sample((2, 50)) * 0.05)
     self.BG = np.random.sample((self.npop, 2))
     self.X = self.X.T
     self.draw_fig = draw_fig
     if draw_fig:
         self.draw()
Beispiel #8
0
    def __init__(self, event_spec=None, betcolor="#0000aa", alpha=0.25):
        self.betcolor = betcolor
        self.alpha = alpha

        sample_space = range(1, 37) + ['0', '00']
        self.event_spec = event_spec
        self.position = None

        if event_spec is not None:
            self.model = BoxModel(sample_space).event(event_spec)
            self.model_type = 'event'
        elif event_spec is None:
            self.model = BoxModel(sample_space)
            self.model_type = 'spin of wheel'
Beispiel #9
0
    def __init__(self, event_spec=None,
                 betcolor="#0000aa", alpha=0.25):
        self.betcolor = betcolor
        self.alpha = alpha

        sample_space = range(1,37) + ['0', '00']
        self.event_spec = event_spec
        self.position = None

        if event_spec is not None:
            self.model = BoxModel(sample_space).event(event_spec)
            self.model_type = 'event'
        elif event_spec is None:
            self.model = BoxModel(sample_space)
            self.model_type = 'spin of wheel'
Beispiel #10
0
 def __init__(self, nblue, nred, ndraw, draw_fig=True):
     self.nblue, self.nred, self.ndraw = nblue, nred, ndraw
     self.box = BoxModel(["B"] * nblue + ["R"] * nred, replace=False)
     self.X = np.random.sample((nblue + nred, 2))
     self.draw_fig = draw_fig
     if draw_fig:
         self.draw()
Beispiel #11
0
    def __init__(self, event_spec=odd_test, betcolor="#0000aa", alpha=0.25):

        roulette_example.__init__(self, event_spec, betcolor, alpha)

        # overwrite the model
        self.model = Geometric(BoxModel(range(1, 37) + ['0', '00']),
                               event_spec)
Beispiel #12
0
def bet(event, amount, ntimes, initial_amount=0):
    odds = (len(range(1, 37)) - len(event)) / len(event)
    binom = Binomial(ntimes, BoxModel(sample_space), event)
    rv = RandomVariable(
        binom, lambda outcome: amount * (odds * outcome -
                                         (ntimes - outcome)) + initial_amount)
    return rv
class BloodPressure(ProbabilitySpace):

    figsize = (5.5, 5.5)
    alpha = 0.1
    ptsize = 5
    sample_ptsize = 60

    def __init__(self, draw_fig=True):
        self.npop, self.ndraw = 5000, 50
        self.box = BoxModel(np.random.random_integers(-15, 0,
                                                       size=(self.npop,)),
                                                       replace=True)
        self.X = (np.mgrid[0:1:10j,0:1:5j].reshape((2,50)) + 
                  np.random.sample((2,50)) * 0.05)
        self.BG = np.random.sample((self.npop,2))
        self.X = self.X.T
        self.draw_fig = draw_fig
        if draw_fig:
            self.draw()

    def draw(self, color={'R':'red','B':'blue'}):
        self.figure.clf()
        ax, X, BG = self.axes, self.X, self.BG
        ax.scatter(BG[:,0], BG[:,1], s=self.ptsize, color='gray', alpha=self.alpha)            
        ax.set_xticks([]);    ax.set_xlim([-0.1,1.1])            
        ax.set_yticks([]);    ax.set_ylim([-0.1,1.1])       

    @property
    def figure(self):
        if not hasattr(self, "_figure"):
            self._figure = plt.figure(figsize=self.figsize)
        self._axes = self._figure.gca()
        return self._figure
    
    @property
    def axes(self):
        self.figure
        return self._axes

    def draw_sample_pts(self, bgcolor={'R':'red','B':'blue'},
                        color={'R':'red','B':'blue'}):
        self.draw(color=bgcolor)
        ax, X, sample = self.axes, self.X, self._sample
        mean, sd = self.outcome
        for i in range(50):
            ax.text(X[i,0], X[i,1], '%d' % sample[i], color='red')
        ax.set_title("average(sample)=%0.1f, SD(sample)=%0.1f" % (np.mean(sample), np.std(sample)), fontsize=15)
        return self.figure

    def trial(self, bgcolor={'R':'red','B':'blue'},
              color={'R':'red','B':'blue'}):
        self._sample = self.box.sample(self.ndraw)
        self.outcome = np.mean(self._sample), np.std(self._sample)
        if self.draw_fig:
            self.draw_sample_pts(color=color, bgcolor=bgcolor)
        return self.outcome
 def __init__(self, draw_fig=True):
     self.npop, self.ndraw = 5000, 50
     self.box = BoxModel(np.random.random_integers(-15, 0,
                                                    size=(self.npop,)),
                                                    replace=True)
     self.X = (np.mgrid[0:1:10j,0:1:5j].reshape((2,50)) + 
               np.random.sample((2,50)) * 0.05)
     self.BG = np.random.sample((self.npop,2))
     self.X = self.X.T
     self.draw_fig = draw_fig
     if draw_fig:
         self.draw()
Beispiel #15
0
class roulette_example(ProbabilitySpace):

    def __init__(self, event_spec=None,
                 betcolor="#0000aa", alpha=0.25):
        self.betcolor = betcolor
        self.alpha = alpha

        sample_space = range(1,37) + ['0', '00']
        self.event_spec = event_spec
        self.position = None

        if event_spec is not None:
            self.model = BoxModel(sample_space).event(event_spec)
            self.model_type = 'event'
        elif event_spec is None:
            self.model = BoxModel(sample_space)
            self.model_type = 'spin of wheel'

    @property
    def mass_function(self):
        return self.model.mass_function

    @property
    def sample_space(self):
        return self.model.sample_space

    def trial(self):
        self.outcome = self.model.trial()
        if self.model_type == 'event':
            self.position = self.model.probability_space.outcome
        else:
            self.position = self.outcome
        return self.outcome

    def _repr_html_(self):
        return roulette_trial(event_spec=self.event_spec,
                              outcome=self.position,
                              betcolor=self.betcolor,
                              alpha=self.alpha)
Beispiel #16
0
class roulette_example(ProbabilitySpace):
    def __init__(self, event_spec=None, betcolor="#0000aa", alpha=0.25):
        self.betcolor = betcolor
        self.alpha = alpha

        sample_space = range(1, 37) + ['0', '00']
        self.event_spec = event_spec
        self.position = None

        if event_spec is not None:
            self.model = BoxModel(sample_space).event(event_spec)
            self.model_type = 'event'
        elif event_spec is None:
            self.model = BoxModel(sample_space)
            self.model_type = 'spin of wheel'

    @property
    def mass_function(self):
        return self.model.mass_function

    @property
    def sample_space(self):
        return self.model.sample_space

    def trial(self):
        self.outcome = self.model.trial()
        if self.model_type == 'event':
            self.position = self.model.probability_space.outcome
        else:
            self.position = self.outcome
        return self.outcome

    def _repr_html_(self):
        return roulette_trial(event_spec=self.event_spec,
                              outcome=self.position,
                              betcolor=self.betcolor,
                              alpha=self.alpha)
Beispiel #17
0

def bet(event, amount, ntimes, initial_amount=0):
    odds = (len(range(1, 37)) - len(event)) / len(event)
    binom = Binomial(ntimes, BoxModel(sample_space), event)
    rv = RandomVariable(
        binom, lambda outcome: amount * (odds * outcome -
                                         (ntimes - outcome)) + initial_amount)
    return rv


five = roulette_example(event_spec=lambda outcome: outcome == 5)
five.desc = 'A roulette bet on red numbers.'

sample_space = range(1, 37) + ['0', '00']
sixplays_five = Binomial(6, BoxModel(sample_space), [5])
eightplays_red = Binomial(8, BoxModel(sample_space), red_numbers)

black = roulette_example(event_spec=black_test)
black.desc = 'A roulette bet on black  numbers.'

middle_third = roulette_example(
    event_spec=lambda outcome: outcome in range(13, 25))
middle_third.desc = 'A roulette bet on only the middle third of the possible numbers.'

special_bet = roulette_example(
    event_spec=lambda outcome: outcome in [2, 24, 29])
special_bet.desc = 'A roulette bet on [2,24,29].'


class roulette_geometric(roulette_example):
class BloodPressure(ProbabilitySpace):

    figsize = (5.5, 5.5)
    alpha = 0.1
    ptsize = 5
    sample_ptsize = 60

    def __init__(self, draw_fig=True):
        self.npop, self.ndraw = 5000, 50
        self.box = BoxModel(np.random.random_integers(-15,
                                                      0,
                                                      size=(self.npop, )),
                            replace=True)
        self.X = (np.mgrid[0:1:10j, 0:1:5j].reshape(
            (2, 50)) + np.random.sample((2, 50)) * 0.05)
        self.BG = np.random.sample((self.npop, 2))
        self.X = self.X.T
        self.draw_fig = draw_fig
        if draw_fig:
            self.draw()

    def draw(self, color={'R': 'red', 'B': 'blue'}):
        self.figure.clf()
        ax, X, BG = self.axes, self.X, self.BG
        ax.scatter(BG[:, 0],
                   BG[:, 1],
                   s=self.ptsize,
                   color='gray',
                   alpha=self.alpha)
        ax.set_xticks([])
        ax.set_xlim([-0.1, 1.1])
        ax.set_yticks([])
        ax.set_ylim([-0.1, 1.1])

    @property
    def figure(self):
        if not hasattr(self, "_figure"):
            self._figure = plt.figure(figsize=self.figsize)
        self._axes = self._figure.gca()
        return self._figure

    @property
    def axes(self):
        self.figure
        return self._axes

    def draw_sample_pts(self,
                        bgcolor={
                            'R': 'red',
                            'B': 'blue'
                        },
                        color={
                            'R': 'red',
                            'B': 'blue'
                        }):
        self.draw(color=bgcolor)
        ax, X, sample = self.axes, self.X, self._sample
        mean, sd = self.outcome
        for i in range(50):
            ax.text(X[i, 0], X[i, 1], '%d' % sample[i], color='red')
        ax.set_title("average(sample)=%0.1f, SD(sample)=%0.1f" %
                     (np.mean(sample), np.std(sample)),
                     fontsize=15)
        return self.figure

    def trial(self,
              bgcolor={
                  'R': 'red',
                  'B': 'blue'
              },
              color={
                  'R': 'red',
                  'B': 'blue'
              }):
        self._sample = self.box.sample(self.ndraw)
        self.outcome = np.mean(self._sample), np.std(self._sample)
        if self.draw_fig:
            self.draw_sample_pts(color=color, bgcolor=bgcolor)
        return self.outcome