def plot_data_mlp_to_html(data_points, labels=[]): # print(len(dataPoints)) data_points = cull_to_number(data_points, 250) # print(len(dataPoints)) # print(dataPoints) swap = swapaxes(data_points, 0, 1) # print(swap) timescale = [] for i, date in enumerate(swap[0]): parsedDate = datetime.datetime.strptime(date, '%m/%d/%y %H:%M:%S') timescale.append(parsedDate) # timescale = [datetime.datetime.strptime(date, '%m/%d/%y %H:%M:%S') for date in swap[0]] dates = matplotlib.dates.date2num(timescale) fig, ax = plt.subplots(figsize=[9.28, 4.8]) plt.rcParams.update({'figure.autolayout': True}) ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(10)) ax.grid(which='major', axis='both', linestyle="-", alpha=0.25, linewidth=1) ax.tick_params(labelsize='medium', width=1) # Read labels from list p1 = ax.plot_date(dates, swap[1], color='red', linestyle='solid', marker=None, label=labels[0]) p2 = ax.plot_date(dates, swap[2], color='green', linestyle='solid', marker=None, label=labels[1]) p3 = ax.plot_date(dates, swap[3], color='blue', linestyle='solid', marker=None, label=labels[2]) s1 = ax.scatter(dates, swap[1], color='#00000000', s=50) s2 = ax.scatter(dates, swap[2], color='#00000000', s=50) s3 = ax.scatter(dates, swap[3], color='#00000000', s=50) ax.legend() # xlabels = ax.get_xticklabels() # plt.setp(xlabels, rotation=30, horizontalalignment='right') ax.set(ylim=[0, 100], xlabel='Dată', ylabel='Procent (%)', title='Grafic umiditate plante') # Create HTML plugins.clear(fig) tooltip_plugin1 = plugins.PointLabelTooltip( s1, extract_point_position(swap[0], swap[1])) tooltip_plugin2 = plugins.PointLabelTooltip( s2, extract_point_position(swap[0], swap[2])) tooltip_plugin3 = plugins.PointLabelTooltip( s3, extract_point_position(swap[0], swap[3])) plugins.connect(fig, tooltip_plugin1, tooltip_plugin2, tooltip_plugin3, plugins.Zoom(), plugins.Reset()) html_str = fig_to_html(fig) return html_str
def gen_html(self, dataset=None, channels=["FSC-A", "SSC-A"]): if not dataset: dataset = self.dataset data = [dataset[i].values for i in channels] fig = plt.figure() ax = fig.add_subplot(111) plot = ax.scatter(data[0], data[1]) plugins.clear(fig) plugins.connect(fig, plugins.LinkedBrush(plot), plugins.ClickSendToBack(plot)) the_html = mpld3.fig_to_html(fig) with open("initialfigure.html", "w") as file: file.write(the_html) o = bs(open("initialfigure.html"), "html.parser") script = str(o.find_all("script")[0]) script_2 = script.replace("<script>", "").replace("</script>", "") with open("the_figure.js", "w") as file: file.write(script_2) with open("the_figure.html", "w") as file: the_html = the_html.replace( script, "<script src='.\\the_figure.js'></script>") file.write(the_html)
def create_plot(): fig, ax = plt.subplots() points = ax.scatter(np.random.rand(50), np.random.rand(50), s=500, alpha=0.3) plugins.clear(fig) plugins.connect(fig, plugins.Reset(), plugins.Zoom(), ClickInfo(points)) return fig
def create_plot(): fig, ax = plt.subplots() points = ax.scatter(random_x, random_y, s=500, alpha=0.3) plugins.clear(fig) ax.set_title('Click info', size=14) plugins.connect(fig, plugins.Reset(), plugins.Zoom(), ClickInfo(points)) return fig
def plot_vdot_race(data): #CSS element for the tooltip label css = """ div { font-family: Avenir, Helvetica, sans-serif; border: 1px solid black; padding-left: 5px; padding-right: 5px; text-align: center; color: #000000; background-color: #ffffff; } """ #plt.style.use('seaborn-poster') #sets the size of the charts plt.style.use('ggplot') x_axis = [] y_axis = [] label = [] #print (data) for key in data: label.append("Race: " + str(data[key][1]) + "<br/>" + "VDOT: " + str(data[key][3])) y_axis.append(data[key][3]) datetime_obj = datetime.strptime(data[key][4], '%Y-%m-%d %H:%M:%S+00:00') x_axis.append(datetime_obj) dates = matplotlib.dates.date2num(x_axis) fig, ax = plt.subplots() plt.xlabel("Race dates", fontsize=20) plt.ylabel("VDOT Scores", fontsize=20) plt.title("VDOT Score Over Time", fontsize=25) line = plt.plot_date(dates, y_axis, linestyle='solid', marker='.', markersize=14) plugins.clear(fig) # clear all plugins from the figure tooltip = plugins.PointHTMLTooltip(line[0], label, hoffset=-60, voffset=-70, css=css) plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom(), tooltip) return mpld3.fig_to_html(fig)
def make_html_plot_for_file(filename, my_title): my_fontsize = 20 # read in csv file if os.stat(filename).st_size: data = np.genfromtxt(filename, delimiter=',') else: # empty data file data = np.zeros([2, 2]) if len(data.shape) == 1: return "<h2> " + my_title + " has no data </h2>" x = data[:, 0] fig, ax = plt.subplots(figsize=(10, 5)) for k in range(1, data.shape[1]): y = data[:, k] # sort data x_sorted = [x1 for (x1, y1) in sorted(zip(x, y))] y_sorted = [y1 for (x1, y1) in sorted(zip(x, y))] lines = ax.plot(x_sorted, y_sorted, '.-', markersize=15, label='ion ' + str(k - 1)) plt.legend(fontsize=my_fontsize, loc='best') plt.title(my_title, fontsize=my_fontsize) ax.grid() plt.xticks(fontsize=my_fontsize) plt.yticks(fontsize=my_fontsize) plt.xlim([np.min(x), np.max(x)]) #90% of the time that this function takes is taken up after this line plugins.clear(fig) plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom(enabled=True), plugins.MousePosition(fontsize=my_fontsize)) java_txt = mpld3.fig_to_html(fig) plt.close() return java_txt
def spladder_viz(options): """Main visualization code""" ### parse parameters from options object options = settings.parse_args(options, identity='viz') ### create plot directory if it does not exist yet if options.testdir != '-': dirname = options.testdir else: dirname = options.outdir if not os.path.exists(os.path.join(dirname, 'plots')): os.mkdir(os.path.join(dirname, 'plots')) if options.format == 'd3': try: import mpld3 from mpld3 import plugins except ImportError: sys.stderr.write("ERROR: missing package for output format d3. Package mpld3 required") sys.exit(1) ### load gene information gene_names = get_gene_names(options) rows = get_plot_len(options) gs = gridspec.GridSpec(rows, 1) ### set color maps cmap_cov = plt.get_cmap('jet') cmap_edg = plt.get_cmap('jet') ### plot log scale? log_tag = '' if options.log: log_tag = '.log' event_tag = '' ### did we get any labels? if ',' in options.labels: options.labels = options.labels.strip(',').split(',') assert len(options.labels) == len(options.bam_fnames), "The number of given labels (%i) needs to match the number of given bam file groups (%i)" % (len(options.labels), len(options.bam_fnames)) # Collect genes to be plotted - there are three cases possible # 1) the user provides a gene ID # 2) all genes containing a significant event of a given type from differential testing are plotted # 3) all genes that contain any event are plotted ### the user chose a specific gene for plotting ### create pairs of gene ids and an event_id (the latter is None by default) if options.gene_name is not None: gids = [[sp.where(sp.array(gene_names) == options.gene_name)[0][0], options.event_id]] if len(gids) == 0: sys.stderr.write('ERROR: provided gene ID %s could not be found, please check for correctness\n' % options.gene_name) sys.exit(1) ### the plotting happens on the results of spladder test ### the user chooses to plot the top k significant events ### this requires the event type to be specified elif options.test_result > 0: gene_names = [] for event_type in options.event_types: ### the testing script should generate a setup file for the test ### SETUP is structured as follows: ### [gene_strains, event_strains, dmatrix0, dmatrix1, event_type, options] labels = options.test_labels.split(':') options.labels = labels if options.testdir != '-': testdir = dirname else: testdir = os.path.join(dirname, 'testing_%s_vs_%s' % (labels[0], labels[1])) SETUP = pickle.load(open(os.path.join(testdir, 'test_setup_C%i_%s.pickle' % (options.confidence, event_type)), 'rb')) ### get strains to plot idx1 = sp.where(sp.in1d(SETUP[0], SETUP[6]['conditionA']))[0] idx2 = sp.where(sp.in1d(SETUP[0], SETUP[6]['conditionB']))[0] ### load test results for l, line in enumerate(open(os.path.join(testdir, 'test_results_C%i_%s.tsv' % (options.confidence, event_type)), 'r')): if l == 0: continue if l > options.test_result: break sl = line.strip().split('\t') gene_names.append([sl[1], sl[0]]) gids = get_gene_ids(options, gene_names) ### no gene specified but result provided - plot all genes with confirmed events ### if an event_id is provided, only the associated gene will be plotted else: gids = get_gene_ids(options) ### iterate over genes to plot for gid in gids: ### gather information about the gene we plot gene = load_genes(options, idx=[gid[0]])[0] if options.verbose: print('plotting information for gene %s' % gene.name) gene.from_sparse() ### event to plot is specified with the gene id list if gid[1] is not None: event_info = [x[::-1] for x in re.split(r'[._]', gid[1][::-1], maxsplit=1)[::-1]] event_info[1] = int(event_info[1]) - 1 event_info = sp.array(event_info, dtype='str')[sp.newaxis, :] event_tag = '.%s' % gid[1] ### get all confident events of the current gene else: event_info = get_conf_events(options, gid[0]) ### go over different plotting options axes = [] ### plot result of testing if options.test_result > 0: fig = plt.figure(figsize = (9, 5), dpi=200) gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) _add_ax(fig, axes, gs) _add_ax(fig, axes, gs) _plot_event(options, event_info, fig, axes[1], gs, None, padding=100) start, stop = axes[1].get_xlim() plot_bam(options, gene, options.bam_fnames, fig, axes[0], gs, None, cmap_cov, cmap_edg, single=False, sharex=axes[1], start=int(start), stop=int(stop)) ### plot custom layout else: ### set defaults if not options.user: options.splicegraph = True options.transcripts = True if options.format == 'd3': fig = plt.figure(figsize = (12, 2*rows), dpi=100) else: fig = plt.figure(figsize = (18, 3*rows), dpi=200) xlim = None ### plot splicing graph if options.splicegraph: _plot_splicegraph(gene, fig, axes, gs) xlim = axes[-1].get_xlim() ### plot annotated transcripts if options.transcripts: sharex = None if len(axes) == 0 else axes[0] axes.append(fig.add_subplot(gs[len(axes), 0], sharex=sharex)) multiple(gene.exons, ax=axes[-1], x_range=xlim) axes[-1].set_title('Annotated Transcripts') ### plot coverage information for a set of given samples if len(options.bam_fnames) > 0: plot_bam(options, gene, options.bam_fnames, fig, axes, gs, xlim, cmap_cov, cmap_edg) ### plot all the samples in a single plot if len(options.bam_fnames) > 1: plot_bam(options, gene, options.bam_fnames, fig, axes, gs, xlim, cmap_cov, cmap_edg, single=False) ### plot segment counts if len(options.bam_fnames) == 0 or False: # add option for segment plots if options.test_result > 0: _plot_segments(options, gid, fig, axes, gs, [idx1, idx2]) else: _plot_segments(options, gid, fig, axes, gs) ### plot structure of a single given event _plot_event(options, event_info, fig, axes, gs, xlim) ### we only need to adapt the xoom for one axis object - as we share the x zoom_x = [float(x) for x in options.zoom_x.split(',')] xlim = axes[0].get_xlim() xdiff = xlim[1] - xlim[0] axes[0].set_xlim([xlim[0] + (zoom_x[0] * xdiff), xlim[0] + (zoom_x[1] * xdiff)]) for ax in axes: vax.clean_axis(ax) plt.tight_layout() ### save plot into file if options.format == 'd3': out_fname = os.path.join(dirname, 'plots', 'gene_overview_C%i_%s%s%s.html' % (options.confidence, gene.name, event_tag, log_tag)) plugins.clear(fig) plugins.connect(fig, plugins.Zoom(enabled=True)) mpld3.save_html(fig, open(out_fname, 'w')) else: if options.test_result > 0: out_fname = os.path.join(dirname, 'plots', 'gene_overview_C%i_%s%s%s.%s' % (options.confidence, gene.name, event_tag, log_tag, options.format)) else: out_fname = os.path.join(dirname, 'plots', 'gene_overview_C%i_%s%s%s.%s' % (options.confidence, gene.name, event_tag, log_tag, options.format)) plt.savefig(out_fname, format=options.format, bbox_inches='tight') plt.close(fig)
def plot_beats_per_mile(data): #divide meters by this factor to get in terms of miles convert_meters_to_miles = 1609.344 #plt.style.use('seaborn-poster') #sets the size of the charts plt.style.use('ggplot') #Data is dictionary mapping id to (activity_name, start_date_local, average_hr, distance, total_elevation_gain) data_by_week = {} for key in data: datetime_obj = datetime.strptime(data[key][1], '%Y-%m-%d %H:%M:%S') year_week_val = datetime_obj.isocalendar()[:-1] if year_week_val not in data_by_week: #Storing average_hr, distance, total_elevation_gain data_by_week[year_week_val] = [(data[key][2], data[key][3], data[key][4])] else: data_by_week[year_week_val].append( (data[key][2], data[key][3], data[key][4])) x_axis = [] x_label = [] y_axis = [] for key in data_by_week: print(key) total_hr_each_week = 0 distance_week = 0 for activity in data_by_week[key]: total_hr_each_week += activity[0] * (activity[1] / convert_meters_to_miles) distance_week += activity[1] / convert_meters_to_miles avg_hr_per_mile = total_hr_each_week / distance_week x_label.append(str(key[0]) + "-" + str(key[1])) x_axis.append(key[0] * 52 + key[1]) y_axis.append(avg_hr_per_mile) total_hr_each_week = 0 distance_week = 0 fig, ax = plt.subplots() plt.xlabel("Weeks", fontsize=20) plt.ylabel("Average Heartrate Per Mile", fontsize=20) plt.title("Average Heartrate Per Mile Sorted by Week", fontsize=25) line = plt.plot(x_axis, y_axis, linestyle='solid', marker='.', markersize=14) x = np.asarray(x_axis) y = np.asarray(y_axis) b, m = polyfit(x, y, 1) #Plots regression line plt.plot(x, b + m * x, linestyle='solid') plugins.clear(fig) # clear all plugins from the figure #tooltip = plugins.PointHTMLTooltip(line[0], label, #hoffset = -60, voffset = -70, css = css) plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom()) return mpld3.fig_to_html(fig)
def plotPower(sid, MCP='', pow=0, ss=0): powerdata = PowerTableModel.objects.filter(SID=sid)[::-1][0] parsdata = ParameterModel.objects.filter(SID=sid)[::-1][0] powtab = powerdata.data powtxt = powtab.round(2) cols = dict(zip(['BF', 'BH', 'RFT', 'UN'], Set1_9.mpl_colors)) sub = int(parsdata.Subj) newsubs = powtab.newsamplesize amax = int(50) css = """ table{border-collapse: collapse} td{background-color: rgba(217, 222, 230,50)} table, th, td{border: 1px solid;border-color: rgba(217, 222, 230,50);text-align: right;font-size: 12px} """ hover_BF = [ pd.DataFrame([ 'Bonferroni', 'Sample Size: ' + str(newsubs[i]), 'Power: ' + str(powtxt['BF'][i]) ]).to_html(header=False, index_names=False, index=False) for i in range(len(powtab)) ] hover_BH = [ pd.DataFrame([ 'Benjamini-Hochberg', 'Sample Size: ' + str(newsubs[i]), 'Power: ' + str(powtxt['BH'][i]) ]).to_html(header=False, index_names=False, index=False) for i in range(len(powtab)) ] hover_RFT = [ pd.DataFrame([ 'Random Field Theory', 'Sample Size: ' + str(newsubs[i]), 'Power: ' + str(powtxt['RFT'][i]) ]).to_html(header=False, index_names=False, index=False) for i in range(len(powtab)) ] hover_UN = [ pd.DataFrame([ 'Uncorrected', 'Sample Size: ' + str(newsubs[i]), 'Power: ' + str(powtxt['UN'][i]) ]).to_html(header=False, index_names=False, index=False) for i in range(len(powtab)) ] fig, axs = plt.subplots(1, 1, figsize=(8, 5)) fig.patch.set_facecolor('None') lty = ['--' if all(powtab.BF == powtab.RFT) else '-'] BF = axs.plot(newsubs, powtab.BF, 'o', markersize=15, alpha=0, label="") BH = axs.plot(newsubs, powtab.BH, 'o', markersize=15, alpha=0, label="") RFT = axs.plot(newsubs, powtab.RFT, 'o', markersize=15, alpha=0, label="") UN = axs.plot(newsubs, powtab.UN, 'o', markersize=15, alpha=0, label="") plugins.clear(fig) plugins.connect( fig, plugins.PointHTMLTooltip(BF[0], hover_BF, hoffset=0, voffset=10, css=css)) plugins.connect( fig, plugins.PointHTMLTooltip(BH[0], hover_BH, hoffset=0, voffset=10, css=css)) plugins.connect( fig, plugins.PointHTMLTooltip(RFT[0], hover_RFT, hoffset=0, voffset=10, css=css)) plugins.connect( fig, plugins.PointHTMLTooltip(UN[0], hover_UN, hoffset=0, voffset=10, css=css)) axs.plot(newsubs, powtab.BF, color=cols['BF'], lw=2, label="Bonferroni") axs.plot(newsubs, powtab.BH, color=cols['BH'], lw=2, label="Benjamini-Hochberg") axs.plot(newsubs, powtab.RFT, color=cols['RFT'], lw=2, linestyle=str(lty[0]), label="Random Field Theory") axs.plot(newsubs, powtab.UN, color=cols['UN'], lw=2, label="Uncorrected") text = "None" if pow != 0: if all(powtab[MCP] < pow): text = "To obtain a statistical power of " + str( pow ) + " this study would require a sample size larger than 300 subjects." else: min = int( np.min( [i for i, elem in enumerate(powtab[MCP] > pow, 1) if elem]) + sub - 1) axs.plot([min, min], [0, powtab[MCP][min - sub]], color=cols[MCP]) axs.plot([sub, min], [powtab[MCP][min - sub], powtab[MCP][min - sub]], color=cols[MCP]) text = "To obtain a statistical power of %s this study would require a sample size of %s subjects." % ( pow, min) amax = max(min, amax) if ss != 0: ss_pow = powtab[MCP][ss] axs.plot([ss, ss], [0, ss_pow], color=cols[MCP], linestyle="--") axs.plot([sub, ss], [ss_pow, ss_pow], color=cols[MCP], linestyle="--") xticks = [ x for x in list(np.arange((np.ceil(sub / 10.)) * 10, 100, 10)) if not x == np.round(ss / 10.) * 10 ] axs.set_xticks(xticks + [ss]) axs.set_yticks(list(np.arange(0, 1.1, 0.1))) text = "A sample size of %s subjects with %s control comes with a power of %s." % ( ss, MCP, str(np.round(ss_pow, decimals=2))) amax = max(ss, amax) axs.set_ylim([0, 1]) axs.set_xlim([sub, amax]) axs.set_title("Power curves") axs.set_xlabel("Subjects") axs.set_ylabel("Average power") axs.legend(loc="lower right", frameon=False, title="") code = mpld3.fig_to_html(fig) out = {"code": code, "text": text} return out
def problem_view(request, problem_id): user = request.user problem = get_object_or_404(Problem, id=problem_id) if problem.user_id != user and not user.is_superuser: raise PermissionDenied parse_error = False a = None b = None c = None a_copy = None b_copy = None result = None figure = None parse_result = parse_problem(problem.problem_text) print parse_result if parse_result is not None: a, b, c, x = parse_result if a and b and c and x: result = simple_simplex(copy.deepcopy(a), copy.deepcopy(b), copy.deepcopy(c)) b.pop(0) a_copy = copy.deepcopy(a) b_copy = copy.deepcopy(b) if len(x) is 2: tmp = [0, 0] tmp[1] = 1 a.insert(0, copy.deepcopy(tmp)) tmp[0] = 1 tmp[1] = 0 a.insert(0, copy.deepcopy(tmp)) b.insert(0, 0) b.insert(0, 0) dots = [] for i in range(len(b)): dots.append([]) shape_x = [] for i in xrange(0, len(b)): for j in xrange(i + 1, len(b)): if a[i][0] == a[j][0] and a[i][1] == a[j][1]: continue shape_a = np.array([[a[i][0], a[i][1]], [a[j][0], a[j][1]]]) shape_b = np.array([b[i], b[j]]) res = np.linalg.solve(shape_a, shape_b) dots[i].append(res) dots[j].append(res) # fig, ax = plt.subplots() fig = plt.figure() ax = fig.add_subplot(111) for dot in dots: ax.plot( [float(dot[0][0]), float(dot[1][0])], [float(dot[0][1]), float(dot[1][1])], ls='-', color='green', marker='o', lw=2) # print([dot[0], dot[1]]) ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_title('Plot of 2D Problem!', size=14) plugins.clear(fig) plugins.connect(fig, plugins.Reset(), plugins.Zoom(enabled=True), plugins.BoxZoom()) figure = fig_to_html(fig, d3_url=STATIC_URL + 'js/d3.min.js', mpld3_url=STATIC_URL + 'js/mpld3.v0.2.js', use_http=True) else: figure = 'Larger than 2D!' else: parse_error = True return render_to_response( 'problems/view.html', { 'user': user, 'problem': problem, 'parse_error': parse_error, 'figure': figure, 'a': a_copy, 'b': b_copy, 'c': c, 'result': result, 'view_name': 'Problem - %s' % problem.id, })
def plotPower(sid,MCP='',pow=0,ss=0): powerdata = PowerTableModel.objects.filter(SID=sid)[::-1][0] parsdata = ParameterModel.objects.filter(SID=sid)[::-1][0] powtab = powerdata.data powtxt = powtab.round(2) cols = dict(zip(['BF','BH','RFT','UN'],Set1_9.mpl_colors)) sub = int(parsdata.Subj) newsubs = powtab.newsamplesize amax = int(np.min(powtab.newsamplesize)+50) css = """ table{border-collapse: collapse} td{background-color: rgba(217, 222, 230,50)} table, th, td{border: 1px solid;border-color: rgba(217, 222, 230,50);text-align: right;font-size: 12px} """ hover_BF = [pd.DataFrame(['Bonferroni','Sample Size: '+str(newsubs[i]),'Power: '+str(powtxt['BF'][i])]).to_html(header=False,index_names=False,index=False) for i in range(len(powtab)) if 'BF' in powtab.columns] hover_BH = [pd.DataFrame(['Benjamini-Hochberg','Sample Size: '+str(newsubs[i]),'Power: '+str(powtxt['BH'][i])]).to_html(header=False,index_names=False,index=False) for i in range(len(powtab)) if 'BH' in powtab.columns] hover_RFT = [pd.DataFrame(['Random Field Theory','Sample Size: '+str(newsubs[i]),'Power: '+str(powtxt['RFT'][i])]).to_html(header=False,index_names=False,index=False) for i in range(len(powtab)) if 'RFT' in powtab.columns] hover_UN = [pd.DataFrame(['Uncorrected','Sample Size: '+str(newsubs[i]),'Power: '+str(powtxt['UN'][i])]).to_html(header=False,index_names=False,index=False) for i in range(len(powtab)) if 'UN' in powtab.columns] fig,axs=plt.subplots(1,1,figsize=(8,5)) fig.patch.set_facecolor('None') lty = ['--' if all(powtab.BF==powtab.RFT) else '-'] BF=axs.plot(powtab.newsamplesize,powtab.BF,'o',markersize=15,alpha=0,label="") if 'BF' in powtab.columns else 'nan' BH=axs.plot(powtab.newsamplesize,powtab.BH,'o',markersize=15,alpha=0,label="") if 'BH' in powtab.columns else 'nan' RFT=axs.plot(powtab.newsamplesize,powtab.RFT,'o',markersize=15,alpha=0,label="") if 'RFT' in powtab.columns else 'nan' UN=axs.plot(powtab.newsamplesize,powtab.UN,'o',markersize=15,alpha=0,label="") if 'UN' in powtab.columns else 'nan' plugins.clear(fig) plugins.connect(fig, plugins.PointHTMLTooltip(BF[0], hover_BF,hoffset=0,voffset=10,css=css)) plugins.connect(fig, plugins.PointHTMLTooltip(RFT[0], hover_RFT,hoffset=0,voffset=10,css=css)) plugins.connect(fig, plugins.PointHTMLTooltip(UN[0], hover_UN,hoffset=0,voffset=10,css=css)) if 'BH' in powtab.columns: plugins.connect(fig, plugins.PointHTMLTooltip(BH[0], hover_BH,hoffset=0,voffset=10,css=css)) axs.plot(newsubs,powtab.BH,color=cols['BH'],lw=2,label="Benjamini-Hochberg") axs.plot(newsubs,powtab.BF,color=cols['BF'],lw=2,label="Bonferroni") axs.plot(newsubs,powtab.RFT,color=cols['RFT'],lw=2,linestyle=str(lty[0]),label="Random Field Theory") axs.plot(newsubs,powtab.UN,color=cols['UN'],lw=2,label="Uncorrected") text = "None" if pow != 0: if MCP == 'BH' and not 'BH' in powtab.columns: text = "There is not enough power to estimate a threshold for FDR control. As such it's impossible to predict power for FDR control." elif all(powtab[MCP]<pow): text = "To obtain a statistical power of "+str(pow)+" this study would require a sample size larger than 600 subjects." amax = max(powtab.newsamplesize) else: min = int(np.min([i for i,elem in enumerate(powtab[MCP]>pow,1) if elem])+sub-1) axs.plot([min,min],[0,powtab[MCP][min-sub]],color=cols[MCP]) axs.plot([sub,min],[powtab[MCP][min-sub],powtab[MCP][min-sub]],color=cols[MCP]) text = "To obtain a statistical power of %s this study would require a sample size of %s subjects." %(pow,min) amax = max(min,amax) if ss != 0: if MCP == 'BH' and not 'BH' in powtab.columns: text = "There is not enough power to estimate a threshold for FDR control. As such it's impossible to predict power for FDR control." else: ss_pow = powtab[MCP][ss] axs.plot([ss,ss],[0,ss_pow],color=cols[MCP],linestyle="--") axs.plot([sub,ss],[ss_pow,ss_pow],color=cols[MCP],linestyle="--") xticks = [x for x in list(np.arange((np.ceil(sub/10.))*10,100,10)) if not x == np.round(ss/10.)*10] axs.set_xticks(xticks+[ss]) axs.set_yticks(list(np.arange(0,1.1,0.1))) text = "A sample size of %s subjects with %s control comes with a power of %s." %(ss,MCP,str(np.round(ss_pow,decimals=2))) amax = max(ss,amax) axs.set_ylim([0,1]) axs.set_xlim([sub,amax]) axs.set_title("Power curves") axs.set_xlabel("Subjects") axs.set_ylabel("Average power") axs.legend(loc="lower right",frameon=False,title="") code = mpld3.fig_to_html(fig) out = { "code":code, "text":text } return out
def shallow_water(ql=np.array([3.0, 5.0]), qr=np.array([3.0, -5.0]), g=1.0, time=2.0, tmax=5.0, hmax=None, humin=None, humax=None): # Create figure # Create a figure #fig, axfull = plt.subplots(2,2, figsize=(13, 12)) fig, axfull = plt.subplots(2,2, figsize=(10, 8)) fig.subplots_adjust(left=0.05, right=0.9, bottom=0.1, top=0.9, hspace=0.3, wspace=0.15) # Have to do this to avoid issue with mpld3 ax = axfull[0] # First row of plots axsol = axfull[1] # Second row of plost # Calculate dq with ql and qr and other parameters dq = np.array([qr[0]-ql[0], qr[1]-ql[1]]) iters = 100 iter_charac = 2 # eps required for bug in mpld3 (ql[0] cannot be the same than qr[0]) eps = 0.00000001 # Calculate plotting boundaries if not specified if hmax is None: hmax = max(ql[0],qr[0]) + 7.0 if humax is None: humax = 3*max(abs(ql[1]),abs(qr[1])) if humin is None: humin = -3*max(abs(ql[1]),abs(qr[1])) # PLOT PHASE PLANE xxL = np.linspace(0,ql[0],iters) xxL2 = np.linspace(ql[0],hmax,iters) xxR = np.linspace(0,qr[0]+eps,iters) xxR2 = np.linspace(qr[0]+eps,hmax,iters) #Plot midpoint qm = -1 +0.0*ql midpoint = ax[0].plot(qm[0],qm[1],'ok', alpha=0.9, markersize=8, markeredgewidth=1) # Plot hugoloci initial state yyL = hugoloci(g,xxL,ql[0],ql[1],-1) yyL2 = hugoloci(g,xxL2,ql[0],ql[1],-1) yyR = hugoloci(g,xxR,qr[0],qr[1],1) yyR2 = hugoloci(g,xxR2,qr[0],qr[1],1) hugol = ax[0].plot(xxL,yyL, '--r', linewidth=1.5) hugol2 = ax[0].plot(xxL2,yyL2, '-r', linewidth=2, label = 'Hugoniot Loci') hugor = ax[0].plot(xxR,yyR, '--r', linewidth=1.5, label = 'Hugoniot Loci (unphysical)') hugor2 = ax[0].plot(xxR2,yyR2, '-r', linewidth=2) # Plot integral curve initial state yyL = intcurve(g,xxL,ql[0],ql[1],-1) yyL2 = intcurve(g,xxL2,ql[0],ql[1],-1) yyR = intcurve(g,xxR,qr[0],qr[1],1) yyR2 = intcurve(g,xxR2,qr[0],qr[1],1) intcl = ax[0].plot(xxL,yyL, '-b', linewidth=2, label = 'Integral Curves') intcl2 = ax[0].plot(xxL2,yyL2, '--b', linewidth=1.5, label = 'Integral Curves (unphysical)') intcr = ax[0].plot(xxR,yyR, '-b', linewidth=2) intcr2 = ax[0].plot(xxR2,yyR2, '--b', linewidth=1.5) # Plot ql and qr points = ax[0].plot([ql[0],qr[0]], [ql[1], qr[1]], 'ok', alpha=0.7, markersize=10, markeredgewidth=1) #data = ["q_l", "q_r"] # Plot markers offsetx = 0.3*hmax/10 offsety = -3*offsetx qlmarker = ax[0].plot(ql[0]+offsetx, ql[1]+offsety, 'ok', marker=(r"$ q_l $"), markersize=15) qmmarker = ax[0].plot(qm[0]+offsetx, qm[1]+offsety, 'ok', marker=(r"$ q_m $"), markersize=15) qrmarker = ax[0].plot(qr[0]+offsetx, qr[1]+offsety, 'ok', marker=(r"$ q_r $"), markersize=15) # Set axis 1 properties ax[0].set_title("Phase plane", fontsize=18) ax[0].axis([0,hmax,humin,humax]) ax[0].set_xlabel('h', fontsize=17) ax[0].set_ylabel('hu', fontsize=17) #ax[0].set_aspect('equal') ax[0].grid(alpha=0.1,color='k', linestyle='--') legend = ax[0].legend(loc='upper left', shadow=True, fontsize = 8) # PLOT x-t PLANE x_xtp = np.linspace(-10,10,iter_charac) x_xtp2 = np.linspace(-11,11,iter_charac) # Shock speeds lam1 and lam2 lam2 = ql[1]/ql[0] - np.sqrt(g*ql[0]) lam1 = qr[1]/qr[0] + np.sqrt(g*qr[0]) char1 = x_xtp/lam1 char2 = x_xtp/lam2 char3 = x_xtp2/lam1 char4 = x_xtp2/lam2 shock1 = ax[1].plot(x_xtp, char1, '-k', linewidth=4, label="1 or 2 shock") shock2 = ax[1].plot(x_xtp, char2, '-k', linewidth=4) rar1 = ax[1].plot(x_xtp2, char3, '-k', linewidth=1, label="1 or 2 rarefaction") rar2 = ax[1].plot(x_xtp2, char4, '-k', linewidth=1) # For other 4 rarefaction lines on each side x_xtp3 = np.linspace(-11.1,11.1,iter_charac) x_xtp4 = np.linspace(-11.2,11.2,iter_charac) x_xtp5 = np.linspace(-11.3,11.3,iter_charac) x_xtp6 = np.linspace(-11.4,11.4,iter_charac) char1a = x_xtp3/lam1; char2a = x_xtp3/lam2 char1b = x_xtp4/lam1; char2b = x_xtp4/lam2 char1c = x_xtp5/lam1; char2c = x_xtp5/lam2 char1d = x_xtp6/lam1; char2d = x_xtp6/lam2 rar1a = ax[1].plot(x_xtp3, char1a, '-k', linewidth=1) rar2a = ax[1].plot(x_xtp3, char2a, '-k', linewidth=1) rar1b = ax[1].plot(x_xtp4, char1b, '-k', linewidth=1) rar2b = ax[1].plot(x_xtp4, char2b, '-k', linewidth=1) rar1c = ax[1].plot(x_xtp5, char1c, '-k', linewidth=1) rar2c = ax[1].plot(x_xtp5, char2c, '-k', linewidth=1) rar1d = ax[1].plot(x_xtp6, char1d, '-k', linewidth=1) rar2d = ax[1].plot(x_xtp6, char2d, '-k', linewidth=1) timedot = ax[1].plot([100000,1000000,9], [-10,-10,time], 'ok' , alpha=0.7, markersize=10) timeline = ax[1].plot([-12,0,12], [time, time, time], '--k', linewidth = 3, label="time") # Set axis 2 properties ax[1].set_title("x-t plane", fontsize=18) ax[1].set_xlabel('x', fontsize=17) ax[1].set_ylabel('t', fontsize=17) ax[1].axis([-10,10,-0,tmax]) ax[1].grid(alpha=0.1,color='k', linestyle='--') legend = ax[1].legend(loc='upper center', shadow=True, fontsize = 8) # PLOT SOLUTIONS xsol = np.linspace(-10,10,2*iters) hsol = 0*xsol + ql[0] husol = 0*xsol + ql[1] q1 = axsol[0].plot(xsol,hsol, '-k', linewidth = 4, alpha = 1.0) q2 = axsol[1].plot(xsol,husol, '-k', linewidth = 4, alpha = 1.0) def solplot(xsol,ql,qr,qm,g): hl = ql[0]; hm = qm[0]; hr = qr[0] ul = ql[1]/hl; um = qm[1]/hm; ur = qr[1]/hr lam = np.empty(4, dtype=float) # Set axis 3 properties axsol[0].set_title("Depth h at time = t", fontsize=18) axsol[0].set_xlabel('x', fontsize=17) axsol[0].set_ylabel('h', fontsize=17) axsol[0].axis([-10,10,0,hmax]) axsol[0].grid(alpha=0.1,color='k', linestyle='--') # Set axis 4 properties axsol[1].set_title("Momentum hu at time = t", fontsize=18) axsol[1].set_xlabel('x', fontsize=17) axsol[1].set_ylabel('hu', fontsize=17) axsol[1].axis([-10,10,humin,humax]) axsol[1].grid(alpha=0.1,color='k', linestyle='--') # Remove defult mpld3 plugins plugins.clear(fig) # Call mpld3 custom PPLane plugin to interact with plot plugins.connect(fig, PPlaneNLPlugin(points[0],midpoint[0], g,iters,iter_charac,time, hmax, offsetx, hugol[0],hugor[0],intcl[0],intcr[0], hugol2[0],hugor2[0],intcl2[0],intcr2[0], qlmarker[0],qmmarker[0],qrmarker[0], shock1[0],shock2[0],rar1[0],rar2[0], rar1a[0],rar2a[0],rar1b[0],rar2b[0], rar1c[0],rar2c[0],rar1d[0],rar2d[0], timedot[0],timeline[0], q1[0],q2[0])) return fig
def spladder_viz(): """Main visualization code""" ### parse command line parameters options = parse_options(sys.argv) ### create plot directory if it does not exist yet if not os.path.exists(os.path.join(options.outdir, 'plots')): os.mkdir(os.path.join(options.outdir, 'plots')) if options.format == 'd3': try: import mpld3 from mpld3 import plugins except ImportError: sys.stderr.write( "ERROR: missing package for format d3. Package mpld3 required") sys.exit(1) ### load gene information genes = load_genes(options) rows = get_plot_len(options) gs = gridspec.GridSpec(rows, 1) ### get coloring cmap_cov = plt.get_cmap('jet') cmap_edg = plt.get_cmap('jet') ### plot log scale? log_tag = '' if options.log: log_tag = '.log' event_tag = '' ### did we get any labels? if options.labels != '-': options.labels = options.labels.strip(',').split(',') assert len(options.labels) == len( options.bams.strip(':').split(':') ), "The number of given labels (%i) needs to match the number of given bam file groups (%i)" % ( len(options.labels), len(options.bams.strip(':').split(':'))) ### the user specified a gene to plot if options.gene_name is not None: gid = sp.where( sp.array([x.name.split('.')[0] for x in genes]) == options.gene_name.split('.')[0])[0] if gid.shape[0] == 0: sys.stderr.write( 'ERROR: provided gene ID %s could not be found, please check for correctness\n' % options.gene_name) sys.exit(1) gids = [ sp.where(sp.array([x.name for x in genes]) == options.gene_name)[0][0] ] ### no gene specified but result provided - plot all genes with confirmed events ### if an event_id is provided, only the associated gene will be plotted else: gids = get_gene_ids(options) ### iterate over genes to plot for gid in gids: if options.format == 'd3': fig = plt.figure(figsize=(12, 2 * rows), dpi=100) else: fig = plt.figure(figsize=(18, 3 * rows), dpi=200) axes = [] ### gather information about the gene we plot gene = get_gene(genes[gid]) if options.verbose: print 'plotting information for gene %s' % gene.name ### plot splicing graph axes.append(fig.add_subplot(gs[len(axes), 0])) plot_graph(gene.splicegraph.vertices, gene.splicegraph.edges, axes[-1]) xlim = axes[-1].get_xlim() axes[-1].set_title('Splicing graph for %s' % gene.name) ### plot annotated transcripts if options.transcripts: axes.append(fig.add_subplot(gs[len(axes), 0], sharex=axes[0])) multiple(gene.exons, ax=axes[-1], x_range=xlim) axes[-1].set_title('Annotated Transcripts') ### plot coverage information for a set of samples if options.bams != '-': samples = options.bams.strip(':').split(':') plot_bam(options, gene, samples, fig, axes, gs, xlim, cmap_cov, cmap_edg) ### plot all the samples in a single plot if len(samples) > 1: plot_bam(options, gene, samples, fig, axes, gs, xlim, cmap_cov, cmap_edg, single=False) ### plot segment counts (segments, edges, edge_idx) = get_seg_counts(options, gid) axes.append(fig.add_subplot(gs[len(axes), 0], sharex=axes[0])) if identity() == 'matlab': cov_from_segments(gene, segments, edges, edge_idx, axes[-1], xlim=xlim, log=options.log, grid=True, order='F') else: cov_from_segments(gene, segments, edges, edge_idx, axes[-1], xlim=xlim, log=options.log, grid=True, order='C') axes[-1].set_title('Segment counts') ### plot structure of a single given event #if options.event_id is not None: axes.append(fig.add_subplot(gs[len(axes), 0], sharex=axes[0])) ### user defined event to plot if options.event_id is not None: event_info = [ x[::-1] for x in re.split( r'[._]', options.event_id[::-1], maxsplit=1)[::-1] ] event_info[1] = int(event_info[1]) - 1 event_info = sp.array(event_info, dtype='str')[sp.newaxis, :] event_tag = '.%s' % options.event_id ### get all significant events of the current gene else: event_info = get_conf_events(options, gid) plot_event(options, event_info, axes[-1], xlim) ### we only need to adapt the xoom for one axis object - as we share the x zoom_x = [float(x) for x in options.zoom_x.split(',')] xlim = axes[0].get_xlim() xdiff = xlim[1] - xlim[0] axes[0].set_xlim( [xlim[0] + (zoom_x[0] * xdiff), xlim[0] + (zoom_x[1] * xdiff)]) plt.tight_layout() ### save plot into file if options.format == 'd3': out_fname = os.path.join( options.outdir, 'plots', 'gene_overview_C%i_%s%s%s.html' % (options.confidence, gene.name, event_tag, log_tag)) plugins.clear(fig) plugins.connect(fig, plugins.Zoom(enabled=True)) mpld3.save_html(fig, open(out_fname, 'w')) else: out_fname = os.path.join( options.outdir, 'plots', 'gene_overview_C%i_%s%s%s.%s' % (options.confidence, gene.name, event_tag, log_tag, options.format)) plt.savefig(out_fname, format=options.format, bbox_inches='tight') plt.close(fig)
def linear_phase_plane(ql=np.array([-2.0, 2.0]),qr=np.array([0.0, 3.0]), r1=None, r2=None, lam1=None, lam2=None, q1min=-5, q1max=5, q2min =-5, q2max=5, domain=5, time=1.0, title1=None, title2=None): # Create figure # Create a figure fig, ax = plt.subplots(1,3, figsize=(13.5, 5.0)) fig.subplots_adjust(left=0.05, right=0.9, bottom=0.2, top=0.9, hspace=0.3, wspace=0.15) #Create subfigure ax1 for phaseplane #ax[0] = fig.add_subplot(2,2,1) # Calculate dq from ql and qr dq = np.array([qr[0]-ql[0], qr[1]-ql[1]]) # If eigenvectors not specified, default to Acoustics rho0 = 1.0 zz = 2.0 if r1 is None: r1 = np.array([-zz, 1]) if r2 is None: r2 = np.array([zz, 1]) if lam1 is None: lam1 = -zz/rho0 if lam2 is None: lam2 = zz/rho0 # Choose left and right eigenvectors if (lam1 < lam2): laml = lam1; lamr = lam2 rl = r1; rr = r2 else: laml = lam2; lamr = lam1 rl = r2; rr = r1 # Assign titles to solution plots if title1 is None: title1 = "q1" if title2 is None: title2 = "q2" #Plot eigenlines across ql and qr eps = 0.00000000001 # To avoid bugs in D3 ml = rl[1]/rl[0] mr = rr[1]/rr[0] + eps linesla = ax[0].plot([q1min,q1max],[ml*(q1min - ql[0]) + ql[1],ml*(q1max - ql[0]) + ql[1]], '-k') lineslb = ax[0].plot([q1min-eps,q1max+eps],[mr*(q1min - ql[0]) + ql[1],mr*(q1max - ql[0]) + ql[1]], '-k') linesra = ax[0].plot([q1min-2*eps,q1max+2*eps],[mr*(q1min - qr[0]) + qr[1],mr*(q1max - qr[0]) + qr[1]], '-k') linesrb = ax[0].plot([q1min-3*eps,q1max+3*eps],[ml*(q1min - qr[0]) + qr[1],ml*(q1max - qr[0]) + qr[1]], '-k') # Plot ql and qr points = ax[0].plot([ql[0],qr[0]], [ql[1], qr[1]], 'ok', alpha=0.7, markersize=10, markeredgewidth=1) data = ["q_l", "q_r"] offset = 0.4*0.5*(q1max-q1min)/5.0 qlmarker = ax[0].plot(ql[0] + offset, ql[1] - offset, 'ok', marker=(r"$ q_l $"), markersize=15) qrmarker = ax[0].plot(qr[0] + offset, qr[1] - offset, 'ok', marker=(r"$ q_r $"), markersize=15) #Plot midpoint det = rl[0]*rr[1] - rr[0]*rl[1] alL = (rr[1]*dq[0] - rr[0]*dq[1])/det qm = ql + alL*rl midpoint = ax[0].plot(qm[0],qm[1],'ok', alpha=0.9, markersize=8, markeredgewidth=1) qmmarker = ax[0].plot(qm[0]+offset,qm[1]-0.7*offset, 'k',marker=(r"$ q_m $"),markersize=20) # Set axis 1 properties ax[0].set_title("Phase Plane", fontsize=18) ax[0].axis([q1min,q1max,q2min,q2max]) ax[0].grid(alpha=0.1,color='k', linestyle='--') ax[0].set_xlabel(title1) ax[0].set_ylabel(title2) # Remove defult mpld3 plugins plugins.clear(fig) # Create solutionl line with six points where solution should be ctleft = laml*time ctright = lamr*time domain = max(domain,abs(ctleft)+1,abs(ctright)+1) # Readjust xdomain if necessarry xsol = np.array([-domain,ctleft,ctleft,ctright,ctright,domain]) qsol1 = 1*xsol qsol1[0:2] = ql[0] qsol1[2:4] = qm[0] qsol1[4:6] = qr[0] # Set axis 2 properties ax[1].set_title(title1, fontsize=18) ax[1].axis([-domain,domain,q1min,q1max]) ax[1].grid(alpha=0.1,color='k', linestyle='--') ax[1].set_xlabel('x') #ax[1].set_ylabel(title1) # Plot solution qone = ax[1].plot(xsol, qsol1, '-k', linewidth = 4, alpha = 1.0) #Create subfigure ax2 for solution plane #ax[2] = fig.add_subplot(2,2,2) # Create solutionl line with six points xsol2 = np.array([-domain,ctleft,ctleft,ctright,ctright,domain]) qsol2 = 1*xsol2 qsol2[0:2] = ql[1] qsol2[2:4] = qm[1] qsol2[4:6] = qr[1] # Set axis 2 properties ax[2].set_title(title2, fontsize=18) ax[2].axis([-domain,domain,q2min,q2max]) ax[2].grid(alpha=0.1,color='k', linestyle='--') ax[2].set_xlabel('x') #ax[2].set_ylabel(title2) # Plot solution qtwo = ax[2].plot(xsol2, qsol2, '-k', linewidth = 4, alpha = 1.0) # Call mpld3 custom PPLane plugin to interact with plot plugins.connect(fig, PPlanePlugin(points[0],midpoint[0], linesla[0],lineslb[0],linesra[0],linesrb[0], qlmarker[0],qmmarker[0],qrmarker[0],qone[0],qtwo[0], rl[0],rl[1],rr[0],rr[1])) return fig
def spladder_viz(options): """Main visualization code""" ### parse parameters from options object options = settings.parse_args(options, identity='viz') ### create plot directory if it does not exist yet if options.testdir != '-': dirname = options.testdir else: dirname = options.outdir if not os.path.exists(os.path.join(dirname, 'plots')): os.mkdir(os.path.join(dirname, 'plots')) if options.format == 'd3': try: import mpld3 from mpld3 import plugins except ImportError: sys.stderr.write( "ERROR: missing package for output format d3. Package mpld3 required" ) sys.exit(1) ### load gene information gene_names = get_gene_names(options) rows = get_plot_len(options) gs = gridspec.GridSpec(rows, 1) ### set color maps cmap_cov = plt.get_cmap('jet') cmap_edg = plt.get_cmap('jet') ### plot log scale? log_tag = '' if options.log: log_tag = '.log' event_tag = '' ### did we get any labels? if ',' in options.labels: options.labels = options.labels.strip(',').split(',') assert len(options.labels) == len( options.bam_fnames ), "The number of given labels (%i) needs to match the number of given bam file groups (%i)" % ( len(options.labels), len(options.bam_fnames)) # Collect genes to be plotted - there are three cases possible # 1) the user provides a gene ID # 2) all genes containing a significant event of a given type from differential testing are plotted # 3) all genes that contain any event are plotted ### the user chose a specific gene for plotting ### create pairs of gene ids and an event_id (the latter is None by default) if options.gene_name is not None: gids = [[ sp.where(sp.array(gene_names) == options.gene_name)[0][0], options.event_id ]] if len(gids) == 0: sys.stderr.write( 'ERROR: provided gene ID %s could not be found, please check for correctness\n' % options.gene_name) sys.exit(1) ### the plotting happens on the results of spladder test ### the user chooses to plot the top k significant events ### this requires the event type to be specified elif options.test_result > 0: gene_names = [] for event_type in options.event_types: ### the testing script should generate a setup file for the test ### SETUP is structured as follows: ### [gene_strains, event_strains, dmatrix0, dmatrix1, event_type, options] labels = options.test_labels.split(':') options.labels = labels if options.testdir != '-': testdir = dirname else: testdir = os.path.join( dirname, 'testing_%s_vs_%s' % (labels[0], labels[1])) SETUP = pickle.load( open( os.path.join( testdir, 'test_setup_C%i_%s.pickle' % (options.confidence, event_type)), 'rb')) ### get strains to plot idx1 = sp.where(sp.in1d(SETUP[0], SETUP[6]['conditionA']))[0] idx2 = sp.where(sp.in1d(SETUP[0], SETUP[6]['conditionB']))[0] ### load test results for l, line in enumerate( open( os.path.join( testdir, 'test_results_C%i_%s.tsv' % (options.confidence, event_type)), 'r')): if l == 0: continue if l > options.test_result: break sl = line.strip().split('\t') gene_names.append([sl[1], sl[0]]) gids = get_gene_ids(options, gene_names) ### no gene specified but result provided - plot all genes with confirmed events ### if an event_id is provided, only the associated gene will be plotted else: gids = get_gene_ids(options) ### iterate over genes to plot for gid in gids: ### gather information about the gene we plot gene = load_genes(options, idx=[gid[0]])[0] if options.verbose: print('plotting information for gene %s' % gene.name) gene.from_sparse() ### event to plot is specified with the gene id list if gid[1] is not None: event_info = [ x[::-1] for x in re.split(r'[._]', gid[1][::-1], maxsplit=1)[::-1] ] event_info[1] = int(event_info[1]) - 1 event_info = sp.array(event_info, dtype='str')[sp.newaxis, :] event_tag = '.%s' % gid[1] ### get all confident events of the current gene else: event_info = get_conf_events(options, gid[0]) ### go over different plotting options axes = [] ### plot result of testing if options.test_result > 0: fig = plt.figure(figsize=(9, 5), dpi=200) gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) _add_ax(fig, axes, gs) _add_ax(fig, axes, gs) _plot_event(options, event_info, fig, axes[1], gs, None, padding=100) start, stop = axes[1].get_xlim() plot_bam(options, gene, options.bam_fnames, fig, axes[0], gs, None, cmap_cov, cmap_edg, single=False, sharex=axes[1], start=int(start), stop=int(stop)) ### plot custom layout else: ### set defaults if not options.user: options.splicegraph = True options.transcripts = True if options.format == 'd3': fig = plt.figure(figsize=(12, 2 * rows), dpi=100) else: fig = plt.figure(figsize=(18, 3 * rows), dpi=200) xlim = None ### plot splicing graph if options.splicegraph: _plot_splicegraph(gene, fig, axes, gs) xlim = axes[-1].get_xlim() ### plot annotated transcripts if options.transcripts: sharex = None if len(axes) == 0 else axes[0] axes.append(fig.add_subplot(gs[len(axes), 0], sharex=sharex)) multiple(gene.exons, ax=axes[-1], x_range=xlim) axes[-1].set_title('Annotated Transcripts') ### plot coverage information for a set of given samples if len(options.bam_fnames) > 0: plot_bam(options, gene, options.bam_fnames, fig, axes, gs, xlim, cmap_cov, cmap_edg) ### plot all the samples in a single plot if len(options.bam_fnames) > 1: plot_bam(options, gene, options.bam_fnames, fig, axes, gs, xlim, cmap_cov, cmap_edg, single=False) ### plot segment counts if len(options.bam_fnames ) == 0 or False: # add option for segment plots if options.test_result > 0: _plot_segments(options, gid, fig, axes, gs, [idx1, idx2]) else: _plot_segments(options, gid, fig, axes, gs) ### plot structure of a single given event _plot_event(options, event_info, fig, axes, gs, xlim) ### we only need to adapt the xoom for one axis object - as we share the x zoom_x = [float(x) for x in options.zoom_x.split(',')] xlim = axes[0].get_xlim() xdiff = xlim[1] - xlim[0] axes[0].set_xlim( [xlim[0] + (zoom_x[0] * xdiff), xlim[0] + (zoom_x[1] * xdiff)]) for ax in axes: vax.clean_axis(ax) plt.tight_layout() ### save plot into file if options.format == 'd3': out_fname = os.path.join( dirname, 'plots', 'gene_overview_C%i_%s%s%s.html' % (options.confidence, gene.name, event_tag, log_tag)) plugins.clear(fig) plugins.connect(fig, plugins.Zoom(enabled=True)) mpld3.save_html(fig, open(out_fname, 'w')) else: if options.test_result > 0: out_fname = os.path.join( dirname, 'plots', 'gene_overview_C%i_%s%s%s.%s' % (options.confidence, gene.name, event_tag, log_tag, options.format)) else: out_fname = os.path.join( dirname, 'plots', 'gene_overview_C%i_%s%s%s.%s' % (options.confidence, gene.name, event_tag, log_tag, options.format)) plt.savefig(out_fname, format=options.format, bbox_inches='tight') plt.close(fig)
def result(): try: g.conn = sqlite3.connect('case_data.db') g.curr = g.conn.cursor() g.curr.execute("SELECT country_name FROM interval_tb") country = g.curr.fetchone()[0] g.curr.execute("SELECT duration FROM interval_tb") period = g.curr.fetchall() g.curr.execute("SELECT restriction FROM interval_tb") restrictions = g.curr.fetchall() g.curr.execute("SELECT * FROM cases_tb WHERE country_name=?", (country, )) country_statistics = g.curr.fetchone() g.conn.commit() g.conn.close() plt.rcParams.update({'font.size': 12}) def differential(initial, time, *args): # Holds initial conditions for the population susceptible, exposed, infected, recovered = initial # System of differential equations # Represents changes in the susceptible, exposed, infected, and recovered population dSdt = -(beta * susceptible * infected) / POPULATION_SIZE dEdt = beta * susceptible * infected / POPULATION_SIZE - SIGMA * exposed dIdt = SIGMA * exposed - GAMMA * infected dRdt = GAMMA * infected return dSdt, dEdt, dIdt, dRdt POPULATION_SIZE = country_statistics[3] BETA = 0.956 SIGMA = 1 / 5.2 GAMMA = 1 / 2.3 REPRODUCTION_NUMBER = BETA / GAMMA period = list(period) time = [0] restrictions = list(restrictions) contact_state = [] for i in range(len(period)): period[i] = period[i][0] for i in range(len(restrictions)): restrictions[i] = restrictions[i][0] time += list(accumulate(period)) for j in range(len(period)): if restrictions[j] == "Lockdown": contact_state.append(0.26) elif restrictions[j] == "Vacation": contact_state.append(0.46) elif restrictions[j] == "School closure": contact_state.append(0.8) else: contact_state.append(1) susceptible_initial = POPULATION_SIZE - \ country_statistics[2] - country_statistics[1] exposed_initial = 0 infected_initial = country_statistics[2] recovered_initial = country_statistics[1] infected_population = 0 current_maximum = 0 fig, ax = plt.subplots() for graph in range(len(period)): beta = BETA * contact_state[graph] duration = np.linspace(time[graph], time[graph + 1], period[graph] * 2 + 1) solution = odeint(differential, (susceptible_initial, exposed_initial, infected_initial, recovered_initial), duration, args=(beta, SIGMA, GAMMA, POPULATION_SIZE)) susceptible_initial = solution[period[graph] * 2, 0] exposed_initial = solution[period[graph] * 2, 1] infected_initial = solution[period[graph] * 2, 2] recovered_initial = solution[period[graph] * 2, 3] current_maximum = max(solution[:, 2]) if current_maximum > infected_population: infected_population = current_maximum if graph == 0: ax.plot(duration, solution[:, 0], 'r', label='Susceptible') ax.plot(duration, solution[:, 1], 'g', label='Exposed') ax.plot(duration, solution[:, 2], 'b', label='Infectious') ax.plot(duration, solution[:, 3], 'y', label='Recovered') else: ax.plot(duration, solution[:, 0], 'r') ax.plot(duration, solution[:, 1], 'g') ax.plot(duration, solution[:, 2], 'b') ax.plot(duration, solution[:, 3], 'y') ax.set_xlim(0, time[-1]) ax.set_ylim(0, POPULATION_SIZE + POPULATION_SIZE * 0.01) ax.legend(loc='best') ax.set_xlabel('Time (days)') ax.set_ylabel('Population', rotation='horizontal') fig.set_size_inches(8, 6) ax.yaxis.set_label_coords(-0.1, 1.02) plugins.clear(fig) plugins.connect(fig, plugins.Reset()) plugins.connect(fig, plugins.BoxZoom(enabled=True)) plugins.connect(fig, plugins.Zoom()) seir_graph = mpld3.fig_to_html(fig) plt.close() effective_reproduction_number = REPRODUCTION_NUMBER * \ susceptible_initial/POPULATION_SIZE effective_reproduction_number = float( "{:0.3f}".format(effective_reproduction_number)) return { 'graph': seir_graph, 'r0': REPRODUCTION_NUMBER, 'rt': effective_reproduction_number, 'susceptible_state': int(susceptible_initial), 'exposed_state': int(exposed_initial), 'infected_state': int(infected_initial), 'recovered_state': int(recovered_initial), 'max_active_cases': int(infected_population) } except: return jsonify(0)
def spladder_viz(options): """Main visualization code""" ### parse parameters from options object options = settings.parse_args(options, identity='viz') ### create plot directory if it does not exist yet dirname = options.outdir if options.testdir == '-' else options.testdir if not os.path.exists(os.path.join(dirname, 'plots')): os.mkdir(os.path.join(dirname, 'plots')) if options.format == 'd3': try: import mpld3 from mpld3 import plugins except ImportError: sys.stderr.write( "ERROR: missing package for output format d3. Package mpld3 required" ) sys.exit(1) ### load gene information all_gene_names = get_gene_names(options.outdir, options.confidence, options.validate_sg, options.verbose) ### set color maps cmap_cov = plt.get_cmap('jet') cmap_edg = plt.get_cmap('jet') ### Data Range RangeData = namedtuple('RangeData', ['chr', 'start', 'stop']) plots = [] test_tag = [] ### if the --test option was given, populate the options object with additional track fields ### otherwise just create a single plot if options.test is None: plots.append(options.data_tracks) test_tag.append('') else: for test_info in options.test: _parse_test_info(test_info, options.outdir, options.confidence, plots, test_tag) for plot_data in plots: if len(options.data_tracks) > 0: plot_data.extend(options.data_tracks) ### generate all plots to be completed for p, plot_data in enumerate(plots): ### get range information genes, gene_names, gids = [], [], [] events, eids = [], [] coords = [] for range_info in options.range: ### genes if range_info[0] == 'gene': _parse_gene_info(range_info[1:], genes, gene_names, gids, all_gene_names, options.outdir, options.confidence, options.validate_sg, options.verbose) ### events elif range_info[0] == 'event': _parse_event_info(eids, gids, range_info[1:], events, options.outdir, options.confidence, options.verbose) ### coordinate ranges elif range_info[0] == 'coordinate': coords.append( RangeData._make([ range_info[1], int(range_info[2]), int(range_info[3]) ])) ### check data tracks for additional range information if no --range was given if len(genes) + len(events) + len(coords) == 0: for range_info in plot_data: ### splicegraph / transcripts if range_info[0] in ['splicegraph', 'transcript']: _parse_gene_info(range_info[1:], genes, gene_names, gids, all_gene_names, options.outdir, options.confidence, options.validate_sg, options.verbose) ### events elif range_info[0] == 'event': _parse_event_info(eids, gids, range_info[1:], events, options.outdir, options.confidence, options.verbose) ### gene (this is only needed internally for --test mode) elif range_info[0] == 'gene': _parse_gene_info(range_info[1:], genes, gene_names, gids, all_gene_names, options.outdir, options.confidence, options.validate_sg, options.verbose) ### check that everything is on the same chromosome plotchrm = np.unique([_.chr for _ in events + genes + coords]) if plotchrm.shape[0] > 1: sys.stderr.write( 'ERROR: the provided gene/event/coordinate ranges are on different chromosomes and canot be plotted jointly\n' ) sys.exit(1) ### identify the plotting range plotrange, plotrange_orig = _set_plotting_range(genes, events, coords) ### parse all elements to be plotted as data tracks data_tracks = [] for data_element in plot_data: track_types = data_element[0].split(',') for track_type in track_types: data_tracks.append(dt.DataTrack(track_type, data_element[1:])) ### set up figure and layout gs = gridspec.GridSpec(len(data_tracks), 1, hspace=0.05) fig = plt.figure(figsize=(15, 3 * len(data_tracks)), dpi=200) axes = [] for i, data_track in enumerate(data_tracks): ### plot splicing graph if data_track.type == 'splicegraph': ax = _add_ax(axes, fig, gs) if len(data_track.event_info) == 0: _genes = genes _gene_names = gene_names else: _genes, _gene_names, _gids = [], [], [] _parse_gene_info(range_info[1:], _genes, _gene_names, _gids, all_gene_names, options.outdir, options.confidence, options.validate_sg, options.verbose) for gene in _genes: gene.from_sparse() plot_graph(gene.splicegraph.vertices, gene.splicegraph.edges, ax, xlim=plotrange, label=gene.name) gene.to_sparse() ax.set_ylabel('splicing graph') ax.get_yaxis().set_label_coords(1.02, 0.5) ### plot annotated transcripts if data_track.type == 'transcript': ax = _add_ax(axes, fig, gs) if len(data_track.event_info) == 0: _genes = genes _gene_names = gene_names else: _genes, _gene_names, _gids = [], [], [] _parse_gene_info(range_info[1:], _genes, _gene_names, _gids, all_gene_names, options.outdir, options.confidence, options.validate_sg, options.verbose) for gene in _genes: gene.from_sparse() multiple(gene.exons, ax=ax, x_range=plotrange, labels=gene.transcripts, grid=True) gene.to_sparse() ax.set_ylabel('transcripts') ax.get_yaxis().set_label_coords(1.02, 0.5) ### plot events if data_track.type == 'event': ax = _add_ax(axes, fig, gs) ### no event ids given - plot the one from range if len(data_track.event_info) == 0: _events = events ### events are given in the track - plot those instead else: _eids, _events = [], [] _parse_event_info(_eids, gids, data_track.event_info, _events, options.outdir, options.confidence, options.verbose) event_list = [[event.exons1, event.exons2] for event in _events] labels = ['_'.join([_.event_type, str(_.id)]) for _ in _events] multiple(event_list, ax=ax, x_range=plotrange, color='green', padding=None, grid=True, labels=labels) vax.clean_axis(ax, allx=True) ax.set_ylabel('events') ax.get_yaxis().set_label_coords(1.02, 0.5) ### plot coverage tracks if data_track.type == 'coverage': ax = _add_ax(axes, fig, gs) min_sample_size = 5 ### TODO make that an option caxes = [] labels = [] norm = plt.Normalize(0, len(data_track.bam_fnames)) for g, bam_group in enumerate(data_track.bam_fnames): label = 'group %i' % (g + 1) if len( data_track.group_labels ) == 0 else data_track.group_labels[g] caxes.append( cov_from_bam(plotchrm[0], plotrange[0], plotrange[1], bam_group, subsample=min_sample_size, ax=ax, intron_cnt=True, log=options.log, xlim=plotrange, color_cov=cmap_cov(norm(g)), color_intron_edge=cmap_edg(norm(g)), grid=True, min_intron_cnt=options.mincount, return_legend_handle=True, label=label)) labels.append(label) ax.get_yaxis().set_label_coords(1.02, 0.5) if len(caxes) > 0: ax.legend(caxes, labels) ### plot segment counts if data_track.type == 'segments': ax = _add_ax(axes, fig, gs) for g, gid in enumerate(gids): (segments, edges, edge_idx, strains) = get_seg_counts(gid, options.outdir, options.confidence, options.validate_sg) seg_sample_idx = None if len(data_track.strains) > 0: seg_sample_idx = [] for track_strains in data_track.strains: seg_sample_idx.append( np.where(np.in1d(strains, track_strains))[0]) cov_from_segments(genes[g], segments, edges, edge_idx, ax, xlim=plotrange, log=options.log, grid=True, order='C', sample_idx=seg_sample_idx) ax.get_yaxis().set_label_coords(1.02, 0.5) ax.set_ylabel('segment counts') ### set x axis ticks for i, ax in enumerate(axes): if i == len(axes) - 1: ax.set_xticks( np.around( np.linspace(plotrange_orig[0], plotrange_orig[1], 10))) ax.set_xlabel('chromosome ' + plotchrm[0]) else: ax.set_xticks([]) ### save plot into file if options.format == 'd3': out_fname = os.path.join( dirname, 'plots', '%s%s.html' % (options.outbase, test_tag[p])) plugins.clear(fig) plugins.connect(fig, plugins.Zoom(enabled=True)) mpld3.save_html(fig, open(out_fname, 'w')) else: out_fname = os.path.join( dirname, 'plots', '%s%s.%s' % (options.outbase, test_tag[p], options.format)) plt.savefig(out_fname, format=options.format, bbox_inches='tight') plt.close(fig)
def problem_view(request, problem_id): user = request.user problem = get_object_or_404(Problem, id=problem_id) if problem.user_id != user and not user.is_superuser: raise PermissionDenied parse_error = False a = None b = None c = None a_copy = None b_copy = None result = None figure = None parse_result = parse_problem(problem.problem_text) print parse_result if parse_result is not None: a, b, c, x = parse_result if a and b and c and x: result = simple_simplex(copy.deepcopy(a), copy.deepcopy(b), copy.deepcopy(c)) b.pop(0) a_copy = copy.deepcopy(a) b_copy = copy.deepcopy(b) if len(x) is 2: tmp = [0, 0] tmp[1] = 1 a.insert(0, copy.deepcopy(tmp)) tmp[0] = 1 tmp[1] = 0 a.insert(0, copy.deepcopy(tmp)) b.insert(0, 0) b.insert(0, 0) dots = [] for i in range(len(b)): dots.append([]) shape_x = [] for i in xrange(0, len(b)): for j in xrange(i + 1, len(b)): if a[i][0] == a[j][0] and a[i][1] == a[j][1]: continue shape_a = np.array([[a[i][0], a[i][1]], [a[j][0], a[j][1]]]) shape_b = np.array([b[i], b[j]]) res = np.linalg.solve(shape_a, shape_b) dots[i].append(res) dots[j].append(res) # fig, ax = plt.subplots() fig = plt.figure() ax = fig.add_subplot(111) for dot in dots: ax.plot([float(dot[0][0]), float(dot[1][0])], [float(dot[0][1]), float(dot[1][1])], ls='-', color='green', marker='o', lw=2) # print([dot[0], dot[1]]) ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_title('Plot of 2D Problem!', size=14) plugins.clear(fig) plugins.connect(fig, plugins.Reset(), plugins.Zoom(enabled=True), plugins.BoxZoom()) figure = fig_to_html(fig, d3_url=STATIC_URL + 'js/d3.min.js', mpld3_url=STATIC_URL + 'js/mpld3.v0.2.js', use_http=True) else: figure = 'Larger than 2D!' else: parse_error = True return render_to_response('problems/view.html', { 'user': user, 'problem': problem, 'parse_error': parse_error, 'figure': figure, 'a': a_copy, 'b': b_copy, 'c': c, 'result': result, 'view_name': 'Problem - %s' % problem.id, })
def getHTML(self, params): # print(params) global current_gene data_max = 0 fig = plt.figure(figsize=(9, 7)) gs = gridspec.GridSpec(4, 1, height_ratios=[6, 1, 1, 1]) gene = params["freq"].upper() range_ext = int(params["range"]) searched = "False" lines = [] if gene.startswith("CHR"): temp = gene.split(":") current_gene = ["Region", temp[0][3:], int(temp[1]), int(temp[2]), "+"] else: for item in genes: if item[0] == gene: current_gene = item break else: temp_gene = self.search_SGD(gene) print(temp_gene) searched = "True" for item in genes: if item[0] == temp_gene[0]: current_gene = item break else: current_gene = temp_gene print(gene) # Todo add possibility to search SGD defaulting to SGD coordinates print( "*" * 40 + "\nQuery by user:"******";\nrange extension:" + str(range_ext) + " ;Checked Boxes:" + str(params["check_boxes"]) + ";SGD used:" + searched + "\n" + "*" * 40 ) # print(params) splt1 = plt.subplot(gs[0, :]) splt1.set_title( "{}-Chromosome {}:{}:{}, strand:{}".format( current_gene[0], current_gene[1], current_gene[2], current_gene[3], current_gene[4] ), size=20, ) # splt1.set_xlabel('Distance from TSS (nt)') splt1.axes.xaxis.set_ticklabels([]) splt1.set_ylabel("Normalized counts per million reads\n ", size=16, labelpad=15) n = 0 fill_colors = [ "#921B16", "#D6701C", "#251F47", "#68A691", "#68A691", "#447604", "#232621", "#0BBE30", "#BC3908", "#191923", "#391923", "#591923", ] for item in params["check_boxes"]: if current_gene[4] == "+": data = data_sets[data_sets_names[int(item)]][current_gene[1]][ current_gene[2] - range_ext : current_gene[3] + range_ext ] factor = 100.0 / len(data) data = ndimage.interpolation.zoom(data, factor) _ = splt1.plot(data, label=data_sets_legend[int(item)], color=fill_colors[n], alpha=0.3, lw=3) lines.extend(_) splt1.fill_between(range(0, len(data)), 0, data, alpha=0.2, color=fill_colors[n]) if current_gene[4] == "-": data = data_sets[data_sets_names[int(item)]][current_gene[1]][ current_gene[2] - range_ext : current_gene[3] + range_ext ] factor = 100.0 / len(data) data = ndimage.interpolation.zoom(data[::-1], factor) print(data) _ = splt1.plot(data, label=data_sets_legend[int(item)], color=fill_colors[n], alpha=0.3, lw=3) lines.extend(_) splt1.fill_between(range(0, len(data)), 0, data, alpha=0.2, color=fill_colors[n]) if np.max(data) > data_max: data_max = np.max(data) n += 1 # plot2 if current_gene[4] == "+": y_values1 = data_sets["genes"][current_gene[1]][ 0, current_gene[2] - range_ext : current_gene[3] + range_ext ] y_values2 = data_sets["genes"][current_gene[1]][ 1, current_gene[2] - range_ext : current_gene[3] + range_ext ] else: y_values1 = data_sets["genes"][current_gene[1]][ 0, current_gene[2] - range_ext : current_gene[3] + range_ext ][::-1] y_values2 = data_sets["genes"][current_gene[1]][ 1, current_gene[2] - range_ext : current_gene[3] + range_ext ][::-1] # splt2.plot(y_values, 'grey', linewidth=2) factor = 100.0 / len(y_values1) splt2 = plt.subplot(gs[1, :]) y_values1 = ndimage.interpolation.zoom(y_values1, factor) y_values2 = ndimage.interpolation.zoom(y_values2, factor) x_values = range(0, len(y_values1)) splt2.plot([0, len(y_values1)], [0, 0], "black", linewidth=1.5) splt2.fill_between(x_values, y_values1 / 4.0, y_values1, color="#FFB30F") splt2.fill_between(x_values, y_values2 / 4.0, y_values2, color="#FD151B") splt2.set_ylim(-1.5, 1.5) splt2.text(1.01, 0.5, "GENES", fontsize=12, transform=splt2.transAxes, verticalalignment="center") splt2.yaxis.set_tick_params(color="w") splt2.set_yticks([-0.5, 0.5]) splt2.spines["left"].set_position(("outward", 10)) splt2.set_yticklabels([]) splt2.axes.xaxis.set_ticklabels([]) # plot3 if current_gene[4] == "+": y_values1 = data_sets["CUTS"][current_gene[1]][0, current_gene[2] - range_ext : current_gene[3] + range_ext] y_values2 = data_sets["CUTS"][current_gene[1]][1, current_gene[2] - range_ext : current_gene[3] + range_ext] else: y_values1 = data_sets["CUTS"][current_gene[1]][ 0, current_gene[2] - range_ext : current_gene[3] + range_ext ][::-1] y_values2 = data_sets["CUTS"][current_gene[1]][ 1, current_gene[2] - range_ext : current_gene[3] + range_ext ][::-1] # splt2.plot(y_values, 'grey', linewidth=2) factor = 100.0 / len(y_values1) splt3 = plt.subplot(gs[2, :]) y_values1 = ndimage.interpolation.zoom(y_values1, factor) y_values2 = ndimage.interpolation.zoom(y_values2, factor) x_values = range(0, len(y_values1)) splt3.plot([0, len(y_values1)], [0, 0], "black", linewidth=1.5) splt3.fill_between(x_values, y_values1 / 4.0, y_values1, color="#028090") splt3.fill_between(x_values, y_values2 / 4.0, y_values2, color="#6EEB83") splt3.set_ylim(-1.5, 1.5) splt3.text(1.01, 0.5, "CUTS", fontsize=12, transform=splt3.transAxes, verticalalignment="center") splt3.yaxis.set_tick_params(color="w") splt3.set_yticks([-0.5, 0.5]) splt3.spines["left"].set_position(("outward", 10)) splt3.set_yticklabels([]) splt3.axes.xaxis.set_ticklabels([]) # plot4 if current_gene[4] == "+": y_values1 = data_sets["SUTS"][current_gene[1]][0, current_gene[2] - range_ext : current_gene[3] + range_ext] y_values2 = data_sets["SUTS"][current_gene[1]][1, current_gene[2] - range_ext : current_gene[3] + range_ext] else: y_values1 = data_sets["SUTS"][current_gene[1]][ 0, current_gene[2] - range_ext : current_gene[3] + range_ext ][::-1] y_values2 = data_sets["SUTS"][current_gene[1]][ 1, current_gene[2] - range_ext : current_gene[3] + range_ext ][::-1] # splt2.plot(y_values, 'grey', linewidth=2) factor = 100.0 / len(y_values1) splt4 = plt.subplot(gs[3, :]) y_values1 = ndimage.interpolation.zoom(y_values1, factor) y_values2 = ndimage.interpolation.zoom(y_values2, factor) x_values = range(0, len(y_values1)) splt4.plot([0, len(y_values1)], [0, 0], "black", linewidth=1.5) splt4.fill_between(x_values, y_values1 / 4.0, y_values1, color="#028090") splt4.fill_between(x_values, y_values2 / 4.0, y_values2, color="#6EEB83") splt4.set_ylim(-1.5, 1.5) splt4.text(1.01, 0.5, "SUTS", fontsize=12, transform=splt4.transAxes, verticalalignment="center") splt4.yaxis.set_tick_params(color="w") splt4.set_yticks([-0.5, 0.5]) splt4.spines["left"].set_position(("outward", 10)) splt4.set_yticklabels([]) splt4.axes.xaxis.set_ticklabels([]) leg = splt1.legend(ncol=3) leg.set_title("") for legobj in leg.legendHandles: legobj.set_linewidth(3.0) size = (current_gene[3] + range_ext) - (current_gene[2] - range_ext) splt1.set_ylim(0, np.max(data_max) * 1.3) # print(str(plt.ylim()[1] - 5)) splt1.text(0.02, 0.02, "Luis Soares", fontsize=6, transform=splt1.transAxes, verticalalignment="top") leg_line = leg.get_lines() number_of_samples = len(leg_line) class HighlightLines(plugins.PluginBase): """A plugin to highlight lines on hover""" JAVASCRIPT = """ mpld3.register_plugin("linehighlight", LineHighlightPlugin); LineHighlightPlugin.prototype = Object.create(mpld3.Plugin.prototype); LineHighlightPlugin.prototype.constructor = LineHighlightPlugin; LineHighlightPlugin.prototype.requiredProps = ["legend_ids","line_ids"]; LineHighlightPlugin.prototype.defaultProps = {alpha_bg:0.3, alpha_fg:1.0} function LineHighlightPlugin(fig, props){ mpld3.Plugin.call(this, fig, props); }; LineHighlightPlugin.prototype.draw = function(){ var obj=[] for(var i=0; i<this.props.legend_ids.length; i++){ obj=obj.concat([mpld3.get_element(this.props.legend_ids[i], this.fig), mpld3.get_element(this.props.line_ids[i], this.fig)]); alpha_fg = this.props.alpha_fg; alpha_bg = this.props.alpha_bg; } %s } """ % ( create_java(number_of_samples * 2) ) def __init__(self, legend, lines, samples): self.lines = lines self.legend = legend self.dict_ = { "type": "linehighlight", "legend_ids": [utils.get_id(line) for line in legend], "line_ids": [utils.get_id(line) for line in lines], "alpha_bg": lines[0].get_alpha(), "alpha_fg": 1.0, } class TopToolbar(plugins.PluginBase): """Plugin for moving toolbar to top of figure""" JAVASCRIPT = """ mpld3.register_plugin("toptoolbar", TopToolbar); TopToolbar.prototype = Object.create(mpld3.Plugin.prototype); TopToolbar.prototype.constructor = TopToolbar; function TopToolbar(fig, props){ mpld3.Plugin.call(this, fig, props); }; TopToolbar.prototype.draw = function(){ // the toolbar svg doesn't exist // yet, so first draw it this.fig.toolbar.draw(); // then change the y position to be // at the top of the figure this.fig.toolbar.toolbar.attr("y", 2); // then remove the draw function, // so that it is not called again this.fig.toolbar.draw = function() {} } """ def __init__(self): self.dict_ = {"type": "toptoolbar"} plugins.clear(fig) plugins.connect( fig, TopToolbar(), HighlightLines(leg_line, lines, number_of_samples), plugins.Reset(), plugins.BoxZoom() ) file = cStringIO.StringIO() mpld3.save_html(fig, file) return file.getvalue()
def render(self, filename="output.html"): if self.html: # write matplotlib/d3 plots to html file import matplotlib.pyplot as plt, mpld3 import matplotlib.axes from mpld3 import plugins from jinja2 import Environment, FileSystemLoader else: # show plots in separate matplotlib windows import matplotlib import matplotlib.pyplot as plt import matplotlib.axes figures = list() for group in self.datasets: fig, axes = plt.subplots(len(group["dataset"]), sharex=True, sharey=True) # scale unified scaling figures to same ranges and add some margin if group["unified_scaling"]: ymin = 0 ymax = 0 for i in range(len(group["dataset"])): ymin = np.min((np.min(group["dataset"][i]["data"]), ymin)) * 1.05 ymax = np.max((np.max(group["dataset"][i]["data"]), ymax)) * 1.05 # plot each group of data for d_i in range(len(group["dataset"])): d = group["dataset"][d_i] if not issubclass(type(axes), matplotlib.axes.SubplotBase): ax = axes[d_i] else: ax = axes axes = [axes] ax.set_title(d["title"]) if group["unified_scaling"]: ax.set_ylim([ymin, ymax]) for data_i in range(0, len(d["data"])): if len(d["data"][data_i].shape) > 1: # data matrices for i in range(0, d["data"][data_i].shape[1]): l = group["labels"][i] if data_i == 0 else "" if i < 6 and "contains_base" in group and group["contains_base"]: ls = "--" else: ls = "-" ax.plot( d["time"], d["data"][data_i][:, i], label=l, color=colors[i], alpha=1 - (data_i / 2.0), linestyle=ls, ) else: # data vector ax.plot( d["time"], d["data"][data_i], label=group["labels"][d_i], color=colors[0], alpha=1 - (data_i / 2.0), ) ax.grid(b=True, which="both", color="0.4") if "y_label" in group: ax.set_ylabel(group["y_label"]) ax.set_xlabel("Time (s)") plt.setp([a.get_xticklabels() for a in axes[:-1]], visible=False) # plt.setp([a.get_yticklabels() for a in axes], fontsize=8) if self.html: # TODO: show legend properly (see mpld3 bug #274) handles, labels = ax.get_legend_handles_labels() # leg = fig.legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='') leg = axes[0].legend( handles, labels, loc="upper right", fancybox=True, fontsize=10, title="", prop={"size": 7} ) else: if idf.opt["plotPerJoint"]: font_size = 30 else: font_size = 12 matplotlib.rcParams.update({"font.size": font_size}) matplotlib.rcParams.update({"axes.labelsize": font_size - 2}) matplotlib.rcParams.update({"axes.linewidth": font_size / 15.0}) matplotlib.rcParams.update({"axes.titlesize": font_size}) matplotlib.rcParams.update({"legend.fontsize": font_size}) matplotlib.rcParams.update({"xtick.labelsize": font_size - 2}) matplotlib.rcParams.update({"ytick.labelsize": font_size - 2}) matplotlib.rcParams.update({"lines.linewidth": font_size / 15.0}) matplotlib.rcParams.update({"patch.linewidth": font_size / 15.0}) matplotlib.rcParams.update({"grid.linewidth": font_size / 20.0}) handles, labels = ax.get_legend_handles_labels() leg = plt.figlegend( handles, labels, loc="upper right", fancybox=True, fontsize=10, title="", prop={"size": font_size - 4}, ) leg.draggable() fig.subplots_adjust(hspace=2) fig.set_tight_layout(True) if self.html: plugins.clear(fig) plugins.connect( fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom(enabled=False), plugins.MousePosition(fontsize=14), ) figures.append(mpld3.fig_to_html(fig)) else: plt.show() if self.html: path = os.path.dirname(os.path.abspath(__file__)) template_environment = Environment( autoescape=False, loader=FileSystemLoader(os.path.join(path, "../output")), trim_blocks=False ) context = {"figures": figures} outfile = os.path.join(path, "..", "output", "output.html") with open(outfile, "w") as f: html = template_environment.get_template("templates/index.html").render(context) f.write(html) print("Saved output at file://{}".format(outfile))
def spladder_viz(): """Main visualization code""" ### parse command line parameters options = parse_options(sys.argv) ### create plot directory if it does not exist yet if not os.path.exists(os.path.join(options.outdir, 'plots')): os.mkdir(os.path.join(options.outdir, 'plots')) if options.format == 'd3': try: import mpld3 from mpld3 import plugins from modules.d3test import ClickInfo except ImportError: sys.stderr.write("ERROR: missing package for format d3. Package mpld3 required") sys.exit(1) ### load gene information genes = load_genes(options) rows = get_plot_len(options) gs = gridspec.GridSpec(rows, 1) ### get coloring cmap_cov = plt.get_cmap('jet') cmap_edg = plt.get_cmap('jet') ### plot log scale? log_tag = '' if options.log: log_tag = '.log' event_tag = '' ### did we get any labels? if options.labels != '-': options.labels = options.labels.strip(',').split(',') assert len(options.labels) == len(options.bams.strip(':').split(':')), "The number of given labels (%i) needs to match the number of given bam file groups (%i)" % (len(options.labels), len(options.bams.strip(':').split(':'))) ### the user specified a gene to plot if options.gene_name is not None: if isinstance(genes[0].name, sp.ndarray): gids = sp.where(sp.array([x.name[0] for x in genes]) == options.gene_name)[0] if gids.shape[0] == 0: gids = sp.where(sp.array([x.name[0].startswith(options.gene_name) for x in genes]))[0] else: gids = sp.where(sp.array([x.name for x in genes]) == options.gene_name)[0] if gids.shape[0] == 0: gids = sp.where(sp.array([x.name.startswith(options.gene_name) for x in genes]))[0] if gids.shape[0] == 0: sys.stderr.write('ERROR: provided gene ID %s could not be found, please check for correctness\n' % options.gene_name) sys.exit(1) ### no gene specified but result provided - plot all genes with confirmed events else: gids = get_gene_ids(options) ### iterate over genes to plot for gid in gids: if options.format == 'd3': fig = plt.figure(figsize = (12, 2*rows), dpi=100) else: fig = plt.figure(figsize = (18, 3*rows), dpi=200) axes = [] ### gather information about the gene we plot gene = get_gene(genes[gid]) if options.verbose: print 'plotting information for gene %s' % gene.name ### plot splicing graph axes.append(fig.add_subplot(gs[len(axes), 0])) plot_graph(gene.splicegraph.vertices, gene.splicegraph.edges, axes[-1]) xlim = axes[-1].get_xlim() axes[-1].set_title('Splicing graph for %s' % gene.name) ### plot annotated transcripts if options.transcripts: axes.append(fig.add_subplot(gs[len(axes), 0], sharex=axes[0])) multiple(gene.exons, ax=axes[-1], x_range=xlim) axes[-1].set_title('Annotated Transcripts') ### plot coverage information for a set of samples if options.bams != '-': samples = options.bams.strip(':').split(':') plot_bam(options, gene, samples, fig, axes, gs, xlim, cmap_cov, cmap_edg) ### plot all the samples in a single plot if len(samples) > 1: plot_bam(options, gene, samples, fig, axes, gs, xlim, cmap_cov, cmap_edg, single=False) ### plot segment counts (segments, edges, edge_idx) = get_seg_counts(options, gid) axes.append(fig.add_subplot(gs[len(axes), 0], sharex=axes[0])) if identity() == 'matlab': cov_from_segments(gene, segments, edges, edge_idx, axes[-1], xlim=xlim, log=options.log, grid=True, order='F') else: cov_from_segments(gene, segments, edges, edge_idx, axes[-1], xlim=xlim, log=options.log, grid=True, order='C') axes[-1].set_title('Segment counts') ### plot structure of a single given event #if options.event_id is not None: axes.append(fig.add_subplot(gs[len(axes), 0], sharex=axes[0])) ### user defined event to plot if options.event_id is not None: event_info = [x[::-1] for x in re.split(r'[._]', options.event_id[::-1], maxsplit=1)[::-1]] event_info[1] = int(event_info[1]) - 1 event_info = sp.array(event_info, dtype='str')[sp.newaxis, :] event_tag = '.%s' % options.event_id ### get all significant events of the current gene else: event_info = get_conf_events(options, gid) plot_event(options, event_info, axes[-1], xlim) plt.tight_layout() ### save plot into file if options.format == 'd3': out_fname = os.path.join(options.outdir, 'plots', 'gene_overview_%s%s%s.html' % (gene.name, event_tag, log_tag)) plugins.clear(fig) plugins.connect(fig, plugins.Zoom(enabled=True), ClickInfo(sp.ones((10000,), dtype='int'))) mpld3.save_html(fig, open(out_fname, 'w')) else: out_fname = os.path.join(options.outdir, 'plots', 'gene_overview_%s%s%s.%s' % (gene.name, event_tag, log_tag, options.format)) plt.savefig(out_fname, format=options.format, bbox_inches='tight') plt.close(fig)
def plotData(NQuery, input_table, FigureStrBase, html_dir=None, png_dir=None, xvariable='SurfaceDensity', yvariable='VelocityDispersion', zvariable='Radius', xMin=None, xMax=None, yMin=None, yMax=None, zMin=None, zMax=None, interactive=False, show_log=True, min_marker_width=3, max_marker_width=0.05): """ This is where documentation needs to be added Parameters ---------- NQuery FigureStrBase : str The start of the output filename, e.g. for "my_file.png" it would be my_file xMin xMax yMin yMax zMin zMax min_marker_width : int or float, optional Sets the pixel width of the smallest marker to be plotted. If <1, it is interpreted to be a fraction of the total pixels along the shortest axis. max_marker_width : int or float, optional Sets the pixel width of the smallest marker to be plotted. If <1, it is interpreted to be a fraction of the total pixels along the shortest axis. """ if len(input_table) == 0: raise ValueError("The input table is empty.") figure = matplotlib.figure.Figure() if interactive: from matplotlib import pyplot from matplotlib import _pylab_helpers backend = getattr(matplotlib.backends, 'backend_{0}'.format(matplotlib.rcParams['backend']).lower()) canvas = backend.FigureCanvas(figure) figmanager = backend.FigureManager(canvas, 1) figmanager.canvas.figure.number = 1 _pylab_helpers.Gcf.set_active(figmanager) else: figure = matplotlib.figure.Figure() canvas = FigureCanvasAgg(figure) ax = figure.gca() d = input_table Author = d['Names'] Run = d['IDs'] x_ax = d[xvariable] y_ax = d[yvariable] z_ax = d[zvariable] # Check if limits are given if xMin is None: xMin = x_ax.min() if xMax is None: xMax = x_ax.max() if yMin is None: yMin = y_ax.min() if yMax is None: yMax = y_ax.max() if zMin is None: zMin = z_ax.min() if zMax is None: zMax = z_ax.max() if d['IsSimulated'].dtype == 'bool': IsSim = d['IsSimulated'] else: IsSim = d['IsSimulated'] == 'True' if show_log: if not label_dict_html[xvariable].startswith('log'): label_dict_html[xvariable] = 'log ' + label_dict_html[xvariable] label_dict_html[yvariable] = 'log ' + label_dict_html[yvariable] if not label_dict_png[xvariable].startswith('log'): label_dict_png[xvariable] = 'log ' + label_dict_png[xvariable] label_dict_png[yvariable] = 'log ' + label_dict_png[yvariable] # Select points within the limits Use_x_ax = (x_ax > xMin) & (x_ax < xMax) Use_y_ax = (y_ax > yMin) & (y_ax < yMax) Use_z_ax = (z_ax > zMin) & (z_ax < zMax) # intersects the three subsets defined above Use = Use_x_ax & Use_y_ax & Use_z_ax nptstoplot = np.count_nonzero(Use) if nptstoplot == 0: log.debug("Use: {0}".format(Use)) log.debug("Use_x_ax: {0}".format(Use_x_ax)) log.debug("xmin: {0} xmax: {1}".format(xMin, xMax)) log.debug("x_ax: {0}".format(x_ax)) log.debug("Use_y_ax: {0}".format(Use_y_ax)) log.debug("ymin: {0} ymax: {1}".format(yMin, yMax)) log.debug("y_ax: {0}".format(y_ax)) log.debug("Use_z_ax: {0}".format(Use_z_ax)) log.debug("zmin: {0} zmax: {1}".format(zMin, zMax)) log.debug("z_ax: {0}".format(z_ax)) return None,None else: log.debug("Found {0} points to plot".format(nptstoplot)) UniqueAuthor = list(set(Author[Use])) NUniqueAuthor = len(UniqueAuthor) colors = list(matplotlib.cm.jet(np.linspace(0, 1, NUniqueAuthor))) random.seed(12) random.shuffle(colors) # NOTE this does NOT work with mpld3 # ax.loglog() # Set marker sizes based on a minimum and maximum pixel size, then scale # the rest between. bbox = \ ax.get_window_extent().transformed(figure.dpi_scale_trans.inverted()) min_axis_size = min(bbox.width, bbox.height) * figure.dpi if max_marker_width < 1: max_marker_width *= min_axis_size if min_marker_width < 1: min_marker_width *= min_axis_size marker_conversion = max_marker_width / \ (np.log10(z_ax[Use].max())-np.log10(z_ax[Use].min())) marker_widths = (marker_conversion * (np.log10(np.array(z_ax))-np.log10(z_ax[Use].min())) + min_marker_width) marker_sizes = marker_widths**2 scatters = [] markers = ['o', 's'] for iAu, color in zip(UniqueAuthor, colors): ObsPlot = ((Author == iAu) & (~IsSim)) & Use SimPlot = ((Author == iAu) & (IsSim)) & Use if show_log: plot_x = np.log10(x_ax) plot_y = np.log10(y_ax) if any(ObsPlot): # Change to logs on next commit scatter = \ ax.scatter(plot_x[ObsPlot], plot_y[ObsPlot], marker=markers[0], s=marker_sizes[ObsPlot], color=color, alpha=0.5, edgecolors='k', label=iAu) scatters.append(scatter) labels = [] for row in d[ObsPlot]: colnames = ['<div>{title}</div>'.format(title=col) for col in row.colnames] values = ['<div>{title}</div>'.format(title=str(val)) for val in row] label = "" for col, val in zip(colnames, values): label += col+" "+val+" \n " labels.append(label) tooltip = plugins.PointHTMLTooltip(scatter, labels, voffset=10, hoffset=10) plugins.connect(figure, tooltip) if any(SimPlot): # Change to logs on next commit scatter = \ ax.scatter(plot_x[SimPlot], plot_y[SimPlot], marker=markers[1], s=marker_sizes[SimPlot], color=color, alpha=0.5, edgecolors='k', label=iAu) scatters.append(scatter) labels = [] for row in d[SimPlot]: colnames = ['<div>{title}</div>'.format(title=col) for col in row.colnames] values = ['<div>{title}</div>'.format(title=str(val)) for val in row] label = "" for col, val in zip(colnames, values): label += col+" "+val+" \n " labels.append(label) tooltip = plugins.PointHTMLTooltip(scatter, labels, voffset=10, hoffset=10, css=css) plugins.connect(figure, tooltip) ax.set_xlabel(label_dict_html[xvariable], fontsize=16) ax.set_ylabel(label_dict_html[yvariable], fontsize=16) # Set plot limits. Needed for conversion of pixel units to plot units. # Pad the maximum marker width on. inv = ax.transData.inverted() pad_x, pad_y = inv.transform((marker_widths.max(), marker_widths.max())) - \ inv.transform((0.0, 0.0)) if show_log: ax.set_xlim(np.log10(xMin.value)-pad_x, np.log10(xMax.value)+pad_x) ax.set_ylim(np.log10(yMin.value)-pad_y, np.log10(yMax.value)+pad_y) else: ax.set_xlim(xMin.value - pad_x, xMax.value + pad_x) ax.set_ylim(yMin.value - pad_y, yMax.value + pad_y) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # ax.legend(UniqueAuthor, loc='center left', bbox_to_anchor=(1.0, 0.5), # prop={'size':12}, markerscale = .7, scatterpoints = 1) if hasattr(mpld3.plugins, 'InteractiveLegendPlugin'): plugins.connect(figure, plugins.InteractiveLegendPlugin(scatters, UniqueAuthor, alpha_unsel=0.0, alpha_over=0.5)) # Adding fake points to show the size # Try floor and ceil. Pick the one closest to the max/min. max_z = round_to_pow_10(z_ax[Use].max()) min_z = round_to_pow_10(z_ax[Use].min()) mid_z = round_to_pow_10((max_z + min_z) / 2., log=False) if mid_z == max_z: fake_z_marker_width = np.array([max_z]) elif mid_z == max_z or mid_z == min_z: fake_z_marker_width = np.array([max_z, min_z]) else: fake_z_marker_width = np.array([max_z, mid_z, min_z]) fake_marker_sizes = (marker_conversion * (fake_z_marker_width-np.log10(z_ax[Use].min())) + min_marker_width)**2 # Set the axis fraction to plot the points at. Adjust if the largest # will overlap with the next. sep_ax_frac = 0.05 if np.sqrt(fake_marker_sizes[0])/float(min_axis_size) > 0.05: sep_ax_frac = np.sqrt(fake_marker_sizes[0])/float(min_axis_size) \ + 0.005 xfake = [0.1] * fake_z_marker_width.shape[0] yfake = [0.95 - sep_ax_frac*x for x in range(fake_z_marker_width.shape[0])] # xfake = [xax_limits[0] + xax_limits[0]*2., # xax_limits[0] + xax_limits[0]*2., # xax_limits[0] + xax_limits[0]*2.] # yfake = [yax_limits[1] - yax_limits[1]*0.01, # yax_limits[1] - yax_limits[1]*0.3, # yax_limits[1] - yax_limits[1]*0.6] ax.scatter(np.array(xfake), np.array(yfake), marker='+', s=fake_marker_sizes, transform=ax.transAxes, facecolors='g') for xf, yf, rad in zip(xfake, yfake, fake_z_marker_width): ax.text(xf + 0.05, yf-0.01, str(10**rad) + ' ' + str(zMin.unit), transform=ax.transAxes) # Saving the plots if html_dir is None: html_dir = "" if png_dir is None: png_dir = "" html_file = os.path.join(html_dir, FigureStrBase+NQuery+'.html') png_file = os.path.join(png_dir, FigureStrBase+NQuery+".png") html = mpld3.fig_to_html(figure) with open(html_file, 'w') as f: f.write(html) if interactive: # from matplotlib import pyplot as plt # plt.ion() # plt.show() mpld3.show() # Clear out the plugins plugins.clear(figure) # Use latex labels for the mpl outputted plot ax.set_xlabel(label_dict_png[xvariable], fontsize=16) ax.set_ylabel(label_dict_png[yvariable], fontsize=16) # Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis legend = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), handlelength=4) legend.draw_frame(False) figure.savefig(png_file, bbox_inches='tight', dpi=150) # figure.savefig(FigureStrBase+NQuery+'.pdf',bbox_inches='tight',dpi=150) return html_file, png_file
def render(self, idf, filename='output.html'): progress_inst = helpers.Progress(idf.opt) self.progress = progress_inst.progress if idf.opt['outputFilename']: filename = idf.opt['outputFilename'] if idf.opt['outputAs'] == 'html': # write matplotlib/d3 plots to html file import matplotlib import matplotlib.pyplot as plt, mpld3 import matplotlib.axes from mpld3 import plugins from jinja2 import Environment, FileSystemLoader elif idf.opt['outputAs'] in ['pdf', 'interactive', 'tikz']: # show plots in separate matplotlib windows import matplotlib if idf.opt['outputAs'] == 'pdf': from matplotlib.backends.backend_pdf import PdfPages pp = PdfPages(filename) import matplotlib.pyplot as plt import matplotlib.axes else: print("No proper output method given. Not plotting.") return font_size = 10 if idf.opt['outputAs'] in ['pdf', 'tikz']: if idf.opt['plotPerJoint']: font_size = 30 else: font_size = 12 matplotlib.rcParams.update({'font.size': font_size}) matplotlib.rcParams.update({'axes.labelsize': font_size - 5}) matplotlib.rcParams.update({'axes.linewidth': font_size / 15.}) matplotlib.rcParams.update({'axes.titlesize': font_size - 2}) matplotlib.rcParams.update({'legend.fontsize': font_size - 2}) matplotlib.rcParams.update({'xtick.labelsize': font_size - 5}) matplotlib.rcParams.update({'ytick.labelsize': font_size - 5}) matplotlib.rcParams.update({'lines.linewidth': font_size / 15.}) matplotlib.rcParams.update({'patch.linewidth': font_size / 15.}) matplotlib.rcParams.update({'grid.linewidth': font_size / 20.}) # skip some samples so graphs don't get too large/detailed TODO: change skip so that some # maximum number of points is plotted (determined by screen etc.) skip = 5 #create figures and plots figures = list() for ds in self.progress(range(len(self.datasets))): group = self.datasets[ds] fig, axes = plt.subplots(len(group['dataset']), sharex=True, sharey=True) # scale unified scaling figures to same ranges and add some margin if group['unified_scaling']: ymin = 0 ymax = 0 for i in range(len(group['dataset'])): ymin = np.min( (np.min(group['dataset'][i]['data']), ymin)) * 1.05 ymax = np.max( (np.max(group['dataset'][i]['data']), ymax)) * 1.05 #plot each group of data for d_i in range(len(group['dataset'])): d = group['dataset'][d_i] if not issubclass(type(axes), matplotlib.axes.SubplotBase): ax = axes[d_i] else: ax = axes axes = [axes] if idf.opt['outputAs'] != 'tikz': ax.set_title(d['title']) if group['unified_scaling']: ax.set_ylim([ymin, ymax]) for data_i in range(0, len(d['data'])): if len(d['data'][data_i].shape) > 1: #data matrices for i in range(0, d['data'][data_i].shape[1]): l = group['labels'][i] if data_i == 0 else '' if i < 6 and 'contains_base' in group and group[ 'contains_base']: ls = 'dashed' else: ls = '-' dashes = () # type: Tuple if idf.opt['plotErrors']: if idf.opt['plotPrioriTorques']: n = 3 else: n = 2 if i == n: ls = 'dashed' dashes = (3, 0.5) ax.plot(d['time'][::skip], d['data'][data_i][::skip, i], label=l, color=colors[i], alpha=1 - (data_i / 2.0), linestyle=ls, dashes=dashes) else: #data vector ax.plot(d['time'][::skip], d['data'][data_i][::skip], label=group['labels'][d_i], color=colors[0], alpha=1 - (data_i / 2.0)) ax.grid(which='both', linestyle="dotted", alpha=0.8) if 'y_label' in group: ax.set_ylabel(group['y_label']) if idf.opt['outputAs'] != 'tikz': ax.set_xlabel("Time (s)") plt.setp([a.get_xticklabels() for a in axes[:-1]], visible=False) #plt.setp([a.get_yticklabels() for a in axes], fontsize=8) if idf.opt['plotLegend']: handles, labels = ax.get_legend_handles_labels() if idf.opt['outputAs'] == 'html': #TODO: show legend properly (see mpld3 bug #274) #leg = fig.legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='') leg = axes[0].legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='', prop={'size': 8}) else: leg = plt.figlegend(handles, labels, loc='upper right', fancybox=True, fontsize=font_size, title='', prop={'size': font_size - 3}) leg.draggable() fig.subplots_adjust(hspace=2) fig.set_tight_layout(True) if idf.opt['outputAs'] == 'html': plugins.clear(fig) plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom(enabled=False), plugins.MousePosition(fontsize=14, fmt=".5g")) figures.append(mpld3.fig_to_html(fig)) elif idf.opt['outputAs'] == 'interactive': plt.show(block=False) elif idf.opt['outputAs'] == 'pdf': pp.savefig(plt.gcf()) elif idf.opt['outputAs'] == 'tikz': from matplotlib2tikz import save as tikz_save tikz_save('{}_{}_{}.tex'.format( filename, group['dataset'][0]['title'].replace('_', '-'), ds // idf.model.num_dofs), figureheight='\\figureheight', figurewidth='\\figurewidth', show_info=False) if idf.opt['outputAs'] == 'html': path = os.path.dirname(os.path.abspath(__file__)) template_environment = Environment( autoescape=False, loader=FileSystemLoader(os.path.join(path, '../output')), trim_blocks=False) context = {'figures': figures, 'text': self.text} outfile = os.path.join(path, '..', 'output', filename) import codecs with codecs.open(outfile, 'w', 'utf-8') as f: html = template_environment.get_template( "templates/index.html").render(context) f.write(html) print("Saved output at file://{}".format(outfile)) elif idf.opt['outputAs'] == 'interactive': #keep non-blocking plot windows open plt.show() elif idf.opt['outputAs'] == 'pdf': pp.close()