def test_vaccines_sequential(do_plot=False): sc.heading('Testing sequential vaccine...') n_days = 60 p1 = cv.variant('beta', days=20, n_imports=20) num_doses = {i:(i**2)*(i%2==0) for i in np.arange(n_days)} # Test subtarget and fluctuating doses n_doses = [] subtarget = dict(inds=np.arange(int(base_pars.pop_size//2)), vals=0.1) pfizer = cv.vaccinate_num(vaccine='pfizer', sequence='age', num_doses=num_doses, subtarget=subtarget) sim = cv.Sim(base_pars, n_days=n_days, rescale=False, use_waning=True, variants=p1, interventions=pfizer, analyzers=lambda sim: n_doses.append(sim.people.doses.copy())) sim.run() n_doses = np.array(n_doses) if do_plot: fully_vaccinated = (n_doses == 2).sum(axis=1) first_dose = (n_doses == 1).sum(axis=1) pl.stackplot(sim.tvec, first_dose, fully_vaccinated) # Stacked bars by 10 year age # At the end of the simulation df = pd.DataFrame(n_doses.T) df['age_bin'] = np.digitize(sim.people.age,np.arange(0,100,10)) df['fully_vaccinated'] = df[60]==2 df['first_dose'] = df[60]==1 df['unvaccinated'] = df[60]==0 out = df.groupby('age_bin').sum() out[["unvaccinated", "first_dose","fully_vaccinated"]].plot(kind="bar", stacked=True) # Part-way through the simulation df = pd.DataFrame(n_doses.T) df['age_bin'] = np.digitize(sim.people.age,np.arange(0,100,10)) df['fully_vaccinated'] = df[40]==2 df['first_dose'] = df[40]==1 df['unvaccinated'] = df[40]==0 out = df.groupby('age_bin').sum() out[["unvaccinated", "first_dose","fully_vaccinated"]].plot(kind="bar", stacked=True) return sim
def test_vaccines_sequential(do_plot=False): sc.heading('Testing sequential vaccine...') p1 = cv.variant('sa variant', days=20, n_imports=20) def age_sequence(people): return np.argsort(-people.age) n_doses = [] pfizer = cv.vaccinate_num(vaccine='pfizer', sequence=age_sequence, num_doses=lambda sim: sim.t) sim = cv.Sim(base_pars, rescale=False, use_waning=True, variants=p1, interventions=pfizer, analyzers=lambda sim: n_doses.append(sim.people.vaccinations.copy())) sim.run() n_doses = np.array(n_doses) if do_plot: fully_vaccinated = (n_doses == 2).sum(axis=1) first_dose = (n_doses == 1).sum(axis=1) pl.stackplot(sim.tvec, first_dose, fully_vaccinated) # Stacked bars by 10 year age # At the end of the simulation df = pd.DataFrame(n_doses.T) df['age_bin'] = np.digitize(sim.people.age,np.arange(0,100,10)) df['fully_vaccinated'] = df[60]==2 df['first_dose'] = df[60]==1 df['unvaccinated'] = df[60]==0 out = df.groupby('age_bin').sum() out[["unvaccinated", "first_dose","fully_vaccinated"]].plot(kind="bar", stacked=True) # Part-way through the simulation df = pd.DataFrame(n_doses.T) df['age_bin'] = np.digitize(sim.people.age,np.arange(0,100,10)) df['fully_vaccinated'] = df[40]==2 df['first_dose'] = df[40]==1 df['unvaccinated'] = df[40]==0 out = df.groupby('age_bin').sum() out[["unvaccinated", "first_dose","fully_vaccinated"]].plot(kind="bar", stacked=True) return sim
def plot_tickets(tracker_name, db_name, image_name): conn = sqlite3.connect(db_name) cur = conn.cursor() rows = cur.execute("select json from tickets") all_issues = (json.loads(r[0]) for r in rows) issues = [i for i in all_issues if i["tracker"]["name"] == tracker_name] cur.close() conn.close() data = [reduce_journal(analyse_journal(i)) for i in issues] data = itertools.chain.from_iterable(data) data = sorted(data, key=lambda x: x[0]) data = [split_sum(d) for d in sum_journal(data)] pylab.figure(figsize=(9, 10)) pylab.subplot(2, 1, 1) pylab.title(tracker_name) x1, y1 = zip(*data) y1 = zip(*y1) pylab.grid() pylab.stackplot(x1, y1, colors=COLORS) high = pylab.Rectangle((0, 0), 1, 1, fc=COLORS[0]) normal = pylab.Rectangle((0, 0), 1, 1, fc=COLORS[1]) low = pylab.Rectangle((0, 0), 1, 1, fc=COLORS[2]) pylab.legend([low, normal, high], ["Low", "Normal", "High"], loc=2) pylab.subplot(2, 1, 2) pylab.title(tracker_name + " (Die letzen 5 Wochen)") current_data = filter_by_time(data, datetime.timedelta(days=45)) x2, y2 = zip(*current_data) y2 = zip(*y2) pylab.grid() pylab.stackplot(x2, y2, colors=COLORS) pylab.savefig(image_name)
# Handle MOOSE developers option if options.moose_dev and options.authors: raise Exception("Can not specify both --authors and --moose-dev"); elif options.moose_dev: options.authors = 'moose' # Extract the data dates, data, contrib, contributors = getData(options) # Create the figure fig, ax1 = pylab.subplots() # Plot the data if options.stack: # stack plot handles = pylab.stackplot(dates, data) for i in range(len(handles)): handles[i].set_label(contributors[i]) else: # line plot handles = [] for i in range(len(contributors)): x = numpy.array(dates) y = data[i,:] idx = y>0 h = ax1.plot(x[idx], y[idx], label=contributors[i], linewidth=2, markevery=60, marker=marker.next(), color=color.next()) handles.append(h[0]) lgnd = pylab.legend(handles, contributors, loc='upper left') lgnd.draw_frame(False) # Add labels
def MakePlot(infile, plotfile, aa_order): """Makes plots from input file *infile*. *infile* contains the amino-acid frequencies over time. *plotfile* is the name of the created PDF. *aa_order* is a list giving the order of amino acids from top to bottom. """ labelfrac = 0.01 # only label residues that rise above this level in legend # read input file aminoacids = mapmuts.sequtils.AminoAcids() colors = ['b', 'r', 'g', 'c', 'm', 'y' ] + ['k'] * len(aminoacids) # order corresponds to aa_order colors = colors[:len(aminoacids)] colors.reverse() aa_order.reverse() aa_indices = dict([(aa_order[i], i) for i in range(len(aa_order))]) lines = [ line for line in open(infile).readlines() if not (line.isspace() or line[0] == '#') ] dates = [] counts = [] aafracs = [[] for aa in aminoacids] for line in lines: entries = line.split('\t') dates.append(float(entries[0])) counts.append(int(entries[3])) i = 0 for aa in aminoacids: frac = float(entries[4 + i]) / counts[-1] aafracs[aa_indices[aa]].append(frac) i += 1 labeled_aas = [] for i in range(len(aa_order)): aa = aa_order[i] maxfrac = max(aafracs[i]) if maxfrac >= labelfrac: labeled_aas.append(aa) # make plot matplotlib.rc('font', size=9) fig = pylab.figure(figsize=(3, 1.9)) (lmargin, bmargin, rmargin, tmargin) = (0.15, 0.22, 0.01, 0.18) axis = pylab.axes( [lmargin, bmargin, 1.0 - lmargin - rmargin, 1.0 - tmargin - bmargin]) plotareas = pylab.stackplot(dates, aafracs, colors=colors) pylab.ylabel('fraction', size=10) pylab.xlabel('date', size=10) axis.set_ylim([0, 1.0]) yticker = matplotlib.ticker.FixedLocator([0.0, 0.5, 1.0]) axis.yaxis.set_major_locator(yticker) axis.set_xlim([min(dates), max(dates)]) dateticks = [ year for year in range(int(math.ceil(min(dates))), int(max(dates)) + 1) ] xticker = matplotlib.ticker.FixedLocator(dateticks) axis.xaxis.set_major_locator(xticker) yformatter = matplotlib.ticker.FixedFormatter( ['%d' % year for year in dateticks]) axis.xaxis.set_major_formatter(yformatter) patches = [] i = 0 assert len(aa_order) == len(plotareas) == len(colors) for (aa, color) in zip(aa_order, colors): if aa in labeled_aas: patch = pylab.Rectangle((0, 0), 1, 1, color=color) patches.append(patch) i += 1 assert len(labeled_aas) == len(patches) patches.reverse() labeled_aas.reverse() pylab.legend(patches, labeled_aas, ncol=len(labeled_aas), handlelength=0.8, fontsize=10, handletextpad=0.4, columnspacing=1, bbox_to_anchor=(0.5, 0.98), loc='lower center') print "Creating the plot file %s" % plotfile pylab.savefig(plotfile) print "Now making JPG version." jpgfile = "%s.jpg" % os.path.splitext(plotfile)[0] os.system('convert -density 500 %s %s' % (plotfile, jpgfile))
b=cnm.estimates.b, f=cnm.estimates.f, dims=cnm.estimates.dims, tottime='SEE VARIABLES t_XX', noisyC=cnm.estimates.noisyC, shifts=cnm.estimates.shifts, num_comps=cnm.estimates.A.shape[-1], t_online=cnm.t_online, t_detect=cnm.t_detect, t_shapes=cnm.t_shapes) cnm.save( os.path.join( base_folder, 'Zebrafish/results_analysis_online_1EPOCH_gSig6_equalized_Plane_NEW_' + str(ID) + '.hdf5')) #%% pl.figure() pl.stackplot( np.arange(len(cnm.t_detect)), 1e3 * np.array(cnm.t_motion), 1e3 * (np.array(cnm.t_online) - np.array(cnm.t_detect) - np.array(cnm.t_shapes) - np.array(cnm.t_motion)), 1e3 * np.array(cnm.t_detect), 1e3 * np.array(cnm.t_shapes)) pl.title('Processing time per frame') pl.xlabel('Frame #') pl.ylabel('Processing time [ms]') pl.ylim([0, 1000]) pl.legend(labels=['motion', 'process', 'detect', 'shapes']) #%% cnm.estimates.plot_contours()
utils = pad(utils) labels = ['ADAM', 'Avocado', 'Cannoli', 'BDG-Formats', 'Utils'] figure() title('Lines of code across the BDG projects over time') xlabel('Time') ylabel('Lines of source code') stackplot(dates, adam_core, adam_apis, adam_cli, adam_python, adam_r, avocado_core, avocado_cli, cannoli, formats, utils, colors = ["#FF0000", "#EE0000", "#DD0000", "#CC0000", "#BB0000", "#00FF00", "#00DD00", "#0000FF", "#FF00FF", "#808080"], edgecolor='none') legend([Patch(color="#FF0000"), Patch(color="#00FF00"), Patch(color="#0000FF"), Patch(color="#FF00FF"), Patch(color="#808080")], labels, loc=2) xlim(0, (last_date - start_date).days) xticks([0, (date(2014, 1, 1) - start_date).days, (date(2015, 1, 1) - start_date).days, (date(2016, 1, 1) - start_date).days,
def MakePlot(infile, plotfile, aa_order): """Makes plots from input file *infile*. *infile* contains the amino-acid frequencies over time. *plotfile* is the name of the created PDF. *aa_order* is a list giving the order of amino acids from top to bottom. """ labelfrac = 0.01 # only label residues that rise above this level in legend # read input file aminoacids = mapmuts.sequtils.AminoAcids() colors = ['b', 'r', 'g', 'c', 'm', 'y'] + ['k'] * len(aminoacids) # order corresponds to aa_order colors = colors[ : len(aminoacids)] colors.reverse() aa_order.reverse() aa_indices = dict([(aa_order[i], i) for i in range(len(aa_order))]) lines = [line for line in open(infile).readlines() if not (line.isspace() or line[0] == '#')] dates = [] counts = [] aafracs = [[] for aa in aminoacids] for line in lines: entries = line.split('\t') dates.append(float(entries[0])) counts.append(int(entries[3])) i = 0 for aa in aminoacids: frac = float(entries[4 + i]) / counts[-1] aafracs[aa_indices[aa]].append(frac) i += 1 labeled_aas = [] for i in range(len(aa_order)): aa = aa_order[i] maxfrac = max(aafracs[i]) if maxfrac >= labelfrac: labeled_aas.append(aa) # make plot matplotlib.rc('font', size=9) fig = pylab.figure(figsize=(3, 1.9)) (lmargin, bmargin, rmargin, tmargin) = (0.15, 0.22, 0.01, 0.18) axis = pylab.axes([lmargin, bmargin, 1.0 - lmargin - rmargin, 1.0 - tmargin - bmargin]) plotareas = pylab.stackplot(dates, aafracs, colors=colors) pylab.ylabel('fraction', size=10) pylab.xlabel('date', size=10) axis.set_ylim([0, 1.0]) yticker = matplotlib.ticker.FixedLocator([0.0, 0.5, 1.0]) axis.yaxis.set_major_locator(yticker) axis.set_xlim([min(dates), max(dates)]) dateticks = [year for year in range(int(math.ceil(min(dates))), int(max(dates)) + 1)] xticker = matplotlib.ticker.FixedLocator(dateticks) axis.xaxis.set_major_locator(xticker) yformatter = matplotlib.ticker.FixedFormatter(['%d' % year for year in dateticks]) axis.xaxis.set_major_formatter(yformatter) patches = [] i = 0 assert len(aa_order) == len(plotareas) == len(colors) for (aa, color) in zip(aa_order, colors): if aa in labeled_aas: patch = pylab.Rectangle((0, 0), 1, 1, color=color) patches.append(patch) i += 1 assert len(labeled_aas) == len(patches) patches.reverse() labeled_aas.reverse() pylab.legend(patches, labeled_aas, ncol=len(labeled_aas), handlelength=0.8, fontsize=10, handletextpad=0.4, columnspacing=1, bbox_to_anchor=(0.5, 0.98), loc='lower center') print "Creating the plot file %s" % plotfile pylab.savefig(plotfile) print "Now making JPG version." jpgfile = "%s.jpg" % os.path.splitext(plotfile)[0] os.system('convert -density 500 %s %s' % (plotfile, jpgfile))
beta=0.015, n_days=90, ) # Define the prioritization function def prioritize_by_age(people): return np.argsort(-people.age) # Record the number of doses each person has received each day so # that we can plot the rollout in this example. Without a custom # analyzer, only the total number of doses will be recorded n_doses = [] # Define sequence based vaccination pfizer = cv.vaccinate_num(vaccine='pfizer', sequence=prioritize_by_age, num_doses=100) sim = cv.Sim(pars=pars, interventions=pfizer, analyzers=lambda sim: n_doses.append(sim.people.doses.copy())) sim.run() pl.figure() n_doses = np.array(n_doses) fully_vaccinated = (n_doses == 2).sum(axis=1) first_dose = (n_doses == 1).sum(axis=1) pl.stackplot(sim.tvec, first_dose, fully_vaccinated) pl.legend(['First dose', 'Fully vaccinated']) pl.show()
if code=='2': quotas[1].append(cuml) if code=='3': quotas[2].append(cuml) if code=='4': quotas[3].append(cuml) if code=='6': quotas[4].append(cuml) if code=='7': quotas[5].append(cuml) years = range(1989,2013) print quotas plot = plt.stackplot(years,quotas[0],quotas[1],quotas[2],quotas[3],quotas[4],quotas[5], colors=['#377EB8','#7E1137','y','r','m','#55BA87']) plt.legend(["East Asia & Pacific","Europe & Central Asia","Latin America","Middle East & N Africa","South Asia","Sub-Saharan Africa"], loc='upper left') plt.xlim(1989,2012) plt.ylabel('Total Number of Countries with a Gender Quota') plt.xlabel('Year') plt.savefig('quotas/quotasStacked.png') plt.savefig('quotas/quotasStacked.eps',bbox_inches='tight') plt.gcf().clear() #Reserved Only data = open('quotaTimesRes.csv','r') quotas = [[],[],[],[],[],[]]
formats.append(formats[-1]) utils.append(utils[-1]) labels = ['ADAM', 'Avocado', 'Cannoli', 'BDG-Formats', 'Utils'] figure() title('Unique contributors across the BDG projects over time') xlabel('Time') ylabel('Unique contributors') stackplot(dates, adam, avocado, cannoli, formats, utils, colors = ["#FF0000", "#00FF00", "#0000FF", "#FF00FF", "#808080"]) legend([Patch(color="#FF0000"), Patch(color="#00FF00"), Patch(color="#0000FF"), Patch(color="#FF00FF"), Patch(color="#808080")], ['ADAM', 'Avocado', 'Cannoli', 'bdg-formats', 'bdg-utils'], loc=2) xlim(0, (last_date - start_date).days) xticks([0, (date(2014, 1, 1) - start_date).days, (date(2015, 1, 1) - start_date).days, (date(2016, 1, 1) - start_date).days, (date(2017, 1, 1) - start_date).days,
try: with h5py.File(fname, "r") as h5: Hp = h5[table][:] except KeyError, e: logger.info("Failed to read data from %s: %s" % (fname, e)) exit(1) except IOError, e: logger.info("Failed to open %s fname: %s" % (fname, e)) exit(1) epochs = Hp.shape[0] n_layers = Hp.shape[1] if args.stacked: ylim = 2 * Hp[-1].sum() pylab.ylim([ylim, 0]) pylab.stackplot(np.arange(epochs), Hp[:, ::-1].T) else: ylim = 2 * Hp[-1].min() pylab.ylim([ylim, 0]) pylab.plot(Hp) #pylab.figsize(12, 8) pylab.xlabel("Epochs") #pylab.ylabel("avg_{x~testdata} log( E_{h~q}[p(x,h)/q(h|x)]") pylab.legend(["layer %d" % i for i in xrange(n_layers)], loc="lower right") pylab.show(block=True)
import numpy as np import pylab as plt Y = [[3,4,5,6],[2,2,2,2],[1,2,3,1]] X = range(4) plt.stackplot(X, Y, baseline="zero") plt.show()