Ejemplo n.º 1
0
def simulationWithoutDrug(numViruses, maxPop, maxBirthProb, clearProb,
                          numTrials):
    """
    Run the simulation and plot the graph for problem 3 (no drugs are used,
    viruses do not have any drug resistance).
    For each of numTrials trial, instantiates a patient, runs a simulation
    for 300 timesteps, and plots the average virus population size as a
    function of time.

    numViruses: number of SimpleVirus to create for patient (an integer)
    maxPop: maximum virus population for patient (an integer)
    maxBirthProb: Maximum reproduction probability (a float between 0-1)
    clearProb: Maximum clearance probability (a float between 0-1)
    numTrials: number of simulation runs to execute (an integer)
    """
    # Debugging!
    verbose = False
    # Initialize the data-storing variables
    time_steps = 300
    step_data = []
    averaged_steps = []
    for index in range(time_steps):
        step_data.append(0)
        # averaged_steps.append(0)

    # Here we do the main looping!
    for i in range(numTrials):
        # Debugging!
        if verbose:
            print("Beginning trial number {}".format(i))
        # Initialize the trial variables
        virus_list = []
        for index in range(numViruses):
            virus_list.append(SimpleVirus(maxBirthProb, clearProb))
        patient = Patient(virus_list, maxPop)
        for i in range(time_steps):
            step_data[i] += patient.update()
    # Average the data:
    for index in range(time_steps):
        averaged_steps.append(step_data[index] / float(numTrials))
    # Debugging!
    if verbose:
        print("Here's the averages: \n{}".format(averaged_steps))

    # Draw the graph!
    pylab.figure()
    pylab.title("Average Virus Population over {} Time Steps".format(
                time_steps))
    pylab.ylabel("Virus Population")
    pylab.xlabel("Time Steps")
    pylab.legend(loc='best')
    pylab.ylim(0, 1100)
    pylab.xkcd()
    pylab.plot(averaged_steps)
    pylab.show()
Ejemplo n.º 2
0
 def statistics():
     """Builds a pylab plot with information about all invoices in the database"""
     dates = []
     costs = []
     pylab.xkcd()
     pylab.figure()
     for invoice in Invoice.get_all():
         dates.append(invoice.id)
         costs.append(invoice.amount)
     pylab.legend(('Invoice Amounts', ))
     pylab.plot(dates, costs, marker='o', label='Charge')
     pylab.xlabel('Invoice Number')
     pylab.ylabel('Money')
     pylab.legend(loc=2)
     ax = pylab.axes()
     ax.spines['top'].set_visible(False)
     ax.spines['right'].set_visible(False)
     ax.tick_params(axis=u'both', which=u'both', length=0)
     return pylab
Ejemplo n.º 3
0
def draw_sigmoid(t):
    '''
    Simple plotting function that draws a sigmoid curve in a xkcd (<3) way.
    For multiple t, subplots are being created.
    @t: list with min 1 and max 4 integer values.
    '''
    if len(t) > 4 or t < 1:
        raise ValueError(
            "Wrong length of t. (has to be smaller than 4 and can't be < 1.")
    import numpy as np
    import pylab
    from scipy.optimize import curve_fit

    x = np.linspace(-10, 10, 100)

    with pylab.xkcd():

        pylab.figure(1, figsize=(8, 6))

        plotno = 221
        for nom in t:

            def sigmoid(k):
                return 1 / (1 + np.exp(-k / nom))

            y = sigmoid(x)
            ax = pylab.subplot(plotno)

            # Move left y-axis and bottim x-axis to centre, passing through (0,0)
            ax.spines['left'].set_position('center')
            ax.spines['bottom'].set_position('center')

            # Eliminate upper and right axes
            ax.spines['right'].set_color('none')
            ax.spines['top'].set_color('none')

            # Show ticks in the left and lower axes only
            ax.xaxis.set_ticks_position('none')
            ax.yaxis.set_ticks_position('none')
            ax.title.set_text('Sigmoid (t = -t / ' + str(nom) + ')')
            ax.set_yticks([.05, .95])
            ax.set_yticklabels([0, 1])
            ax.set_xticks([-5, 5, 8])
            ax.set_xticklabels([-5, 5, 'Time'])

            pylab.plot(x, y)

            plotno += 1

        pylab.tight_layout()

        pylab.show()
Ejemplo n.º 4
0
    def plot_midas(self, xkcd = False):
        """Plot the MIDAS data

        .. seealso:: full documentation about MIDAS in :meth:`cellnopt.core.midas.plot`
        """
        if xkcd:
            from pylab import xkcd, gcf
            with xkcd():
                self.midas.plot()
                f = gcf()
                f.set_facecolor("white")
        else:
            self.midas.plot()
Ejemplo n.º 5
0
def plot_random_pd():
    def norm(x, x0, sigma):
        return np.exp(-0.5 * (x - x0) ** 2 / sigma ** 2)


    def sigmoid(x, x0, alpha):
        return 1. / (1. + np.exp(- (x - x0) / alpha))

    x = np.linspace(0, 1, 100)
    y2 =  (0.1 * np.sin(norm(x, 0.2, 0.05)) +  0.25 * norm(x, 0.6, 0.05) +
          .5*norm(x, .5, .08) +
           np.sqrt(norm(x, 0.8, 0.06)) +0.1 * (1 - sigmoid(x, 0.45, 0.15)))
    with plt.xkcd():
        #plt.setp(plt.gca().get_xticklabels(), visible=False)
        #plt.setp(plt.gca().get_yticklabels(), visible=False)
        plt.axes(xticks=[], yticks=[], frameon=False)
        plt.plot(x, y2)
Ejemplo n.º 6
0
John = .189
Rohith = .137
Henry = .030

import pylab
yj = []
yr = []
yh = []
'''
for x in range(0,220):
    yj.append(40)
    yr.append(59)
    yh.append(75)
'''
for x in range(220, 2 * 365):
    yj.append(42 + (x - 220) * John)
    yr.append(59 + (x - 220) * Rohith)
    yh.append(75 + (x - 220) * Henry)

pylab.xkcd()
pylab.plot(yj, 'r')
pylab.plot(yr, 'g')
pylab.plot(yh, 'k')
pylab.legend(['John', 'Rohith', 'Henry'], loc='upper left')
#pylab.figlegend(("John","Rohith","Henry"),"upper left")
pylab.xlabel("Days From May 15, 2015")
pylab.ylabel("Phone Tool Icons")
pylab.title("Earning icons at current velocity")
pylab.show()
Ejemplo n.º 7
0
             False:["You Lost", 0],
             None:["It is a Draw!", 0]}

    while True:
        what_happened = rps()
        print stats[what_happened][0]
        stats[what_happened][1] += 1

        again = str(raw_input("Play again (Y/N)? ")).upper()
        if again != 'Y':
            break

    total = sum([stats[ky][1] for ky in stats.keys()])
    print 'You won', round((stats[True][1]*100.0)/(total), 2), '% of the time.'
    

    # comment out this section of you don't have pylab
    pylab.rcParams['toolbar'] = 'None'
    pylab.figure(figsize=(8,8), facecolor='white')
    pylab.xkcd()
    pylab.pie([stats[True][1], stats[False][1], stats[None][1]],
             labels=['Wins', 'Losses', 'Draws'],
             colors=['yellowgreen', 'lightcoral', 'lightskyblue'],
             explode=(0.02, 0.02, 0.02),
             startangle=90)
    pylab.axis('equal')
    pylab.title('random game stats')
    s_out = str(raw_input('Do you want to save the output (Y/N)? ')).upper()
    if s_out == 'Y':
        pylab.savefig('results.png')
    pylab.show()
Ejemplo n.º 8
0
from numpy import *
import math
import scipy.stats as ss
import pylab as plt

plt.xkcd()  #before all of the plots!

dt = 0.001
lx, ly = 1., 0.
x = [1.]
y = [0.]
for i in range(0, 50000):
    dx = math.asin(ly / math.sqrt(ly * ly + lx * lx)) * dt
    dy = -math.asin(lx / math.sqrt(ly * ly + lx * lx)) * dt
    lx += dx
    ly += dy
    x.append(lx)
    y.append(ly)

plt.plot(x, y, color='red')
plt.show()
Ejemplo n.º 9
0
    def show(self, path=".", file_name=None, force=False, \
        img_type="png", xkcd = False, label = False):
        """
        This creates a plot of the hyperbola, if it does not already exist.

        Parameters:
        ----------
        file_name     : str
            Name  of image. If 'show', then just display.
        path          : str
            Path to store image. The folder is created if does not exist
        force         : Boolean
            Force rbuild of images if they exist.
        preview       : Boolean
            Format output for preview
        img_type      : str
            The type of image: "png", "gif", ...
        """


        if file_name is None:
            file_name_ = self.url
        else:
            file_name_ = file_name
    
        fname = path + "/" + file_name_ + "." + img_type
        if os.path.isfile(fname) and not force and file_name != 'show':
            print("The file \'" + fname + "\' exists, \
            not regenerating. Delete file to force regeneration.", file=sys.stderr)
            return fname.replace('%2', '%252')

        d = 2 * int(float(self.c))
        xmin = self.h - d
        xmax = self.h + d
        ymin = self.k - d
        ymax = self.k + d


        X = np.linspace(xmin, xmax, 200)
        Y = np.linspace(ymin, ymax, 200)
        X,Y = plt.meshgrid(X,Y)
        f = make_func(self.expr, ('x', 'y'))
        Z = f(X,Y)
        
        
        # The plotting code
        if xkcd:
            plt.xkcd()        
        
        fig, ax = plt.subplots(figsize=(6, 6))
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        for label in ['bottom', 'left']:
            ax.spines[label].set_position('zero')  # this is what zeros the axes
            ax.spines[label].set_linewidth(3)
            ax.spines[label].set_alpha(0.6)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        plt.xlim(xmin,xmax)
        plt.ylim(ymin,ymax)
        ax.set_xticks(tools.non_zero_range(xmin + 1, xmax))
        ax.set_yticks(tools.non_zero_range(ymin + 1, ymax))
        # Plot the hyperbola
        c_plot = plt.contour(X,Y,Z,[1])
                
                   
                
        # Plot the central rectangle
        if self.trans == 'x':
            a = self.a
            b = self.b
        else:
            a = self.b
            b = self.a

        plt.plot([self.h + a, self.h - a, self.h - a, \
                  self.h + a, self.h + a],
                 [self.k + b, self.k + b, self.k - b, \
                  self.k - b, self.k + b], color = (.3, .7, .3, .5),
                 ls = "dashed", lw = 2)

        plt.plot([self.h + a, self.h - a, self.h, self.h], 
                 [self.k, self.k, self.k + b, self.k - b],
                 'o', color = (1,0,0,.5), lw=20)
        if self.trans == 'x':
            plt.plot([self.h - self.c, self.h + self.c], 
                     [self.k, self.k], 'o', color = (0, 0, 1, .5), lw = 20)
        else:
            plt.plot([self.h, self.h], 
                     [self.k  - self.c, self.k  + self.c], 
                     'o', color = (0, 0, 1, .5), lw = 20)

        plt.plot([xmin, xmax], 
                 [b/a*(xmin - self.h) + self.k, b/a*(xmax - self.h) + self.k],
                color = (1,0,1,.5), ls = 'dashed')
        plt.plot([xmin, xmax], 
                 [-b/a*(xmin - self.h) + self.k, -b/a*(xmax - self.h) + self.k],
                color = (1,0,1,.5), ls = 'dashed')
        
        plt.grid()
        
        
        if file_name == 'show':
            plt.show()
            plt.close()
        else:
            tools.make_folder_if_necessary(".", path)
            plt.savefig(fname) 
            plt.close()
            
        return fname.replace('%2','%252')
Ejemplo n.º 10
0
#!/usr/bin/python

import sys, pylab as pl, numpy as np, time

pl.xkcd()
fig = pl.figure()

cols = sys.argv[1]
files = sys.argv[2:]
n = len(files)
fl = ", ".join(files)

fig.suptitle(time.strftime("%c")+"\n" +fl, fontsize=14)

nc, nr = [1, n]
if (n > 2):
   nc = int(pl.ceil(pl.sqrt(n)))
   nr = int(pl.ceil(1.0 * n / nc))

pl.rcParams.update({'font.size': 8})

for idx, file in enumerate(files): 
  fig.add_subplot(nr,nc,idx+1)
  fig.subplots_adjust(top=0.85)

  data = np.loadtxt(file, delimiter=',')
  x = data[:,0]
  for yi in cols.split():
    y = data[:,yi]
    pl.plot(x,y, lw = 0.5)
Ejemplo n.º 11
0
    Returns the st dev '''
    results = []
    for Trail in range(Trails):
        print(Trail)
        results.append(noReplacementSimulation(numTrials))
    stddev = stat.stdev(results)
    mean = stat.mean(results)
    return results, stddev, mean


Trials = 200
numTrials = 50
bins = 20
r, rd, rm = runsim(Trials, numTrials)
r2, rd2, rm2 = runsim(Trials, numTrials)
with plt.xkcd():
    fig, axes = plt.subplots(1, 2)
    plt.suptitle("Number 3 of same color are drawn for\n "
                 "{} tests with {} runs each.".format(Trials, numTrials))
    axes[0].hist(r, color="y", density=True, bins=bins)
    axes[1].hist(r2, color="r", density=True, bins=bins)
    for ax in axes:
        ax.set(xlabel='Probability of 3 of same color',
               ylabel='pdf for {} trials'.format(Trials))
    # plt.tight_layout()
    fig.set_size_inches(10, 8)  # Size of the plot
print(
    rd,
    "  ",
    rd2,
    " \nmean: ",
Ejemplo n.º 12
0

# To test the whole model
n_test_samples = 1000
n_train_samples = [
    10, 50, 100, 200, 300, 400, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000,
    7000, 8000, 9000, 10000, 20000, 30000, 40000, 50000, 60000
]

#for n_train_sample in n_train_samples:
#    test_model(n_test_samples, n_train_sample)

np.save('computed_data/scores', np.array(scores))

import pylab as plt
plt.xkcd()
plt.figure()
plt.title('SW Matching')
plt.xlabel('PW Plate')
plt.ylabel('SW Plate')
# To retrieve closest images
x = []
y = []
for i in range(len(x_test)):
    #for i in range(3):
    x.append(y_test[i])  # Plate #
    predictions = retrieve_closest_images(x_test[i], y_test[i])
    y.append(predictions[0])  # Top Prediction

plt.plot(x, y)
plt.savefig('results.png')
Ejemplo n.º 13
0
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    ax.set_ylim([0, ymax])
    ax.set_xlim([np.min(year), np.max(year)+1.0])
    plt.xlabel('year')
    plt.xticks(year + xtickoffset, year, fontsize=16.0)
    plt.yticks(np.arange(0,ymax+1,3),fontsize=20.0)
    plt.title('Number of PISM publications')
    plt.tight_layout()

year, no_of_pubs, no_of_uaf_pubs = np.loadtxt('pism-publications.csv', delimiter=',', skiprows=1, 
               dtype=int,  unpack=True)

plt.xkcd(scale=1, length=100, randomness=1)
bar_width = 0.5

### bar graph with total pubs ###
ax = startit()
ax.bar(year + bar_width/2, no_of_pubs, bar_width, 
       color='#C6DBEF', edgecolor='#3182BD', linewidth=2.5)
completeit(ax,year,np.max(no_of_pubs) + 1,bar_width)
saveit('pism-publications.png')

### bar graph with UAF pubs in different color ###
ax = startit()
ax.bar(year + bar_width/2, no_of_pubs, bar_width, 
       color='#C6DBEF', edgecolor='#3182BD', linewidth=2.5)
ax.bar(year + bar_width/2, no_of_uaf_pubs, bar_width, 
       color='#FFEA00', edgecolor='#FFD500', linewidth=2.5)