def plot_snapshot(self, t, resolution=1, **kwargs): if 'plot' not in globals(): print("Cannot plot, is cartopy installed?") return() if self.sourcegrid is None: msg = 'Must have a source grid to plot a snapshot.' raise ValueError(msg) map_x = self.sourcegrid[0][0::resolution] map_y = self.sourcegrid[1][0::resolution] if type(self.stats['data_quantity']) != str: data_quantity = self.stats['data_quantity'].decode() else: data_quantity = self.stats['data_quantity'] if data_quantity == 'DIS': quant_unit = 'Displacement (m)' elif data_quantity == 'VEL': quant_unit = 'Velocity (m/s)' elif data_quantity == 'ACC': quant_unit = 'Acceleration (m/s^2)' plot.plot_grid(map_x, map_y, self.get_snapshot(t, resolution=resolution), title='Discretized wave field after %g seconds' % t, quant_unit=quant_unit, **kwargs)
def plot_snapshot(self,t,resolution=1,**kwargs): if self.sourcegrid is None: msg = 'Must have a source grid to plot a snapshot.' raise ValueError(msg) # ToDo: Replace all the hardcoded geographical boundary values! map_x = self.sourcegrid[0][0::resolution] map_y = self.sourcegrid[1][0::resolution] plot.plot_grid(map_x,map_y,self.get_snapshot(t,resolution=resolution),**kwargs)
def plot_snapshot(self, t, resolution=1, **kwargs): if self.sourcegrid is None: msg = 'Must have a source grid to plot a snapshot.' raise ValueError(msg) # ToDo: Replace all the hardcoded geographical boundary values! map_x = self.sourcegrid[0][0::resolution] map_y = self.sourcegrid[1][0::resolution] plot.plot_grid(map_x, map_y, self.get_snapshot(t, resolution=resolution), **kwargs)
def test_gauss_smoothing(sourcegrid, map): # grd = np.load(sourcegrid)[:, 0:10000] v = np.ones(grd.shape[1]) ihalf = grd.shape[1] // 2 v[ihalf:] = 10 np.save('temp_coord.npy', grd) np.save('temp_vals.npy', v) plot_grid(grd[0], grd[1], v) smooth_map = apply_smoothing_sphere('temp_vals.npy', 'test', 'temp_coord.npy', 500000) print smooth_map.shape plot_grid(grd[0], grd[1], smooth_map)
weights1[0] = 0. #print weights1 # spectra --- much harder to assign manually, since we need weights for every location. just assigning ones.\n", weights2 = np.ones((np.shape(grd)[-1], np.shape(basis2)[0])) i = 0 for spec in params_gaussian_spectra: weights2[:, i] *= spec['weight'] print 'Plotting...' from noisi.util import plot distr = np.dot(weights1, basis1) plot.plot_grid(grd[0], grd[1], distr, outfile=os.path.join(sourcepath, 'geog_distr_startingmodel.png')) plt.figure() plt.semilogx(freq, np.dot(weights2[0, :], basis2)) plt.xlabel('Frequency (Hz)') plt.ylabel('Source power (scaled)') plt.savefig(os.path.join(sourcepath, 'freq_distr_startingmodel.png')) # Save to an hdf5 file print basis2 with h5py.File(os.path.join(sourcepath, 'step_0', 'starting_model.h5'), 'w') as fh: fh.create_dataset('coordinates', data=grd.astype(np.float32))
elif distributions[i] in ['ocean', 'homogeneous']: basis_geo[i, :] = get_geodist(distributions[i]) else: print(distributions) raise NotImplementedError('Unknown geographical distributions. \ Must be \'gaussian\', \'homogeneous\' or \'ocean\'.') try: print('Plotting...') from noisi.util import plot for i in range(num_bases): plot.plot_grid(grd[0], grd[1], basis_geo[i, :], normalize=False, outfile=os.path.join( sourcepath, 'geog_distr_basis{}.png'.format(i))) except ImportError: print('Plotting not possible (is basemap installed?)') ######################### # spectrum ######################### if measr_config['bandpass'] is None: basis_spec = np.array(np.ones(len(freq)), ndmin=2) else: num_sbases = len(measr_config['bandpass']) basis_spec = np.zeros((num_sbases, len(freq)))
def plot(self, **options): # plot the distribution for i in range(self.distr_basis.shape[-1]): m = self.distr_basis[:, i] plot_grid(self.src_loc[0], self.src_loc[1], m, **options)
elif distributions[i] in ['ocean','homogeneous']: basis_geo[i,:] = get_geodist(distributions[i]) else: print(distributions) raise NotImplementedError('Unknown geographical distributions. \ Must be \'gaussian\', \'homogeneous\' or \'ocean\'.') try: print('Plotting...') from noisi.util import plot for i in range(num_bases): plot.plot_grid(grd[0],grd[1],basis_geo[i,:],normalize=False, outfile = os.path.join(sourcepath,'geog_distr_basis{}.png'.format(i))) except ImportError: print('Plotting not possible (is basemap installed?)') ######################### # spectrum ######################### if measr_config['bandpass'] is None: basis_spec = np.array(np.ones(len(freq)),ndmin=2) else: num_sbases = len(measr_config['bandpass']) basis_spec = np.zeros((num_sbases,len(freq))) for i in range(num_sbases): basis_spec[i,:] = get_specbasis(measr_config['bandpass'][i])
if gaussian_blobs: i = 1 for blob in params_gaussian_blobs: weights1[i] = blob['rel_weight'] i+=1 if no_background: weights1[0] = 0. # from noisi.util import plot distr = np.dot(weights1,basis1) plot.plot_grid(grd[0],grd[1],distr,outfile = os.path.join(sourcepath,'geog_distr_startingmodel.png')) plt.figure() plt.semilogx(freq,basis2[0,:]) plt.xlabel('Frequency (Hz)') plt.ylabel('Source power (scaled)') plt.savefig(os.path.join(sourcepath,'freq_distr_startingmodel.png')) # Save to an hdf5 file with h5py.File(os.path.join(sourcepath,'step_0','starting_model.h5'),'w') as fh: fh.create_dataset('coordinates',data=grd.astype(np.float32)) fh.create_dataset('frequencies',data=freq.astype(np.float32)) fh.create_dataset('distr_basis',data=basis1.astype(np.float32))
def setup_source_startingmodel(self, args): # plotting: colors = ['purple', 'g', 'b', 'orange'] colors_cmaps = [ plt.cm.Purples, plt.cm.Greens, plt.cm.Blues, plt.cm.Oranges ] print("Setting up source starting model.", end="\n") with io.open(os.path.join(args.source_model, 'source_config.yml'), 'r') as fh: source_conf = yaml.safe_load(fh) with io.open(os.path.join(source_conf['project_path'], 'config.yml'), 'r') as fh: conf = yaml.safe_load(fh) with io.open(source_conf['source_setup_file'], 'r') as fh: parameter_sets = yaml.safe_load(fh) if conf['verbose']: print("The following input parameters are used:", end="\n") pp = pprint.PrettyPrinter() pp.pprint(parameter_sets) # load the source locations of the grid grd = np.load(os.path.join(conf['project_path'], 'sourcegrid.npy')) # add the approximate spherical surface elements if grd.shape[-1] < 50000: surf_el = get_spherical_surface_elements(grd[0], grd[1]) else: warn('Large grid; surface element computation slow. Using \ approximate surface elements.') surf_el = np.ones(grd.shape[-1]) * conf['grid_dx_in_m']**2 # get the relevant array sizes wfs = glob(os.path.join(conf['project_path'], 'greens', '*.h5')) if wfs != []: if conf['verbose']: print('Found wavefield stats.') else: pass else: raise FileNotFoundError('No wavefield database found. Run \ precompute_wavefield first.') with WaveField(wfs[0]) as wf: df = wf.stats['Fs'] n = wf.stats['npad'] freq = np.fft.rfftfreq(n, d=1. / df) n_distr = len(parameter_sets) coeffs = np.zeros((grd.shape[-1], n_distr)) spectra = np.zeros((n_distr, len(freq))) # fill in the distributions and the spectra for i in range(n_distr): coeffs[:, i] = self.distribution_from_parameters( grd, parameter_sets[i], conf['verbose']) # plot outfile = os.path.join(args.source_model, 'source_starting_model_distr%g.png' % i) if create_plot: plot_grid(grd[0], grd[1], coeffs[:, i], outfile=outfile, cmap=colors_cmaps[i % len(colors_cmaps)], sequential=True, normalize=False, quant_unit='Spatial weight (-)', axislabelpad=-0.1, size=10) spectra[i, :] = self.spectrum_from_parameters( freq, parameter_sets[i]) # plotting the spectra # plotting is not necessarily done to make sure code runs on clusters if create_plot: fig1 = plt.figure() ax = fig1.add_subplot('111') for i in range(n_distr): ax.plot(freq, spectra[i, :] / spectra.max(), color=colors[i % len(colors_cmaps)]) ax.set_xlabel('Frequency / Nyquist Frequency') plt.xticks([ 0, freq.max() * 0.25, freq.max() * 0.5, freq.max() * 0.75, freq.max() ], ['0', '0.25', '0.5', '0.75', '1']) ax.set_ylabel('Rel. PSD norm. to strongest spectrum (-)') fig1.savefig( os.path.join(args.source_model, 'source_starting_model_spectra.png')) # Save to an hdf5 file with h5py.File( os.path.join(args.source_model, 'iteration_0', 'starting_model.h5'), 'w') as fh: fh.create_dataset('coordinates', data=grd) fh.create_dataset('frequencies', data=freq) fh.create_dataset('model', data=coeffs.astype(np.float)) fh.create_dataset('spectral_basis', data=spectra.astype(np.float)) fh.create_dataset('surface_areas', data=surf_el.astype(np.float)) # Save to an hdf5 file with h5py.File(os.path.join(args.source_model, 'spectral_model.h5'), 'w') as fh: uniform_spatial = np.ones(coeffs.shape) * 1.0 fh.create_dataset('coordinates', data=grd) fh.create_dataset('frequencies', data=freq) fh.create_dataset('model', data=uniform_spatial.astype(np.float)) fh.create_dataset('spectral_basis', data=spectra.astype(np.float)) fh.create_dataset('surface_areas', data=surf_el.astype(np.float))
def plot(self,**options): # plot the distribution for m in self.spatial_source_model: plot_grid(self.src_loc[0],self.src_loc[1],m,**options)
def plot(self,**options): # plot the distribution m = self.expand_distr() plot_grid(self.src_loc[0],self.src_loc[1],m,**options)