def plot_scatter_clickable(obj, var, axis_names=None, axis_ranges=None): global exit_program exit_program = True k = obj.shape[1] fig, ax = plt.subplots() ax.set_title("Pareto front") if k == 2: ax.plot(obj[:, 0], obj[:, 1], marker='o', picker=True, pickradius=5, linestyle='None') if axis_names is not None and len(axis_names) == 2: plt.xlabel(axis_names[0]) plt.ylabel(axis_names[1]) fig.canvas.mpl_connect('pick_event', lambda e: onpick(e, var, obj, False)) elif k == 3: ax = fig.add_subplot(projection='3d') ax.plot(obj[:, 0], obj[:, 1], obj[:, 2], marker='o', picker=True, pickradius=5, linestyle='None') if axis_names is not None and len(axis_names) == 3: ax.set_xlabel(axis_names[0]) ax.set_ylabel(axis_names[1]) ax.set_zlabel(axis_names[2]) fig.canvas.mpl_connect('pick_event', lambda e: onpick(e, var, obj, True)) else: raise Exception("Wrong dimension count") if axis_ranges is not None and axis_ranges.shape[0] == 2: plt.xlim(axis_ranges[0]) plt.ylim(axis_ranges[1]) if k == 3: plt.zlim(axis_ranges[2]) plt.show()
def plot_band2D(self, efermi=None, spin=0, band=None, cmap='jet', save=False, figsize=(8, 6), figname='BAND2D', xlim=None, ylim=None, zlim=None, fontsize=16, dpi=600, format='png'): '''Plot band structure Attribute: efermi : a Fermi level or a list of Fermi levels spin : 0 for spin unpolarized and LSORBIT = .TRUE. 0 or 1 for spin polarized label : label for high symmetric points, e.g. 'G-X-L-W-G' if hybridXC=True, the lavel should be a list of labels plus their coordinates color : a list of three color codes for band curves, high symmetric kpoint grid, and Fermi level ''' band_idx = band if band_idx == None: idx_vbm = int(self.nelec) if self.soc == False: idx_vbm = idx_vbm // 2 # Estimation for insulator, generally wrong for metal band_idx = [idx_vbm - 1, idx_vbm] else: assert band_idx[0] <= band_idx[1] # from band[0] to band[1] if band_idx[0] < 1: band_idx[ 0] = 1 # index used in OUTCAR, will be shifted to start at zero if band_idx[1] > self.nbands: band_idx[ 1] = self.nbands # Cannot larger than the number of bands band_idx[0] = band_idx[0] - 1 band_idx[1] = band_idx[1] - 1 band, proj_kpath, sym_kpoint_coor, klabel = self._generate_band( self.vasprun, efermi, spin, klabel=None) # Get X, Y kpoint = vasp_io.KPOINTS() plane, krange, npoint = kpoint.get_spin_kmesh() deltax = 2 * krange[0] / (npoint[0] - 1) deltay = 2 * krange[1] / (npoint[1] - 1) X, Y = np.mgrid[-krange[0]:(krange[0] + deltax * 0.5):deltax, -krange[1]:(krange[1] + deltay * 0.5):deltay] Z = band.reshape(npoint[0], npoint[1], self.nbands) ##---------------------------------------------------------- ##Plotting: ##---------------------------------------------------------- fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='3d') # Plot bands vmin = Z[:, :, band_idx[0]:band_idx[1] + 1].min() vmax = Z[:, :, band_idx[0]:band_idx[1] + 1].max() for ith in range(band_idx[0], band_idx[1] + 1): surf = ax.plot_surface(X, Y, Z[:, :, ith], cmap=cmap, vmin=vmin, vmax=vmax, linewidth=0, antialiased=False) # Graph adjustments ax.tick_params(labelsize=fontsize) if xlim == None: xlim = [X.min(), X.max()] if ylim == None: ylim = [Y.min(), Y.max()] if zlim != None: plt.zlim(zlim) plt.xlim(xlim) plt.ylim(ylim) if plane == 'xy': x_label = r'$k_x$' y_label = r'$k_y$' elif plane == 'xz': x_label = r'$k_x$' y_label = r'$k_z$' elif plane == 'yz': x_label = r'$k_y$' y_label = r'$k_z$' ax.set_xlabel(x_label + r' ($\AA^{-1}$)', size=fontsize + 4) ax.set_ylabel(y_label + r' ($\AA^{-1}$)', size=fontsize + 4) ax.set_zlabel('Energy (eV)', size=fontsize + 4) ax.set_xticks([xlim[0], 0, xlim[1]]) ax.set_yticks([ylim[0], 0, ylim[1]]) ax.xaxis.labelpad = 15 ax.yaxis.labelpad = 15 ax.zaxis.labelpad = 15 cbar = fig.colorbar(surf, shrink=0.5, aspect=20) cbar.ax.tick_params(labelsize=fontsize + 4) plt.tight_layout() if save == True: fig.savefig('Band.' + format, dpi=dpi, format=format) else: plt.show()
def compare_three_features(feature_names, scaled=False, xlimit=0, ylimit=0, zlimit=0, ts_size=0.3): ''' the features name should be in the following format: feature_names=['poi', 'from_this_person_to_poi', 'from_poi_to_this_person', 'salary'] where the first field 'poi' is used to distinguish pois from non-pois and the rest are axes of the 3D plot. For example, try this: feature_names=['poi', 'from_this_person_to_poi', 'from_poi_to_this_person', 'salary'] compare_three_features(feature_names) It allows scaling each feature (by maximum value) to demonstrate if it would be meaning ful to scale this feature while conbining. ''' short_data = featureFormat(my_dataset, feature_names, sort_keys=True) short_labels, short_features = targetFeatureSplit(short_data) #simple train-test split: #why split? Because I want to understand the trend, not look at all the information #then I might mentally overfit x_train, x_test, y_train, y_test = train_test_split(short_features, short_labels, test_size=ts_size, random_state=42) #find correlaion between these two: first = [] second = [] third = [] for item in x_train: first.append(item[0]) second.append(item[1]) third.append(item[2]) if scaled: first /= max(first) second /= max(second) third /= max(third) #print("first", first) #print("second", second) r2 = np.corrcoef([first, second, third]) #[0, 1] print("correlation coefficient", r2) #let's divide up the training sample into the two classes: #all pois: first_poi = [] first_non_poi = [] second_poi = [] second_non_poi = [] third_poi = [] third_non_poi = [] for i in range(0, len(y_train)): if y_train[i] == 1: first_poi.append(first[i]) second_poi.append(second[i]) third_poi.append(third[i]) else: first_non_poi.append(first[i]) second_non_poi.append(second[i]) third_non_poi.append(third[i]) #plot fig = plt.figure() ax = fig.add_subplot(111, projection='3d') if xlimit != 0: plt.xlim(-10, xlimit) if ylimit != 0: plt.ylim(-10, ylimit) if zlimit != 0: plt.zlim(-10, zlimit) ax.scatter(first_non_poi, second_non_poi, third_non_poi, facecolor="blue", s=20, edgecolors="blue", alpha=0.5) ax.scatter(first_poi, second_poi, third_poi, facecolor="none", edgecolors="red", s=20) ax.set_xlabel(feature_names[1]) ax.set_ylabel(feature_names[2]) ax.set_zlabel(feature_names[3]) plt.show() return 1
def plot(self, filename=None, show=True, legend=False, elim=None): """Plot the band structure. :param filename: Filename of the plot (if it is None, plot will not be saved). :param show: Show the plot in a matplotlib frontend. :param legend: Show a plot legend describing the bands. :param elim: Limits on the "energy" axis. """ import matplotlib.pyplot as plt if self.kvectors is None: # Zero-dimensional system plt.plot(self.energies[0], linewidth=0, marker='+') elif self.kvectors.dim == 1: for b, energy in enumerate(self.energies.T): plt.plot(self.kvectors.pathLength, energy, label=str(b)) if self.kvectors.specialpoints_idx is not None: specialpoints = self.kvectors.pathLength[self.kvectors.specialpoints_idx] plt.xticks(specialpoints, self.kvectors.specialpoints_labels) plt.xlim(min(specialpoints), max(specialpoints)) if elim is not None: plt.ylim(elim) if legend: plt.legend() else: from mpl_toolkits.mplot3d import Axes3D # noqa from matplotlib import cm fig = plt.figure() ax = fig.add_subplot(111, projection='3d') eMin = np.nanmin(self.energies) eMax = np.nanmax(self.energies) for band in range(self.energies.shape[-1]): energy = self.energies[..., band].copy() energy[np.isnan(energy)] = np.nanmin(energy) ax.plot_surface(self.kvectors.points_masked[..., 0], self.kvectors.points_masked[..., 1], energy, cstride=1, rstride=1, cmap=cm.cool, vmin=eMin, vmax=eMax, linewidth=0.001, antialiased=True ) if elim is not None: plt.zlim(elim) # === output === if filename is not None: plt.savefig(filename.format(**self.params)) if show: plt.show()
def run( step, parset, H ): import matplotlib.pyplot as plt import numpy as np from h5parm import solFetcher solsets = getParSolsets( step, parset, H ) soltabs = getParSoltabs( step, parset, H ) ants = getParAxis( step, parset, H, 'ant' ) pols = getParAxis( step, parset, H, 'pol' ) dirs = getParAxis( step, parset, H, 'dir' ) plotType = parset.getString('.'.join(["LoSoTo.Steps", step, "PlotType"]), '' ) axesToPlot = parset.getStringVector('.'.join(["LoSoTo.Steps", step, "Axes"]), '' ) minZ, maxZ = parset.getDoubleVector('.'.join(["LoSoTo.Steps", step, "MinMax"]), [0,0] ) prefix = parset.getString('.'.join(["LoSoTo.Steps", step, "Prefix"]), '' ) if plotType.lower() in ['1d', '2d']: for soltab in openSoltabs( H, soltabs ): sf = solFetcher(soltab) logging.info("Plotting soltab: "+soltab._v_name) sf.setSelection(ant=ants, pol=pols, dir=dirs) # some checks for axis in axesToPlot: if axis not in sf.getAxesNames(): logging.error('Axis \"'+axis+'\" not found.') return 1 if (len(axesToPlot) != 2 and plotType == '2D') or \ (len(axesToPlot) != 1 and plotType == '1D'): logging.error('Wrong number of axes.') return 1 for vals, coord in sf.getValuesIter(returnAxes=axesToPlot): # TODO: implement flag control, using different color? title = '' for axis in coord: if axis in axesToPlot: continue title += str(coord[axis])+'_' title = title[:-1] if plotType == '2D': fig = plt.figure() ax = plt.subplot(111) plt.title(title) plt.ylabel(axesToPlot[0]) plt.xlabel(axesToPlot[1]) p = ax.imshow(coord[axesToPlot[1]], coord[axesToPlot[0]], vals) if not (minZ == 0 and maxZ == 0): plt.zlim(zmin=minZ, zmax=maxZ) plt.savefig(title+'.png') logging.info("Saving "+prefix+title+'.png') if plotType == '1D': fig = plt.figure() ax = plt.subplot(111) plt.title(title) plt.ylabel(sf.getType()) if not (minZ == 0 and maxZ == 0): plt.ylim(ymin=minZ, ymax=maxZ) plt.xlabel(axesToPlot[0]) p = ax.plot(coord[axesToPlot[0]], vals) plt.savefig(prefix+title+'.png') logging.info("Saving "+prefix+title+'.png') elif plotType.lower() == 'tecscreen': # Plot various TEC-screen properties for st_scr in openSoltabs(H, soltabs): # Check if soltab is a tecscreen table full_name = st_scr._v_parent._v_name + '/' + st_scr._v_name if st_scr._v_title != 'tecscreen': logging.warning('Solution table {0} is not a tecscreen solution ' 'table. Skipping.'.format(full_name)) continue logging.info('Using input solution table: {0}'.format(full_name)) # Plot TEC screens as images solset = st_scr._v_parent sf_scr = solFetcher(st_scr) r, axis_vals = sf_scr.getValues() source_names = axis_vals['dir'] station_names = axis_vals['ant'] station_dict = H.getAnt(solset) station_positions = [] for station in station_names: station_positions.append(station_dict[station]) times = axis_vals['time'] tec_screen, axis_vals = sf_scr.getValues() times = axis_vals['time'] residuals = sf_scr.getValues(weight=True, retAxesVals=False) height = st_scr._v_attrs['height'] order = st_scr._v_attrs['order'] beta_val = st_scr._v_attrs['beta'] r_0 = st_scr._v_attrs['r_0'] pp = sf_scr.t.piercepoint if (minZ == 0 and maxZ == 0): min_tec = None max_tec = None else: min_tec = minZ max_tec = maxZ make_tec_screen_plots(pp, tec_screen, residuals, np.array(station_positions), np.array(source_names), times, height, order, beta_val, r_0, prefix=prefix, remove_gradient=True, show_source_names=False, min_tec=min_tec, max_tec=max_tec) return 0
def plot(self, filename=None, show=True, legend=False, elim=None): """Plot the band structure. :param filename: Filename of the plot (if it is None, plot will not be saved). :param show: Show the plot in a matplotlib frontend. :param legend: Show a plot legend describing the bands. :param elim: Limits on the "energy" axis. """ import matplotlib.pyplot as plt if self.kvectors is None: # Zero-dimensional system plt.plot(self.energies[0], linewidth=0, marker='+') elif self.kvectors.dim == 1: for b, energy in enumerate(self.energies.T): plt.plot(self.kvectors.pathLength, energy, label=str(b)) if self.kvectors.specialpoints_idx is not None: specialpoints = self.kvectors.pathLength[ self.kvectors.specialpoints_idx] plt.xticks(specialpoints, self.kvectors.specialpoints_labels) plt.xlim(min(specialpoints), max(specialpoints)) if elim is not None: plt.ylim(elim) if legend: plt.legend() else: from mpl_toolkits.mplot3d import Axes3D # noqa from matplotlib import cm fig = plt.figure() ax = fig.add_subplot(111, projection='3d') eMin = np.nanmin(self.energies) eMax = np.nanmax(self.energies) for band in range(self.energies.shape[-1]): energy = self.energies[..., band].copy() energy[np.isnan(energy)] = np.nanmin(energy) ax.plot_surface(self.kvectors.points_masked[..., 0], self.kvectors.points_masked[..., 1], energy, cstride=1, rstride=1, cmap=cm.cool, vmin=eMin, vmax=eMax, linewidth=0.001, antialiased=True) if elim is not None: plt.zlim(elim) # === output === if filename is not None: plt.savefig(filename.format(**self.params)) if show: plt.show()
obsPx.append(x) obsPy.append(y) obsPz.append(z) if iteration < 0: targetX.append(x) targetY.append(y) targetZ.append(z) if status > 0: partTX.append(x) partTY.append(y) partTZ.append(z) else: obsTx.append(x) obsTy.append(y) obsTz.append(z) fig = plt.figure(projection='3d') fig.set_size_inches(14, 14) plt.scatter(obsPx, obsPy, obsPz, s=60, c='w', marker='o') plt.scatter(partPX, partPY, partPZ, s=60, c='r', marker='o') plt.scatter(obsTx, obsTy, obsTz, s=60, c='w', marker='o') plt.scatter(partTX, partTY, partTZ, s=60, c='g', marker='o') plt.xlim(-12, 12) plt.ylim(-12, 12) plt.zlim(-10, 10) plt.show()
def run(step, parset, H): import matplotlib.pyplot as plt import numpy as np from h5parm import solFetcher solsets = getParSolsets(step, parset, H) soltabs = getParSoltabs(step, parset, H) ants = getParAxis(step, parset, H, 'ant') pols = getParAxis(step, parset, H, 'pol') dirs = getParAxis(step, parset, H, 'dir') plotType = parset.getString('.'.join(["LoSoTo.Steps", step, "PlotType"]), '') axesToPlot = parset.getStringVector( '.'.join(["LoSoTo.Steps", step, "Axes"]), '') minZ, maxZ = parset.getDoubleVector( '.'.join(["LoSoTo.Steps", step, "MinMax"]), [0, 0]) prefix = parset.getString('.'.join(["LoSoTo.Steps", step, "Prefix"]), '') if plotType.lower() in ['1d', '2d']: for soltab in openSoltabs(H, soltabs): sf = solFetcher(soltab) logging.info("Plotting soltab: " + soltab._v_name) sf.setSelection(ant=ants, pol=pols, dir=dirs) # some checks for axis in axesToPlot: if axis not in sf.getAxesNames(): logging.error('Axis \"' + axis + '\" not found.') return 1 if (len(axesToPlot) != 2 and plotType == '2D') or \ (len(axesToPlot) != 1 and plotType == '1D'): logging.error('Wrong number of axes.') return 1 for vals, coord in sf.getValuesIter(returnAxes=axesToPlot): # TODO: implement flag control, using different color? title = '' for axis in coord: if axis in axesToPlot: continue title += str(coord[axis]) + '_' title = title[:-1] if plotType == '2D': fig = plt.figure() ax = plt.subplot(111) plt.title(title) plt.ylabel(axesToPlot[0]) plt.xlabel(axesToPlot[1]) p = ax.imshow(coord[axesToPlot[1]], coord[axesToPlot[0]], vals) if not (minZ == 0 and maxZ == 0): plt.zlim(zmin=minZ, zmax=maxZ) plt.savefig(title + '.png') logging.info("Saving " + prefix + title + '.png') if plotType == '1D': fig = plt.figure() ax = plt.subplot(111) plt.title(title) plt.ylabel(sf.getType()) if not (minZ == 0 and maxZ == 0): plt.ylim(ymin=minZ, ymax=maxZ) plt.xlabel(axesToPlot[0]) p = ax.plot(coord[axesToPlot[0]], vals) plt.savefig(prefix + title + '.png') logging.info("Saving " + prefix + title + '.png') elif plotType.lower() == 'tecscreen': # Plot various TEC-screen properties for st_scr in openSoltabs(H, soltabs): # Check if soltab is a tecscreen table full_name = st_scr._v_parent._v_name + '/' + st_scr._v_name if st_scr._v_title != 'tecscreen': logging.warning( 'Solution table {0} is not a tecscreen solution ' 'table. Skipping.'.format(full_name)) continue logging.info('Using input solution table: {0}'.format(full_name)) # Plot TEC screens as images solset = st_scr._v_parent sf_scr = solFetcher(st_scr) r, axis_vals = sf_scr.getValues() source_names = axis_vals['dir'] station_names = axis_vals['ant'] station_dict = H.getAnt(solset) station_positions = [] for station in station_names: station_positions.append(station_dict[station]) times = axis_vals['time'] tec_screen, axis_vals = sf_scr.getValues() times = axis_vals['time'] residuals = sf_scr.getValues(weight=True, retAxesVals=False) height = st_scr._v_attrs['height'] order = st_scr._v_attrs['order'] beta_val = st_scr._v_attrs['beta'] r_0 = st_scr._v_attrs['r_0'] pp = sf_scr.t.piercepoint if (minZ == 0 and maxZ == 0): min_tec = None max_tec = None else: min_tec = minZ max_tec = maxZ make_tec_screen_plots(pp, tec_screen, residuals, np.array(station_positions), np.array(source_names), times, height, order, beta_val, r_0, prefix=prefix, remove_gradient=True, show_source_names=False, min_tec=min_tec, max_tec=max_tec) return 0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 16 13:45:33 2017 @author: punit """ from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np k = np.loadtxt('H2D.txt') fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = k[:, 0] y = k[:, 1] z = k[:, 2] z2 = k[:, 3] ax.plot(x, y, z, color='r') ax.plot(x, y, z2, color='g') plt.zlim(-5, 5) plt.show()
def run( step, parset, H ): import matplotlib.pyplot as plt import numpy as np from h5parm import solFetcher solsets = getParSolsets( step, parset, H ) soltabs = getParSoltabs( step, parset, H ) ants = getParAxis( step, parset, H, 'ant' ) pols = getParAxis( step, parset, H, 'pol' ) dirs = getParAxis( step, parset, H, 'dir' ) plotType = parset.getString('.'.join(["LoSoTo.Steps", step, "PlotType"]), '' ) axesToPlot = parset.getStringVector('.'.join(["LoSoTo.Steps", step, "Axes"]), '' ) minZ, maxZ = parset.getDoubleVector('.'.join(["LoSoTo.Steps", step, "MinMax"]), [0,0] ) prefix = parset.getString('.'.join(["LoSoTo.Steps", step, "Prefix"]), '' ) if plotType.lower() != 'tecscreen': for soltab in openSoltabs( H, soltabs ): sf = solFetcher(soltab) logging.info("Plotting soltab: "+soltab._v_name) sf.setSelection(ant=ants, pol=pols, dir=dirs) # some checks for axis in axesToPlot: if axis not in sf.getAxesNames(): logging.error('Axis \"'+axis+'\" not found.') return 1 if (len(axesToPlot) != 2 and plotType == '2D') or \ (len(axesToPlot) != 1 and plotType == '1D'): logging.error('Wrong number of axes.') return 1 for vals, coord in sf.getValuesIter(returnAxes=axesToPlot): # TODO: implement flag control, using different color? title = '' for axis in coord: if axis in axesToPlot: continue title += str(coord[axis])+'_' title = title[:-1] if plotType == '2D': fig = plt.figure() ax = plt.subplot(111) plt.title(title) plt.ylabel(axesToPlot[0]) plt.xlabel(axesToPlot[1]) p = ax.imshow(coord[axesToPlot[1]], coord[axesToPlot[0]], vals) if not (minZ == 0 and maxZ == 0): plt.zlim(zmin=minZ, zmax=maxZ) plt.savefig(title+'.png') logging.info("Saving "+prefix+title+'.png') if plotType == '1D': fig = plt.figure() ax = plt.subplot(111) plt.title(title) plt.ylabel(sf.getType()) if not (minZ == 0 and maxZ == 0): plt.ylim(ymin=minZ, ymax=maxZ) plt.xlabel(axesToPlot[0]) p = ax.plot(coord[axesToPlot[0]], vals) plt.savefig(prefix+title+'.png') logging.info("Saving "+prefix+title+'.png') else: # Plot TEC screens i = 0 st_tec = None st_pp = None st_tfw = None # Find required soltabs for st in openSoltabs(H, soltabs): if st._v_title == 'tec': st_tec = st tec_indx = i elif st._v_title == 'tecfitwhite': st_tfw = st elif st._v_title == 'piercepoint': st_pp = st i += 1 if st_tec is None or st_pp is None or st_tfw is None: logging.warning('One or more of the required TEC solution tables ' 'not found') return 1 solset = soltabs[tec_indx].split('/')[0] station_dict = H.getAnt(solset) station_names = station_dict.keys() station_positions = station_dict.values() source_dict = H.getSou(solset) source_names = source_dict.keys() source_positions = source_dict.values() sf_tec = solFetcher(st_tec) r, axis_vals = sf_tec.getValues() times = axis_vals['time'] N_sources = len(source_names) N_times = len(times) N_stations = len(station_names) N_piercepoints = N_sources * N_stations rr = np.reshape(r.transpose([0, 2, 1]), [ N_piercepoints, N_times]) sf_pp = solFetcher(st_pp) pp = sf_pp.getValues(retAxesVals=False) height = st_tfw._v_attrs['height'] order = st_tfw._v_attrs['order'] beta_val = st_tfw._v_attrs['beta'] r_0 = st_tfw._v_attrs['r_0'] sf_tfw = solFetcher(st_tfw) tec_fit_white = sf_tfw.getValues(retAxesVals=False) tec_fit = sf_tfw.getValues(weight=True, retAxesVals=False) make_tec_screen_plots(pp, rr, tec_fit_white, tec_fit, np.array(station_positions), np.array(source_names), times, height, order, beta_val, r_0, prefix=prefix, remove_gradient=True) return 0