def plot_segmentation_dictionary(self, x, segmentation_dictionary, figsize=(10, 5)): """ Utility method used to visualize how the segmentation dictionary interacts with the time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :param segmentation_dictionary: A dictionary of the form {'signal_type': [(from, to), (from, to)], ..., 'signal_type': [(from, to), (from, to)]}. :type segmentation_dictionary: dict :param figsize: The size of the figure where we will plot the segmentation on top of the provided time series ((10, 5) default). :type figsize: tuple """ data = x fig, ax = plt.subplots() fig.set_size_inches(figsize[0], figsize[1]) # fix this!! colors = 'bgrcmykwbgrcmykwbgrcmykw' data.plot(ax=ax) for i, (k, v) in enumerate(segmentation_dictionary.items()): for start, end in v: if type(start) != np.datetime64: start = data.index.values[start] end = data.index.values[end] plt.axvspan(start, end, color=colors[i], alpha=0.5) legend = [mpatches.Patch(color=colors[i], label="{}".format(k)) for i, k in enumerate(segmentation_dictionary.keys())] plt.legend(handles=legend) plt.show()
def screeplot(filepath, sigma, comps, div=2, vis=False): y = sigma x = np.arange(len(y)) + 1 plt.subplot(2, 1, 1) plt.plot(x, y, "o-", ms=2) xticks = ["Comp." + str(i) if i%2 == 0 else "" for i in x] plt.xticks(x, xticks, rotation=45, fontsize=20) # plt.yticks([0, .25, .5, .75, 1], fontsize=20) plt.yticks(fontsize=15) plt.ylabel("Variance", fontsize=20) plt.xlim([0, len(y)]) plt.title("Plot of the variance of each Singular component", fontsize=25) plt.axvspan(10, 11, facecolor='g', alpha=0.5) filepath_g = os.path.join(filepath, "graphs") if not os.path.exists(filepath_g): os.makedirs(filepath_g) plt.savefig(filepath_g + "/scree_plot.png", bbox_inches='tight') if vis: plt.show()
def plotEvents(self, x, r=(0, 200), figsize=(5, 5), save=False, figname='mam-median-evts', figtype='png'): """ Plots all the computed events **Parameters** x : double A list of the input data r : int A tuple contains the range of the plotting data figsize : float A tuple of the sizes of the figure save : boolean Indicates if the figure will be saved figname : string The name of the saved figure figtype : string The type of the saved figure (supports png and pdf) """ x = np.asarray(x) plt.figure(figsize=figsize) for i in range(r[0], r[1]): plt.plot(x[i, :], 'k', lw=0.1) plt.plot(np.apply_along_axis(np.median, 0, x[r[0]:r[1], :]), 'r', lw=1) plt.plot(np.apply_along_axis(mad, 0, x[r[0]:r[1], :]), 'b', lw=1) plt.axvspan(45, 89, fc='grey', alpha=0.5, edgecolor='none') plt.axvspan(135, 179, fc='grey', alpha=0.5, edgecolor='none')
def screeplot(filepath, sigma, comps, div=2, vis=False): y = sigma x = np.arange(len(y)) + 1 plt.subplot(2, 1, 1) plt.plot(x, y, "o-", ms=2) xticks = ["Comp." + str(i) if i % 2 == 0 else "" for i in x] plt.xticks(x, xticks, rotation=45, fontsize=20) # plt.yticks([0, .25, .5, .75, 1], fontsize=20) plt.yticks(fontsize=15) plt.ylabel("Variance", fontsize=20) plt.xlim([0, len(y)]) plt.title("Plot of the variance of each Singular component", fontsize=25) plt.axvspan(10, 11, facecolor='g', alpha=0.5) filepath_g = os.path.join(filepath, "graphs") if not os.path.exists(filepath_g): os.makedirs(filepath_g) plt.savefig(filepath_g + "/scree_plot.png", bbox_inches='tight') if vis: plt.show()
def draw_axvspan(rows, score_min, score_max, **kwargs): range_list = [] for row in rows: if score_min <= row[1] <= score_max: range_list.append(row[0]) range_list.sort() if len(range_list) > 2: plt.axvspan(range_list[0], range_list[-1], **kwargs)
def plotEvent(self, x, n_plot=None, events_color='black', events_lw=0.1, show_median=True, median_color='red', median_lw=0.5, show_mad=True, mad_color='blue', mad_lw=0.5): """ Plots an event after clustering. **Parameters** x : double (list or array) Data to be plotted n_plot : int Number of events that will be plotted events_color : string Lines color events_lw : float Line width show_median : boolean If it's True the median will appear in the figure median_color : strin Median curve color median_lw : float Median curve width show_mad : boolean It it's true the mad will appear in the figure mad_color : string Mad curve color mad_lw : float Mad curve width """ x = np.asarray(x) if n_plot is None: n_plot = x.shape[0] for i in range(n_plot): plt.plot(x[i, :], color=events_color, lw=events_lw) if show_median: MEDIAN = np.apply_along_axis(np.median, 0, x) plt.plot(MEDIAN, color=median_color, lw=median_lw) if show_mad: MAD = np.apply_along_axis(mad, 0, x) plt.plot(MAD, color=mad_color, lw=mad_lw) plt.axvspan(45, 89, fc='grey', alpha=.5, edgecolor='none') plt.axvspan(135, 179, fc='grey', alpha=.5, edgecolor='none')
def axvspan_mask(x,mask): """ Plot these three quantities x : independent variable mask : what ranges are masked out """ sL = ma.flatnotmasked_contiguous(ma.masked_array(mask,~mask)) if sL is not None: for s in sL: plt.axvspan(x[s.start],x[s.stop-1],color='LightGrey')
def plot_events(evts_matrix, n_plot=None, n_channels=4, events_color='black', events_lw=0.1, show_median=True, median_color='red', median_lw=0.5, show_mad=True, mad_color='blue', mad_lw=0.5): """Plot events. Formal parameters: evts_matrix: a matrix of events. Rows are events. Cuts from different recording sites are glued one after the other on each row. n_plot: an integer, the number of events to plot (if 'None', default, all are shown). n_channels: an integer, the number of recording channels. events_color: the color used to display events. events_lw: the line width used to display events. show_median: should the median event be displayed? median_color: color used to display the median event. median_lw: line width used to display the median event. show_mad: should the MAD be displayed? mad_color: color used to display the MAD. mad_lw: line width used to display the MAD. Returns: Nothing, the function is used for its side effect. """ if n_plot is None: n_plot = evts_matrix.shape[0] cut_length = evts_matrix.shape[1] // n_channels for i in range(n_plot): plt.plot(evts_matrix[i, :], color=events_color, lw=events_lw) if show_median: MEDIAN = np.apply_along_axis(np.median, 0, evts_matrix) plt.plot(MEDIAN, color=median_color, lw=median_lw) if show_mad: MAD = np.apply_along_axis(mad, 0, evts_matrix) plt.plot(MAD, color=mad_color, lw=mad_lw) left_boundary = np.arange(cut_length, evts_matrix.shape[1], cut_length*2) for l in left_boundary: plt.axvspan(l, l+cut_length-1, facecolor='grey', alpha=0.5, edgecolor='none') plt.xticks([])
def plot_events(evts_matrix, n_plot=None, n_channels=4, events_color='black', events_lw=0.1, show_median=True, median_color='red', median_lw=0.5, show_mad=True, mad_color='blue', mad_lw=0.5): """Plot events. Formal parameters: evts_matrix: a matrix of events. Rows are events. Cuts from different recording sites are glued one after the other on each row. n_plot: an integer, the number of events to plot (if 'None', default, all are shown). n_channels: an integer, the number of recording channels. events_color: the color used to display events. events_lw: the line width used to display events. show_median: should the median event be displayed? median_color: color used to display the median event. median_lw: line width used to display the median event. show_mad: should the MAD be displayed? mad_color: color used to display the MAD. mad_lw: line width used to display the MAD. Returns: Nothing, the function is used for its side effect. """ if n_plot is None: n_plot = evts_matrix.shape[0] cut_length = evts_matrix.shape[1] // n_channels for i in range(n_plot): plt.plot(evts_matrix[i, :], color=events_color, lw=events_lw) if show_median: MEDIAN = np.apply_along_axis(np.median, 0, evts_matrix) plt.plot(MEDIAN, color=median_color, lw=median_lw) if show_mad: MAD = np.apply_along_axis(mad, 0, evts_matrix) plt.plot(MAD, color=mad_color, lw=mad_lw) left_boundary = np.arange(cut_length, evts_matrix.shape[1], cut_length * 2) for l in left_boundary: plt.axvspan(l, l + cut_length - 1, facecolor='grey', alpha=0.5, edgecolor='none') plt.xticks([]) return
def fig_psd(vgp, summary, lctype="granulation"): """ display the power spectral density plots towards the light curve. TODO: improve this function for more lctypes, now we just implement for granulation component. """ from scipy import signal fig = plt.figure(figsize=(6.9, 5.5)) if lctype == "granulation": fluxes = vgp.y2 d = np.median(np.diff(vgp.lc.lcf.time)) * 24 * 3600 fft = np.fft.rfft(fluxes) power = (fft * np.conj(fft)).real / len(fluxes) freq = np.fft.rfftfreq(len(fluxes), d) freq *= 1e6 w0 = np.exp(summary.loc["granulation_logw0"]["mean"]) w0 = w0 / (24 * 3600) S0 = np.exp(summary.loc["granulation_logSw4"]["mean"]) / w0**4 Q = np.exp(summary.loc["granulation_logQ"]["mean"]) w = freq * 1e-6 * 2 * np.pi S_w = np.sqrt(8 * np.pi) * S0 * w0**4 / ( (w**2 - w0**2)**2 + w0**2 * w**2 / Q**2) plt.loglog(freq, power / np.median(power), color="k") plt.loglog(freq, (S_w / np.median(S_w)), color="red") plt.ylim( np.min(S_w / np.median(S_w)) * 1e-2, np.max(S_w / np.median(S_w)) * 10) plt.ylabel("power") plt.xlabel("$\mu Hz$") plt.axvspan(1 / (2.5 * 24 * 3600) * 1e6, np.max(freq), lw=2, alpha=0.5) if lctype == "rotation": f, Pxx_den = signal.periodogram( vgp.y1, 1 / np.median(np.diff(vgp.lc.lcf.time)) / 24 / 3600, detrend=False) if lctype == "total": f, Pxx_den = signal.periodogram( vgp.lc.lcf.flux, 1 / np.median(np.diff(vgp.lc.lcf.time)) / 24 / 3600, detrend=False) #plt.xlim([1e-7, 1/1.5/24/3600]) plt.xlabel('frequency [Hz]') plt.ylabel('$PSD [V^{2}/Hz]$') return fig
def plotspecmodel(w,tspec,mspec,res,mask): """ Plot these three quantities tspec : target spectrum mspec : model spectrum res : residuals mask : wavelenth mask (plot as regions) """ plt.plot(w,tspec) plt.plot(w,mspec) plt.plot(w,res) sL = ma.flatnotmasked_contiguous(ma.masked_array(mask,~mask)) if sL is not None: for s in sL: plt.axvspan(w[s.start],w[s.stop-1],color='LightGrey') plt.ylim(-0.2,1.2) plt.xlim(min(w), max(w))
def make_area_prob_plot(self): #plt.axvspan(0, 0.49475, alpha=0.2, color='gray',label='400') plt.axvspan(0, 0.49475, alpha=0.2, color='gray', label='600') plt.axvspan(0, 0.4435, alpha=0.2, color='gray', label='800') #plt.axvspan(0, 0.4267, alpha=0.2, color='gray',label='200') plt.axvspan(0, 0.3665, alpha=0.2, color='gray', label='1000') plt.axvspan(0, 0.245, alpha=0.2, color='gray', label='1200') plt.axhspan(500, 1200, alpha=0.2, color='gray', label='Ages') plt.axhspan(500, 1000, alpha=0.2, color='gray', label='Ages') plt.axhspan(500, 800, alpha=0.2, color='gray', label='Ages') plt.axhspan(500, 600, alpha=0.2, color='gray', label='Ages') plt.xlim(-0.1, 1.1) plt.ylim(0, 2000) plt.xlabel('Observed Angular Separation') plt.ylabel('Age')
def plotting_NLL(self, tau1_near_min, NLL_near_min_tau1, tau2_near_min, NLL_near_min_tau2, F_near_min,\ NLL_near_min_F, tau1_min, error_tau1, tau2_min,error_tau2, F_min, error_F): #Plot of tau1 against NLL with errors plt.plot(tau1_near_min, NLL_near_min_tau1, color='k') leftedge = tau1_min - error_tau1 rightedge = tau1_min + error_tau1 plt.axvspan(leftedge, rightedge, color='lightcoral', label='error on tau1') plt.axvline(x=tau1_min, color='b', label='tau1 min') plt.xlabel('tau1') plt.ylabel('NLL') plt.legend() plt.savefig('3tau1_error.png', dpi=360) plt.show() #Plot of tau2 against NLL with errors plt.plot(tau2_near_min, NLL_near_min_tau2, color='k') leftedge = tau2_min - error_tau2 rightedge = tau2_min + error_tau2 plt.axvspan(leftedge, rightedge, color='lightcoral', label='error on tau 2') plt.axvline(x=tau2_min, color='b', label='tau2 min') plt.xlabel('tau2') plt.ylabel('NLL') plt.legend() plt.savefig('3tau2_error.png', dpi=360) plt.show() #Plot of F against NLL with errors plt.plot(F_near_min, NLL_near_min_F, color='k') leftedge = F_min - error_F rightedge = F_min + error_F plt.axvspan(leftedge, rightedge, color='lightcoral', label='error F') plt.axvline(x=F_min, color='b', label='F min') plt.xlabel('F') plt.ylabel('NLL') plt.legend() plt.savefig('3F_error.png', dpi=360) plt.show()
YpU += Yp_u YpD += Yp_d no_eprimes = no_eprimes + 1 print '-'*30 print no_eprimes plt.text(2, 60, str(lims[0])+'< spin < '+str(lims[1]), fontsize=30, weight='bold') plt.text(2, 40, 'No eprimes = '+str(no_eprimes), fontsize=25, weight='bold') #plt.plot(X, Y, 'k-', linewidth=2) #plt.plot(X, Yp, 'r-', linewidth=2) plt.plot(X, YU, 'k-', linewidth=2) plt.plot(X, YD, 'k-', linewidth=2) #plt.plot(X, YpU, 'r-', linewidth=2) #plt.plot(X, YpD, 'r-', linewidth=2) plt.axvspan(-5,0, facecolor='0.85', linewidth=0) minor_locator = MultipleLocator(0.10) plt.gca().xaxis.set_minor_locator(minor_locator) plt.gca().tick_params(which='minor', length=5, width=2) plt.gca().tick_params(which='major', length=10, width=2, labelsize=15) #plt.legend(handles=[nps, ps], ncol=2, fontsize=20) plt.xlim([-2, 4]) plt.ylim([-50, 50]) plt.setp(plt.gca().get_yticklabels(), visible=False) plt.gca().tick_params(width=2, labelsize=15) for tick in plt.gca().xaxis.get_major_ticks()+plt.gca().yaxis.get_major_ticks(): tick.label1.set_fontweight('bold') for x in ['top', 'bottom', 'left', 'right']: plt.gca().spines[x].set_linewidth(2)
EdgeRange = int(round(Image.shape[0] * .05 / 10) * 10) plt.figure(figsize=(16, 9)) plt.subplot(311) plt.plot(VerticalProfile) if SelectEdgeManually: plt.title('Select approximate middle of knife edge') EdgePosition = plt.ginput(1) plt.title('Vertical Profile\n(zoom reguion selected manually, width = ' + str(EdgeRange) + ' px, approx. 5% of image)') else: EdgePosition = [[LSF(VerticalProfile).argmax(), np.nan]] plt.title('Vertical Profile\n(zoom region selected automatically, width ' + '= ' + str(EdgeRange) + ' px, approx. 5% of image)') plt.axvspan(EdgePosition[0][0] - EdgeRange, EdgePosition[0][0] + EdgeRange, facecolor='r', alpha=0.5) plt.subplot(312) plt.plot(LSF(VerticalProfile)) plt.axvspan(EdgePosition[0][0] - EdgeRange, EdgePosition[0][0] + EdgeRange, facecolor='r', alpha=0.5) plt.title('LSF') # plt.subplot(413) # plt.plot(MTF(VerticalProfile)) # plt.title('MTF') plt.subplot(3, 3, 7)
def plot_manhattan(gdl, y=None, y_label=None, title=None, output_fname=None, snp_color='#d0d0d0', snp_marker='o', hl_snps=None, hl_snp_color='#cc3300', hl_snp_marker='*', hl_snp_label=None, snp_alpha=0.3, add_bonf_line=True, bonf_line_color='#b06a7a'): starting_pos = 0 ticks = [] chrom_spacing = 25000000 plt.figure(figsize=(12, 6)) if y is None: if add_bonf_line: # Add bonferroni significance threshold line: plt.axhline(-np.log10(0.05 / gdl.M), ls='--', zorder=1, color='#263640') y = {c: -np.log10(pval) for c, pval in gdl.p_values.items()} y_label = "$-log_{10}(p-value)$" unique_chr = gdl.genotype_index for i, c in enumerate(unique_chr): pos = gdl.genotypes[c]['G'].pos.values max_pos = pos.max() xmin = starting_pos #- (chrom_spacing / 2) xmax = max_pos + starting_pos #+ (chrom_spacing / 2) if i % 2 == 1: plt.axvspan(xmin=xmin, xmax=xmax, zorder=0, color='#808080') # TODO: Fix tick positioning ticks.append((xmin + xmax) / 2) plt.scatter(pos + starting_pos, y[c], c=snp_color, alpha=snp_alpha, label=None, marker=snp_marker) if hl_snps is not None: plt.scatter((pos + starting_pos)[hl_snps[c]], y[c][hl_snps[c]], c=hl_snp_color, alpha=snp_alpha, label=hl_snp_label, marker=hl_snp_marker) starting_pos += max_pos #+ chrom_spacing plt.xticks(ticks, unique_chr) plt.xlabel("Genomic Position") plt.ylabel(y_label) if title is not None: plt.title(title) plt.tight_layout() if output_fname is not None: plt.savefig(output_fname) else: plt.show() plt.close()
from autov.autov import lambda2freq plt.style.use('seaborn-paper') hf_data = np.genfromtxt( "/home/koopman/lab/optics/mul/hf/hf_152_183_296_refl_data.txt", delimiter=',') mf_data = np.genfromtxt( "/home/koopman/lab/optics/mul/mf/mf_257_310_500_refl_data.txt", delimiter=',') plt.plot(lambda2freq(hf_data[:, 0]), hf_data[:, 1]) # band numbers from Jan 5th, 2018 telecon here: #https://phy-wiki.princeton.edu/advactwiki/pmwiki.php?n=Telecons.OpticsAndHWPlates?action=download&upname=FTS_2017_Janupdate.pdf plt.axvspan((145 - 36 / 2.), (145 + 36 / 2.), alpha=0.2, color='black', label='_nolegend_') plt.axvspan((222.0 - 73 / 2.), (222.0 + 73 / 2.), alpha=0.2, color='black', label='_nolegend_') plt.ylim([0, 0.08]) plt.axhline(0.01, color='black', linestyle='--') plt.xlabel("Frequency [GHz]") plt.ylabel("Reflectance [%]") plt.title("HF AR Coating Reflectance") plt.savefig("./hf_arc_refl.png", format='png') plt.clf() plt.plot(lambda2freq(mf_data[:, 0]), mf_data[:, 1]) plt.axvspan((96 - 22 / 2.), (96 + 22 / 2.),
color='g') plt.ylim(-0.1, 1.1) plt.xlim(0, len(dirac) // 2) if name == 'dirac': plt.ylabel(' '.join( ['polynomial fit of order', str(degree), '\nfitted MTF @ Nyquist'])) plt.text( 0.618 * len(dirac) // 2, MTF(data)[len(dirac) // 2] - 0.1, ' '.join([ str( np.round(polynomialfit(MTF(data), degree)[len(dirac) // 2], 3) * 100), '%' ]), fontsize=12, backgroundcolor='w') plt.subplot(4, len(plots), 1) plt.plot(dirac, 'b') plt.ylim(-0.1, 4.1) plt.axvspan(len(dirac) // 2 - ShowRegion // 2, len(dirac) // 2 + ShowRegion // 2, facecolor='r', alpha=0.7) plt.title('Ideal knife edge\n red zoom-region\n is shown right') if SaveFigure: plt.savefig('MTF_' + str(int(time.time() * 10)) + '.png') else: plt.show()
def main(**kwargs): DefaultKwargs.update(kwargs) parser = argparse.ArgumentParser() for key, val in list(DefaultKwargs.items()): try: assert np.allclose(int(val), float(val)) _type = int except Exception as e: try: float(val) _type = int except: _type = str parser.add_argument('--' + key, default=val, type=_type) args = parser.parse_args() # Dump contents of args into locals nDocPerBatch = args.nDocPerBatch nDocTotal = args.nDocTotal nWordsPerDoc = args.nWordsPerDoc nFixedInitLaps = args.nFixedInitLaps Kinit = args.Kinit creationProposalName = args.creationProposalName targetUID = args.targetUID doInteractiveViz = args.doInteractiveViz Kfresh = args.Kfresh outputdir = args.outputdir print("OUTPUT: ", outputdir) nBatch = int(nDocTotal // nDocPerBatch) LPkwargs = DefaultLPkwargs import BarsK10V900 Data = BarsK10V900.get_data(nDocTotal=nDocTotal, nWordsPerDoc=nWordsPerDoc) Data.alwaysTrackTruth = 1 DataIterator = Data.to_iterator(nBatch=nBatch, nLap=10) # Use first few docs to initialize! initPRNG = np.random.RandomState(5678) #initDocIDs = initPRNG.choice(Data.nDoc, 25, replace=False) initDocIDs = DataIterator.IDsPerBatch[0][:4] InitData = Data.select_subset_by_mask(initDocIDs) hmodel = bnpy.HModel.CreateEntireModel('moVB', 'HDPTopicModel', 'Mult', dict(alpha=0.5, gamma=10), dict(lam=0.1), Data) hmodel.init_global_params(InitData, K=Kinit, initname='kmeansplusplus', seed=5678) # Do some fixed-truncation local/global steps SS = None SSmemory = dict() nDocsSeenBefore = 0 for lap in range(nFixedInitLaps): for batchID in range(nBatch): Dbatch = DataIterator.getBatch(batchID) LPbatch = hmodel.calc_local_params(Dbatch, **LPkwargs) SSbatch = hmodel.get_global_suff_stats(Dbatch, LPbatch, doPrecompEntropy=1, doTrackTruncationGrowth=1) if batchID in SSmemory: SS -= SSmemory[batchID] SSmemory[batchID] = SSbatch if SS is None: SS = SSbatch.copy() else: SS += SSbatch hmodel.update_global_params(SS) nDocsSeenBefore += SSbatch.nDoc Lines = dict() Lines['xs'] = list() for batchID in range(nBatch): print('batch %d/%d' % (batchID + 1, nBatch)) Dbatch = DataIterator.getBatch(batchID) LPbatch = hmodel.calc_local_params(Dbatch, **LPkwargs) SSbatch = hmodel.get_global_suff_stats(Dbatch, LPbatch, doPrecompEntropy=1, doTrackTruncationGrowth=1) nDocsSeenBefore += SSbatch.nDoc if batchID in SSmemory: SS -= SSmemory[batchID] SSmemory[batchID] = SSbatch if SS is None: SS = SSbatch.copy() else: SS += SSbatch if batchID == 0: xSSbatch, propSSbatch = createSplitStats( Dbatch, hmodel, LPbatch, curSSwhole=SS, creationProposalName=creationProposalName, targetUID=targetUID, batchPos=batchID, newUIDs=np.arange(100, 100 + Kfresh), LPkwargs=LPkwargs, returnPropSS=1) xSSbatch_first = xSSbatch LPbatch_first = LPbatch xSS = xSSbatch.copy() propSS_agg = propSSbatch.copy() else: xSSbatch, propSSbatch = assignSplitStats(Dbatch, hmodel, LPbatch, SS, xSS, targetUID=targetUID, LPkwargs=LPkwargs, returnPropSS=1) xSS += xSSbatch propSS_agg += propSSbatch propSS_whole = propSS_agg.copy() for rembatchID in range(batchID + 1, nBatch): if rembatchID in SSmemory: remSSbatch = SSmemory[rembatchID].copy() Kextra = propSS_whole.K - SSbatch.K if Kextra > 0: remSSbatch.insertEmptyComps(Kextra) propSS_whole += remSSbatch hmodel.update_global_params(SS) if batchID < 32 or (batchID + 1) % 4 == 0: curLscore = hmodel.calc_evidence(SS=SS) curLbyterm = hmodel.calc_evidence(SS=SS, todict=1) propSS = SS.copy() propSS.transferMassFromExistingToExpansion(uid=targetUID, xSS=xSS) for field in ['sumLogPi', 'sumLogPiRemVec']: arr = getattr(propSS, field) arr_direct = getattr(propSS_whole, field) if not np.allclose(arr, arr_direct): print(' Error detected in field: %s' % (field)) from IPython import embed embed() print(' SS field %s verified' % (field)) for field in [ 'gammalnTheta', 'slackTheta', 'slackThetaRem', 'gammalnSumTheta', 'gammalnThetaRem' ]: arr = getattr(propSS._ELBOTerms, field) arr_direct = getattr(propSS_whole._ELBOTerms, field) if not np.allclose(arr, arr_direct): print(' Error detected in field: %s' % (field)) from IPython import embed embed() print(' ELBO field %s verified' % (field)) propModel = hmodel.copy() propModel.update_global_params(propSS) propLscore = propModel.calc_evidence(SS=propSS) propLbyterm = propModel.calc_evidence(SS=propSS, todict=1) assert np.allclose(SS.getCountVec().sum(), propSS.getCountVec().sum()) print(' curLscore %.3f' % (curLscore)) print('propLscore %.3f' % (propLscore)) highlightComps = np.hstack([targetUID, np.arange(Kinit, propSS.K)]) if propLscore > curLscore: print('ACCEPTED!') else: print('REJECTED <<<<<<<<<< :(') if doInteractiveViz: bnpy.viz.PlotComps.plotCompsFromHModel( propModel, compsToHighlight=highlightComps) pylab.show(block=False) keypress = input("Press key to continue >>>") if keypress.count('embed'): from IPython import embed embed() Lines['xs'].append(nDocsSeenBefore) for key in ['Ldata', 'Lentropy', 'Lalloc', 'LcDtheta']: for versionName in ['cur', 'prop']: versionKey = versionName + "-" + key if versionName.count('cur'): val = curLbyterm[key] else: val = propLbyterm[key] try: Lines[versionKey].append(val) except KeyError: Lines[versionKey] = [val] pylab.figure(figsize=(6, 6)) pylab.hold('on') pylab.subplots_adjust(left=0.15, bottom=0.15, right=0.95, top=0.95) legendKeys = ['Ldata', 'Lentropy', 'Lalloc', 'LcDtheta', 'Ltotal'] Lines['cur-Ltotal'] = np.zeros_like(Lines['cur-Ldata']) Lines['prop-Ltotal'] = np.zeros_like(Lines['cur-Ldata']) Lines['xs'] = np.asarray(Lines['xs']) for basekey in legendKeys: if basekey.count('total'): linewidth = 4 alpha = 1 else: linewidth = 3 alpha = 0.5 for modelkey in ['prop', 'cur']: key = modelkey + '-' + basekey Lines[key] = np.asarray(Lines[key]) if key.count('cur'): label = basekey style = '-' if key.count('total') == 0: Lines['cur-Ltotal'] += Lines[key] else: label = None style = '--' if key.count('total') == 0: Lines['prop-Ltotal'] += Lines[key] diffval = Lines['prop-' + basekey] - Lines['cur-' + basekey] pylab.plot(Lines['xs'], diffval, style, color=getColor(key), linewidth=linewidth, alpha=alpha, label=label) pylab.gca().set_xscale('log') M = int(np.ceil(np.log(nDocTotal) / np.log(2))) xticks = np.asarray([2**x for x in range(0, M + 1)]) if xticks.size > 5: xticks = xticks[::2] # keep every second if xticks[-1] < M: xticks = np.append(xticks, M) xlims = [1.0 / 8.0, xticks[-1] * 2] pylab.xlim(xlims) pylab.xticks(xticks) pylab.gca().set_xticklabels(xticks) pylab.ylim([args.ymin, args.ymax]) pylab.plot(xlims, np.zeros_like(xlims), 'k--') pylab.xlabel('number of docs processed') pylab.ylabel('L gain (proposal - current)') good_xs = np.flatnonzero(diffval > 0) if good_xs.size > 0: xstart = Lines['xs'][good_xs[0]] xstop = Lines['xs'][good_xs[-1]] + nDocPerBatch // 2 pylab.axvspan(xstart, xstop, color='green', alpha=0.2) if xstart > nDocPerBatch: pylab.axvspan(xticks[0], xstart, color='red', alpha=0.2) if xstop < nDocTotal: pylab.axvspan(xstop, xticks[-1], color='red', alpha=0.2) else: pylab.axvspan(xlims[0], xlims[-1], color='red', alpha=0.2) pylab.draw() lhandles, labels = pylab.gca().get_legend_handles_labels() order = [0, 1, 4, 2, 3] lhandles = [lhandles[o] for o in order] labels = [labels[o] for o in order] pylab.legend(lhandles, labels, loc='lower left', ncol=1) keys = [ 'nWordsPerDoc', 'nDocPerBatch', 'nDocTotal', 'Kinit', 'targetUID', 'nFixedInitLaps' ] filesuffix = '' for key in keys: filesuffix += '-%s=%d' % (key, getattr(args, key)) filename = os.path.join(outputdir, 'ELBOgain') pylab.savefig(filename + filesuffix + '.png', bbox_inches='tight', pad_inches=0) bnpy.viz.PlotComps.plotCompsFromHModel(hmodel, compsToHighlight=[targetUID]) filename = os.path.join(outputdir, 'BeforeComps') pylab.savefig(filename + filesuffix + '.png', bbox_inches='tight', pad_inches=0) seedModel = hmodel.copy() seedModel.update_global_params(xSSbatch_first) bnpy.viz.PlotComps.plotCompsFromHModel(seedModel) filename = os.path.join(outputdir, 'FirstFreshComps') pylab.savefig(filename + filesuffix + '.png', bbox_inches='tight', pad_inches=0) bnpy.viz.PlotComps.plotCompsFromHModel(propModel, compsToHighlight=highlightComps) filename = os.path.join(outputdir, 'AfterComps') pylab.savefig(filename + filesuffix + '.png', bbox_inches='tight', pad_inches=0) print(filename + filesuffix + '.png', '<<<<<<') # Show document subset! Dfirst = DataIterator.getBatch(0) DocTypeMat = Dfirst.getDocTypeCountMatrix() PRNG = np.random.RandomState(0) if Dfirst.nDoc > 25: relDocs = PRNG.choice(nDocPerBatch, 25, replace=False) DocTypeMat = DocTypeMat[relDocs] else: relDocs = np.arange(Dfirst.nDoc) bnpy.viz.BarsViz.showTopicsAsSquareImages(DocTypeMat, vmax=5, cmap='bone_r') filename = os.path.join(outputdir, 'FirstDocs') pylab.savefig(filename + filesuffix + '.png', bbox_inches='tight', pad_inches=0) # Show reassigned subset of document subset! relResp = LPbatch_first['resp'][:, targetUID] for relID, d in enumerate(relDocs): start = Dfirst.doc_range[d] stop = Dfirst.doc_range[d + 1] DocTypeMat[relID, Dfirst.word_id[start:stop]] *= relResp[start:stop] bnpy.viz.BarsViz.showTopicsAsSquareImages(DocTypeMat, vmax=5, cmap='bone_r') filename = os.path.join(outputdir, 'FirstRelevantDocs') pylab.savefig(filename + filesuffix + '.png', bbox_inches='tight', pad_inches=0) if args.doShowAfter: pylab.show(block=False) keypress = input("Press key to continue >>>") if keypress.count('embed'): from IPython import embed embed()
#!/usr/bin/env python """ Plot spectral profile extracted using RSGISLib """ import numpy from matplotlib import pylab as plt roi_data = numpy.genfromtxt('roi_stats.csv', delimiter=',') wavelengths = roi_data[0,1:] radiance = roi_data[1,1:] plt.plot(wavelengths, radiance, color='black') plt.axvspan(433, 453, color='yellow') plt.axvspan(450, 515, color='blue') plt.axvspan(525, 600, color='green') plt.axvspan(630, 680, color='red') plt.axvspan(845, 885, color='0.5') plt.axvspan(1560, 1660, color='0.5') plt.axvspan(2100, 2300, color='0.5') plt.xlabel('Wavelength (nm)') plt.ylabel('Radiance (nW/cm$2$/sr/nm)') plt.xlim((400,2500)) plt.show() plt.savefig('fenix_radiance_ls8.pdf')
kwargs.update(transform=ax2.transAxes) # switch to the middle axes ax2.plot((-d2,+d2),(-d,+d), **kwargs) # top left ax2.plot((-d2,+d2),(1-d,1+d), **kwargs) # bottom left ax2.plot((1-d2,1+d2),(-d,+d), **kwargs) # bottom right ax2.plot((1-d2,1+d2),(1-d,1+d), **kwargs) # top right kwargs.update(transform=ax3.transAxes) # switch to the right axes ax3.plot((-d3,+d3),(-d,+d), **kwargs) # top left ax3.plot((-d3,+d3),(1-d,1+d), **kwargs) # bottom left fig.suptitle(toplabel, fontsize=16, ) # highlight expanded region plt.axvspan(explims[0],explims[1],color='lightgrey',alpha=0.4) plt.show() # expanded plot fig = plt.figure() ex = fig.add_subplot(1,1,1) # plot limits ex.set_xlim(explims) ax.set_ylim(-0.01,0.81) plt.errorbar(data[xcolumn],data[ycolumn], yerr= data[yerrcolumn],\
pl.subplot(515) pl.title("w") w_ = np.linalg.norm(logdata["w"], axis=1)[sl] print "w_.shape", w_.shape dw = np.diff(logdata["w"], axis=0) print "dw.shape", dw.shape dw_ = np.linalg.norm(dw[sl], axis=1) pl.plot(dw_, "-o") pl.xlabel("t [steps]") # mark icroscoped region for j in range(5): pl.subplot(5, 1, j + 1) pl.axvspan(micro_x[0], micro_x[1], 0., 1., facecolor="k", alpha=0.2) if self.saveplot: pl.gcf().set_size_inches((12, 7)) pl.gcf().savefig("%s-plot_all.pdf" % (sys.argv[0][:-3]), dpi=300, bbox_inches="tight") pl.show() def plot_microscope(self): for i, logdata in enumerate(self.X): # sphero_res_learner_1D/log-learner-20150315-233141-eta-0.001000-theta-0.200000-g-0.999000-target-sine.npz # sphero_res_learner_1D/log-learner-20150315-230854-eta-0.001000-theta-0.200000-g-0.999000-target-sine.npz # sl = slice(70, 140)
def threshold_influence(inp, value_func=get_sign_changes, resolution=100): """ Investigate influence of threshold """ def plot_matrix(data): plt.tick_params( axis='both', which='both', labelleft='off', bottom='off', top='off', labelbottom='off', left='off', right='off') plt.imshow( data, interpolation='nearest', cmap=get_matrix_cmap(), vmin=0, vmax=3) plt.colorbar(ticks=range(np.max(data)+1), extend='min') global THRESHOLD threshold_list = np.logspace(-4, 0, resolution) # compute stdev of difference between reference and embedded 3 node motif cur_diffs = [] for raw, enh_res in inp['data']: _, rd = raw _, rdm, _ = rd for enh in enh_res: _, ed = enh _, edm, _ = ed if not edm is None: diff = abs(rdm - edm[:-1,:-1]) cur_diffs.extend(diff.ravel()) stdev = np.std(cur_diffs) # produce data first_data, last_data, std_data = None, None, None pairs = [] for thres in tqdm(threshold_list): THRESHOLD = thres data = [] for raw, enh_res in inp['data']: # for each parameter configuration data.append([handle_enh_entry(raw, enh, value_func) for enh in enh_res]) data = np.array(data) if thres == threshold_list[0]: first_data = data if thres == threshold_list[-1]: last_data = data if thres >= stdev and std_data is None: std_data = data mat_res = np.sum(data[data>0]) pairs.append((thres, mat_res)) print('Data shape:', data.shape) total_num = data[data>=0].size * 3 # plot result value_func_name = value_func.__name__[4:] plt.figure() nz_vec = [(t, m/total_num) for t,m in pairs if m>0] z_vec = [(t, m/total_num) for t,m in pairs if m<=0] plt.plot(*zip(*nz_vec), 'o') plt.plot(*zip(*z_vec), 'o', color='red') plt.axvspan( xmin=1e-6, xmax=stdev, alpha=0.1, color='blue') plt.annotate('correlation stdev ({:.02})'.format(stdev), xy=(stdev, .03), xycoords='data', xytext=(50, 20), textcoords='offset points', arrowprops=dict(arrowstyle='->')) plt.xscale('log') plt.title('Influence of binning threshold on number of {}'.format(value_func_name)) plt.xlabel('binning threshold') plt.ylabel('frequency of {}'.format(value_func_name)) # inside plots plt.style.use('default') ax = plt.axes([0.1, 0.5, .2, .2]) plot_matrix(first_data) ax = plt.axes([0.7, 0.4, .2, .2]) plot_matrix(last_data) ax = plt.axes([0.4, 0.2, .2, .2]) plot_matrix(std_data) # save result save_figure('images/threshold_influence_{}.pdf'.format(value_func_name), bbox_inches='tight')
plt.plot(MTF(data), label='orig') # for degree in range(10,25): # plt.plot(polynomialfit(MTF(data), degree), label=str(degree)) # plt.legend() degree = 4 plt.plot(polynomialfit(MTF(data), degree), label=str(degree), color='r') plt.plot(np.ones(N) * polynomialfit(MTF(data), degree)[len(dirac) / 2], color='g') plt.ylim(-0.1, 1.1) plt.xlim(0, len(dirac) / 2) if name == 'dirac': plt.ylabel(' '.join(['polynomial fit of order', str(degree), '\nfitted MTF @ Nyquist'])) plt.text(0.618 * len(dirac) / 2, MTF(data)[len(dirac) / 2] - 0.1, ' '.join([str(np.round(polynomialfit(MTF(data), degree)[len(dirac) / 2], 3) * 100), '%']), fontsize=12, backgroundcolor='w') plt.subplot(4, len(plots), 1) plt.plot(dirac, 'b') plt.ylim(-0.1, 1.1) plt.axvspan(len(dirac) / 2 - ShowRegion / 2, len(dirac) / 2 + ShowRegion / 2, facecolor='r', alpha=0.5) plt.title('Ideal knife edge\n red zoom-region\n is shown right') if SaveFigure: plt.savefig('MTF_' + str(int(time.time() * 10)) + '.png') else: plt.show()
def plot(self, title, xlim=None, ylim=None, plot_type='amplitude', show_limits=False, show_ssa_limits=False, beam_on=False, annotate=False, beam_start=20, beam_end=22, hide_fwd=False): """ Plot signals of interest in RF Station time-series simulation. Supports amplitude, phase and cartesian plots with a number of options. """ fund_k_probe = self.fund_mode_dict['k_probe'] fund_k_drive = self.fund_mode_dict['k_drive'] fund_k_em = self.fund_mode_dict['k_em'] fund_k_beam = self.fund_mode_dict['k_beam'] # Amplitude if plot_type == 'amplitude': if hide_fwd == False: plt.plot(self.trang * 1e3, np.abs(self.E_fwd) * fund_k_drive, '-', label=r'Forward $\left(\vec E_{\rm fwd}\right)$', linewidth=2) plt.plot(self.trang * 1e3, np.abs(self.E_reverse / fund_k_em), '-', label=r'Reverse $\left(\vec E_{\rm reverse}\right)$', linewidth=2) plt.plot(self.trang * 1e3, np.abs(self.cav_v), '-', label=r'Cavity Field', linewidth=2, color='r') plt.plot(self.trang * 1e3, np.abs(self.set_point / fund_k_probe), '-', label=r'Set-point $\left(\vec E_{\rm sp}\right)$', linewidth=2, color='c') # Y label plt.ylabel('Amplitude [V]', fontsize=30) if show_limits == True: plt.plot(self.trang * 1e3, np.abs(self.set_point / fund_k_probe) * (1 + 1e-4), label='Upper limit', linewidth=2, color='m') plt.plot(self.trang * 1e3, np.abs(self.set_point / fund_k_probe) * (1 - 1e-4), label='Lower limit', linewidth=2, color='y') plt.axhspan(16e6 / 1.00005, 16e6 * 1.00005, color='blue', alpha=0.2) if show_ssa_limits == True: # If SSA noise were a sine wave, this would be the amplitude limit ssa_limit = 4e-2 * fund_k_drive * np.sqrt(3.8e3) plt.plot(self.trang * 1e3, np.abs(self.set_point / fund_k_probe) + ssa_limit / np.sqrt(2) / 2, label='SSA Upper (RMS) limit', linewidth=2, color='m') plt.plot(self.trang * 1e3, np.abs(self.set_point / fund_k_probe) - ssa_limit / np.sqrt(2) / 2, label='SSA Lower (RMS) limit', linewidth=2, color='y') low_index = np.where(self.trang == 20e-3)[0][0] high_index = np.where(self.trang == 49.9e-3)[0][0] ssa_std = np.std(self.E_fwd[low_index:high_index] * fund_k_drive) ssa_std_percent = 100 * ssa_std / (fund_k_drive * np.sqrt(3.8e3)) ssa_std_text = r'$\sigma_{\rm SSA}\,=\,$' + '%.2f %% RMS' % ( np.abs(ssa_std_percent)) plt.text(35, 13e6, ssa_std_text, verticalalignment='top', fontsize=30) # Phase if plot_type == 'phase': plt.plot(self.trang * 1e3, np.angle(self.cav_v, deg=True), '-', label=r'Cavity Field', linewidth=2, color='r') plt.plot(self.trang * 1e3, np.angle(self.set_point / fund_k_probe, deg=True), label=r'Set-point $\left(\vec E_{\rm sp}\right)$', linewidth=2, color='c') if show_limits: plt.plot(self.trang * 1e3, 1e-2 * np.ones(len(self.trang)), label='Upper limit', linewidth=2, color='m') plt.plot(self.trang * 1e3, -1e-2 * np.ones(len(self.trang)), label='Lower limit', linewidth=2, color='y') plt.axhspan(-4e-3, 4e-3, color='blue', alpha=0.2) # Y label plt.ylabel('Phase [degrees]', fontsize=30) # Cartesian coordinates if plot_type == 'cartesian': plt.plot(self.trang * 1e3, np.real(self.E_fwd) * fund_k_drive, '-', label=r'Forward $\Re \left(\vec E_{\rm fwd}\right)$', linewidth=2) plt.plot(self.trang * 1e3, np.imag(self.E_fwd) * fund_k_drive, '-', label=r'Forward $\Im \left(\vec E_{\rm fwd}\right)$', linewidth=2) plt.plot(self.trang * 1e3, np.real(self.cav_v), '-', label=r'$\Re$ Cavity Field', linewidth=2) plt.plot(self.trang * 1e3, np.imag(self.cav_v), '-', label=r'$\Im$ Cavity Field', linewidth=2) # Add annotation for a very specific plot if annotate: delta_E_fwd_text = r'$\Delta \left| \vec E_{\rm fwd} \right| \approx \,$' + '%.d MV' % ( round(np.abs(fund_k_beam) * 100e-6 * 1e-6)) plt.annotate(delta_E_fwd_text, xy=(21.05, 18e6), fontsize=25) index_of_21 = np.where(self.trang == 21e-3) plt.annotate(s='', xy=(21, np.abs(self.E_fwd[index_of_21]) * fund_k_drive), xytext=(21, np.abs(self.cav_v[index_of_21])), arrowprops=dict(arrowstyle='<->')) # Add clear red shade if beam current is on to highlight the location of the beam train if beam_on: plt.axvspan(beam_start, beam_end, color='red', alpha=0.2) plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.title(title, fontsize=40, y=1.02) plt.xlabel('Time [ms]', fontsize=30) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) plt.rc('font', **{'size': 20}) plt.legend(loc='upper right') plt.show()
# width EdgeRange = int(round(Image.shape[0] * .05 / 10) * 10) plt.figure(figsize=(16, 9)) plt.subplot(311) plt.plot(VerticalProfile) if SelectEdgeManually: plt.title('Select approximate middle of knife edge') EdgePosition = plt.ginput(1) plt.title('Vertical Profile\n(zoom reguion selected manually, width = ' + str(EdgeRange) + ' px, approx. 5% of image)') else: EdgePosition = [[LSF(VerticalProfile).argmax(), np.nan]] plt.title('Vertical Profile\n(zoom region selected automatically, width ' + '= ' + str(EdgeRange) + ' px, approx. 5% of image)') plt.axvspan(EdgePosition[0][0] - EdgeRange, EdgePosition[0][0] + EdgeRange, facecolor='r', alpha=0.5) plt.subplot(312) plt.plot(LSF(VerticalProfile)) plt.axvspan(EdgePosition[0][0] - EdgeRange, EdgePosition[0][0] + EdgeRange, facecolor='r', alpha=0.5) plt.title('LSF') # plt.subplot(413) # plt.plot(MTF(VerticalProfile)) # plt.title('MTF') plt.subplot(3, 3, 7) plt.plot(VerticalProfile) plt.xlim(EdgePosition[0][0] - EdgeRange, EdgePosition[0][0] + EdgeRange) plt.title('Zoomed Edge')
data = np.loadtxt(filename) x = data[:, 0] y = data[:, 1] x, y = zip(*sorted(zip(x, y))) plt.plot(x, y, "{{line_type}}", label=label) ax = plt.gca() for lines_and_labels in {{lines_and_labels}}: next_color = ax._get_lines.get_next_color() for x_pos, label in lines_and_labels: plt.axvline(x_pos, label=label, color=next_color) for ranges in {{ranges}}: next_color = ax._get_lines.get_next_color() for x1, x2 in ranges: plt.axvspan(x1, x2, color=next_color) for a_label, a_x, a_y in {{annotations}}: plt.annotate(a_label, xy=(a_x, a_y), xytext=(-20, 20), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')) plt.title('{{title}}') plt.xlabel('{{xlabel}}') plt.ylabel('{{ylabel}}')
# get equivalent atom from passified structure i_x, at_p = get_similar(at_e, p_str) print '{:5.3f}'.format(distance(at_e, at_p)), x, y_u, y_d = get_at_pdos(c+'p', i_x) x = [o(p) for p in x] plt.plot(x, y_u, 'r-', linewidth=2.5) ps,= plt.plot(x, y_d, 'r-', label='H passivated', linewidth=2.5) print minor_locator = MultipleLocator(0.10) plt.gca().xaxis.set_minor_locator(minor_locator) plt.gca().tick_params(which='minor', length=5, width=2) plt.gca().tick_params(which='major', length=10, width=2, labelsize=15) plt.legend(handles=[nps, ps], ncol=2, fontsize=20) plt.axvspan(o(-5),o(-3.313), facecolor='0.85', linewidth=0) plt.axvspan(o(-2.27),o(0.0), facecolor='0.85', linewidth=0) plt.xlim([o(-5), o(0)]) plt.ylim([-60, 60]) plt.setp(plt.gca().get_yticklabels(), visible=False) plt.gca().tick_params(width=2, labelsize=15) for tick in plt.gca().xaxis.get_major_ticks()+plt.gca().yaxis.get_major_ticks(): tick.label1.set_fontweight('bold') for x in ['top', 'bottom', 'left', 'right']: plt.gca().spines[x].set_linewidth(2) plt.gca().get_legend().get_frame().set_linewidth(2) plt.xlabel('Energy [eV]', fontweight='bold', fontsize=20) plt.gcf().set_size_inches(20., 3.5)
# open h5py file and convert to numpy array path = '/rxs/rx1' f = h5py.File(file_name, 'r') data = f[path + '/' + field] arr = np.array(data) if arr.ndim != 1: print "exiting, data needs to be 1D" exit(0) # convert x-axis to time time = np.arange(0, f.attrs['dt'] * f.attrs['Iterations'], f.attrs['dt']) time = time / 1E-9 # set plotting params plt.rcParams['figure.figsize'] = 10, 6 plt.rcParams['xtick.labelsize'] = 13 plt.rcParams['ytick.labelsize'] = 13 # plot A-scan plt.plot(time, arr, 'red', linewidth=2) plt.axvspan(0.5, 1.5, color='blue', alpha=0.5) plt.axvspan(1.8, 2.6, color='green', alpha=0.5) plt.title('A-scan', fontsize=20) plt.xlabel('Time [ns]', fontsize=20) plt.ylabel('Field Strength [V/m]', fontsize=20) plt.grid() plt.savefig(out_dir + '/' + 'A-scan', format='png') print "A-scan plotted and saved in current directory"