def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) ####### test binary files f_bin = viscid.load_file(_viscid_root + "/../sample/ath_sample.*.bin") for i, grid in enumerate(f_bin.iter_times(":")): plt.subplot2grid((2, 2), (0, i)) mpl.plot(grid["bx"]) plt.subplot2grid((2, 2), (1, i)) mpl.plot(grid["by"]) if args.show: mpl.tighten() mpl.mplshow() plt.clf() ####### test ascii files f_tab = viscid.load_file(_viscid_root + "/../sample/ath_sample.*.tab") for i, grid in enumerate(f_tab.iter_times(":")): plt.subplot2grid((2, 2), (0, i)) mpl.plot(grid["bx"]) plt.subplot2grid((2, 2), (1, i)) mpl.plot(grid["by"]) if args.show: mpl.tighten() mpl.mplshow() plt.clf()
def main(): f = viscid.load_file("~/dev/work/tmedium/*.3d.[-1].xdmf") grid = f.get_grid() gslc = "x=-26f:12.5f, y=-15f:15f, z=-15f:15f" # gslc = "x=-12.5f:26f, y=-15f:15f, z=-15f:15f" b_cc = f['b_cc'][gslc] b_cc.name = "b_cc" b_fc = f['b_fc'][gslc] b_fc.name = "b_fc" e_cc = f['e_cc'][gslc] e_cc.name = "e_cc" e_ec = f['e_ec'][gslc] e_ec.name = "e_ec" pp = f['pp'][gslc] pp.name = 'pp' pargs = dict(logscale=True, earth=True) # vlt.clf() # ax1 = vlt.subplot(211) # vlt.plot(f['pp']['y=0f'], **pargs) # # vlt.plot(viscid.magnitude(f['b_cc']['y=0f']), **pargs) # # vlt.show() # vlt.subplot(212, sharex=ax1, sharey=ax1) # vlt.plot(viscid.magnitude(viscid.fc2cc(f['b_fc'])['y=0f']), **pargs) # vlt.show() basename = './tmediumR.3d.{0:06d}'.format(int(grid.time)) viscid.save_fields(basename + '.h5', [b_cc, b_fc, e_cc, e_ec, pp]) f2 = viscid.load_file(basename + ".xdmf") pargs = dict(logscale=True, earth=True) vlt.clf() ax1 = vlt.subplot(211) vlt.plot(f2['pp']['y=0f'], style='contour', levels=5, colorbar=None, colors='k', **pargs) vlt.plot(viscid.magnitude(f2['b_cc']['y=0f']), **pargs) vlt.subplot(212, sharex=ax1, sharey=ax1) vlt.plot(viscid.magnitude(viscid.fc2cc(f2['b_fc'])['y=0f']), **pargs) vlt.show() os.remove(basename + '.h5') os.remove(basename + '.xdmf') return 0
def main(): f = viscid.load_file("~/dev/work/tmedium/*.3d.[-1].xdmf") grid = f.get_grid() gslc = "x=-26f:12.5f, y=-15f:15f, z=-15f:15f" # gslc = "x=-12.5f:26f, y=-15f:15f, z=-15f:15f" b_cc = f['b_cc'][gslc] b_cc.name = "b_cc" b_fc = f['b_fc'][gslc] b_fc.name = "b_fc" e_cc = f['e_cc'][gslc] e_cc.name = "e_cc" e_ec = f['e_ec'][gslc] e_ec.name = "e_ec" pp = f['pp'][gslc] pp.name = 'pp' pargs = dict(logscale=True, earth=True) # mpl.clf() # ax1 = mpl.subplot(211) # mpl.plot(f['pp']['y=0f'], **pargs) # # mpl.plot(viscid.magnitude(f['b_cc']['y=0f']), **pargs) # # mpl.show() # mpl.subplot(212, sharex=ax1, sharey=ax1) # mpl.plot(viscid.magnitude(viscid.fc2cc(f['b_fc'])['y=0f']), **pargs) # mpl.show() basename = './tmediumR.3d.{0:06d}'.format(int(grid.time)) viscid.save_fields(basename + '.h5', [b_cc, b_fc, e_cc, e_ec, pp]) f2 = viscid.load_file(basename + ".xdmf") pargs = dict(logscale=True, earth=True) mpl.clf() ax1 = mpl.subplot(211) mpl.plot(f2['pp']['y=0f'], style='contour', levels=5, colorbar=None, colors='k', **pargs) mpl.plot(viscid.magnitude(f2['b_cc']['y=0f']), **pargs) mpl.subplot(212, sharex=ax1, sharey=ax1) mpl.plot(viscid.magnitude(viscid.fc2cc(f2['b_fc'])['y=0f']), **pargs) mpl.show() os.remove(basename + '.h5') os.remove(basename + '.xdmf') return 0
def main(): parser = argparse.ArgumentParser(description="Test xdmf") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f = viscid.load_file(_viscid_root + '/../sample/test.asc') mpl.plot(f['c1'], show=args.show)
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f = viscid.load_file(os.path.join(sample_dir, 'vpic_sample', 'global.vpc')) # some slices that are good to check vlt.clf() vlt.plot(f['bx']['x=:32.01j']) plt.close() vlt.clf() vlt.plot(f['bx']['x=:33.0j']) plt.close() _, axes = vlt.subplots(2, 2, figsize=(8, 4)) for i, ti in enumerate([0, -1]): f.activate_time(ti) vlt.plot(f['n_e']['y=0j'], symmetric=False, ax=axes[0, i]) vlt.plot(f['bx']['y=0j'], symmetric=True, ax=axes[1, i]) axes[0, i].set_title(f.get_grid().time) vlt.auto_adjust_subplots() plt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() plt.close() return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) ####### test 5-moment uniform grids gk_uniform = viscid.load_file(os.path.join(sample_dir, 'sample_gkeyll_uniform_q_*.h5')) plt.figure(figsize=(9, 3)) for i, grid in enumerate(gk_uniform.iter_times(":")): plt.subplot2grid((1, 2), (0, i)) vlt.plot(grid['rho_i'], logscale=True, style='contourf', levels=128) seeds = viscid.Line((-1.2, 0, 0), (1.4, 0, 0), 8) b_lines, _ = viscid.calc_streamlines(grid['b'], seeds, method='euler1', max_length=20.0) vlt.plot2d_lines(b_lines, scalars='#000000', symdir='z', linewidth=1.0) plt.title(grid.format_time('.02f')) vlt.auto_adjust_subplots() plt.suptitle("Uniform Gkeyll Dataset") plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() plt.clf() return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) ####### test 5-moment uniform grids gk_uniform = viscid.load_file(os.path.join(sample_dir, 'sample_gkeyll_uniform_q_*.h5')) _, axes = plt.subplots(1, 2, figsize=(9, 3)) for i, grid in enumerate(gk_uniform.iter_times(":")): vlt.plot(grid['rho_i'], logscale=True, style='contourf', levels=128, ax=axes[i]) seeds = viscid.Line((-1.2, 0, 0), (1.4, 0, 0), 8) b_lines, _ = viscid.calc_streamlines(grid['b'], seeds, method='euler1', max_length=20.0) vlt.plot2d_lines(b_lines, scalars='#000000', symdir='z', linewidth=1.0) plt.title(grid.format_time('.02f')) vlt.auto_adjust_subplots() plt.suptitle("Uniform Gkeyll Dataset") plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() plt.clf() return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) args = vutil.common_argparse(parser) # pylint: disable=unused-variable fiof = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.iof.xdmf')) fac = fiof['fac_tot'] fac_mf = viscid.as_mapfield(fac) fac_sphere = viscid.as_spherefield(fac) if fac_sphere is not fac: raise RuntimeError("cenversion should have been a noop") fac_mf_rad = viscid.as_mapfield(fac, units='rad') fac_sphere_rad = viscid.as_spherefield(fac, units='rad') fac_mf_sphere = viscid.as_spherefield(fac_mf) assert_similar(fac_mf_sphere, fac) fac_mf_sphere_deg_rad = viscid.as_spherefield(fac_mf, units='rad') assert_similar(fac_mf_sphere_deg_rad, fac_sphere_rad) fac_mf_sphere_rad_deg = viscid.as_spherefield(fac_mf_rad, units='deg') assert_similar(fac_mf_sphere_rad_deg, fac) fac_sphere_mf_rad_deg = viscid.as_mapfield(fac_sphere_rad, units='deg') assert_similar(fac_sphere_mf_rad_deg, fac_mf) fac_sphere_mf_rad_rad = viscid.as_mapfield(fac_sphere_rad, units='rad') assert_similar(fac_sphere_mf_rad_rad, fac_mf_rad) fac_mf_T = viscid.as_mapfield(fac, order=('lat', 'lon')) assert_similar(fac_mf_T, fac_mf.T) return 0
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f3d = viscid.load_file(sample_dir + '/sample_xdmf.3d.xdmf', grid_type=ggcm_test_common.MyGGCMGrid) ggcm_test_common.run_test_3d(f3d, __file__, show=args.show) f2d = viscid.load_file(sample_dir + '/sample_xdmf.py_0.xdmf', grid_type=ggcm_test_common.MyGGCMGrid) ggcm_test_common.run_test_2d(f2d, __file__, show=args.show) ggcm_test_common.run_test_timeseries(f2d, __file__, show=args.show) fiof = viscid.load_file(sample_dir + '/sample_xdmf.iof.xdmf') ggcm_test_common.run_test_iof(fiof, __file__, show=args.show)
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f3d = viscid.load_file(_viscid_root + '/../sample/sample.3df.xdmf', grid_type=MyGGCMGrid) pp = f3d['pp'] rr = f3d['rr'] T = f3d['T'] # bmag = timeit(lambda: f3d['bmag']) bmag = f3d["bmag"] plt.subplot(141) mpl.plot(pp, "y=0f,x=-20f:10f", plot_opts="log", earth=True, show=False) plt.subplot(142) mpl.plot(rr, "y=0f,x=-20f:10f", plot_opts="log", earth=True, show=False) plt.subplot(143) mpl.plot(T, "y=0f,x=-20f:10f", plot_opts="log", earth=True, show=False) plt.subplot(144) mpl.plot(bmag, "y=0f,x=-20f:10f", plot_opts="log", earth=True, show=False) if args.show: mpl.mplshow()
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) iono_file = viscid.load_file(_viscid_root + '/../sample/jrrle_sample.iof.*') fac_tot = 1e9 * iono_file["fac_tot"] plot_args = dict(projection="polar", lin=[-4e3, 3e3], bounding_lat=35.0, drawcoastlines=True, # for basemap only, probably will never be used title="Total FAC\n", # make a title, or if a string, use the string as title gridec='gray', label_lat=True, label_mlt=True, colorbar=dict(pad=0.1) # pad the colorbar away from the plot ) ax1 = plt.subplot(121, projection='polar') mpl.plot(fac_tot, ax=ax1, hemisphere='north', **plot_args) ax1.annotate('(a)', xy=(0, 0), textcoords="axes fraction", xytext=(-0.1, 1.0), fontsize=18) ax2 = plt.subplot(122, projection='polar') plot_args['gridec'] = False mpl.plot(fac_tot, ax=ax2, hemisphere="south", style="contourf", levels=50, extend="both", **plot_args) ax2.annotate('(b)', xy=(0, 0), textcoords="axes fraction", xytext=(-0.1, 1.0), fontsize=18) if args.show: mpl.mplshow()
def run_test(show=False): f = viscid.load_file(sample_dir + "/amr.xdmf") plot_kwargs = dict(patchec="y") mpl.plot(f["f"], "z=0.0f", **plot_kwargs) mpl.plt.savefig(next_plot_fname(__file__)) if show: mpl.show()
def run_test(show=False): f = viscid.load_file(os.path.join(viscid.sample_dir, "amr.xdmf")) plot_kwargs = dict(patchec='y') vlt.plot(f['f'], "z=0.0f", **plot_kwargs) plt.savefig(next_plot_fname(__file__)) if show: vlt.show()
def _main(): import viscid from viscid import sample_dir from viscid.plot import vpyplot as vlt logger.setLevel(viscid.logging.DEBUG) f = viscid.load_file(os.path.join(sample_dir, 'vpic_sample', 'global.vpc')) vlt.plot(-f['n_e']['y=0j'], logscale=True, show=True)
def run_test(show=False): f = viscid.load_file(os.path.join(viscid.sample_dir, "amr.xdmf")) plot_kwargs = dict(patchec='y') vlt.plot(f['f'], "z=0.0j", **plot_kwargs) plt.savefig(next_plot_fname(__file__)) if show: vlt.show()
def _main(): import os from viscid.plot import vpyplot as vlt grid = viscid.grid.Grid(time=0.0) crds = viscid.arrays2crds([np.linspace(-1, 1, 32), np.linspace(-1, 1, 32)]) grid.add_field(viscid.full(crds, np.nan, name='V')) seeds0 = viscid.Circle(p0=[0.0, 0.0, 0.0], r=0.8, n=25).get_points() seeds1 = viscid.Circle(p0=[0.0, 0.0, 0.0], r=1.1, n=25).get_points() seeds3 = viscid.Line([-0.5, 0, 0], [0.5, 0, 0], n=5) delmask = np.zeros([seeds0.shape[1]], dtype='bool') curator = viscid.SeedCurator() seeds2 = curator.update(grid['V'], np.array(seeds1), delmask=delmask) vlt.plt.scatter(seeds1[0], seeds1[1], c=[0.0, 1.0, 0.0]) vlt.plt.scatter(seeds2[0], seeds2[1]) vlt.plt.axhline(-1); vlt.plt.axvline(-1) # pylint: disable=multiple-statements vlt.plt.axhline(1); vlt.plt.axvline(1) # pylint: disable=multiple-statements vlt.show() curator = viscid.ReplacementCurator(seeds0) seeds2 = curator.update(grid['V'], np.array(seeds1), delmask=delmask) vlt.plt.scatter(seeds1[0], seeds1[1], c=[0.0, 1.0, 0.0]) vlt.plt.scatter(seeds2[0], seeds2[1]) vlt.plt.axhline(-1); vlt.plt.axvline(-1) # pylint: disable=multiple-statements vlt.plt.axhline(1); vlt.plt.axvline(1) # pylint: disable=multiple-statements vlt.show() curator = viscid.ContinuousCurator(seeds3, cadence=-1) seeds2 = curator.update(grid['V'], np.array(seeds1), delmask=delmask) vlt.plt.scatter(seeds1[0], seeds1[1], c=[0.0, 1.0, 0.0]) vlt.plt.scatter(seeds2[0], seeds2[1]) vlt.plt.axhline(-1); vlt.plt.axvline(-1) # pylint: disable=multiple-statements vlt.plt.axhline(1); vlt.plt.axvline(1) # pylint: disable=multiple-statements vlt.show() target_dir = os.path.join(os.path.expanduser('~'), 'Desktop', 'fluid_movie') print("Attempting to make a movie in:", target_dir) f = viscid.load_file("~/dev/stage/otico_001/otico*.3d.xdmf") xl, xh = f.get_grid().xl_nc, f.get_grid().xh_nc seeds0 = viscid.Circle(p0=0.5 * (xl + xh), r=0.2 * np.max(xh - xl), pole=(0, 0, 1), n=10) seeds1 = viscid.Circle(p0=0.5 * (xl + xh), r=0.4 * np.max(xh - xl), pole=(0, 0, 1), n=10) seeds = viscid.Point(np.concatenate([seeds0.get_points(), seeds1.get_points()], axis=1)) if not os.path.isdir(target_dir): os.mkdir(target_dir) target_fname = os.path.join(target_dir, 'fluid') viscid.follow_fluid(f, seeds, dt=0.0101926 / 2, callback_kwargs=dict(show=False, series_fname=target_fname)) return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f3d = viscid.load_file(os.path.join(sample_dir, 'sample_jrrle.3df.*'), grid_type=ggcm_test_common.MyGGCMGrid) ggcm_test_common.run_test_3d(f3d, __file__, show=args.show) f2d = viscid.load_file(os.path.join(sample_dir, 'sample_jrrle.py_0.*'), grid_type=ggcm_test_common.MyGGCMGrid) ggcm_test_common.run_test_2d(f2d, __file__, show=args.show) ggcm_test_common.run_test_timeseries(f2d, __file__, show=args.show) fiof = viscid.load_file(os.path.join(sample_dir, 'sample_jrrle.iof.*')) ggcm_test_common.run_test_iof(fiof, __file__, show=args.show) return 0
def check(): """Runtime check compiled modules""" import os import sys import numpy as np import viscid ret = 0 check_version() print() ##################################################### # run streamline calculation (checks cython modules) try: cotr = viscid.Cotr(dip_tilt=15.0, dip_gsm=21.0) # pylint: disable=not-callable m = cotr.get_dipole_moment(crd_system='gse') seeds = viscid.seed.Sphere((0.0, 0.0, 0.0), 2.0, pole=-m, ntheta=25, nphi=25, thetalim=(5, 90), philim=(5, 360), phi_endpoint=False) B = viscid.make_dipole(m=m, crd_system='gse', n=(32, 32, 32), l=(-25, -25, -25), h=(25, 25, 25), dtype='f8') lines, _ = viscid.calc_streamlines(B, seeds, ibound=1.0) for line in lines: if np.any(np.isnan(line)): raise ValueError("NaN in line") print("Cython module ran successfully") except Exception as e: print("Cython module has runtime errors.") print(str(e)) ret |= (1 << 0) print() #################################### # load a jrrle file (checks fortran) try: f3d = viscid.load_file( os.path.join(viscid.sample_dir, 'sample_jrrle.3df.*')) _ = np.array(f3d['pp'].data) print("Fortran module ran successfully") except Exception as e: print("Fortran module has runtime errors.") print(str(e)) ret |= (1 << 1) print() return ret
def main(): parser = argparse.ArgumentParser(description="Test xdmf") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f = viscid.load_file(sample_dir + '/test.asc') mpl.plot(f['c1'], show=False) mpl.plt.savefig(next_plot_fname(__file__)) if args.show: mpl.show()
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f = viscid.load_file(os.path.join(viscid.sample_dir, "test.asc")) vlt.plot(f['c1'], show=False) plt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) ####### test binary files f_bin = viscid.load_file(os.path.join(sample_dir, 'ath_sample.*.bin')) for i, grid in enumerate(f_bin.iter_times(":")): plt.subplot2grid((2, 2), (0, i)) vlt.plot(grid['bx']) plt.subplot2grid((2, 2), (1, i)) vlt.plot(grid['by']) plt.suptitle("athena bin (binary) files") vlt.auto_adjust_subplots(subplot_params=dict(top=0.9)) plt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() plt.clf() ####### test ascii files f_tab = viscid.load_file(os.path.join(sample_dir, 'ath_sample.*.tab')) for i, grid in enumerate(f_tab.iter_times(":")): plt.subplot2grid((2, 2), (0, i)) vlt.plot(grid['bx']) plt.subplot2grid((2, 2), (1, i)) vlt.plot(grid['by']) plt.suptitle("athena tab (ascii) files") vlt.auto_adjust_subplots(subplot_params=dict(top=0.9)) plt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() plt.clf() return 0
def main(): parser = argparse.ArgumentParser(description="Test xdmf") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f2d = viscid.load_file(_viscid_root + '/../sample/sample.py_0.xdmf') b2d = viscid.scalar_fields_to_vector([f2d['bx'], f2d['by'], f2d['bz']], name="b") bx2d, by2d, bz2d = b2d.component_fields() #pylint: disable=W0612 f3d = viscid.load_file(_viscid_root + '/../sample/sample.3df.xdmf') b3d = f3d['b'] bx, by, bz = b3d.component_fields() #pylint: disable=W0612 nrows = 4 ncols = 2 plt.subplot2grid((nrows, ncols), (0, 0)) mpl.plot(bx, "z=0,x=:30", earth=True, show=False) plt.subplot2grid((nrows, ncols), (1, 0)) mpl.plot(bx, "z=0.5f,x=0:2,y=-100.0f:100.0f", earth=True, show=False) plt.subplot2grid((nrows, ncols), (2, 0)) mpl.plot(bx, "z=-1,x=-10.0f:,y=-100.0f:100.0f", earth=True, show=False) plt.subplot2grid((nrows, ncols), (3, 0)) mpl.plot(bx, "x=0.0f,y=-5.0f:5.0f,z=-5.0f:5.0f", earth=True, show=False) plt.subplot2grid((nrows, ncols), (0, 1)) mpl.plot(bx2d, "y=20.0f,z=-100.0f:100.0f", earth=True, show=False) plt.subplot2grid((nrows, ncols), (1, 1)) mpl.plot(bx2d, "x=0f:20:-1,y=0.0f,z=0.0f", show=False) plt.subplot2grid((nrows, ncols), (2, 1)) mpl.plot(bx2d, earth=True, show=False) plt.subplot2grid((nrows, ncols), (3, 1)) mpl.plot(bx2d, "z=0.0f,x=-20.0f:0.0f", show=False) if args.show: mpl.mplshow()
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) ####### test binary files f_bin = viscid.load_file(os.path.join(sample_dir, 'ath_sample.*.bin')) _, axes = plt.subplots(2, 2) for i, grid in enumerate(f_bin.iter_times(":")): vlt.plot(grid['bx'], ax=axes[0, i]) vlt.plot(grid['by'], ax=axes[1, i]) plt.suptitle("athena bin (binary) files") vlt.auto_adjust_subplots(subplot_params=dict(top=0.9)) plt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() plt.close() ####### test ascii files f_tab = viscid.load_file(os.path.join(sample_dir, 'ath_sample.*.tab')) _, axes = plt.subplots(2, 2) for i, grid in enumerate(f_tab.iter_times(":")): vlt.plot(grid['bx'], ax=axes[0, i]) vlt.plot(grid['by'], ax=axes[1, i]) plt.suptitle("athena tab (ascii) files") vlt.auto_adjust_subplots(subplot_params=dict(top=0.9)) plt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() plt.close() return 0
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) ####### test binary files f_bin = viscid.load_file(sample_dir + '/ath_sample.*.bin') for i, grid in enumerate(f_bin.iter_times(":")): plt.subplot2grid((2, 2), (0, i)) mpl.plot(grid['bx']) plt.subplot2grid((2, 2), (1, i)) mpl.plot(grid['by']) mpl.plt.suptitle("athena bin (binary) files") mpl.auto_adjust_subplots(subplot_params=dict(top=0.9)) mpl.plt.savefig(next_plot_fname(__file__)) if args.show: mpl.show() plt.clf() ####### test ascii files f_tab = viscid.load_file(sample_dir + '/ath_sample.*.tab') for i, grid in enumerate(f_tab.iter_times(":")): plt.subplot2grid((2, 2), (0, i)) mpl.plot(grid['bx']) plt.subplot2grid((2, 2), (1, i)) mpl.plot(grid['by']) mpl.plt.suptitle("athena tab (ascii) files") mpl.auto_adjust_subplots(subplot_params=dict(top=0.9)) mpl.plt.savefig(next_plot_fname(__file__)) if args.show: mpl.show() plt.clf()
def check(): """Runtime check compiled modules""" import os import sys import numpy as np import viscid ret = 0 check_version() print() ##################################################### # run streamline calculation (checks cython modules) try: cotr = viscid.Cotr(dip_tilt=15.0, dip_gsm=21.0) # pylint: disable=not-callable m = cotr.get_dipole_moment(crd_system='gse') seeds = viscid.seed.Sphere((0.0, 0.0, 0.0), 2.0, pole=-m, ntheta=25, nphi=25, thetalim=(5, 90), philim=(5, 360), phi_endpoint=False) B = viscid.make_dipole(m=m, crd_system='gse', n=(32, 32, 32), l=(-25, -25, -25), h=(25, 25, 25), dtype='f8') lines, _ = viscid.calc_streamlines(B, seeds, ibound=1.0) for line in lines: if np.any(np.isnan(line)): raise ValueError("NaN in line") print("Cython module ran successfully") except Exception as e: print("Cython module has runtime errors.") print(str(e)) ret |= (1 << 0) print() #################################### # load a jrrle file (checks fortran) try: f3d = viscid.load_file(os.path.join(viscid.sample_dir, 'sample_jrrle.3df.*')) _ = np.array(f3d['pp'].data) print("Fortran module ran successfully") except Exception as e: print("Fortran module has runtime errors.") print(str(e)) ret |= (1 << 1) print() return ret
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") parser.add_argument("--keep", action="store_true") args = vutil.common_argparse(parser) # setup a simple force free field x = np.linspace(-2, 2, 20) y = np.linspace(-2.5, 2.5, 25) z = np.linspace(-3, 3, 30) psi = viscid.empty([x, y, z], name='psi', center='node') b = viscid.empty([x, y, z], nr_comps=3, name='b', center='cell', layout='interlaced') X, Y, Z = psi.get_crds_nc("xyz", shaped=True) Xcc, Ycc, Zcc = psi.get_crds_cc("xyz", shaped=True) psi[:, :, :] = 0.5 * (X**2 + Y**2 - Z**2) b['x'] = Xcc b['y'] = Ycc b['z'] = -Zcc # save an hdf5 file with companion xdmf file h5_fname = os.path.join(viscid.sample_dir, "test.h5") viscid.save_fields(h5_fname, [psi, b]) # load the companion xdmf file xdmf_fname = h5_fname[:-3] + ".xdmf" f = viscid.load_file(xdmf_fname) plt.subplot(131) vlt.plot(f['psi'], "y=0") plt.subplot(132) vlt.plot(f['b'].component_fields()[0], "y=0") plt.subplot(133) vlt.plot(f['b'].component_fields()[2], "y=0") plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() if not args.keep: os.remove(h5_fname) os.remove(xdmf_fname) return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) _ = vutil.common_argparse(parser) if _HAS_SCIPY: warnings.filterwarnings("ignore", category=OptimizeWarning) f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[0].xdmf')) mp = viscid.get_mp_info(f['pp'], f['b'], f['j'], f['e_cc'], fit='mp_xloc', slc="x=7f:12.0f, y=-6f:6f, z=-6f:6f", cache=False) Y, Z = mp['pp_max_xloc'].meshgrid(prune=True) # # get normals from paraboloid surface if isinstance(mp['paraboloid'], viscid.DeferredImportError): xfail("Scipy not installed; paraboloid curve fitting not tested") else: parab_n = viscid.paraboloid_normal(Y, Z, *mp['paraboloid'][0]) parab_n = parab_n.reshape(3, -1) # get normals from minvar minvar_y = Y.reshape(-1) minvar_z = Z.reshape(-1) minvar_n = np.zeros([3, len(minvar_y)]) for i in range(minvar_n.shape[1]): p0 = [0.0, minvar_y[i], minvar_z[i]] p0[0] = mp['pp_max_xloc']['y={0[0]}f, z={0[1]}f'.format(p0)] lmn = viscid.find_minvar_lmn_around(f['b'], p0, l=2.0, n=64) minvar_n[:, i] = lmn[2, :] theta = (180 / np.pi) * np.arccos(np.sum(parab_n * minvar_n, axis=0)) # make sure paraboloid normals and minvar normals are closeish # this is a poor check, but at least it's something assert np.min(theta) < 3.0 assert np.average(theta) < 20.0 assert np.median(theta) < 20.0 assert np.max(theta) < 70.0 return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") parser.add_argument("--keep", action="store_true") args = vutil.common_argparse(parser) # setup a simple force free field x = np.linspace(-2, 2, 20) y = np.linspace(-2.5, 2.5, 25) z = np.linspace(-3, 3, 30) psi = viscid.empty([x, y, z], name='psi', center='node') b = viscid.empty([x, y, z], nr_comps=3, name='b', center='cell', layout='interlaced') X, Y, Z = psi.get_crds_nc("xyz", shaped=True) Xcc, Ycc, Zcc = psi.get_crds_cc("xyz", shaped=True) psi[:, :, :] = 0.5 * (X**2 + Y**2 - Z**2) b['x'] = Xcc b['y'] = Ycc b['z'] = -Zcc # save an hdf5 file with companion xdmf file h5_fname = os.path.join(".", "test.h5") viscid.save_fields(h5_fname, [psi, b]) # load the companion xdmf file xdmf_fname = h5_fname[:-3] + ".xdmf" f = viscid.load_file(xdmf_fname) plt.subplot(131) vlt.plot(f['psi'], "y=0") plt.subplot(132) vlt.plot(f['b'].component_fields()[0], "y=0") plt.subplot(133) vlt.plot(f['b'].component_fields()[2], "y=0") plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() if not args.keep: os.remove(h5_fname) os.remove(xdmf_fname) return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) _ = vutil.common_argparse(parser) if _HAS_SCIPY: warnings.filterwarnings("ignore", category=OptimizeWarning) f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[0].xdmf')) mp = viscid.get_mp_info(f['pp'], f['b'], f['j'], f['e_cc'], fit='mp_xloc', slc="x=7j:12.0j, y=-6j:6j, z=-6j:6j", cache=False) Y, Z = mp['pp_max_xloc'].meshgrid(prune=True) # # get normals from paraboloid surface if isinstance(mp['paraboloid'], viscid.DeferredImportError): xfail("Scipy not installed; paraboloid curve fitting not tested") else: parab_n = viscid.paraboloid_normal(Y, Z, *mp['paraboloid'][0]) parab_n = parab_n.reshape(3, -1) # get normals from minvar minvar_y = Y.reshape(-1) minvar_z = Z.reshape(-1) minvar_n = np.zeros([3, len(minvar_y)]) for i in range(minvar_n.shape[1]): p0 = [0.0, minvar_y[i], minvar_z[i]] p0[0] = mp['pp_max_xloc']['y={0[0]}f, z={0[1]}f'.format(p0)] lmn = viscid.find_minvar_lmn_around(f['b'], p0, l=2.0, n=64) minvar_n[:, i] = lmn[2, :] theta = (180 / np.pi) * np.arccos(np.sum(parab_n * minvar_n, axis=0)) # make sure paraboloid normals and minvar normals are closeish # this is a poor check, but at least it's something assert np.min(theta) < 3.0 assert np.average(theta) < 20.0 assert np.median(theta) < 20.0 assert np.max(theta) < 70.0 return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.py_0.xdmf')) xl, xh = f.get_grid().xl_nc, f.get_grid().xh_nc seeds0 = viscid.Circle(p0=0.5 * (xl + xh), r=0.2 * np.max(xh - xl), pole=(0, 0, 1), n=10) seeds1 = viscid.Circle(p0=0.5 * (xl + xh), r=0.4 * np.max(xh - xl), pole=(0, 0, 1), n=10) seeds = viscid.Point(np.concatenate([seeds0.get_points(), seeds1.get_points()], axis=1)) viscid.follow_fluid(f, seeds, dt=1.0, speed_scale=1 / 6.4e3, callback_kwargs=dict(show=args.show, series_fname='plots/fluidtrace')) return 0
def main(): parser = argparse.ArgumentParser(description="Test xdmf") parser.add_argument("--show", "--plot", action="store_true") parser.add_argument("--keep", action="store_true") args = vutil.common_argparse(parser) # setup a simple force free field x = np.linspace(-2, 2, 20) y = np.linspace(-2.5, 2.5, 25) z = np.linspace(-3, 3, 30) psi = viscid.empty([x, y, z], name="psi", center="node") b = viscid.empty([x, y, z], nr_comps=3, name="b", center="cell", layout="interlaced") X, Y, Z = psi.get_crds_nc("xyz", shaped=True) Xcc, Ycc, Zcc = psi.get_crds_cc("xyz", shaped=True) psi[:, :, :] = 0.5 * (X ** 2 + Y ** 2 - Z ** 2) b["x"] = Xcc b["y"] = Ycc b["z"] = -Zcc # save an hdf5 file with companion xdmf file h5_fname = sample_dir + "/test.h5" viscid.save_fields(h5_fname, [psi, b]) # load the companion xdmf file xdmf_fname = h5_fname[:-3] + ".xdmf" f = viscid.load_file(xdmf_fname) plt.subplot(131) mpl.plot(f["psi"], "y=0") plt.subplot(132) mpl.plot(f["b"].component_fields()[0], "y=0") plt.subplot(133) mpl.plot(f["b"].component_fields()[2], "y=0") mpl.plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() if not args.keep: os.remove(h5_fname) os.remove(xdmf_fname)
def main(): parser = argparse.ArgumentParser(description="Test xdmf") parser.add_argument("--show", "--plot", action="store_true") parser.add_argument("--keep", action="store_true") args = vutil.common_argparse(parser) # setup a simple force free field x = np.linspace(-2, 2, 20) y = np.linspace(-2.5, 2.5, 25) z = np.linspace(-3, 3, 30) psi = viscid.empty([x, y, z], name='psi', center='node') b = viscid.empty([x, y, z], nr_comps=3, name='b', center='cell', layout='interlaced') X, Y, Z = psi.get_crds_nc("xyz", shaped=True) Xcc, Ycc, Zcc = psi.get_crds_cc("xyz", shaped=True) psi[:, :, :] = 0.5 * (X**2 + Y**2 - Z**2) b['x'] = Xcc b['y'] = Ycc b['z'] = -Zcc fname = sample_dir + '/test.npz' viscid.save_fields(fname, [psi, b]) f = viscid.load_file(fname) plt.subplot(131) mpl.plot(f['psi'], "y=0") plt.subplot(132) mpl.plot(f['b'].component_fields()[0], "y=0") plt.subplot(133) mpl.plot(f['b'].component_fields()[2], "y=0") mpl.plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() if not args.keep: os.remove(fname)
def _main(): global offscreen_vlab parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--notwo", dest='notwo', action="store_true") parser.add_argument("--nothree", dest='nothree', action="store_true") parser.add_argument("--show", "--plot", action="store_true") args = viscid.vutil.common_argparse(parser, default_verb=0) plot2d = not args.notwo plot3d = not args.nothree # plot2d = True # plot3d = True # args.show = True offscreen_vlab = not args.show img = np.load(os.path.join(sample_dir, "logo.npy")) x = np.linspace(-1, 1, img.shape[0]) y = np.linspace(-1, 1, img.shape[1]) z = np.linspace(-1, 1, img.shape[2]) logo = viscid.arrays2field([x, y, z], img) if 1: viscid.logger.info('Testing Point with custom local coordinates...') pts = np.vstack([[-1, -0.5, 0, 0.5, 1], [-1, -0.5, 0, 0.5, 1], [ 0, 0.5, 1, 1.5, 2]]) local_crds = viscid.asarray_datetime64([0, 60, 120, 180, 240], conservative=True) seeds = viscid.Point(pts, local_crds=local_crds) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Line...') seeds = viscid.Line([-1, -1, 0], [1, 1, 2], n=5) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Plane...') seeds = viscid.Plane([0.0, 0.0, 0.0], [1, 1, 1], [1, 0, 0], 2, 2, nl=160, nm=170, NL_are_vectors=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Volume...') seeds = viscid.Volume([-0.8, -0.8, -0.8], [0.8, 0.8, 0.8], n=[64, 64, 3]) # note: can't make a 2d plot of the volume w/o a slice run_test(logo, seeds, plot2d=False, plot3d=plot3d, add_title="3d", show=args.show) if 1: viscid.logger.info('Testing Volume (with ignorable dim)...') seeds = viscid.Volume([-0.8, -0.8, 0.0], [0.8, 0.8, 0.0], n=[64, 64, 1]) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="2d", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (phi, theta)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (theta, phi)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (phi, theta)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (theta, phi)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Patch...') seeds = viscid.SphericalPatch(p0=[0, 0, 0], p1=[0, -0, -1], max_alpha=30.0, max_beta=59.9, nalpha=65, nbeta=80, r=0.5, roll=45.0) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: # this spline test is very custom viscid.logger.info('Testing Spline...') try: import scipy.interpolate as interpolate except ImportError: msg = "XFail: ImportError (is scipy installed?)" if plot2d: try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() plt.annotate(msg, xy=(0.3, 0.4), xycoords='axes fraction') plt.savefig(next_plot_fname(__file__, series='2d')) plt.savefig(next_plot_fname(__file__, series='2d')) plt.savefig(next_plot_fname(__file__, series='3d')) if args.show: plt.show() except ImportError: pass else: knots = np.array([[ 0.2, 0.5, 0.0], [-0.2, 0.5, 0.2], [-0.2, 0.0, 0.4], [ 0.2, 0.0, 0.2], [ 0.2, -0.5, 0.0], [-0.2, -0.5, 0.2]]).T seed_name = "Spline" fld = logo seeds = viscid.Spline(knots) seed_pts = seeds.get_points() interp_fld = viscid.interp_trilin(fld, seeds) if plot2d: try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() vlt.plot(interp_fld) plt.title(seed_name) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: plt.show() plt.clf() from matplotlib import rcParams _ms = rcParams['lines.markersize'] plt.gca().scatter(knots[0, :], knots[1, :], s=(2 * _ms)**2, marker='^', color='y') plt.gca().scatter(seed_pts[0, :], seed_pts[1, :], s=(1.5 * _ms)**2, marker='o', color='k') vlt.plot2d_line(seed_pts, scalars=interp_fld.flat_data, symdir='z') plt.title(seed_name) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: plt.show() except ImportError: pass if plot3d: try: vlab, _ = get_mvi_fig() vlab.points3d(knots[0], knots[1], knots[2], color=(1.0, 1.0, 0), scale_mode='none', scale_factor=0.04) p = vlab.points3d(seed_pts[0], seed_pts[1], seed_pts[2], color=(0, 0, 0), scale_mode='none', scale_factor=0.03) vlab.plot_line(seed_pts, scalars=interp_fld.flat_data, tube_radius=0.01) vlab.axes(p) vlab.title(seed_name) vlab.mlab.roll(-90.0) vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show(stop=True) except ImportError: pass if 1: viscid.logger.info('Testing RectilinearMeshPoints...') f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[-1].xdmf')) slc = 'x=-40j:12j, y=-10j:10j, z=-10j:10j' b = f['b'][slc] z = b.get_crd('z') sheet_iz = np.argmin(b['x']**2, axis=2) sheet_pts = b['z=0:1'].get_points() sheet_pts[2, :] = z[sheet_iz].reshape(-1) isphere_mask = np.sum(sheet_pts[:2, :]**2, axis=0) < 5**2 day_mask = sheet_pts[0:1, :] > -1.0 sheet_pts[2, :] = np.choose(isphere_mask, [sheet_pts[2, :], 0]) sheet_pts[2, :] = np.choose(day_mask, [sheet_pts[2, :], 0]) nx, ny, _ = b.sshape sheet_seed = viscid.RectilinearMeshPoints(sheet_pts.reshape(3, nx, ny)) vx_sheet = viscid.interp_nearest(f['vx'], sheet_seed) try: if not plot2d: raise ImportError from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt vlt.clf() vlt.plot(vx_sheet, symmetric=True) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: vlt.show() except ImportError: pass try: if not plot3d: raise ImportError vlab, _ = get_mvi_fig() mesh = vlab.mesh_from_seeds(sheet_seed, scalars=vx_sheet, clim=(-400, 400)) vlab.plot_earth_3d(crd_system=b) vlab.view(azimuth=+90.0 + 45.0, elevation=90.0 - 25.0, distance=30.0, focalpoint=(-10.0, +1.0, +1.0)) vlab.title("RectilinearMeshPoints") vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show(stop=True) except ImportError: pass # prevent weird xorg bad-instructions on tear down if 'figure' in _global_ns and _global_ns['figure'] is not None: from viscid.plot import vlab vlab.mlab.close(_global_ns['figure']) return 0
def get_mp_info(pp, b, j, e, cache=True, cache_dir=None, slc="x=5.5f:11.0f, y=-4.0f:4.0f, z=-3.6f:3.6f", fit="mp_xloc", fit_p0=(9.0, 0.0, 0.0, 1.0, -1.0, -1.0)): """Get info about m-pause as flattened fields Notes: The first thing this function does is mask locations where the GSE-y current density < 1e-4. This masks out the bow shock and current free regions. This works for southward IMF, but it is not very general. Parameters: pp (ScalarcField): pressure b (VectorField): magnetic field j (VectorField): current density e (VectorField, None): electric field (same centering as b). If None, then the info that requires E will be filled with NaN cache (bool, str): Save to and load from cache, if "force", then don't load from cache if it exists, but do save a cache at the end cache_dir (str): Directory for cache, if None, same directory as that file to which the grid belongs slc (str): slice that gives a box that contains the m-pause fit (str): to which resulting field should the paraboloid be fit, defaults to mp_xloc, but pp_max_xloc might be useful in some circumstances fit_p0 (tuple): Initial guess vector for paraboloid fit Returns: dict: Unless otherwise noted, the entiries are 2D (y-z) fields - **mp_xloc** location of minimum abs(Bz), this works better than max of J^2 for FTEs - **mp_sheath_edge** location where Jy > 0.1 * Jy when coming in from the sheath side - **mp_sphere_edge** location where Jy > 0.1 * Jy when coming in from the sphere side - **mp_width** difference between m-sheath edge and msphere edge - **mp_shear** magnetic shear taken 6 grid points into the m-sheath / m-sphere - **pp_max** max pp - **pp_max_xloc** location of max pp - **epar_max** max e parallel - **epar_max_xloc** location of max e parallel - **paraboloid** numpy.recarray of paraboloid fit. The parameters are given in the 0th element, and the 1st element contains the 1-sigma values for the fit Raises: RuntimeError: if using MHD crds instead of GSE crds """ if not cache_dir: cache_dir = pp.find_info("_viscid_dirname", "./") run_name = pp.find_info("run", None) if cache and run_name: t = pp.time mp_fname = "{0}/{1}.mpause.{2:06.0f}".format(cache_dir, run_name, t) else: mp_fname = "" try: force = cache.strip().lower() == "force" except AttributeError: force = False try: if force or not mp_fname or not os.path.isfile(mp_fname + ".xdmf"): raise IOError() mp_info = {} with viscid.load_file(mp_fname + ".xdmf") as dat: fld_names = [ "mp_xloc", "mp_sheath_edge", "mp_sphere_edge", "mp_width", "mp_shear", "pp_max", "pp_max_xloc", "epar_max", "epar_max_xloc" ] for fld_name in fld_names: mp_info[fld_name] = dat[fld_name]["x=0"] except (IOError, KeyError): mp_info = {} crd_system = viscid.as_crd_system(b, None) if crd_system != 'gse': raise RuntimeError("get_mp_info can't work in MHD crds, " "switch to GSE please") if j.nr_patches == 1: pp_block = pp[slc] b_block = b[slc] j_block = j[slc] if e is None: e_block = np.nan * viscid.empty_like(j_block) else: e_block = e[slc] else: # interpolate an amr grid so we can proceed obnd = pp.get_slice_extent(slc) dx = np.min(pp.skeleton.L / pp.skeleton.n, axis=0) nx = np.ceil((obnd[1] - obnd[0]) / dx) vol = viscid.seed.Volume(obnd[0], obnd[1], nx, cache=True) pp_block = vol.wrap_field(viscid.interp_trilin(pp, vol), name="P").as_cell_centered() b_block = vol.wrap_field(viscid.interp_trilin(b, vol), name="B").as_cell_centered() j_block = vol.wrap_field(viscid.interp_trilin(j, vol), name="J").as_cell_centered() if e is None: e_block = np.nan * viscid.empty_like(j_block) else: e_block = vol.wrap_field(viscid.interp_trilin(e, vol), name="E").as_cell_centered() # jsq = viscid.dot(j_block, j_block) bsq = viscid.dot(b_block, b_block) # extract ndarrays and mask out bow shock / current free regions maskval = 1e-4 jy_mask = j_block['y'].data < maskval masked_bsq = 1.0 * bsq masked_bsq.data = np.ma.masked_where(jy_mask, bsq) xcc = j_block.get_crd_cc('x') nx = len(xcc) mp_xloc = np.argmin(masked_bsq, axis=0) # indices mp_xloc = mp_xloc.wrap(xcc[mp_xloc.data]) # location pp_max = np.max(pp_block, axis=0) pp_max_xloc = np.argmax(pp_block, axis=0) # indices pp_max_xloc = pp_max_xloc.wrap(xcc[pp_max_xloc.data]) # location epar = viscid.project(e_block, b_block) epar_max = np.max(epar, axis=0) epar_max_xloc = np.argmax(epar, axis=0) # indices epar_max_xloc = pp_max_xloc.wrap(xcc[epar_max_xloc.data]) # location _ret = find_mp_edges(j_block, 0.1, 0.1, maskval=maskval) sheath_edge, msphere_edge, mp_width, sheath_ind, sphere_ind = _ret # extract b and b**2 at sheath + 6 grid points and sphere - 6 grid pointns # clipping cases where things go outside the block. clipped ponints are # set to nan step = 6 # extract b if b_block.layout == "flat": comp_axis = 0 ic, _, iy, iz = np.ix_(*[np.arange(si) for si in b_block.shape]) ix = np.clip(sheath_ind + step, 0, nx - 1) b_sheath = b_block.data[ic, ix, iy, iz] ix = np.clip(sheath_ind - step, 0, nx - 1) b_sphere = b_block.data[ic, ix, iy, iz] elif b_block.layout == "interlaced": comp_axis = 3 _, iy, iz = np.ix_(*[np.arange(si) for si in b_block.shape[:-1]]) ix = np.clip(sheath_ind + step, 0, nx - 1) b_sheath = b_block.data[ix, iy, iz] ix = np.clip(sheath_ind - step, 0, nx - 1) b_sphere = b_block.data[ix, iy, iz] # extract b**2 bmag_sheath = np.sqrt(np.sum(b_sheath**2, axis=comp_axis)) bmag_sphere = np.sqrt(np.sum(b_sphere**2, axis=comp_axis)) costheta = (np.sum(b_sheath * b_sphere, axis=comp_axis) / (bmag_sphere * bmag_sheath)) costheta = np.where( (sheath_ind + step < nx) & (sphere_ind - step >= 0), costheta, np.nan) mp_shear = mp_width.wrap((180.0 / np.pi) * np.arccos(costheta)) # don't bother with pretty name since it's not written to file # plane_crds = b_block.crds.slice_keep('x=0', cc=True) # fld_kwargs = dict(center="Cell", time=b.time) mp_width.name = "mp_width" mp_xloc.name = "mp_xloc" sheath_edge.name = "mp_sheath_edge" msphere_edge.name = "mp_sphere_edge" mp_shear.name = "mp_shear" pp_max.name = "pp_max" pp_max_xloc.name = "pp_max_xloc" epar_max.name = "epar_max" epar_max_xloc.name = "epar_max_xloc" mp_info = {} mp_info["mp_width"] = mp_width mp_info["mp_xloc"] = mp_xloc mp_info["mp_sheath_edge"] = sheath_edge mp_info["mp_sphere_edge"] = msphere_edge mp_info["mp_shear"] = mp_shear mp_info["pp_max"] = pp_max mp_info["pp_max_xloc"] = pp_max_xloc mp_info["epar_max"] = epar_max mp_info["epar_max_xloc"] = epar_max_xloc # cache new fields to disk if mp_fname: viscid.save_fields(mp_fname + ".h5", mp_info.values()) try: _paraboloid_params = fit_paraboloid(mp_info[fit], p0=fit_p0) mp_info["paraboloid"] = _paraboloid_params except ImportError as _exception: try: msg = _exception.message except AttributeError: msg = _exception.msg mp_info["paraboloid"] = viscid.DeferredImportError(msg) mp_info["mp_width"].pretty_name = "Magnetopause Width" mp_info["mp_xloc"].pretty_name = "Magnetopause $X_{gse}$ Location" mp_info["mp_sheath_edge"].pretty_name = "Magnetosheath Edge" mp_info["mp_sphere_edge"].pretty_name = "Magnetosphere Edge" mp_info["mp_shear"].pretty_name = "Magnetic Shear" mp_info["pp_max"].pretty_name = "Max Pressure" mp_info["pp_max_xloc"].pretty_name = "Max Pressure Location" mp_info["epar_max"].pretty_name = "Max E Parallel" mp_info["epar_max_xloc"].pretty_name = "Max E Parallel Location" return mp_info
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 29 11:31:06 2019 @author: jaa """ import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import viscid import pandas as pd viscid.calculator.evaluator.enabled = True from viscid.plot import vpyplot as vlt # This load the variables import h5_filereader_jeff as reader reader.ex.shape run = "/run/media/jaa/C2BCB9BCBCB9AB75/DIRAC_RUNs/SCALING/weak_2_scaling_256/pfd.xdmf" vf = viscid.load_file(run, force_reload=True)
def main(): parser = argparse.ArgumentParser(description="Test calc") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f3d = viscid.load_file(_viscid_root + '/../sample/sample.3df.[0].xdmf') f_iono = viscid.load_file(_viscid_root + "/../sample/*.iof.[0].xdmf") b = f3d["b"] pp = f3d["pp"] # plot a scalar cut plane of pressure pp_src = mvi.field2source(pp, center='node') scp = mlab.pipeline.scalar_cut_plane(pp_src, plane_orientation='z_axes', transparent=True, opacity=0.5, view_controls=False) scp.implicit_plane.normal = [0, 0, -1] scp.implicit_plane.origin = [0, 0, 0] # i don't know why this log10 doesn't seem to work scp.module_manager.scalar_lut_manager.lut.scale = 'log10' scp.module_manager.scalar_lut_manager.lut_mode = 'Reds' scp.module_manager.scalar_lut_manager.reverse_lut = True scp.module_manager.scalar_lut_manager.show_scalar_bar = True # calculate B field lines && topology in viscid and plot them seeds = viscid.SphericalPatch([0, 0, 0], [2, 0, 1], 30, 15, r=5.0, nalpha=5, nbeta=5) b_lines, topo = viscid.calc_streamlines(b, seeds, ibound=3.5, obound0=[-25, -20, -20], obound1=[15, 20, 20]) mvi.plot_lines(b_lines, scalars=viscid.topology2color(topo)) # Use Mayavi (VTK) to calculate field lines using an interactive seed b_src = mvi.field2source(b, center='node') bsl2 = mlab.pipeline.streamline(b_src, seedtype='sphere', integration_direction='both', seed_resolution=4) bsl2.stream_tracer.maximum_propagation = 20. bsl2.seed.widget.center = [-11, 0, 0] bsl2.seed.widget.radius = 1.0 bsl2.streamline_type = 'tube' bsl2.tube_filter.radius = 0.03 bsl2.stop() # this stop/start was a hack to get something to work? bsl2.start() bsl2.seed.widget.enabled = True # Plot the ionosphere too fac_tot = 1e9 * f_iono['fac_tot'] crd_system = 'gse' m = mvi.plot_ionosphere(fac_tot, crd_system=crd_system, bounding_lat=30.0, vmin=-300, vmax=300, opacity=0.75) m.module_manager.scalar_lut_manager.lut_mode = 'RdBu' m.module_manager.scalar_lut_manager.reverse_lut = True mvi.plot_blue_marble(r=1.0, orientation=(0, 21.5, -45.0)) # now shade the night side with a transparent black hemisphere mvi.plot_earth_3d(radius=1.01, crd_system="gse", night_only=True, opacity=0.5) mlab.axes(pp_src, nb_labels=5) mlab.orientation_axes() mvi.resize([1200, 800]) mlab.view(azimuth=40, elevation=70, distance=35.0, focalpoint=[-3, 0, 0]) # # Save Figure # print("saving png") # mvi.mlab.savefig('mayavi_msphere_sample.png') # print("saving x3d") # # x3d files can be turned into COLLADA files with meshlab, and # # COLLADA (.dae) files can be opened in OS X's preview # # # # IMPORTANT: for some reason, using bounding_lat in mvi.plot_ionosphere # # causes a segfault when saving x3d files # # # mvi.mlab.savefig('mayavi_msphere_sample.x3d') # print("done") if args.show: mlab.show()
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") parser.add_argument("--interact", "-i", action="store_true") args = vutil.common_argparse(parser) f3d = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[0].xdmf')) f_iono = viscid.load_file( os.path.join(sample_dir, "sample_xdmf.iof.[0].xdmf")) b = f3d["b"] v = f3d["v"] pp = f3d["pp"] e = f3d["e_cc"] vlab.mlab.options.offscreen = not args.show vlab.figure(size=(1280, 800)) ########################################################## # make b a dipole inside 3.1Re and set e = 0 inside 4.0Re cotr = viscid.Cotr(time='1990-03-21T14:48', dip_tilt=0.0) # pylint: disable=not-callable moment = cotr.get_dipole_moment(crd_system=b) isphere_mask = viscid.make_spherical_mask(b, rmax=3.1) viscid.fill_dipole(b, m=moment, mask=isphere_mask) e_mask = viscid.make_spherical_mask(b, rmax=4.0) viscid.set_in_region(e, 0.0, alpha=0.0, mask=e_mask, out=e) ###################################### # plot a scalar cut plane of pressure pp_src = vlab.field2source(pp, center='node') scp = vlab.scalar_cut_plane(pp_src, plane_orientation='z_axes', opacity=0.5, transparent=True, view_controls=False, cmap="inferno", logscale=True) scp.implicit_plane.normal = [0, 0, -1] scp.implicit_plane.origin = [0, 0, 0] scp.enable_contours = True scp.contour.filled_contours = True scp.contour.number_of_contours = 64 cbar = vlab.colorbar(scp, title=pp.name, orientation='vertical') cbar.scalar_bar_representation.position = (0.01, 0.13) cbar.scalar_bar_representation.position2 = (0.08, 0.76) ###################################### # plot a vector cut plane of the flow vcp = vlab.vector_cut_plane(v, scalars=pp_src, plane_orientation='z_axes', view_controls=False, mode='arrow', cmap='Greens_r') vcp.implicit_plane.normal = [0, 0, -1] vcp.implicit_plane.origin = [0, 0, 0] ############################## # plot very faint isosurfaces vx_src = vlab.field2source(v['x'], center='node') iso = vlab.iso_surface(vx_src, contours=[0.0], opacity=0.008, cmap='Pastel1') ############################################################## # calculate B field lines && topology in Viscid and plot them seedsA = viscid.SphericalPatch([0, 0, 0], [2, 0, 1], 30, 15, r=5.0, nalpha=5, nbeta=5) seedsB = viscid.SphericalPatch([0, 0, 0], [1.9, 0, -20], 30, 15, r=5.0, nalpha=1, nbeta=5) seeds = np.concatenate([seedsA, seedsB], axis=1) b_lines, topo = viscid.calc_streamlines(b, seeds, ibound=3.5, obound0=[-25, -20, -20], obound1=[15, 20, 20], wrap=True) vlab.plot_lines(b_lines, scalars=viscid.topology2color(topo)) ###################################################################### # plot a random circle at geosynchronus orbit with scalars colored # by the Matplotlib viridis color map, just because we can; this is # a useful toy for debugging circle = viscid.Circle(p0=[0, 0, 0], r=6.618, n=128, endpoint=True) scalar = np.sin(circle.as_local_coordinates().get_crd('phi')) surf = vlab.plot_line(circle.get_points(), scalars=scalar, clim=0.8, cmap="Spectral_r") ###################################################################### # Use Mayavi (VTK) to calculate field lines using an interactive seed # These field lines are colored by E parallel epar = viscid.project(e, b) epar.name = "Epar" bsl2 = vlab.streamline(b, epar, seedtype='plane', seed_resolution=4, integration_direction='both', clim=(-0.05, 0.05)) # now tweak the VTK streamlines bsl2.stream_tracer.maximum_propagation = 20. bsl2.seed.widget.origin = [-11, -5.0, -2.0] bsl2.seed.widget.point1 = [-11, 5.0, -2.0] bsl2.seed.widget.point2 = [-11.0, -5.0, 2.0] bsl2.streamline_type = 'tube' bsl2.tube_filter.radius = 0.03 bsl2.stop() # this stop/start was a hack to get something to update bsl2.start() bsl2.seed.widget.enabled = False cbar = vlab.colorbar(bsl2, title=epar.name, label_fmt='%.3f', orientation='horizontal') cbar.scalar_bar_representation.position = (0.15, 0.01) cbar.scalar_bar_representation.position2 = (0.72, 0.10) ############################################################### # Make a contour at the open-closed boundary in the ionosphere seeds_iono = viscid.Sphere(r=1.063, pole=-moment, ntheta=256, nphi=256, thetalim=(0, 180), philim=(0, 360), crd_system=b) _, topo_iono = viscid.calc_streamlines(b, seeds_iono, ibound=1.0, nr_procs='all', output=viscid.OUTPUT_TOPOLOGY) topo_iono = np.log2(topo_iono) m = vlab.mesh_from_seeds(seeds_iono, scalars=topo_iono, opacity=1.0, clim=(0, 3), color=(0.992, 0.445, 0.0)) m.enable_contours = True m.actor.property.line_width = 4.0 m.contour.number_of_contours = 4 #################################################################### # Plot the ionosphere, note that the sample data has the ionosphere # at a different time, so the open-closed boundary found above # will not be consistant with the field aligned currents fac_tot = 1e9 * f_iono['fac_tot'] m = vlab.plot_ionosphere(fac_tot, bounding_lat=30.0, vmin=-300, vmax=300, opacity=0.75, rotate=cotr, crd_system=b) m.actor.property.backface_culling = True ######################################################################## # Add some markers for earth, i.e., real earth, and dayside / nightside # representation vlab.plot_blue_marble(r=1.0, lines=False, ntheta=64, nphi=128, rotate=cotr, crd_system=b) # now shade the night side with a transparent black hemisphere vlab.plot_earth_3d(radius=1.01, night_only=True, opacity=0.5, crd_system=b) #################### # Finishing Touches # vlab.axes(pp_src, nb_labels=5) oa = vlab.orientation_axes() oa.marker.set_viewport(0.75, 0.75, 1.0, 1.0) # note that resize won't work if the current figure has the # off_screen_rendering flag set # vlab.resize([1200, 800]) vlab.view(azimuth=45, elevation=70, distance=35.0, focalpoint=[-2, 0, 0]) ############## # Save Figure # print("saving png") # vlab.savefig('mayavi_msphere_sample.png') # print("saving x3d") # # x3d files can be turned into COLLADA files with meshlab, and # # COLLADA (.dae) files can be opened in OS X's preview # # # # IMPORTANT: for some reason, using bounding_lat in vlab.plot_ionosphere # # causes a segfault when saving x3d files # # # vlab.savefig('mayavi_msphere_sample.x3d') # print("done") vlab.savefig(next_plot_fname(__file__)) ########################### # Interact Programatically if args.interact: vlab.interact() ####################### # Interact Graphically if args.show: vlab.show() try: vlab.mlab.close() except AttributeError: pass return 0
def main(): mhd_type = "C" make_plots = 1 test_fc = 1 test_ec = 1 test_div = 1 test_interp = 1 test_streamline = 1 mhd_type = mhd_type.upper() if mhd_type.startswith("C"): if mhd_type in ("C", ): f = viscid.load_file("$WORK/tmedium/*.3d.[-1].xdmf") elif mhd_type in ("C2", "C3"): f = viscid.load_file("$WORK/tmedium2/*.3d.[-1].xdmf") else: raise ValueError() catol = 1e-8 rtol = 5e-6 elif mhd_type in ("F", "FORTRAN"): f = viscid.load_file("$WORK/tmedium3/*.3df.[-1]") catol = 1e-8 rtol = 7e-2 else: raise ValueError() ISLICE = slice(None) # ISLICE = 'y=0f:0.15f' # ################# # # test out fc2cc if test_fc: b = f['b'][ISLICE] b1 = f['b1'][ISLICE] compare_vectors(b, b1, viscid.fc2cc, catol=catol, rtol=rtol, make_plots=make_plots) ################# # test out ec2cc if test_ec: e_cc = f['e_cc'][ISLICE] e_ec = f['e_ec'][ISLICE] if mhd_type not in ("F", "FORTRAN"): compare_vectors(e_cc, e_ec, viscid.ec2cc, catol=catol, rtol=rtol, make_plots=make_plots) ################# # test out divfc # Note: Relative error on Div B is meaningless b/c the coordinates # are not the same up to order (dx/4) I think. You can see this # since (fcdiv - divb_trimmed) is both noisy and stripy if test_div: bnd = 0 if mhd_type not in ("F", "FORTRAN"): b1 = f['b1'][ISLICE] divb = f['divB'][ISLICE] if bnd: trimmed = divb else: trimmed = divb['x=1:-1, y=1:-1, z=1:-1'] b1mag = viscid.magnitude(viscid.fc2cc(b1, bnd=bnd)) divb1 = viscid.div_fc(b1, bnd=bnd) viscid.set_in_region(trimmed, trimmed, alpha=0.0, beta=0.0, out=trimmed, mask=viscid.make_spherical_mask(trimmed, rmax=5.0)) viscid.set_in_region(divb1, divb1, alpha=0.0, beta=0.0, out=divb1, mask=viscid.make_spherical_mask(divb1, rmax=5.0)) reldiff = (divb1 - trimmed) / b1mag reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"] reldiff.name = divb1.name + " - " + trimmed.name reldiff.pretty_name = divb1.pretty_name + " - " + trimmed.pretty_name abs_max_rel_diff = np.nanmax(np.abs(reldiff)) max_crd_diff = [0.0] * 3 for i, d in enumerate('xyz'): max_crd_diff[i] = np.max(trimmed.get_crd(d) - divb1.get_crd(d)) print("divB max absolute relative diff: {0:.3e} " "(crds: X: {1[0]:.3e}, Y: {1[1]:.3e}, Z: {1[2]:.3e})" "".format(abs_max_rel_diff, max_crd_diff)) # plot differences? if make_plots: ax1 = plt.subplot(311) vlt.plot(divb['y=0f'], symmetric=True, earth=True) plt.subplot(312, sharex=ax1, sharey=ax1) vlt.plot(divb1['y=0f'], symmetric=True, earth=True) plt.subplot(313, sharex=ax1, sharey=ax1) vlt.plot(reldiff['y=0f'], symmetric=True, earth=True) vlt.show() # Since the coordinates will be different by order dx^2 (i think), # there is no way to compare the divB from simulation with the # one we get here. However, they should be the same up to a few %, and # down to noise level with stripes of enhanced noise. These stripes # are the errors in the coordinate values (since the output only # gives us weird nc = averaged cc locations) # # if abs_max_rel_diff > rtol or np.any(np.abs(max_crd_diff) > catol): # raise RuntimeError("Tolerance exceeded on divB calculation") if test_streamline: b_cc = f['b_cc']['x=-40f:12f, y=-15f:15f, z=-15f:15f'] b_fc = f['b_fc']['x=-40f:12f, y=-15f:15f, z=-15f:15f'] cotr = viscid.cotr.Cotr() r_mask = 3.0 # set b_cc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_cc) viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask) # set b_fc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_fc) viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask) seeds = viscid.Volume([-10, 0, -5], [10, 0, 5], (16, 1, 3)) sl_kwargs = dict(ibound=1.0, method=viscid.EULER1A) lines_cc, topo_cc = viscid.calc_streamlines(b_cc, seeds, **sl_kwargs) lines_fc, topo_fc = viscid.calc_streamlines(b_fc, seeds, **sl_kwargs) if make_plots: plt.figure(figsize=(10, 6)) ax0 = plt.subplot(211) topo_cc_colors = viscid.topology2color(topo_cc) vlt.plot(f['pp']['y=0f'], logscale=True, earth=True, cmap='plasma') vlt.plot2d_lines(lines_cc, topo_cc_colors, symdir='y') ax0 = plt.subplot(212, sharex=ax0, sharey=ax0) topo_fc_colors = viscid.topology2color(topo_fc) vlt.plot(f['pp']['y=0f'], logscale=True, earth=True, cmap='plasma') vlt.plot2d_lines(lines_fc, topo_fc_colors, symdir='y') plt.xlim(-20, 10) plt.ylim(-10, 10) vlt.auto_adjust_subplots() vlt.show() if test_interp: # test interpolation with E . B / B b_cc = f['b_cc'] b_fc = f['b_fc'] e_cc = f['e_cc'] e_ec = f['e_ec'] cotr = viscid.cotr.Cotr() r_mask = 3.0 # set b_cc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_cc) viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask) # set b_fc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_fc) viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask) # zero out e_cc inside some sphere viscid.set_in_region(e_cc, e_cc, alpha=0.0, beta=0.0, out=e_cc, mask=viscid.make_spherical_mask(e_cc, rmax=r_mask)) # zero out e_ec inside some sphere viscid.set_in_region(e_ec, e_ec, alpha=0.0, beta=0.0, out=e_ec, mask=viscid.make_spherical_mask(e_ec, rmax=r_mask)) tmp = viscid.empty([ np.linspace(-10, 10, 64), np.linspace(-10, 10, 64), np.linspace(-10, 10, 64) ], center="Cell") b_cc_interp = viscid.interp_linear(b_cc, tmp) b_fc_interp = viscid.interp_linear(b_fc, tmp) e_cc_interp = viscid.interp_linear(e_cc, tmp) e_ec_interp = viscid.interp_linear(e_ec, tmp) epar_cc = viscid.dot(e_cc_interp, b_cc_interp) / viscid.magnitude(b_cc_interp) epar_ecfc = viscid.dot(e_ec_interp, b_fc_interp) / viscid.magnitude(b_fc_interp) if make_plots: # plt.figure() # ax0 = plt.subplot(121) # vlt.plot(b_cc['x']['y=0f'], clim=(-40, 40)) # plt.subplot(122, sharex=ax0, sharey=ax0) # vlt.plot(b_fc['x']['y=0f'], clim=(-40, 40)) # vlt.show() plt.figure(figsize=(14, 5)) ax0 = plt.subplot(131) vlt.plot(epar_cc['y=0f'], symmetric=True, cbarlabel="Epar CC") plt.subplot(132, sharex=ax0, sharey=ax0) vlt.plot(epar_ecfc['y=0f'], symmetric=True, cbarlabel="Epar ECFC") plt.subplot(133, sharex=ax0, sharey=ax0) vlt.plot(((epar_cc - epar_ecfc) / epar_cc)['y=0f'], clim=(-10, 10), cbarlabel="Rel Diff") vlt.auto_adjust_subplots() vlt.show() return 0
import seaborn as sns import viscid from viscid.plot import vpyplot as vlt import matplotlib.pyplot as plt f = viscid.load_file('./otico_001.3d.xdmf') mymap = sns.diverging_palette(28, 240, s=95, l=50, as_cmap=True) figure = plt.figure(figsize=(14, 10)) g = f.get_grid(time=12) vlt.plot(g['bx']['z=0'], cmap=mymap, style='contourf', levels=256) vlt.savefig('OT_bx.png') plt.show()
def _main(): f = viscid.load_file("$WORK/xi_fte_001/*.3d.[4050f].xdmf") mp = get_mp_info(f['pp'], f['b'], f['j'], f['e_cc'], fit='mp_xloc', slc="x=6.5f:10.5f, y=-4f:4f, z=-4.8f:3f", cache=False) y, z = mp['pp_max_xloc'].meshgrid_flat(prune=True) x = mp['pp_max_xloc'].data.reshape(-1) Y, Z = mp['pp_max_xloc'].meshgrid(prune=True) x2 = paraboloid(Y, Z, *mp['paraboloid'][0]) skip = 117 n = paraboloid_normal(Y, Z, *mp['paraboloid'][0]).reshape(3, -1)[:, ::skip] minvar_y = Y.reshape(-1)[::skip] minvar_z = Z.reshape(-1)[::skip] minvar_n = np.zeros([3, len(minvar_y)]) for i in range(minvar_n.shape[0]): p0 = [0.0, minvar_y[i], minvar_z[i]] p0[0] = mp['pp_max_xloc']['y={0[0]}f, z={0[1]}f'.format(p0)] minvar_n[:, i] = viscid.find_minvar_lmn_around(f['b'], p0, l=2.0, n=64)[2, :] # 2d plots, normals don't look normal in the matplotlib projection if False: # pylint: disable=using-constant-test from matplotlib import pyplot as plt from viscid.plot import vpyplot as vlt normals = paraboloid_normal(Y, Z, *mp['paraboloid'][0]) p0 = np.array([x2, Y, Z]).reshape(3, -1) p1 = p0 + normals.reshape(3, -1) vlt.scatter_3d(np.vstack([x, y, z])[:, ::skip], equal=True) for i in range(0, p0.shape[1], skip): plt.gca().plot([p0[0, i], p1[0, i]], [p0[1, i], p1[1, i]], [p0[2, i], p1[2, i]], color='c') # z2 = _ellipsiod(X, Y, *popt) plt.gca().plot_surface(Y, Z, x2, color='r') vlt.show() # mayavi 3d plots, normals look better here if True: # pylint: disable=using-constant-test from viscid.plot import vlab vlab.points3d(x[::skip], y[::skip], z[::skip], scale_factor=0.25, color=(0.0, 0.0, 1.0)) mp_width = mp['mp_width']['x=0'] mp_sheath_edge = mp['mp_sheath_edge']['x=0'] mp_sphere_edge = mp_sheath_edge - mp_width vlab.mesh(x2, Y, Z, scalars=mp_width.data) vlab.mesh(mp_sheath_edge.data, Y, Z, opacity=0.75, color=(0.75, ) * 3) vlab.mesh(mp_sphere_edge.data, Y, Z, opacity=0.75, color=(0.75, ) * 3) n = paraboloid_normal(Y, Z, *mp['paraboloid'][0]).reshape(3, -1)[:, ::skip] vlab.quiver3d(x2.reshape(-1)[::skip], Y.reshape(-1)[::skip], Z.reshape(-1)[::skip], n[0], n[1], n[2], color=(1, 0, 0)) vlab.quiver3d(x2.reshape(-1)[::skip], Y.reshape(-1)[::skip], Z.reshape(-1)[::skip], minvar_n[0], minvar_n[1], minvar_n[2], color=(0, 0, 1)) vlab.show()
df_f=pd.DataFrame(np.array(e_field)) hdf=pd.HDFStore('/disk/plasmaz/jaa/Critical_Balance/CB8waves_104_1/Raw_outputs/pfd.002000.xdmf',mode='r') hdf.groups() hdf.keys() hdf.items() read_panda_xdmf=pd.read_xdmf('/disk/plasmaz/jaa/Critical_Balance/CB8waves_104_1/Raw_outputs/pfd.002000.xdmf') read_panda_h5=pd.read_hdf(filename1) # This is how to pass from np.array to pd.dataframe data = np.array([['','Col1','Col2'],['Row1',1,2],['Row2',3,4]]) pd.DataFrame(data=data[1:,1:], # values index=data[1:,0], # 1st column as index columns=data[0,1:]) # 1st row as the column names f = viscid.load_file(os.path.join('pfd.002000.xdmf')) dataframe = f.to_dataframe() dataframe.to_hdf('example.h5', 'key', complevel=9) f2 = viscid.from_dataframe(pd.read_hdf(filename1)) f2.print_tree()
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-s', "--slices", default="y=0.0,x=0.0", help="comma separated list of slices, one figure per " "slice; default is 'y=0.0,x=0.0'") parser.add_argument("--sample", default="", help="optional datafile to plot sample data with grid " "(requires Viscid to be in your PYTHONPATH)") parser.add_argument('-p', "--sample_var", default="rr", help="optional sample quantity to plot") parser.add_argument('-o', "--plot_opts", default="", help="options for sample plot") parser.add_argument("grid2", nargs=1, help="RUN.grid2 file") parser.add_argument("hgrid2", nargs=1, help="RUN.hgrid2 file") args = parser.parse_args() x, y, z = read_grid(args.grid2[0]) dx, dy, dz = read_grid(args.hgrid2[0]) dxmin = np.min(dx) dymin = np.min(dy) dzmin = np.min(dz) # setup fld if we're plotting a sample fld = None if args.sample: try: import viscid from viscid.plot import mpl viscid.readers.openggcm.GGCMGrid.mhd_to_gse_on_read = False fld = viscid.load_file(args.sample)[args.sample_var] except ImportError: print("Must have Viscid in your PYTHONPATH to plot a sample") except KeyError: print("Warning; unknown variable for sample") except TypeError: # given if the file doesnt exist, it will print its own warning pass except RuntimeError: # given if the calculator fails, it will print its own warning pass wrats = [1, 5] hrats = [1, 3] guides = [1.0, 2.0, 10.0] guide_colors = "rgy" circles = [1.0, 3.0, 6.0, 10.0, 20.0] circle_colors = 'krgby' for slc in args.slices.split(','): plane_dir, plane_loc = slc.lower().split('=') xstr, ystr = "xyz".replace(plane_dir, '') plane_str = "{0} Plane ({1} = {2})".format("-".join([xstr, ystr]).upper(), plane_dir, plane_loc) _ = plt.figure() gspec = GridSpec(2, 2, width_ratios=wrats, height_ratios=hrats) ax_mesh = plt.subplot(gspec[3]) ax_xcrds = plt.subplot(gspec[1], sharex=ax_mesh) ax_ycrds = plt.subplot(gspec[2], sharey=ax_mesh) # plot grid cells if fld is not None: mpl.plot(fld, slc, ax=ax_mesh, style="contourf", levels=100, plot_opts=args.plot_opts, colorbar=dict(ax=[ax_mesh, ax_xcrds], fraction=0.1)) xarr = [x, y, z]["xyz".index(xstr)] yarr = [x, y, z]["xyz".index(ystr)] dxarr = [dx, dy, dz]["xyz".index(xstr)] dyarr = [dx, dy, dz]["xyz".index(ystr)] _dxmin = np.min(dxarr) _dymin = np.min(dyarr) _dxmax = np.max(dxarr) _dymax = np.max(dyarr) plot_2d_gridcells(xarr, yarr, circles=circles, colors=circle_colors, ax=ax_mesh) ax_mesh.set_xlabel(xstr) # plot x vs dx for horizontal axis ax_xcrds.plot(xarr, dxarr) for i, guide in enumerate(guides): if guide * _dxmin > _dxmax: continue ax_xcrds.axhline(guide * _dxmin, color=guide_colors[i % len(guide_colors)], linestyle='--') ax_xcrds.set_ylabel('d' + xstr) # plot x vs dx for vertical axis ax_ycrds.plot(dyarr, yarr) for i, guide in enumerate(guides): if guide * _dymin > _dymax: continue ax_ycrds.axvline(guide * _dymin, color=guide_colors[i % len(guide_colors)], linestyle='--') ax_ycrds.set_ylabel(ystr) ax_ycrds.set_xlabel("d" + ystr) plt.suptitle(plane_str) info = """min dx: {0:.3g} min dy: {1:.3g} min dz: {2:.3g}""".format(dxmin, dymin, dzmin) ax = plt.subplot(gspec[0]) ax.axis('off') ax.annotate(info, xy=(0, 0), xytext=(-0.3, 0.3), textcoords='axes fraction') plt.show() return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--notwo", dest='notwo', action="store_true") parser.add_argument("--nothree", dest='nothree', action="store_true") parser.add_argument("--show", "--plot", action="store_true") args = viscid.vutil.common_argparse(parser, default_verb=0) plot2d = not args.notwo plot3d = not args.nothree # plot2d = True # plot3d = True # args.show = True img = np.load(os.path.join(sample_dir, "logo.npy")) x = np.linspace(-1, 1, img.shape[0]) y = np.linspace(-1, 1, img.shape[1]) z = np.linspace(-1, 1, img.shape[2]) logo = viscid.arrays2field([x, y, z], img) if 1: viscid.logger.info('Testing Line...') seeds = viscid.Line([-1, -1, 0], [1, 1, 2], n=5) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Plane...') seeds = viscid.Plane([0.0, 0.0, 0.0], [1, 1, 1], [1, 0, 0], 2, 2, nl=160, nm=170, NL_are_vectors=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Volume...') seeds = viscid.Volume([-0.8, -0.8, -0.8], [0.8, 0.8, 0.8], n=[64, 64, 3]) # note: can't make a 2d plot of the volume w/o a slice run_test(logo, seeds, plot2d=False, plot3d=plot3d, add_title="3d", show=args.show) if 1: viscid.logger.info('Testing Volume (with ignorable dim)...') seeds = viscid.Volume([-0.8, -0.8, 0.0], [0.8, 0.8, 0.0], n=[64, 64, 1]) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="2d", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (phi, theta)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (theta, phi)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (phi, theta)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (theta, phi)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Patch...') seeds = viscid.SphericalPatch(p0=[0, 0, 0], p1=[0, -0, -1], max_alpha=30.0, max_beta=59.9, nalpha=65, nbeta=80, r=0.5, roll=45.0) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing RectilinearMeshPoints...') f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[-1].xdmf')) slc = 'x=-40f:12f, y=-10f:10f, z=-10f:10f' b = f['b'][slc] z = b.get_crd('z') sheet_iz = np.argmin(b['x']**2, axis=2) sheet_pts = b['z=0:1'].get_points() sheet_pts[2, :] = z[sheet_iz].reshape(-1) isphere_mask = np.sum(sheet_pts[:2, :]**2, axis=0) < 5**2 day_mask = sheet_pts[0:1, :] > -1.0 sheet_pts[2, :] = np.choose(isphere_mask, [sheet_pts[2, :], 0]) sheet_pts[2, :] = np.choose(day_mask, [sheet_pts[2, :], 0]) nx, ny, _ = b.sshape sheet_seed = viscid.RectilinearMeshPoints(sheet_pts.reshape(3, nx, ny)) vx_sheet = viscid.interp_nearest(f['vx'], sheet_seed) try: if not plot2d: raise ImportError from matplotlib import pyplot as plt from viscid.plot import vpyplot as vlt vlt.clf() vlt.plot(vx_sheet, symmetric=True) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: vlt.show() except ImportError: pass try: if not plot3d: raise ImportError from viscid.plot import vlab vlab.clf() mesh = vlab.mesh_from_seeds(sheet_seed, scalars=vx_sheet, clim=(-400, 400)) vlab.plot_earth_3d(crd_system=b) vlab.view(azimuth=+90.0 + 45.0, elevation=90.0 - 25.0, distance=30.0, focalpoint=(-10.0, +1.0, +1.0)) vlab.title("RectilinearMeshPoints") vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show() except ImportError: pass # prevent weird xorg bad-instructions on tear down if 'figure' in _global_ns and _global_ns['figure'] is not None: from viscid.plot import vlab vlab.mlab.close(_global_ns['figure']) return 0
def _main(): import os from viscid.plot import vpyplot as vlt grid = viscid.grid.Grid(time=0.0) crds = viscid.arrays2crds([np.linspace(-1, 1, 32), np.linspace(-1, 1, 32)]) grid.add_field(viscid.full(crds, np.nan, name='V')) seeds0 = viscid.Circle(p0=[0.0, 0.0, 0.0], r=0.8, n=25).get_points() seeds1 = viscid.Circle(p0=[0.0, 0.0, 0.0], r=1.1, n=25).get_points() seeds3 = viscid.Line([-0.5, 0, 0], [0.5, 0, 0], n=5) delmask = np.zeros([seeds0.shape[1]], dtype='bool') curator = viscid.SeedCurator() seeds2 = curator.update(grid['V'], np.array(seeds1), delmask=delmask) vlt.plt.scatter(seeds1[0], seeds1[1], c=[0.0, 1.0, 0.0]) vlt.plt.scatter(seeds2[0], seeds2[1]) vlt.plt.axhline(-1) vlt.plt.axvline(-1) # pylint: disable=multiple-statements vlt.plt.axhline(1) vlt.plt.axvline(1) # pylint: disable=multiple-statements vlt.show() curator = viscid.ReplacementCurator(seeds0) seeds2 = curator.update(grid['V'], np.array(seeds1), delmask=delmask) vlt.plt.scatter(seeds1[0], seeds1[1], c=[0.0, 1.0, 0.0]) vlt.plt.scatter(seeds2[0], seeds2[1]) vlt.plt.axhline(-1) vlt.plt.axvline(-1) # pylint: disable=multiple-statements vlt.plt.axhline(1) vlt.plt.axvline(1) # pylint: disable=multiple-statements vlt.show() curator = viscid.ContinuousCurator(seeds3, cadence=-1) seeds2 = curator.update(grid['V'], np.array(seeds1), delmask=delmask) vlt.plt.scatter(seeds1[0], seeds1[1], c=[0.0, 1.0, 0.0]) vlt.plt.scatter(seeds2[0], seeds2[1]) vlt.plt.axhline(-1) vlt.plt.axvline(-1) # pylint: disable=multiple-statements vlt.plt.axhline(1) vlt.plt.axvline(1) # pylint: disable=multiple-statements vlt.show() target_dir = os.path.join(os.path.expanduser('~'), 'Desktop', 'fluid_movie') print("Attempting to make a movie in:", target_dir) f = viscid.load_file("~/dev/stage/otico_001/otico*.3d.xdmf") xl, xh = f.get_grid().xl_nc, f.get_grid().xh_nc seeds0 = viscid.Circle(p0=0.5 * (xl + xh), r=0.2 * np.max(xh - xl), pole=(0, 0, 1), n=10) seeds1 = viscid.Circle(p0=0.5 * (xl + xh), r=0.4 * np.max(xh - xl), pole=(0, 0, 1), n=10) seeds = viscid.Point( np.concatenate( [seeds0.get_points(), seeds1.get_points()], axis=1)) if not os.path.isdir(target_dir): os.mkdir(target_dir) target_fname = os.path.join(target_dir, 'fluid') viscid.follow_fluid(f, seeds, dt=0.0101926 / 2, callback_kwargs=dict(show=False, series_fname=target_fname)) return 0
#!/usr/bin/env python import matplotlib matplotlib.use("Agg") import viscid from viscid.plot import mpl steps = range(0, 4) flds = ['rr', 'vx', 'pp'] plot_kwargs = dict() f = viscid.load_file("run.3d.xdmf") for step in steps: print("Plotting step {}".format(step)) f.activate_time(step) for fld in flds: mpl.plt.figure() dat = f[fld] mpl.plot(dat, marker='o', **plot_kwargs) mpl.plt.savefig("%s-xy-%06d.png" % (fld, step), dpi=200) mpl.plt.close()
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") parser.add_argument("--interact", "-i", action="store_true") args = vutil.common_argparse(parser) f3d = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[0].xdmf')) f_iono = viscid.load_file(os.path.join(sample_dir, "sample_xdmf.iof.[0].xdmf")) b = f3d["b"] v = f3d["v"] pp = f3d["pp"] e = f3d["e_cc"] vlab.figure(size=(1280, 800), offscreen=not args.show) ########################################################## # make b a dipole inside 3.1Re and set e = 0 inside 4.0Re cotr = viscid.Cotr(time='1990-03-21T14:48', dip_tilt=0.0) # pylint: disable=not-callable moment = cotr.get_dipole_moment(crd_system=b) isphere_mask = viscid.make_spherical_mask(b, rmax=3.1) viscid.fill_dipole(b, m=moment, mask=isphere_mask) e_mask = viscid.make_spherical_mask(b, rmax=4.0) viscid.set_in_region(e, 0.0, alpha=0.0, mask=e_mask, out=e) ###################################### # plot a scalar cut plane of pressure pp_src = vlab.field2source(pp, center='node') scp = vlab.scalar_cut_plane(pp_src, plane_orientation='z_axes', opacity=0.5, transparent=True, view_controls=False, cmap="inferno", logscale=True) scp.implicit_plane.normal = [0, 0, -1] scp.implicit_plane.origin = [0, 0, 0] scp.enable_contours = True scp.contour.filled_contours = True scp.contour.number_of_contours = 64 cbar = vlab.colorbar(scp, title=pp.name, orientation='vertical') cbar.scalar_bar_representation.position = (0.01, 0.13) cbar.scalar_bar_representation.position2 = (0.08, 0.76) ###################################### # plot a vector cut plane of the flow vcp = vlab.vector_cut_plane(v, scalars=pp_src, plane_orientation='z_axes', view_controls=False, mode='arrow', cmap='Greens_r') vcp.implicit_plane.normal = [0, 0, -1] vcp.implicit_plane.origin = [0, 0, 0] ############################## # plot very faint isosurfaces vx_src = vlab.field2source(v['x'], center='node') iso = vlab.iso_surface(vx_src, contours=[0.0], opacity=0.008, cmap='Pastel1') ############################################################## # calculate B field lines && topology in Viscid and plot them seedsA = viscid.SphericalPatch([0, 0, 0], [2, 0, 1], 30, 15, r=5.0, nalpha=5, nbeta=5) seedsB = viscid.SphericalPatch([0, 0, 0], [1.9, 0, -20], 30, 15, r=5.0, nalpha=1, nbeta=5) seeds = np.concatenate([seedsA, seedsB], axis=1) b_lines, topo = viscid.calc_streamlines(b, seeds, ibound=3.5, obound0=[-25, -20, -20], obound1=[15, 20, 20], wrap=True) vlab.plot_lines(b_lines, scalars=viscid.topology2color(topo)) ###################################################################### # plot a random circle at geosynchronus orbit with scalars colored # by the Matplotlib viridis color map, just because we can; this is # a useful toy for debugging circle = viscid.Circle(p0=[0, 0, 0], r=6.618, n=128, endpoint=True) scalar = np.sin(circle.as_local_coordinates().get_crd('phi')) surf = vlab.plot_line(circle.get_points(), scalars=scalar, clim=0.8, cmap="Spectral_r") ###################################################################### # Use Mayavi (VTK) to calculate field lines using an interactive seed # These field lines are colored by E parallel epar = viscid.project(e, b) epar.name = "Epar" bsl2 = vlab.streamline(b, epar, seedtype='plane', seed_resolution=4, integration_direction='both', clim=(-0.05, 0.05)) # now tweak the VTK streamlines bsl2.stream_tracer.maximum_propagation = 20. bsl2.seed.widget.origin = [-11, -5.0, -2.0] bsl2.seed.widget.point1 = [-11, 5.0, -2.0] bsl2.seed.widget.point2 = [-11.0, -5.0, 2.0] bsl2.streamline_type = 'tube' bsl2.tube_filter.radius = 0.03 bsl2.stop() # this stop/start was a hack to get something to update bsl2.start() bsl2.seed.widget.enabled = False cbar = vlab.colorbar(bsl2, title=epar.name, label_fmt='%.3f', orientation='horizontal') cbar.scalar_bar_representation.position = (0.15, 0.01) cbar.scalar_bar_representation.position2 = (0.72, 0.10) ############################################################### # Make a contour at the open-closed boundary in the ionosphere seeds_iono = viscid.Sphere(r=1.063, pole=-moment, ntheta=256, nphi=256, thetalim=(0, 180), philim=(0, 360), crd_system=b) _, topo_iono = viscid.calc_streamlines(b, seeds_iono, ibound=1.0, nr_procs='all', output=viscid.OUTPUT_TOPOLOGY) topo_iono = np.log2(topo_iono) m = vlab.mesh_from_seeds(seeds_iono, scalars=topo_iono, opacity=1.0, clim=(0, 3), color=(0.992, 0.445, 0.0)) m.enable_contours = True m.actor.property.line_width = 4.0 m.contour.number_of_contours = 4 #################################################################### # Plot the ionosphere, note that the sample data has the ionosphere # at a different time, so the open-closed boundary found above # will not be consistant with the field aligned currents fac_tot = 1e9 * f_iono['fac_tot'] m = vlab.plot_ionosphere(fac_tot, bounding_lat=30.0, vmin=-300, vmax=300, opacity=0.75, rotate=cotr, crd_system=b) m.actor.property.backface_culling = True ######################################################################## # Add some markers for earth, i.e., real earth, and dayside / nightside # representation vlab.plot_blue_marble(r=1.0, lines=False, ntheta=64, nphi=128, rotate=cotr, crd_system=b) # now shade the night side with a transparent black hemisphere vlab.plot_earth_3d(radius=1.01, night_only=True, opacity=0.5, crd_system=b) #################### # Finishing Touches # vlab.axes(pp_src, nb_labels=5) oa = vlab.orientation_axes() oa.marker.set_viewport(0.75, 0.75, 1.0, 1.0) # note that resize won't work if the current figure has the # off_screen_rendering flag set # vlab.resize([1200, 800]) vlab.view(azimuth=45, elevation=70, distance=35.0, focalpoint=[-2, 0, 0]) ############## # Save Figure # print("saving png") # vlab.savefig('mayavi_msphere_sample.png') # print("saving x3d") # # x3d files can be turned into COLLADA files with meshlab, and # # COLLADA (.dae) files can be opened in OS X's preview # # # # IMPORTANT: for some reason, using bounding_lat in vlab.plot_ionosphere # # causes a segfault when saving x3d files # # # vlab.savefig('mayavi_msphere_sample.x3d') # print("done") vlab.savefig(next_plot_fname(__file__)) ########################### # Interact Programatically if args.interact: vlab.interact() ####################### # Interact Graphically if args.show: vlab.show() try: vlab.mlab.close() except AttributeError: pass return 0
def _main(): f = viscid.load_file('~/dev/work/xi_fte_001/*.3d.*.xdmf') time_slice = ':' times = np.array([grid.time for grid in f.iter_times(time_slice)]) # XYZ coordinates of virtual satelites in warped "plasma sheet coords" x_sat_psc = np.linspace(-30, 0, 31) # X (GSE == PSC) y_sat_psc = np.linspace(-10, 10, 21) # Y (GSE == PSC) z_sat_psc = np.linspace(-2, 2, 5) # Z in PSC (z=0 is the plasma sheet) # the GSE z location of the virtual satelites in the warped plasma sheet # coordinates, so sat_z_gse_ts['x=5j, y=1j, z=0j'] would give the # plasma sheet location at x=5.0, y=1.0 # These fields depend on time because the plasma sheet moves in time sat_z_gse_ts = viscid.zeros([times, x_sat_psc, y_sat_psc, z_sat_psc], crd_names='txyz', center='node', name='PlasmaSheetZ_GSE') vx_ts = viscid.zeros_like(sat_z_gse_ts) bz_ts = viscid.zeros_like(sat_z_gse_ts) for itime, grid in enumerate(f.iter_times(time_slice)): print("Processing time slice", itime, grid.time) gse_slice = 'x=-35j:0j, y=-15j:15j, z=-6j:6j' bx = grid['bx'][gse_slice] bx_argmin = np.argmin(bx**2, axis=2) z_gse = bx.get_crd('z') # ps_zloc_gse is the plasma sheet z location along the GGCM grid x/y ps_z_gse = viscid.zeros_like(bx[:, :, 0:1]) ps_z_gse[...] = z_gse[bx_argmin] # Note: Here you could apply a gaussian filter to # ps_z_gse[:, :, 0].data in order to smooth the surface # if desired. Scipy / Scikit-Image have some functions # that do this # ok, we found the plasma sheet z GSE location on the actual GGCM # grid, but we just want a subset of that grid for our virtual # satelites, so just interpolate the ps z location to our subset ps_z_gse_subset = viscid.interp_trilin(ps_z_gse, sat_z_gse_ts[itime, :, :, 0:1], wrap=True) # now we know the plasma sheet z location in GSE, and how far # apart we want the satelites in z, so put those two things together # to get a bunch of satelite locations sat_z_gse_ts[itime] = ps_z_gse_subset.data + z_sat_psc.reshape(1, 1, -1) # make a seed generator that we can use to fill the vx and bz # time series for this instant in time sat_loc_gse = sat_z_gse_ts[itime].get_points() sat_loc_gse[2, :] = sat_z_gse_ts[itime].data.reshape(-1) # slicing the field before doing the interpolation makes this # faster for hdf5 data, but probably for other data too vx_ts[itime] = viscid.interp_trilin(grid['vx'][gse_slice], sat_loc_gse, wrap=False ).reshape(vx_ts.shape[1:]) bz_ts[itime] = viscid.interp_trilin(grid['bz'][gse_slice], sat_loc_gse, wrap=False ).reshape(bz_ts.shape[1:]) # 2d plots of the plasma sheet z location to make sure we did the # interpolation correctly if False: # pylint: disable=using-constant-test from viscid.plot import vpyplot as vlt fig, (ax0, ax1) = vlt.subplots(2, 1) # pylint: disable=unused-variable vlt.plot(ps_z_gse, ax=ax0, clim=(-5, 5)) vlt.plot(ps_z_gse_subset, ax=ax1, clim=(-5, 5)) vlt.auto_adjust_subplots() vlt.show() # make a 3d plot of the plasma sheet surface to verify that it # makes sense if True: # pylint: disable=using-constant-test from viscid.plot import vlab fig = vlab.figure(size=(1280, 800), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) vlab.clf() # plot the plasma sheet coloured by vx # Note: points closer to x = 0 are unsightly since the plasma # sheet criteria starts to fall apart on the flanks, so # just remove the first few rows ps_z_gse_tail = ps_z_gse['x=:-2.25j'] ps_mesh_shape = [3, ps_z_gse_tail.shape[0], ps_z_gse_tail.shape[1]] ps_pts = ps_z_gse_tail.get_points().reshape(ps_mesh_shape) ps_pts[2, :, :] = ps_z_gse_tail[:, :, 0] plasma_sheet = viscid.RectilinearMeshPoints(ps_pts) ps_vx = viscid.interp_trilin(grid['vx'][gse_slice], plasma_sheet) _ = vlab.mesh_from_seeds(plasma_sheet, scalars=ps_vx) vx_clim = (-1400, 1400) vx_cmap = 'viridis' vlab.colorbar(title='Vx', clim=vx_clim, cmap=vx_cmap, nb_labels=5) # plot satelite locations as dots colored by Vx with the same # limits and color as the plasma sheet mesh sat3d = vlab.points3d(sat_loc_gse[0], sat_loc_gse[1], sat_loc_gse[2], vx_ts[itime].data.reshape(-1), scale_mode='none', scale_factor=0.2) vlab.apply_cmap(sat3d, clim=vx_clim, cmap=vx_cmap) # plot Earth for reference cotr = viscid.Cotr(dip_tilt=0.0) # pylint: disable=not-callable vlab.plot_blue_marble(r=1.0, lines=False, ntheta=64, nphi=128, rotate=cotr, crd_system='mhd') vlab.plot_earth_3d(radius=1.01, night_only=True, opacity=0.5, crd_system='gse') vlab.view(azimuth=45, elevation=70, distance=35.0, focalpoint=[-9, 3, -1]) vlab.savefig('plasma_sheet_3d_{0:02d}.png'.format(itime)) vlab.show() try: vlab.mlab.close(fig) except TypeError: pass # this happens if the figure is already closed # now do what we will with the time series... this is not a good # presentation of this data, but you get the idea from viscid.plot import vpyplot as vlt fig, axes = vlt.subplots(4, 4, figsize=(12, 12)) for ax_row, yloc in zip(axes, np.linspace(-5, 5, len(axes))[::-1]): for ax, xloc in zip(ax_row, np.linspace(4, 7, len(ax_row))): vlt.plot(vx_ts['x={0}j, y={1}j, z=0j'.format(xloc, yloc)], ax=ax) ax.set_ylabel('') vlt.plt.title('x = {0:g}, y = {1:g}'.format(xloc, yloc)) vlt.plt.suptitle('Vx [km/s]') vlt.auto_adjust_subplots() vlt.show() return 0
#!/usr/bin/env python import matplotlib matplotlib.use("Agg") import viscid from viscid.plot import mpl steps = range(0, 4) flds = ['rr', 'vx', 'vy', 'by', 'pp'] plot_kwargs = dict() f = viscid.load_file("run.3d.xdmf") for step in steps: print("Plotting step {}".format(step)) f.activate_time(step) for fld in flds: mpl.plt.figure() dat = f[fld] mpl.plot(dat, marker='o', **plot_kwargs) mpl.plt.savefig("%s-xy-%06d.png" % (fld, step), dpi=200) mpl.plt.close()
def main(): mhd_type = "C" make_plots = 1 mhd_type = mhd_type.upper() if mhd_type.startswith("C"): if mhd_type in ("C", ): f = viscid.load_file("$WORK/tmedium/*.3d.[-1].xdmf") elif mhd_type in ("C2", "C3"): f = viscid.load_file("$WORK/tmedium2/*.3d.[-1].xdmf") else: raise ValueError() catol = 1e-8 rtol = 2e-6 elif mhd_type in ("F", "FORTRAN"): f = viscid.load_file("$WORK/tmedium3/*.3df.[-1]") catol = 1e-8 rtol = 7e-2 else: raise ValueError() do_fill_dipole = True gslc = "x=-21.2j:12j, y=-11j:11j, z=-11j:11j" b = f['b_cc'][gslc] b1 = f['b_fc'][gslc] e_cc = f['e_cc'][gslc] e_ec = f['e_ec'][gslc] if do_fill_dipole: mask = viscid.make_spherical_mask(b, rmax=3.5) viscid.fill_dipole(b, mask=mask) mask = viscid.make_spherical_mask(b1, rmax=3.5) viscid.fill_dipole(b1, mask=mask) mask = None # seeds = viscid.SphericalCap(r=1.02, ntheta=64, nphi=32, angle0=17, angle=20, # philim=(100, 260), roll=-180.0) # seeds = viscid.SphericalCap(r=1.02, ntheta=64, nphi=32, angle0=17, angle=20, # philim=(0, 10), roll=0.0) seedsN = viscid.Sphere(r=1.02, ntheta=16, nphi=16, thetalim=(15, 25), philim=(0, 300), crd_system=b) seedsS = viscid.Sphere(r=1.02, ntheta=16, nphi=16, thetalim=(155, 165), philim=(0, 300), crd_system=b) bl_kwargs = dict(ibound=0.9, obound0=(-20, -10, -10), obound1=(11, 10, 10)) # blines_cc, topo_cc = viscid.streamlines(b, seeds, **bl_kwargs) blinesN_fc, topoN_fc = viscid.streamlines(b1, seedsN, **bl_kwargs) _, topoS_fc = viscid.streamlines(b1, seedsS, output=viscid.OUTPUT_TOPOLOGY, **bl_kwargs) if True: from viscid.plot import vlab mesh = vlab.mesh_from_seeds(seedsN, scalars=topoN_fc) mesh.actor.property.backface_culling = True # vlab.plot_lines(blines_cc, scalars="#000000", tube_radius=0.03) vlab.plot_lines(blinesN_fc, scalars=viscid.topology2color(topoN_fc), opacity=0.7) vlab.plot_blue_marble(r=1.0) vlab.plot_earth_3d(radius=1.01, crd_system=b, night_only=True, opacity=0.5) vlab.show() if True: vlt.subplot(121, projection='polar') vlt.plot(topoN_fc) vlt.subplot(122, projection='polar') vlt.plot(topoS_fc) vlt.show() return 0
# run eval fld = eval(salted_eqn, {"__builtins__": {}}, local_dict) # pylint: disable=eval-used try: fld.name = result_name fld.pretty_name = result_name except AttributeError: pass return fld if __name__ == "__main__": import os import viscid from viscid.plot import vpyplot as vlt import matplotlib.pyplot as plt enabled = True _d = os.path.dirname(viscid.__file__) _g = viscid.load_file(_d + "/../sample/sample.py_0.xdmf").get_grid() plt.subplot(211) _fld = evaluate(_g, "speed", "sqrt(vx**2 + vy**2 + sqrt(vz**4))") vlt.plot(_fld, show=False) plt.subplot(212) _fld = evaluate(_g, "speed", "sqrt(vx**2 + vy**2 + sqrt(vz**4))", try_numexpr=False) vlt.plot(_fld, show=True) ## ## EOF ##
def main(): mhd_type = "C3" make_plots = 1 mhd_type = mhd_type.upper() if mhd_type.startswith("C"): if mhd_type in ("C", ): f = viscid.load_file("$WORK/tmedium/*.3d.[-1].xdmf") elif mhd_type in ("C2", "C3"): f = viscid.load_file("$WORK/tmedium2/*.3d.[-1].xdmf") else: raise ValueError() catol = 1e-8 rtol = 2e-6 elif mhd_type in ("F", "FORTRAN"): f = viscid.load_file("$WORK/tmedium3/*.3df.[-1]") catol = 1e-8 rtol = 7e-2 else: raise ValueError() b = f['b_cc'] b1 = f['b_fc'] e_cc = f['e_cc'] e_ec = f['e_ec'] # divb = f['divB'] # viscid.interact() if True: bD = viscid.empty_like(b) bD.data = np.array(b.data) b1D = viscid.empty_like(b1) b1D.data = np.array(b1.data) mask5 = viscid.make_spherical_mask(bD, rmax=3.5) mask1_5 = viscid.make_spherical_mask(bD, rmax=1.5) viscid.fill_dipole(bD, mask=mask5) viscid.set_in_region(bD, bD, 0.0, 0.0, mask=mask1_5, out=bD) # compare_vectors(_b, bD, make_plots=True) mask5 = viscid.make_spherical_mask(b1D, rmax=3.5) mask1_5 = viscid.make_spherical_mask(b1D, rmax=1.5) viscid.fill_dipole(b1D, mask=mask5) viscid.set_in_region(b1D, b1D, 0.0, 0.0, mask=mask1_5, out=b1D) compare_vectors(bD["x=1:-1, y=1:-1, z=1:-1"], b1D.as_cell_centered(), make_plots=True) # plt.clf() # dkwargs = dict(symmetric=True, earth=True, clim=(-1e2, 1e2)) # ax1 = plt.subplot(311) # vlt.plot(viscid.div(b1)['y=0j'], **dkwargs) # plt.subplot(312, sharex=ax1, sharey=ax1) # vlt.plot(viscid.div(b)['y=0j'], **dkwargs) # plt.subplot(313, sharex=ax1, sharey=ax1) # vlt.plot(viscid.div(b1D)['y=0j'], **dkwargs) # vlt.show() bD = b1D = mask5 = mask1_5 = None # straight up interpolate b1 to cc crds and compare with b if True: b1_cc = viscid.interp_trilin(b1, b).as_flat() viscid.set_in_region(b, b, alpha=0.0, beta=0.0, out=b, mask=viscid.make_spherical_mask(b, rmax=5.0)) viscid.set_in_region(b1_cc, b1_cc, alpha=0.0, beta=0.0, out=b1_cc, mask=viscid.make_spherical_mask(b1_cc, rmax=5.0)) compare_vectors(b, b1_cc, make_plots=True) # make div? if True: # make seeds for 1.5x supersampling b1 n = 128 seeds = viscid.Volume((5.1, -0.02, -5.0), (12.0, 0.02, 5.0), (n, 3, n)) # do interpolation onto new seeds b2 = viscid.interp_trilin(b1, seeds) div_b = viscid.div(b) div_b1 = viscid.div(b1) div_b2 = viscid.div(b2) viscid.set_in_region(div_b, div_b, alpha=0.0, beta=0.0, out=div_b, mask=viscid.make_spherical_mask(div_b, rmax=5.0)) viscid.set_in_region(div_b1, div_b1, alpha=0.0, beta=0.0, out=div_b1, mask=viscid.make_spherical_mask(div_b1, rmax=5.0)) viscid.set_in_region(div_b2, div_b2, alpha=0.0, beta=0.0, out=div_b2, mask=viscid.make_spherical_mask(div_b2, rmax=5.0)) viscid.set_in_region(divb, divb, alpha=0.0, beta=0.0, out=divb, mask=viscid.make_spherical_mask(divb, rmax=5.0)) plt.clf() ax1 = vlt.subplot(311) vlt.plot(div_b['y=0j'], symmetric=True, earth=True) vlt.subplot(312, sharex=ax1, sharey=ax1) # vlt.plot(div_b1['y=0j'], symmetric=True, earth=True) vlt.plot(div_b2['y=0j'], symmetric=True, earth=True) vlt.subplot(313, sharex=ax1, sharey=ax1) vlt.plot(divb['y=0j'], symmetric=True, earth=True) vlt.show() return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--notwo", dest='notwo', action="store_true") parser.add_argument("--nothree", dest='nothree', action="store_true") parser.add_argument("--show", "--plot", action="store_true") args = viscid.vutil.common_argparse(parser, default_verb=0) plot2d = not args.notwo plot3d = not args.nothree # plot2d = True # plot3d = True # args.show = True img = np.load(os.path.join(sample_dir, "logo.npy")) x = np.linspace(-1, 1, img.shape[0]) y = np.linspace(-1, 1, img.shape[1]) z = np.linspace(-1, 1, img.shape[2]) logo = viscid.arrays2field([x, y, z], img) if 1: viscid.logger.info('Testing Point with custom local coordinates...') pts = np.vstack([[-1, -0.5, 0, 0.5, 1], [-1, -0.5, 0, 0.5, 1], [ 0, 0.5, 1, 1.5, 2]]) local_crds = viscid.asarray_datetime64([0, 60, 120, 180, 240], conservative=True) seeds = viscid.Point(pts, local_crds=local_crds) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Line...') seeds = viscid.Line([-1, -1, 0], [1, 1, 2], n=5) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Plane...') seeds = viscid.Plane([0.0, 0.0, 0.0], [1, 1, 1], [1, 0, 0], 2, 2, nl=160, nm=170, NL_are_vectors=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Volume...') seeds = viscid.Volume([-0.8, -0.8, -0.8], [0.8, 0.8, 0.8], n=[64, 64, 3]) # note: can't make a 2d plot of the volume w/o a slice run_test(logo, seeds, plot2d=False, plot3d=plot3d, add_title="3d", show=args.show) if 1: viscid.logger.info('Testing Volume (with ignorable dim)...') seeds = viscid.Volume([-0.8, -0.8, 0.0], [0.8, 0.8, 0.0], n=[64, 64, 1]) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="2d", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (phi, theta)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (theta, phi)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (phi, theta)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (theta, phi)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Patch...') seeds = viscid.SphericalPatch(p0=[0, 0, 0], p1=[0, -0, -1], max_alpha=30.0, max_beta=59.9, nalpha=65, nbeta=80, r=0.5, roll=45.0) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: # this spline test is very custom viscid.logger.info('Testing Spline...') try: import scipy.interpolate as interpolate except ImportError: msg = "XFail: ImportError (is scipy installed?)" if plot2d: try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() plt.annotate(msg, xy=(0.3, 0.4), xycoords='axes fraction') plt.savefig(next_plot_fname(__file__, series='2d')) plt.savefig(next_plot_fname(__file__, series='2d')) plt.savefig(next_plot_fname(__file__, series='3d')) if args.show: plt.show() except ImportError: pass else: knots = np.array([[ 0.2, 0.5, 0.0], [-0.2, 0.5, 0.2], [-0.2, 0.0, 0.4], [ 0.2, 0.0, 0.2], [ 0.2, -0.5, 0.0], [-0.2, -0.5, 0.2]]).T seed_name = "Spline" fld = logo seeds = viscid.Spline(knots) seed_pts = seeds.get_points() interp_fld = viscid.interp_trilin(fld, seeds) if plot2d: try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() vlt.plot(interp_fld) plt.title(seed_name) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: plt.show() plt.clf() from matplotlib import rcParams _ms = rcParams['lines.markersize'] plt.gca().scatter(knots[0, :], knots[1, :], s=(2 * _ms)**2, marker='^', color='y') plt.gca().scatter(seed_pts[0, :], seed_pts[1, :], s=(1.5 * _ms)**2, marker='o', color='k') vlt.plot2d_line(seed_pts, scalars=interp_fld.flat_data, symdir='z') plt.title(seed_name) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: plt.show() except ImportError: pass if plot3d: try: from viscid.plot import vlab _ = get_mvi_fig(offscreen=not args.show) vlab.points3d(knots[0], knots[1], knots[2], color=(1.0, 1.0, 0), scale_mode='none', scale_factor=0.04) p = vlab.points3d(seed_pts[0], seed_pts[1], seed_pts[2], color=(0, 0, 0), scale_mode='none', scale_factor=0.03) vlab.plot_line(seed_pts, scalars=interp_fld.flat_data, tube_radius=0.01) vlab.axes(p) vlab.title(seed_name) vlab.mlab.roll(-90.0) vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show(stop=True) except ImportError: pass if 1: viscid.logger.info('Testing RectilinearMeshPoints...') f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[-1].xdmf')) slc = 'x=-40j:12j, y=-10j:10j, z=-10j:10j' b = f['b'][slc] z = b.get_crd('z') sheet_iz = np.argmin(b['x']**2, axis=2) sheet_pts = b['z=0:1'].get_points() sheet_pts[2, :] = z[sheet_iz].reshape(-1) isphere_mask = np.sum(sheet_pts[:2, :]**2, axis=0) < 5**2 day_mask = sheet_pts[0:1, :] > -1.0 sheet_pts[2, :] = np.choose(isphere_mask, [sheet_pts[2, :], 0]) sheet_pts[2, :] = np.choose(day_mask, [sheet_pts[2, :], 0]) nx, ny, _ = b.sshape sheet_seed = viscid.RectilinearMeshPoints(sheet_pts.reshape(3, nx, ny)) vx_sheet = viscid.interp_nearest(f['vx'], sheet_seed) try: if not plot2d: raise ImportError from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt vlt.clf() vlt.plot(vx_sheet, symmetric=True) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: vlt.show() except ImportError: pass try: if not plot3d: raise ImportError from viscid.plot import vlab _ = get_mvi_fig(offscreen=not args.show) mesh = vlab.mesh_from_seeds(sheet_seed, scalars=vx_sheet, clim=(-400, 400)) vlab.plot_earth_3d(crd_system=b) vlab.view(azimuth=+90.0 + 45.0, elevation=90.0 - 25.0, distance=30.0, focalpoint=(-10.0, +1.0, +1.0)) vlab.title("RectilinearMeshPoints") vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show(stop=True) except ImportError: pass # prevent weird xorg bad-instructions on tear down if 'figure' in _global_ns and _global_ns['figure'] is not None: from viscid.plot import vlab vlab.mlab.close(_global_ns['figure']) return 0
from scipy.integrate import dblquad #--------------------------------------------------------------------------- #--------------------------------------------------------------------------- # set the path to the file #project_dir = '/run/media/jaa/C2BCB9BCBCB9AB75/DIRAC_RUNs/SCALING/1024_1st' project_dir = '/disk/plasma4/jaa/PSC_things/trillian/TR' #viscid.__name__ #viscid.__doc__ #viscid.__dict__ #The __dict__ attribute will return a dictionary object of module attributes, functions and other definitions and their respective values. #--------------------------------------------------------------------------- #--------------------------------------------------------------------------- # Load the files fro all times f = viscid.load_file(project_dir + "/pfd.xdmf", force_reload=True) #With f.__dict__ it is possible to see which are the elements of the object #These are the keys, all of them are 3D objects # ['hx', 'hy', 'hz'] # ['jx', 'jy', 'jz'] # ['vx_e', 'vx_i', 'vy_e', 'vy_i', 'vz_e', 'vz_i'] #['n_e', 'n_i'] #['Txx_e', 'Txx_i', 'Txy_e', 'Txy_i', 'Txz_e', 'Txz_i', 'Tyy_e', 'Tyy_i', 'Tyz_e', 'Tyz_i', 'Tzz_e', 'Tzz_i'] #--------------------------------------------------------------------------- #Here make the operations #--------------------------------------------------------------------------- #Defining the variables Utotal_av=[]; U_elec_av=[]; U_mag_av =[]; Ki_av =[]; Ke_av =[]; Ki_th_av =[]; Ke_th_av=[]