def plot(self): slope, intercept, rvalue, pvalue, stderr = stats.linregress( self.xvec, self.yvec) fig = plt.figure(figsize=(8, 6)) plt.plot(self.xvec, self.yvec, 'o') # plt.hold(True) # removed intentionally since matplotlib 3.0 a = slope b = intercept ax = plt.gca() # adjust tick size if self.labelsize is not None: ax.tick_params(labelsize=self.labelsize) xlim = ax.get_xlim() x0 = xlim[0] x1 = xlim[1] plt.plot(xlim, [a * x0 + b, a * x1 + b]) if self.title_show_corr: plt.title(self.title + ' r:{:0.3} p:{:0.3}'.format(rvalue, pvalue)) else: plt.title(self.title) plt.xlabel(self.xlabel) plt.ylabel(self.ylabel) path.makedirs_file(self.outfilepath) fig.savefig(self.outfilepath, dpi=300) plt.close()
def run_mriscan(self, mriscan): src = os.path.join(self.preprocessedFolder, mriscan, 'Filtered_4DVolume.nii') if os.path.isfile(src): dst = os.path.join(self.exportFolder, mriscan, 'pBOLD.nii') path.makedirs_file(dst) shutil.copy2(src, dst) print(mriscan, 'OK') else: print(mriscan, 'not found', src)
def save(self, outfile, addticks=True): """Save the attr, can add ticks defined in atlasobj.""" if addticks is False: save_csvmat(outfile, self.data) else: path.makedirs_file(outfile) with open(outfile, 'w', newline='') as f: writer = csv.writer(f) writer.writerow(('Region', 'Value')) for tick, value in zip(self.atlasobj.ticks, self.data): writer.writerow((tick, value))
def download(self, urlpath, outfilepath): """Blocking download file to outfilepath.""" makedirs_file(outfilepath) print(urlpath) r = requests.get(self.full_url(urlpath), stream=True, **self._reqparams) if r.status_code != 200: print('Download not allowed or file not exist') return False with open(outfilepath, 'wb') as f: shutil.copyfileobj(r.raw, f) print('Download OK') return True
def run_feature(self, feature_name, feature_config): """ Export one feature. feature_name is used in sub-classes """ in_file_list, out_file_list = self.get_feature_file_path(feature_config) for file, filedst in zip(in_file_list, out_file_list): if not os.path.isfile(file): print('==Not Exist:', file) continue path.makedirs_file(filedst) #print('Copy:', file, filedst) shutil.copy2(file, filedst)
def get_file(self, urlpath, localpath): """Get file blocking.""" makedirs_file(localpath) url = self.full_url(urlpath) r = requests.get(url, stream=True, **self._reqparams) if r.status_code != 200: self.error(r, url) return False print('Retriving file from {} to {} '.format(url, localpath), end='') with open(localpath, 'wb') as f: shutil.copyfileobj(r.raw, f) print('OK') return True
def save_list_to_csv(list_data, outfile): """ save a list of dicts to a csv file :param list_data: a list of dicts :param outfile: :return: """ path.makedirs_file(outfile) with open(outfile, 'w', newline = '') as f: writer = csv.DictWriter(f, list_data[0].keys(), delimiter = ',') writer.writeheader() for itm in list_data: writer.writerow(itm)
def save(self, outfile, addticks=True): """Save the net, can add ticks defined in atlasobj.""" if addticks is False: save_csvmat(outfile, self.data) else: path.makedirs_file(outfile) with open(outfile, 'w', newline='') as f: writer = csv.writer(f) ticks = self.atlasobj.ticks firstrow = ['Region'] firstrow.extend(ticks) writer.writerow(firstrow) for tick, datarow in zip(self.atlasobj.ticks, self.data): currow = [tick] currow.extend(datarow) writer.writerow(currow)
def plot(self): plt.figure(figsize=(20, 6)) for attr in self.attrs: self.count = attr.data.shape[1] plt.plot(range(1, self.count + 1), attr.data[self.regionIdx, :], '.-', label=attr.scan) plt.xlim([0, self.count + 1]) plt.xticks(range(1, self.count + 1), range(1, self.count * self.stepSize, self.stepSize)) plt.grid(True) plt.legend() plt.title(self.title, fontsize=20) path.makedirs_file(self.outfilepath) plt.savefig(self.outfilepath, dpi=100) plt.close()
def plot(self, sig_positions=None, stat_list=None, adjust_method=None): """ sig_positions should be a vector of 0 and 1, where 1 stands for significance specify adjust_method as a string ('RSN', 'circos'). Defaults to plot_index """ plt.figure(figsize=(20, 6)) plt.xlim(self.xlim) plt.ylim(self.ylim) ax = plt.gca() if stat_list is not None: # keep significant stats according to sig_positions stat_list = list(stat_list) # persist zip new_list = [] for idx, flag in enumerate(sig_positions): if flag: stat_list[idx] += (idx, ) new_list.append(stat_list[idx]) stat_list = new_list if adjust_method == 'RSN': self.adjust_RSN(ax, sig_positions) elif adjust_method == 'circos': self.adjust_circos(ax, sig_positions) else: self.adjust_plot_index(sig_positions) for attr in self.attrs: plt.plot(range(self.count), attr.data, '.-', label=attr.scan) plt.xticks(range(self.count), self.plot_ticks, rotation=60) if sig_positions is not None: self.add_markers() plt.grid(True) plt.legend() plt.title(self.title, fontsize=20) path.makedirs_file(self.outfilepath) plt.savefig(self.outfilepath, dpi=100) plt.close() if stat_list is not None: # add text goes AFTER the image is saved self.add_text(stat_list)
def plot(self): """Do the plot.""" fig = plt.figure(figsize=(20, 8)) netdata_adjusted = self.atlasobj.adjust_mat_col(self.rowsmat) netdata_adjusted = np.nan_to_num(netdata_adjusted) axim = plt.imshow(netdata_adjusted, interpolation='none', cmap=self.get_cmap(), vmin=self.valuerange[0], vmax=self.valuerange[1]) nrow = self.rowsmat.shape[0] _, ncol = netdata_adjusted.shape ax = fig.gca() ax.set_xticks(range(self.count)) ax.set_xticklabels(self.atlasobj.ticks_adjusted, rotation=90) ax.set_yticks(range(nrow)) ax.set_yticklabels(self.rowsticks) ax.set_xlim(-0.5, ncol-0.5) ax.set_ylim(nrow-0.5, -0.5) #fig.colorbar(axim) plt.title(self.title, fontsize=24) path.makedirs_file(self.outfilepath) plt.savefig(self.outfilepath, dpi=100) plt.close()
def plot(self): """Do the plot.""" fig = plt.figure(figsize=(20, 20)) netdata_adjusted = self.atlasobj.adjust_mat(self.net.data) netdata_adjusted = np.nan_to_num(netdata_adjusted) axim = plt.imshow(netdata_adjusted, interpolation='none', cmap=self.cmap, vmin=self.valuerange[0], vmax=self.valuerange[1]) nrow, ncol = netdata_adjusted.shape ax = fig.gca() ax.set_xlim(-0.5, ncol-0.5) ax.set_ylim(nrow-0.5, -0.5) # set ticks if self.show_ticks: ax.set_xticks(range(self.count)) ax.set_xticklabels(self.atlasobj.ticks_adjusted, rotation=90) ax.set_yticks(range(self.count)) ax.set_yticklabels(self.atlasobj.ticks_adjusted) else: ax.set_xticks([]) ax.set_yticks([]) # set colorbar if self.show_colorbar: cbar = fig.colorbar(axim, fraction=0.046, pad=0.04) # change colorbar ticks font size # see https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params # and https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html#matplotlib.axes.Axes.tick_params cbar.ax.tick_params(labelsize = 25, length = 5, width = 5) # save fig plt.title(self.title, fontsize = self.title_font_size) path.makedirs_file(self.outfilepath) plt.savefig(self.outfilepath, dpi = 200) plt.close()
def get_file_progress(self, urlpath, localpath): """Get file blocking, with a fancy progress bar.""" makedirs_file(localpath) url = self.full_url(urlpath) r = requests.get(url, stream=True, **self._reqparams) filesize = int(r.headers['content-length']) if r.status_code != 200: self.error(r, url) return False downloadedsize = 0 progress = 0 print('Retriving file from {} to {} '.format(url, localpath)) with open(localpath, 'wb') as f: for chunk in r.iter_content(chunk_size=self.CHUNK_SIZE): if chunk: downloadedsize = downloadedsize + self.CHUNK_SIZE newprogress = downloadedsize * self.PROGRESSBAR_LENGTH // filesize newprogress = newprogress if newprogress < self.PROGRESSBAR_LENGTH else self.PROGRESSBAR_LENGTH if newprogress != progress: print('#' * (newprogress - progress), end='') progress = newprogress f.write(chunk) print(' OK') return True
def write(self, outedgefile): """Write the edge file.""" path.makedirs_file(outedgefile) np.savetxt(outedgefile, self.net.data, delimiter='\t')
def __init__(self, mriscansfolder, outcsvname): """Use information from the main mriscan folder, export summary to csv.""" self.mriscansfolder = mriscansfolder self.outcsvname = outcsvname path.makedirs_file(self.outcsvname)
def plotRSN(self): """ Similar as plot(), but plot the heatmap according to RSN config file and use black lines to separate RSNs """ fig = plt.figure(figsize=(20, 20)) netdata_adjusted = self.atlasobj.adjust_mat_RSN(self.net.data) netdata_adjusted = np.nan_to_num(netdata_adjusted) axim = plt.imshow(netdata_adjusted, interpolation='none', cmap=self.cmap, vmin=self.valuerange[0], vmax=self.valuerange[1]) nrow, ncol = netdata_adjusted.shape ax = fig.gca() ax.set_xlim(-0.5, ncol-0.5) ax.set_ylim(nrow-0.5, -0.5) # set ticks ticks_adjusted, nodeCount = self.atlasobj.adjust_ticks_RSN() if self.show_ticks: ax.set_xticks(range(self.count)) ax.set_xticklabels(ticks_adjusted, rotation=90) ax.set_yticks(range(self.count)) ax.set_yticklabels(ticks_adjusted) else: ax.set_xticks([]) ax.set_yticks([]) # plot horizontal and vertical lines plotIdx = -0.5 ax.vlines(plotIdx, -0.5, self.count, linewidths = 5) # vposition, start, end ax.hlines(plotIdx, -0.5, self.count, linewidths = 5) # hposition, start, end border = [0] # the border of each RSN, including 0 and max for idx in range(len(nodeCount)): netCount = nodeCount[idx] plotIdx += netCount ax.vlines(plotIdx, -0.5, self.count, linewidths = 5) # vposition, start, end ax.hlines(plotIdx, -0.5, self.count, linewidths = 5) # hposition, start, end border.append(border[-1] + netCount) # add ticks for RSN minorTicks = [] for idx in range(len(border) - 1): minorTicks.append((border[idx] + border[idx+1])/2.0) ax.set_xticks(minorTicks, minor=True) ax.set_yticks(minorTicks, minor=True) ax.tick_params(which="minor", bottom=False, left=False, pad=35, labelsize = 30) # make minor ticks invisible ax.set_xticklabels(self.atlasobj.get_RSN_list(), minor = True) ax.set_yticklabels(self.atlasobj.get_RSN_list(), minor = True) # set colorbar if self.show_colorbar: cbar = fig.colorbar(axim, fraction=0.046, pad=0.04) # change colorbar ticks font size # see https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params # and https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html#matplotlib.axes.Axes.tick_params cbar.ax.tick_params(labelsize = 25, length = 5, width = 5) # save fig plt.title(self.title, fontsize = self.title_font_size) path.makedirs_file(self.outfilepath) plt.savefig(self.outfilepath, dpi=200) plt.close()
def write(self, outnodefile): """Write current data to a new node file.""" path.makedirs_file(outnodefile) with open(outnodefile, 'w', newline='') as f: writer = csv.writer(f, delimiter='\t') writer.writerows(self.nodedata)