From c7c882217824e9c6004f299f49a54e6edde86200 Mon Sep 17 00:00:00 2001 From: "Documenter.jl" Date: Mon, 17 Jul 2023 12:17:04 +0000 Subject: [PATCH] build based on 4f9e488 --- dev/benchmark/index.html | 2 +- dev/contributing/index.html | 2 +- dev/examples/index.html | 2 +- .../postprocess/demo_convert2vti/index.html | 2 +- .../demo_em_extract_slice/index.html | 2 +- .../demo_lineextracting_mt/index.html | 2 +- dev/examples/postprocess/demo_log/index.html | 2 +- .../demo_magnetopause_2d_mt/index.html | 2 +- .../demo_pointextracting/index.html | 2 +- .../demo_pointsextracting/index.html | 2 +- .../index.html | 2 +- .../demo_wave_satellite_mt/index.html | 2 +- .../demo_wave_search_mt/index.html | 2 +- .../demo_wave_tracing_mt/index.html | 2 +- .../postprocess/demo_x_o_points/index.html | 2 +- .../demo_x_points_extracting/index.html | 2 +- .../demo_1d2d_mp_pyplot/index.html | 2 +- .../visualization/demo_1d2d_pyplot/index.html | 2 +- .../demo_1d_animation_pyplot/index.html | 2 +- .../demo_2d_animation_pyplot/index.html | 2 +- .../demo_2d_mp_pyplot/index.html | 2 +- .../demo_2dcontourseries_pyplot/index.html | 2 +- .../demo_2dplot_plots/index.html | 2 +- .../demo_2dplot_pyplot/index.html | 2 +- .../demo_3dcuts_pyplot/index.html | 2 +- .../demo_B_fieldline_mp_pyplot/index.html | 2 +- .../demo_B_fieldline_pyplot/index.html | 2 +- .../demo_bowshock_2d_mt/index.html | 2 +- .../demo_bowshock_2dlocation/index.html | 2 +- .../demo_diff_extracting/index.html | 2 +- .../demo_energy_spectrum/index.html | 2 +- .../demo_field_tracing_2d/index.html | 2 +- .../demo_field_tracing_3d/index.html | 2 +- .../demo_lineextracting_mp_pyplot/index.html | 2 +- .../demo_lineextracting_pyplot/index.html | 2 +- .../index.html | 2 +- .../index.html | 2 +- .../visualization/demo_mesh_pyplot/index.html | 2 +- .../demo_mp_progressbar/index.html | 2 +- .../demo_poynting_mt_pyplot/index.html | 2 +- .../demo_tensor_pyplot/index.html | 2 +- .../visualization/demo_vdf_pyplot/index.html | 2 +- .../visualization/demo_vdfs_pyplot/index.html | 2 +- .../demo_vector_pyplot/index.html | 2 +- dev/gallery/index.html | 2 +- dev/index.html | 2 +- dev/internal/index.html | 38 +++++++++---------- dev/log/index.html | 2 +- dev/manual/index.html | 2 +- dev/python/index.html | 2 +- dev/search/index.html | 2 +- dev/search_index.js | 2 +- 52 files changed, 70 insertions(+), 70 deletions(-) diff --git a/dev/benchmark/index.html b/dev/benchmark/index.html index 36a6745c..32793ba8 100644 --- a/dev/benchmark/index.html +++ b/dev/benchmark/index.html @@ -1,2 +1,2 @@ -Benchmarks · Vlasiator.jl

Benchmarks

The test file information are listed below:

IndexFilenameNumber of CellsDimensionAMRPublic
11d_single.vlsv201NoYes
2bulk.2d.vlsv6,3001NoYes
32d_double.vlsv51,2002NoYes
42d_AFC.vlsv4,612,5002NoYes
53d_EGI.vlsv3,966,5803YesNo

Access to the public data can be found from vlsv_data.

Note

The numbers shown here are comparisons between Analysator v0.9 and Vlasiator.jl v0.9.32 running Python 3.6.9/3.9.7 and Julia 1.8.3 with the scripts perf.jl and perf.py. The timings are collected from a i5-10210U @ 1.6GHz CPU with 16 GB RAM if not specified.

  • Loading meta data[1]
File IndexJulia [ms]Python [ms]Ratio
10.181.196.6
20.511.663.1
32.333.111.3
45062770.5
55492830.5
  • Reading DCCRG grid variables
File IndexJulia [ms]Python [ms]Ratio
10.0040.0717
20.02[2]0.084
30.17[2]0.211.2
420[2]231.1
511[2]111.0
  • Reading field solver grid variables[3]
File IndexSizeJulia [s]Julia, mmap [s]Python [s]Ratio
56.2 GiB Float32188567
  • Plotting 2D density contours on a uniform mesh (no GUI)
File IndexJulia [s]Python [s]Ratio
40.55.411
  • Plotting 2D density slices from a 3D AMR mesh (no GUI)
File IndexJulia [s][4]Python [s]Ratio
50.53.16.2
  • Static virtual satellite tracking from 3D AMR data (26G per frame, 32 MB Cell IDs) on a cluster[5]
FramesJulia, 1 thread [s]Julia, 2 threads [s]Python [s]
84545341220
  • 1See the issue about sorting. The performance of EzXML is also not ideal: we may need to find a better XML parser in Julia.
  • 2Vlasiator.jl can be faster if there is no conversion from Float64 to Float32. See Precision.
  • 3The field solver grid is a regular Cartesian grid at the finest refinement level introduced after Vlasiator 5. Therefore fsgrid variables are quite large for 3D AMR runs: with limited memory (e.g. 16 GB RAM) you may encounter out-of-memory issues when reading fg_b more than once. In Vlasiator.jl, we provide the option usemmap=true for reading large arrays –- see Memory for more.
  • 4The first time execution will be slower due to JIT compilation (which is excluded in the timing here). This is known as "Time-To-First-X" in the Julia community.
  • 5University of Helsinki cluster Vorna with Intel Xeon E5-2697 @ 2.70GHz.
+Benchmarks · Vlasiator.jl

Benchmarks

The test file information are listed below:

IndexFilenameNumber of CellsDimensionAMRPublic
11d_single.vlsv201NoYes
2bulk.2d.vlsv6,3001NoYes
32d_double.vlsv51,2002NoYes
42d_AFC.vlsv4,612,5002NoYes
53d_EGI.vlsv3,966,5803YesNo

Access to the public data can be found from vlsv_data.

Note

The numbers shown here are comparisons between Analysator v0.9 and Vlasiator.jl v0.9.32 running Python 3.6.9/3.9.7 and Julia 1.8.3 with the scripts perf.jl and perf.py. The timings are collected from a i5-10210U @ 1.6GHz CPU with 16 GB RAM if not specified.

  • Loading meta data[1]
File IndexJulia [ms]Python [ms]Ratio
10.181.196.6
20.511.663.1
32.333.111.3
45062770.5
55492830.5
  • Reading DCCRG grid variables
File IndexJulia [ms]Python [ms]Ratio
10.0040.0717
20.02[2]0.084
30.17[2]0.211.2
420[2]231.1
511[2]111.0
  • Reading field solver grid variables[3]
File IndexSizeJulia [s]Julia, mmap [s]Python [s]Ratio
56.2 GiB Float32188567
  • Plotting 2D density contours on a uniform mesh (no GUI)
File IndexJulia [s]Python [s]Ratio
40.55.411
  • Plotting 2D density slices from a 3D AMR mesh (no GUI)
File IndexJulia [s][4]Python [s]Ratio
50.53.16.2
  • Static virtual satellite tracking from 3D AMR data (26G per frame, 32 MB Cell IDs) on a cluster[5]
FramesJulia, 1 thread [s]Julia, 2 threads [s]Python [s]
84545341220
  • 1See the issue about sorting. The performance of EzXML is also not ideal: we may need to find a better XML parser in Julia.
  • 2Vlasiator.jl can be faster if there is no conversion from Float64 to Float32. See Precision.
  • 3The field solver grid is a regular Cartesian grid at the finest refinement level introduced after Vlasiator 5. Therefore fsgrid variables are quite large for 3D AMR runs: with limited memory (e.g. 16 GB RAM) you may encounter out-of-memory issues when reading fg_b more than once. In Vlasiator.jl, we provide the option usemmap=true for reading large arrays –- see Memory for more.
  • 4The first time execution will be slower due to JIT compilation (which is excluded in the timing here). This is known as "Time-To-First-X" in the Julia community.
  • 5University of Helsinki cluster Vorna with Intel Xeon E5-2697 @ 2.70GHz.
diff --git a/dev/contributing/index.html b/dev/contributing/index.html index e85ca2a9..6e89eb51 100644 --- a/dev/contributing/index.html +++ b/dev/contributing/index.html @@ -1,3 +1,3 @@ Contributing · Vlasiator.jl

Contributing

  • Try to explain your contribution with simple language.
  • References are always welcome.
  • Follow the coding standards in the source.

Reporting issues

If you are experiencing issues or have discovered a bug, please report it on GitHub. To make the resolution process easier, please include the version of Julia and Vlasiator.jl in your writeup. These can be found with two commands:

julia> versioninfo()
-julia> using Pkg; Pkg.status()

Feature requests

If you have suggestions of improvement or algorithms that you would like to see implemented in Vlasiator.jl, please open an issue on GitHub. Suggestions as well as feature requests are very welcome.

Code contribution

If you have code that you would like to contribute to Vlasiator.jl, that is awesome! Please open an issue before you create the pull request on GitHub so that we make sure your idea is aligned with our goals for the project.

After your idea is discussed and revised by maintainers, please get the development version of the project by typing the following in the package manager:

] activate @dev

This will create a fresh environment called @dev where you can play with the project components without compromising your normal user environment.

] dev Vlasiator

This will clone all the project components in your ~/.julia folder so that you can modify it and submit a pull request on GitHub later. Don't hesitate to ask questions. We are looking forward to your contributions.

+julia> using Pkg; Pkg.status()

Feature requests

If you have suggestions of improvement or algorithms that you would like to see implemented in Vlasiator.jl, please open an issue on GitHub. Suggestions as well as feature requests are very welcome.

Code contribution

If you have code that you would like to contribute to Vlasiator.jl, that is awesome! Please open an issue before you create the pull request on GitHub so that we make sure your idea is aligned with our goals for the project.

After your idea is discussed and revised by maintainers, please get the development version of the project by typing the following in the package manager:

] activate @dev

This will create a fresh environment called @dev where you can play with the project components without compromising your normal user environment.

] dev Vlasiator

This will clone all the project components in your ~/.julia folder so that you can modify it and submit a pull request on GitHub later. Don't hesitate to ask questions. We are looking forward to your contributions.

diff --git a/dev/examples/index.html b/dev/examples/index.html index 22dc9b2b..28eb23e9 100644 --- a/dev/examples/index.html +++ b/dev/examples/index.html @@ -167,4 +167,4 @@

This demo shows how to plot vector components

card-cover-image

Vector components

-
+
diff --git a/dev/examples/postprocess/demo_convert2vti/index.html b/dev/examples/postprocess/demo_convert2vti/index.html index ce1a13d2..5a7b1f8e 100644 --- a/dev/examples/postprocess/demo_convert2vti/index.html +++ b/dev/examples/postprocess/demo_convert2vti/index.html @@ -6,4 +6,4 @@ Threads.@threads for file in files @info file, Threads.threadid() write_vtk(file; vti=true) -end

This page was generated using DemoCards.jl.

+end

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_em_extract_slice/index.html b/dev/examples/postprocess/demo_em_extract_slice/index.html index bae45749..492d741b 100644 --- a/dev/examples/postprocess/demo_em_extract_slice/index.html +++ b/dev/examples/postprocess/demo_em_extract_slice/index.html @@ -91,4 +91,4 @@ jldsave(outdir*outfile; E, B, n, v, p) end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_lineextracting_mt/index.html b/dev/examples/postprocess/demo_lineextracting_mt/index.html index 94cf9897..ca61b583 100644 --- a/dev/examples/postprocess/demo_lineextracting_mt/index.html +++ b/dev/examples/postprocess/demo_lineextracting_mt/index.html @@ -43,4 +43,4 @@ println("Line extraction finished!") end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_log/index.html b/dev/examples/postprocess/demo_log/index.html index b28b2201..25449b82 100644 --- a/dev/examples/postprocess/demo_log/index.html +++ b/dev/examples/postprocess/demo_log/index.html @@ -11,4 +11,4 @@ scatter(timestamps, speed, markershape=:circle, #yaxis=:log10, - xlabel="Time", ylabel="Time per simulated second [s]")

This page was generated using DemoCards.jl.

+ xlabel="Time", ylabel="Time per simulated second [s]")

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_magnetopause_2d_mt/index.html b/dev/examples/postprocess/demo_magnetopause_2d_mt/index.html index 718cc1cd..e666c03a 100644 --- a/dev/examples/postprocess/demo_magnetopause_2d_mt/index.html +++ b/dev/examples/postprocess/demo_magnetopause_2d_mt/index.html @@ -63,4 +63,4 @@ @time z,x,v,ey = extract_magnetopause_var(files) -jldsave("magnetopause.jld2"; z,x,v,ey)

This page was generated using DemoCards.jl.

+jldsave("magnetopause.jld2"; z,x,v,ey)

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_pointextracting/index.html b/dev/examples/postprocess/demo_pointextracting/index.html index ed6e7fd1..1c6f4834 100644 --- a/dev/examples/postprocess/demo_pointextracting/index.html +++ b/dev/examples/postprocess/demo_pointextracting/index.html @@ -78,4 +78,4 @@ fig.suptitle("Density Pulse Run, location = [12, 0, 0]", fontsize="xx-large") savefig("virtual_satellite.png", bbox_inches="tight") -=#

This page was generated using DemoCards.jl.

+=#

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_pointsextracting/index.html b/dev/examples/postprocess/demo_pointsextracting/index.html index 892a3e86..a7dceb69 100644 --- a/dev/examples/postprocess/demo_pointsextracting/index.html +++ b/dev/examples/postprocess/demo_pointsextracting/index.html @@ -51,4 +51,4 @@ @time extract_vars(files, locations) -println("Virtual satellite extraction done!")

This page was generated using DemoCards.jl.

+println("Virtual satellite extraction done!")

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_pointsextracting_2d_uniform/index.html b/dev/examples/postprocess/demo_pointsextracting_2d_uniform/index.html index b651707a..73bc8e49 100644 --- a/dev/examples/postprocess/demo_pointsextracting_2d_uniform/index.html +++ b/dev/examples/postprocess/demo_pointsextracting_2d_uniform/index.html @@ -71,4 +71,4 @@ @time extract_vars(files, dx) -println("Virtual satellite extraction done!")

This page was generated using DemoCards.jl.

+println("Virtual satellite extraction done!")

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_wave_satellite_mt/index.html b/dev/examples/postprocess/demo_wave_satellite_mt/index.html index 2262a780..d5955a5b 100644 --- a/dev/examples/postprocess/demo_wave_satellite_mt/index.html +++ b/dev/examples/postprocess/demo_wave_satellite_mt/index.html @@ -214,4 +214,4 @@ savefig("virtual_satellite_wave.png"; dpi=300) end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_wave_search_mt/index.html b/dev/examples/postprocess/demo_wave_search_mt/index.html index b424827a..ec09eae0 100644 --- a/dev/examples/postprocess/demo_wave_search_mt/index.html +++ b/dev/examples/postprocess/demo_wave_search_mt/index.html @@ -159,4 +159,4 @@ println("Virtual satellite extraction done!") end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_wave_tracing_mt/index.html b/dev/examples/postprocess/demo_wave_tracing_mt/index.html index 801df61e..bc1f3847 100644 --- a/dev/examples/postprocess/demo_wave_tracing_mt/index.html +++ b/dev/examples/postprocess/demo_wave_tracing_mt/index.html @@ -401,4 +401,4 @@ outdir) end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_x_o_points/index.html b/dev/examples/postprocess/demo_x_o_points/index.html index 60d2dba7..2064476a 100644 --- a/dev/examples/postprocess/demo_x_o_points/index.html +++ b/dev/examples/postprocess/demo_x_o_points/index.html @@ -48,4 +48,4 @@ ax.legend([s1, s2], ["X-point", "O-point"]) end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/postprocess/demo_x_points_extracting/index.html b/dev/examples/postprocess/demo_x_points_extracting/index.html index b4518c88..cdb4a65e 100644 --- a/dev/examples/postprocess/demo_x_points_extracting/index.html +++ b/dev/examples/postprocess/demo_x_points_extracting/index.html @@ -51,4 +51,4 @@ jldsave("x_point_locations.jld2"; x_points_x, x_points_z, ey) end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_1d2d_mp_pyplot/index.html b/dev/examples/visualization/demo_1d2d_mp_pyplot/index.html index 55091bb9..196e870c 100644 --- a/dev/examples/visualization/demo_1d2d_mp_pyplot/index.html +++ b/dev/examples/visualization/demo_1d2d_mp_pyplot/index.html @@ -265,4 +265,4 @@ n -= 1 end println("Finished in $(round(t, digits=2))s.") -end

This page was generated using DemoCards.jl.

+end

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_1d2d_pyplot/index.html b/dev/examples/visualization/demo_1d2d_pyplot/index.html index a3715715..10d7859e 100644 --- a/dev/examples/visualization/demo_1d2d_pyplot/index.html +++ b/dev/examples/visualization/demo_1d2d_pyplot/index.html @@ -237,4 +237,4 @@ end close(plotargs[1]) -println("Finished!")

This page was generated using DemoCards.jl.

+println("Finished!")

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_1d_animation_pyplot/index.html b/dev/examples/visualization/demo_1d_animation_pyplot/index.html index d22ea2c5..3c53b9a7 100644 --- a/dev/examples/visualization/demo_1d_animation_pyplot/index.html +++ b/dev/examples/visualization/demo_1d_animation_pyplot/index.html @@ -31,4 +31,4 @@ frames=length(files), blit=true, repeat_delay=1000, interval=200) # Make sure ffmpeg is available! -anim.save("line.mp4", writer="ffmpeg", fps=30)

This page was generated using DemoCards.jl.

+anim.save("line.mp4", writer="ffmpeg", fps=30)

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_2d_animation_pyplot/index.html b/dev/examples/visualization/demo_2d_animation_pyplot/index.html index 7ca0f0d1..dc5d1fe8 100644 --- a/dev/examples/visualization/demo_2d_animation_pyplot/index.html +++ b/dev/examples/visualization/demo_2d_animation_pyplot/index.html @@ -49,4 +49,4 @@ frames=length(files), blit=true, repeat_delay=1000, interval=50) # Make sure ffmpeg is available! -anim.save("contour.mp4", writer="ffmpeg", fps=30)

This page was generated using DemoCards.jl.

+anim.save("contour.mp4", writer="ffmpeg", fps=30)

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_2d_mp_pyplot/index.html b/dev/examples/visualization/demo_2d_mp_pyplot/index.html index 80c71538..21045d9b 100644 --- a/dev/examples/visualization/demo_2d_mp_pyplot/index.html +++ b/dev/examples/visualization/demo_2d_mp_pyplot/index.html @@ -175,4 +175,4 @@ n -= 1 end println("Finished in $(round(t, digits=2))s.") -end

This page was generated using DemoCards.jl.

+end

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_2dcontourseries_pyplot/index.html b/dev/examples/visualization/demo_2dcontourseries_pyplot/index.html index 42a21c02..44147e29 100644 --- a/dev/examples/visualization/demo_2dcontourseries_pyplot/index.html +++ b/dev/examples/visualization/demo_2dcontourseries_pyplot/index.html @@ -49,4 +49,4 @@ savefig(outdir*lpad(i, 4, '0')*".png", bbox_inches="tight", dpi=100) end -close()

This page was generated using DemoCards.jl.

+close()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_2dplot_plots/index.html b/dev/examples/visualization/demo_2dplot_plots/index.html index 0b77e50d..598cb24e 100644 --- a/dev/examples/visualization/demo_2dplot_plots/index.html +++ b/dev/examples/visualization/demo_2dplot_plots/index.html @@ -22,4 +22,4 @@ ylims!(boxcoords[3], boxcoords[4]) =# -streamplot(meta, nameV, comp="xy", color="w", density=2.0)

This page was generated using DemoCards.jl.

+streamplot(meta, nameV, comp="xy", color="w", density=2.0)

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_2dplot_pyplot/index.html b/dev/examples/visualization/demo_2dplot_pyplot/index.html index f9cede5f..0561c0c3 100644 --- a/dev/examples/visualization/demo_2dplot_pyplot/index.html +++ b/dev/examples/visualization/demo_2dplot_pyplot/index.html @@ -40,4 +40,4 @@ file = "bulk.0000501.vlsv" nameρ = "rho" -main(file, nameρ)

This page was generated using DemoCards.jl.

+main(file, nameρ)

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_3dcuts_pyplot/index.html b/dev/examples/visualization/demo_3dcuts_pyplot/index.html index 6a8587dd..125f20f3 100644 --- a/dev/examples/visualization/demo_3dcuts_pyplot/index.html +++ b/dev/examples/visualization/demo_3dcuts_pyplot/index.html @@ -33,4 +33,4 @@ cb_title_str *= ",["*datainfo.unitLaTeX*"]" cb_title = cb.ax.set_title(cb_title_str, fontsize=14, fontweight="bold") -plt.savefig("test.png", bbox_inches="tight")

This page was generated using DemoCards.jl.

+plt.savefig("test.png", bbox_inches="tight")

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_B_fieldline_mp_pyplot/index.html b/dev/examples/visualization/demo_B_fieldline_mp_pyplot/index.html index 07c9739d..962329e7 100644 --- a/dev/examples/visualization/demo_B_fieldline_mp_pyplot/index.html +++ b/dev/examples/visualization/demo_B_fieldline_mp_pyplot/index.html @@ -162,4 +162,4 @@ n -= 1 end println("Finished in $(round(t, digits=2))s.") -end

This page was generated using DemoCards.jl.

+end

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_B_fieldline_pyplot/index.html b/dev/examples/visualization/demo_B_fieldline_pyplot/index.html index 45eefd43..9d164333 100644 --- a/dev/examples/visualization/demo_B_fieldline_pyplot/index.html +++ b/dev/examples/visualization/demo_B_fieldline_pyplot/index.html @@ -64,4 +64,4 @@ end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_bowshock_2d_mt/index.html b/dev/examples/visualization/demo_bowshock_2d_mt/index.html index 70b22ca8..32409195 100644 --- a/dev/examples/visualization/demo_bowshock_2d_mt/index.html +++ b/dev/examples/visualization/demo_bowshock_2d_mt/index.html @@ -48,4 +48,4 @@ @time x_crossing, y_crossing = extract_bowshock_position(files) -jldsave("example.jld2"; x_crossing, y_crossing)

This page was generated using DemoCards.jl.

+jldsave("example.jld2"; x_crossing, y_crossing)

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_bowshock_2dlocation/index.html b/dev/examples/visualization/demo_bowshock_2dlocation/index.html index d4c25bd9..4fb9be54 100644 --- a/dev/examples/visualization/demo_bowshock_2dlocation/index.html +++ b/dev/examples/visualization/demo_bowshock_2dlocation/index.html @@ -28,4 +28,4 @@ imshow(T', extent=(x[1], x[end], y[1], y[end]), origin="lower", cmap=plt.get_cmap("ocean")) plot(x_crossing, y_crossing, "r") axis("scaled") -savefig("bs_temp_test.png")

This page was generated using DemoCards.jl.

+savefig("bs_temp_test.png")

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_diff_extracting/index.html b/dev/examples/visualization/demo_diff_extracting/index.html index a569e503..6ad826bc 100644 --- a/dev/examples/visualization/demo_diff_extracting/index.html +++ b/dev/examples/visualization/demo_diff_extracting/index.html @@ -54,4 +54,4 @@ #savefig("test_diff.png") end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_energy_spectrum/index.html b/dev/examples/visualization/demo_energy_spectrum/index.html index 2cdcab89..3025109c 100644 --- a/dev/examples/visualization/demo_energy_spectrum/index.html +++ b/dev/examples/visualization/demo_energy_spectrum/index.html @@ -49,4 +49,4 @@ legend() end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_field_tracing_2d/index.html b/dev/examples/visualization/demo_field_tracing_2d/index.html index 051843be..3da524be 100644 --- a/dev/examples/visualization/demo_field_tracing_2d/index.html +++ b/dev/examples/visualization/demo_field_tracing_2d/index.html @@ -31,4 +31,4 @@ streamplot(meta, nameV, comp="xy", color="w", density=1.0) end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_field_tracing_3d/index.html b/dev/examples/visualization/demo_field_tracing_3d/index.html index e5f346bd..72ebcb28 100644 --- a/dev/examples/visualization/demo_field_tracing_3d/index.html +++ b/dev/examples/visualization/demo_field_tracing_3d/index.html @@ -68,4 +68,4 @@ ax.plot3D(x./RE, y./RE, z./RE) end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_lineextracting_mp_pyplot/index.html b/dev/examples/visualization/demo_lineextracting_mp_pyplot/index.html index e96b28f4..fba78cec 100644 --- a/dev/examples/visualization/demo_lineextracting_mp_pyplot/index.html +++ b/dev/examples/visualization/demo_lineextracting_mp_pyplot/index.html @@ -140,4 +140,4 @@ n -= 1 end println("Finished in $(round(t, digits=2))s.") -end

This page was generated using DemoCards.jl.

+end

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_lineextracting_pyplot/index.html b/dev/examples/visualization/demo_lineextracting_pyplot/index.html index 7c97a13e..4e2ab7b7 100644 --- a/dev/examples/visualization/demo_lineextracting_pyplot/index.html +++ b/dev/examples/visualization/demo_lineextracting_pyplot/index.html @@ -102,4 +102,4 @@ println("Finished!") end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_lineextracting_pyplot_basic1/index.html b/dev/examples/visualization/demo_lineextracting_pyplot_basic1/index.html index 6a43bd4a..be7f5f1b 100644 --- a/dev/examples/visualization/demo_lineextracting_pyplot_basic1/index.html +++ b/dev/examples/visualization/demo_lineextracting_pyplot_basic1/index.html @@ -71,4 +71,4 @@ close(fig) end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_lineextracting_pyplot_basic2/index.html b/dev/examples/visualization/demo_lineextracting_pyplot_basic2/index.html index a628350d..a202a7d1 100644 --- a/dev/examples/visualization/demo_lineextracting_pyplot_basic2/index.html +++ b/dev/examples/visualization/demo_lineextracting_pyplot_basic2/index.html @@ -49,4 +49,4 @@ println("plot finished!") end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_mesh_pyplot/index.html b/dev/examples/visualization/demo_mesh_pyplot/index.html index 1dbebd5d..8b80beb5 100644 --- a/dev/examples/visualization/demo_mesh_pyplot/index.html +++ b/dev/examples/visualization/demo_mesh_pyplot/index.html @@ -13,4 +13,4 @@ fig = plt.figure() pcolormesh(meta, "proton/vg_rho"; axisunit=SI) -plotmesh(meta, projection="y"; color="w")

This page was generated using DemoCards.jl.

+plotmesh(meta, projection="y"; color="w")

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_mp_progressbar/index.html b/dev/examples/visualization/demo_mp_progressbar/index.html index 183feba1..fd670840 100644 --- a/dev/examples/visualization/demo_mp_progressbar/index.html +++ b/dev/examples/visualization/demo_mp_progressbar/index.html @@ -235,4 +235,4 @@ end put!(channel, false) # this tells the printing task to finish end -end

This page was generated using DemoCards.jl.

+end

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_poynting_mt_pyplot/index.html b/dev/examples/visualization/demo_poynting_mt_pyplot/index.html index 03707ddf..00568013 100644 --- a/dev/examples/visualization/demo_poynting_mt_pyplot/index.html +++ b/dev/examples/visualization/demo_poynting_mt_pyplot/index.html @@ -269,4 +269,4 @@ x1 = range(extent[1], extent[2], length=length(range1)) x2 = range(extent[3], extent[4], length=length(range2)) -plot_poynting(de_filtered, db_filtered, b̄, x1, x2, frequency_range)

This page was generated using DemoCards.jl.

+plot_poynting(de_filtered, db_filtered, b̄, x1, x2, frequency_range)

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_tensor_pyplot/index.html b/dev/examples/visualization/demo_tensor_pyplot/index.html index 74d23418..51da5894 100644 --- a/dev/examples/visualization/demo_tensor_pyplot/index.html +++ b/dev/examples/visualization/demo_tensor_pyplot/index.html @@ -69,4 +69,4 @@ savefig("ptensor.png", bbox_inches="tight") end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_vdf_pyplot/index.html b/dev/examples/visualization/demo_vdf_pyplot/index.html index ff541f70..821f2425 100644 --- a/dev/examples/visualization/demo_vdf_pyplot/index.html +++ b/dev/examples/visualization/demo_vdf_pyplot/index.html @@ -28,4 +28,4 @@ ax.scatter(xcell, ycell, marker="+", color="w") end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_vdfs_pyplot/index.html b/dev/examples/visualization/demo_vdfs_pyplot/index.html index f3e6a0b5..62594fb7 100644 --- a/dev/examples/visualization/demo_vdfs_pyplot/index.html +++ b/dev/examples/visualization/demo_vdfs_pyplot/index.html @@ -51,4 +51,4 @@ end end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/examples/visualization/demo_vector_pyplot/index.html b/dev/examples/visualization/demo_vector_pyplot/index.html index f302e979..8c946203 100644 --- a/dev/examples/visualization/demo_vector_pyplot/index.html +++ b/dev/examples/visualization/demo_vector_pyplot/index.html @@ -65,4 +65,4 @@ savefig("Bvector.png", bbox_inches="tight") end -main()

This page was generated using DemoCards.jl.

+main()

This page was generated using DemoCards.jl.

diff --git a/dev/gallery/index.html b/dev/gallery/index.html index 6b807998..81e75ef1 100644 --- a/dev/gallery/index.html +++ b/dev/gallery/index.html @@ -1,2 +1,2 @@ -Gallery · Vlasiator.jl

Gallery

PyPlot

  • Proton density in a laminar flow with points denoting cell centers. demo

  • Proton density of Earth's magnetosphere in the meridional cut from 2D simulation, with fieldlines through fixed seeding points. demo

  • Proton density of Earth's magnetosphere in the meridional plane from 3D simulation.

  • Proton density of Earth's magnetosphere in the equatorial plane from 2D simulation, zoomed in to the magnetosheath and foreshock region, with streamlines and density contour at 10 amu/cc. demo

  • Proton density of Earth's magnetosphere in the normal cut planes from 3D simulation. demo

  • Proton phase space distribution projected onto the X-Z plane. demo

Makie

Demos can be found in the Usage section of VlasiatorMakie.

  • Various colored contours from 2D equatorial run

  • Interactive proton density slice from 3D AMR run

  • Three orthogonal slices of proton density from 3D AMR run

  • Isosurface of Bz = 0 from 3D AMR run

  • Proton phase space distribution projected onto the X-Z plane

  • Interactive proton phase space distribution in the three orthogonal planes

  • Proton phase space distribution

ParaView

VLSV files can be converted to the structured VTK format, and then visualized in ParaView.

  • 2D slice contour of density in the meriodional plane with streamlines

  • 2D slices of density viewing from upstream

+Gallery · Vlasiator.jl

Gallery

PyPlot

  • Proton density in a laminar flow with points denoting cell centers. demo

  • Proton density of Earth's magnetosphere in the meridional cut from 2D simulation, with fieldlines through fixed seeding points. demo

  • Proton density of Earth's magnetosphere in the meridional plane from 3D simulation.

  • Proton density of Earth's magnetosphere in the equatorial plane from 2D simulation, zoomed in to the magnetosheath and foreshock region, with streamlines and density contour at 10 amu/cc. demo

  • Proton density of Earth's magnetosphere in the normal cut planes from 3D simulation. demo

  • Proton phase space distribution projected onto the X-Z plane. demo

Makie

Demos can be found in the Usage section of VlasiatorMakie.

  • Various colored contours from 2D equatorial run

  • Interactive proton density slice from 3D AMR run

  • Three orthogonal slices of proton density from 3D AMR run

  • Isosurface of Bz = 0 from 3D AMR run

  • Proton phase space distribution projected onto the X-Z plane

  • Interactive proton phase space distribution in the three orthogonal planes

  • Proton phase space distribution

ParaView

VLSV files can be converted to the structured VTK format, and then visualized in ParaView.

  • 2D slice contour of density in the meriodional plane with streamlines

  • 2D slices of density viewing from upstream

diff --git a/dev/index.html b/dev/index.html index 25d1da2d..244db54f 100644 --- a/dev/index.html +++ b/dev/index.html @@ -4,4 +4,4 @@ \mathbf{u}_\alpha &= \frac{1}{n_\alpha}\int \mathbf{v}f_\alpha(\mathbf{r},\mathbf{v},t)\mathrm{d}\mathbf{v} \end{aligned}\]

The magnetic field is updated using Faraday's law:

\[\nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t}\]

and the electric field is given by the generalized Ohm's law:

\[\mathbf{E} = -\mathbf{u}_\alpha \times\mathbf{B} + \frac{1}{n_\alpha q_\alpha}\mathbf{j}\times\mathbf{B} - \frac{1}{n_\alpha q_\alpha}\nabla\cdot\overleftrightarrow{P}_e + \eta \mathbf{j}\]

The four terms on the right-handed side are the convection term, the Hall term, the electron pressure gradient term, and the resistive term, respectively. The total current density $\mathbf{j}$ is obtained from Ampère's law where the displacement current has been neglected:

\[\nabla\times\mathbf{B} = \mu_0 \mathbf{j}\]

Finally, by determining the electron pressure tensor by using an appropriate equation of state, the evolution of the system can be followed in time. For example, let $\overleftrightarrow{P}_e = p_e \overleftrightarrow{I}$ where $p_e$ is the isotropic scalar electron pressure. In an isothermal process,

\[p_e = n_e k_B T_e\]

where $n_e \approx n_i$ and $T_e$ is a constant. In an adiabatic process with index $\gamma$,

\[p_e / n_e^\gamma = \text{const.}\]

The different processes can be generalized into the polytropic process:

\[p_e / n_e^n = \text{const.}\]

When the ideal gas law applies, the polytropic index $n=1$ for an isothermal process, and $n=\gamma$ for an adiabatic process.

For more details, please refer to Vlasov methods in space physics and astrophysics.

Getting started

To install,

julia> ]
 pkg> add Vlasiator

You can then use the package via

julia> using Vlasiator

Visualization

If you aim at using Matplotlib, besides adding PyPlot and the Vlasiator specific wrapper VlasiatorPyPlot, you should also link to a preinstalled Python version by setting the environment variable and building the PyCall package

ENV["PYTHON"]="your python executable"
-Pkg.build("PyCall")

If ENV["PYTHON"] = "" before building, a private Python distribution will be installed via Miniconda. Details are described in automated matplotlib installation.

You can add Makie.jl and VlasiatorMakie.jl through the pkg manger. The sub-package VlasiatorMakie provides user recipes for Makie.

Add Plots.jl through the pkg manager. Built-in user recipes for Plots are provided.

Author

This module is written by Hongyang Zhou. For citing Vlasiator.jl, please refer to DOI.

+Pkg.build("PyCall")

If ENV["PYTHON"] = "" before building, a private Python distribution will be installed via Miniconda. Details are described in automated matplotlib installation.

You can add Makie.jl and VlasiatorMakie.jl through the pkg manger. The sub-package VlasiatorMakie provides user recipes for Makie.

Add Plots.jl through the pkg manager. Built-in user recipes for Plots are provided.

Author

This module is written by Hongyang Zhou. For citing Vlasiator.jl, please refer to DOI.

diff --git a/dev/internal/index.html b/dev/internal/index.html index b152fb29..bb94880c 100644 --- a/dev/internal/index.html +++ b/dev/internal/index.html @@ -1,29 +1,29 @@ -API Reference · Vlasiator.jl

Internal

Public APIs

Vlasiator.check_plasma_characteristicsMethod
check_plasma_characteristics(n, v, T, B)

Display characteristic plasma parameters given density n, bulk velocity v, temperature T, and magnetic field strength B in SI units.

source
Vlasiator.compute_flux_functionMethod
compute_flux_function(b::AbstractArray{T,N}, Δ::Vector{T}, nG::Int=2) where {T,N}

Calculate the 2D magnetic flux function ψ from the magnetic field b and discrete steps Δ. nG is the number of ghost cells along each dimension in the vector field. ψ is defined as $\psi = \int B_x dz = - \int B_z dx$ from $\mathbf{B} = \hat{y}\times\nabla\psi$ in the X-Z plane and Y is the out-of-plane direction. This is strictly true if B is divergence-free and the guide field By is constant. However, numerically there will be errors. The current implementation calculates ψ by integrating along -z boundary first, and then going along z. Reference: Flux function

source
Vlasiator.extractsatMethod
extractsat(files::AbstractVector{String}, var::String, cid::Int)

Multi-threaded extraction of var at a fixed cell ID cid from files. This assumes that files come from the same grid structure.

source
Vlasiator.find_reconnection_pointsMethod
find_reconnection_points(ψ::Array{T,2}; retol::Float64=1e-4,
-   method::Int=1) -> indices_x, indices_o

Find X-point and O-point indices in 2D magnetic field topology from flux function ψ. The current implementation does not work for the 3 layers near the boundary.

Keywords

  • retol=1e-1: determines the relative tolerance of the ratio w.r.t. |∇ψ|² to accept a gradient as 0.
  • method=1: method 1 compute the cell-centered 1st and 2nd order derivatives and check the Hessian matrix; method 2 check the flux function at each point against its 8 neighbors, which is more deterministic.
source
Vlasiator.getKLdivergenceMethod
getKLdivergence(meta, VDF; species="proton")
-getKLdivergence(meta, vcellids, vcellf; species="proton")

Obtain the KL-divergence ∫ f*log(f/g)dv, where f is the VDF from Vlasiator and g is the analytical Maxwellian distribution that generates the same density as f. The value ranges from [0, +∞], with 0 meaning perfect Maxwellian. Usually the values are quite small. Alternatively, one can pass original vcellids and vcellf directly.

source
Vlasiator.getcellMethod
getcell(meta::MetaVLSV, location:::AbstractVector{<:AbstractFloat}) -> Int

Return cell ID containing the given spatial location in meter, excluding domain boundaries. Only accept 3D location.

source
Vlasiator.getcellinlineMethod
getcellinline(meta, point1::Vector, point2::Vector) -> cellids, distances, coords

Returns cell IDs, distances and coordinates for every cell in a line between two given points point1 and point2. TODO: preallocation?

source
Vlasiator.getcellwithvdfFunction
getcellwithvdf(meta, species::String="proton") -> cellids

Get all the cell IDs with VDF saved associated with meta.

source
Vlasiator.getdensityMethod
getdensity(meta, VDF; species="proton")
+API Reference · Vlasiator.jl

Internal

Public APIs

Vlasiator.check_plasma_characteristicsMethod
check_plasma_characteristics(n, v, T, B)

Display characteristic plasma parameters given density n, bulk velocity v, temperature T, and magnetic field strength B in SI units.

source
Vlasiator.compute_flux_functionMethod
compute_flux_function(b::AbstractArray{T,N}, Δ::Vector{T}, nG::Int=2) where {T,N}

Calculate the 2D magnetic flux function ψ from the magnetic field b and discrete steps Δ. nG is the number of ghost cells along each dimension in the vector field. ψ is defined as $\psi = \int B_x dz = - \int B_z dx$ from $\mathbf{B} = \hat{y}\times\nabla\psi$ in the X-Z plane and Y is the out-of-plane direction. This is strictly true if B is divergence-free and the guide field By is constant. However, numerically there will be errors. The current implementation calculates ψ by integrating along -z boundary first, and then going along z. Reference: Flux function

source
Vlasiator.extractsatMethod
extractsat(files::AbstractVector{String}, var::String, cid::Int)

Multi-threaded extraction of var at a fixed cell ID cid from files. This assumes that files come from the same grid structure.

source
Vlasiator.find_reconnection_pointsMethod
find_reconnection_points(ψ::Array{T,2}; retol::Float64=1e-4,
+   method::Int=1) -> indices_x, indices_o

Find X-point and O-point indices in 2D magnetic field topology from flux function ψ. The current implementation does not work for the 3 layers near the boundary.

Keywords

  • retol=1e-1: determines the relative tolerance of the ratio w.r.t. |∇ψ|² to accept a gradient as 0.
  • method=1: method 1 compute the cell-centered 1st and 2nd order derivatives and check the Hessian matrix; method 2 check the flux function at each point against its 8 neighbors, which is more deterministic.
source
Vlasiator.getKLdivergenceMethod
getKLdivergence(meta, VDF; species="proton")
+getKLdivergence(meta, vcellids, vcellf; species="proton")

Obtain the KL-divergence ∫ f*log(f/g)dv, where f is the VDF from Vlasiator and g is the analytical Maxwellian distribution that generates the same density as f. The value ranges from [0, +∞], with 0 meaning perfect Maxwellian. Usually the values are quite small. Alternatively, one can pass original vcellids and vcellf directly.

source
Vlasiator.getcellMethod
getcell(meta::MetaVLSV, location:::AbstractVector{<:AbstractFloat}) -> Int

Return cell ID containing the given spatial location in meter, excluding domain boundaries. Only accept 3D location.

source
Vlasiator.getcellinlineMethod
getcellinline(meta, point1::Vector, point2::Vector) -> cellids, distances, coords

Returns cell IDs, distances and coordinates for every cell in a line between two given points point1 and point2. TODO: preallocation?

source
Vlasiator.getcellwithvdfFunction
getcellwithvdf(meta, species::String="proton") -> cellids

Get all the cell IDs with VDF saved associated with meta.

source
Vlasiator.getdensityMethod
getdensity(meta, VDF; species="proton")
 getdensity(meta, vcellf; species="proton")
-getdensity(vmesh::VMeshInfo, vcellf)

Get density from VDF of species associated with meta, n = ∫ f(r,v) dV. Alternatively, one can directly pass vcellids as original indices of nonzero VDFs and vcellf as their corresponding values.

source
Vlasiator.getheatfluxvectorMethod
getheatfluxvector(meta, VDF; species="proton")
+getdensity(vmesh::VMeshInfo, vcellf)

Get density from VDF of species associated with meta, n = ∫ f(r,v) dV. Alternatively, one can directly pass vcellids as original indices of nonzero VDFs and vcellf as their corresponding values.

source
Vlasiator.getheatfluxvectorMethod
getheatfluxvector(meta, VDF; species="proton")
 getheatfluxvector(meta, vcellids, vcellf; species="proton")
-getheatfluxvector(vmesh::VMeshInfo, vcellids, vcellf)

Get heat flux vector (3 components) of species from VDF associated with meta, qᵢ = m/2 * ∫ (v - u)²(v - u)ᵢ * f(r,v) dV. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.

source
Vlasiator.getlevelMethod
getlevel(meta::MetaVLSV, cid::Int) -> Int

Return the AMR level of a given cell ID cid.

Warning

This function does not check if the VLSV file of meta actually contains cid; it may be shadowed by refined children.

source
Vlasiator.getmaxwellianityMethod
getmaxwellianity(meta, VDF; species="proton")
-getmaxwellianity(meta, vcellids, vcellf; species="proton")

Obtain the Maxwellian similarity factor -log(1/(2n) * ∫ |f - g| dv), where f is the VDF from Vlasiator and g is the analytical Maxwellian distribution that generates the same density as f. The value ranges from [0, +∞], with 0 meaning not Maxwellian-distributed at all, and +∞ a perfect Maxwellian distribution. Alternatively, one can pass original vcellids and vcellf directly.

source
Vlasiator.getnearestcellwithvdfFunction
getnearestcellwithvdf(meta, id::Int, species::String="proton") -> Int

Find the nearest spatial cell with VDF saved for species of a given cell id associated with meta.

source
Vlasiator.getpressureMethod
getpressure(meta, VDF; species="proton")
+getheatfluxvector(vmesh::VMeshInfo, vcellids, vcellf)

Get heat flux vector (3 components) of species from VDF associated with meta, qᵢ = m/2 * ∫ (v - u)²(v - u)ᵢ * f(r,v) dV. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.

source
Vlasiator.getlevelMethod
getlevel(meta::MetaVLSV, cid::Int) -> Int

Return the AMR level of a given cell ID cid.

Warning

This function does not check if the VLSV file of meta actually contains cid; it may be shadowed by refined children.

source
Vlasiator.getmaxwellianityMethod
getmaxwellianity(meta, VDF; species="proton")
+getmaxwellianity(meta, vcellids, vcellf; species="proton")

Obtain the Maxwellian similarity factor -log(1/(2n) * ∫ |f - g| dv), where f is the VDF from Vlasiator and g is the analytical Maxwellian distribution that generates the same density as f. The value ranges from [0, +∞], with 0 meaning not Maxwellian-distributed at all, and +∞ a perfect Maxwellian distribution. Alternatively, one can pass original vcellids and vcellf directly.

source
Vlasiator.getnearestcellwithvdfFunction
getnearestcellwithvdf(meta, id::Int, species::String="proton") -> Int

Find the nearest spatial cell with VDF saved for species of a given cell id associated with meta.

source
Vlasiator.getpressureMethod
getpressure(meta, VDF; species="proton")
 getpressure(meta, vcellids, vcellf; species="proton")
-getpressure(vmesh::VMeshInfo, vcellids, vcellf)

Get pressure tensor (6 components: Pxx, Pyy, Pzz, Pyz, Pzx, Pxy) of species from VDF associated with meta, pᵢⱼ = m * ∫ (v - u)ᵢ(v - u)ⱼ * f(r,v) dV. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.

source
Vlasiator.getsiblingsMethod
getsiblings(meta::MetaVLSV, cid::Int) -> Vector{Int}

Return sibling cells of a given cid, including itself.

source
Vlasiator.getslicecellMethod
getslicecell(meta, sliceoffset, dir, minCoord, maxCoord) -> idlist, indexlist

Find the cell IDs idlist which are needed to plot a 2d cut through of a 3d mesh, in a direction dir at sliceoffset, and the indexlist, which is a mapping from original order to the cut plane and can be used to select data onto the plane.

source
Vlasiator.getvcellcoordinatesMethod
getvcellcoordinates(meta::MetaVLSV, vcellids::Vector; species="proton")

Return velocity cells' coordinates of species and vcellids.

source
Vlasiator.getvelocityMethod
getvelocity(meta, VDF; species="proton")
+getpressure(vmesh::VMeshInfo, vcellids, vcellf)

Get pressure tensor (6 components: Pxx, Pyy, Pzz, Pyz, Pzx, Pxy) of species from VDF associated with meta, pᵢⱼ = m * ∫ (v - u)ᵢ(v - u)ⱼ * f(r,v) dV. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.

source
Vlasiator.getsiblingsMethod
getsiblings(meta::MetaVLSV, cid::Int) -> Vector{Int}

Return sibling cells of a given cid, including itself.

source
Vlasiator.getslicecellMethod
getslicecell(meta, sliceoffset, dir, minCoord, maxCoord) -> idlist, indexlist

Find the cell IDs idlist which are needed to plot a 2d cut through of a 3d mesh, in a direction dir at sliceoffset, and the indexlist, which is a mapping from original order to the cut plane and can be used to select data onto the plane.

source
Vlasiator.getvcellcoordinatesMethod
getvcellcoordinates(meta::MetaVLSV, vcellids::Vector; species="proton")

Return velocity cells' coordinates of species and vcellids.

source
Vlasiator.getvelocityMethod
getvelocity(meta, VDF; species="proton")
 getvelocity(meta, vcellids, vcellf; species="proton")
-getvelocity(vmesh::VMeshInfo, vcellids, vcellf)

Get bulk velocity from VDF of species, u = ∫ v * f(r,v) dV / n. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.

source
Vlasiator.hasparameterMethod
hasparameter(meta::MetaVLSV, param::String) -> Bool

Check if the VLSV file contains a certain parameter param.

source
Vlasiator.hasvariableMethod
hasvariable(meta::MetaVLSV, var::String) -> Bool

Check if the VLSV file associated with meta contains a variable var.

source
Vlasiator.issameFunction
issame(file1, file2, tol=1e-4; strict=true, verbose=false) -> Bool

Check if two VLSV files file1 and file2 are approximately identical, under relative tolerance tol. If strict=true, the file size difference should be less than 1%.

source
Vlasiator.loadMethod
load(file::AbstractString)) -> MetaVLSV

Generate a MetaVLSV object from file of VLSV format.

source
Vlasiator.readlogMethod
readlog(file::AbstractString)

Read the run log file, check the iteration status and return the timestamps (exluding the last) as well as the model running speed in physical seconds per simulated seconds.

source
Vlasiator.readparameterMethod
readparameter(meta::MetaVLSV, param::String)

Return the parameter value from the VLSV file associated with meta.

source
Vlasiator.readvariableFunction
readvariable(meta::MetaVLSV, var::String, sorted::Bool=true, usemmap::Bool=false) -> Array

Return variable value of var from the VLSV file associated with meta. By default for DCCRG variables are sorted by cell ID. usemmap decides whether to use memory-mapped IO, which is especially useful for large arrays.

source
Vlasiator.readvariableMethod
readvariable(meta::MetaVLSV, var::String, cid::Int) -> Array

Read variable var in cell cid associated with meta.

source
Vlasiator.readvariableMethod
readvariable(meta::MetaVLSV, var::String, ids::Vector{Int}) -> Array

Read variable var in a collection of cells ids associated with meta. if ids is empty, return the whole sorted array of var.

source
Vlasiator.readvcellsMethod
readvcells(meta::MetaVLSV, cid::Int; species="proton") -> vcellids, vcellf

Read velocity cells of species from a spatial cell of ID cid associated with meta, and return a map of velocity cell ids vcellids and corresponding value vcellf.

source
Vlasiator.refinesliceMethod
refineslice(meta, idlist::Vector{Int}, data::AbstractVector, normal::Symbol) -> Vector
+getvelocity(vmesh::VMeshInfo, vcellids, vcellf)

Get bulk velocity from VDF of species, u = ∫ v * f(r,v) dV / n. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.

source
Vlasiator.hasparameterMethod
hasparameter(meta::MetaVLSV, param::String) -> Bool

Check if the VLSV file contains a certain parameter param.

source
Vlasiator.hasvariableMethod
hasvariable(meta::MetaVLSV, var::String) -> Bool

Check if the VLSV file associated with meta contains a variable var.

source
Vlasiator.issameFunction
issame(file1, file2, tol=1e-4; strict=true, verbose=false) -> Bool

Check if two VLSV files file1 and file2 are approximately identical, under relative tolerance tol. If strict=true, the file size difference should be less than 1%.

source
Vlasiator.loadMethod
load(file::AbstractString)) -> MetaVLSV

Generate a MetaVLSV object from file of VLSV format.

source
Vlasiator.readlogMethod
readlog(file::AbstractString)

Read the run log file, check the iteration status and return the timestamps (exluding the last) as well as the model running speed in physical seconds per simulated seconds.

source
Vlasiator.readparameterMethod
readparameter(meta::MetaVLSV, param::String)

Return the parameter value from the VLSV file associated with meta.

source
Vlasiator.readvariableFunction
readvariable(meta::MetaVLSV, var::String, sorted::Bool=true, usemmap::Bool=false) -> Array

Return variable value of var from the VLSV file associated with meta. By default for DCCRG variables are sorted by cell ID. usemmap decides whether to use memory-mapped IO, which is especially useful for large arrays.

source
Vlasiator.readvariableMethod
readvariable(meta::MetaVLSV, var::String, cid::Int) -> Array

Read variable var in cell cid associated with meta.

source
Vlasiator.readvariableMethod
readvariable(meta::MetaVLSV, var::String, ids::Vector{Int}) -> Array

Read variable var in a collection of cells ids associated with meta. if ids is empty, return the whole sorted array of var.

source
Vlasiator.readvcellsMethod
readvcells(meta::MetaVLSV, cid::Int; species="proton") -> vcellids, vcellf

Read velocity cells of species from a spatial cell of ID cid associated with meta, and return a map of velocity cell ids vcellids and corresponding value vcellf.

source
Vlasiator.refinesliceMethod
refineslice(meta, idlist::Vector{Int}, data::AbstractVector, normal::Symbol) -> Vector
 refineslice(meta, idlist::Vector{Int}, data::AbstractMatrix, normal::Symbol) -> Matrix
-refineslice(meta, idlist::Vector{Int}, data::AbstractArray, dir::Int)

Generate data on the finest refinement level given cellids idlist and variable data on the slice perpendicular to normal. If data is 2D, then the first dimension is treated as vector components.

source
Vlasiator.write_vlsvMethod
write_vlsv(filein, fileout, newvars::Vector{Tuple{Vector, String, VarInfo}};
-   force=false)

Generate a new VLSV fileout based on filein, with newvars added. force=true overwrites the existing fileout.

source
Vlasiator.write_vtkMethod
write_vtk(meta::MetaVLSV; kwargs...)
-write_vtk(file::AbstractString; kwargs...)

Convert VLSV file to VTK format.

Keywords

  • vars::Vector{String}=[""]: select which variables to convert.
  • ascii::Bool=false: output stored in ASCII or compressed binary format.
  • maxamronly::Bool=false: generate image files on the highest refinement level only.
  • box::Vector: selected box range in 3D.
  • outdir::String="": output directory.
  • verbose::Bool=false: display logs during conversion.
source

PyPlot Wrapper APIs

Modules = [VlasiatorPyPlot]
-Pages   = ["VlasiatorPyPlot.jl"]

Private APIs

Base.ndimsMethod
ndims(meta::MetaVLSV) -> Int

Return the simulation spatial dimension of VLSV data.

source
Vlasiator.curlMethod
curl(A::AbstractArray{T,N}, dx:Union{Vector{U}, NTuple{3,U}}) where {T,N,U}

Calculate 2nd order cell-centered ∇×A where A is a 4D array of size (3, nx, ny, nz) and dx is a vector of grid intervals in each dimension.

source
Vlasiator.divergenceMethod
divergence(A::AbstractArray{T,N}, dx::Vector{U}=ones(T, 3)) where {T,N,U}

Calculate 2nd order cell-centered ∇⋅A where A is a 4D array of size (3, nx, ny, nz) and dx is a vector of grid intervals in each dimension.

source
Vlasiator.downsample_fgMethod
downsample_fg(meta::MetaVLSV, v_fg::Array)
-downsample_fg(meta::MetaVLSV, var::String)

Downsample a field solver array v_fg to the spatial grid associated with meta.

source
Vlasiator.fillmeshMethod
fillmesh(meta::MetaVLSV, vars::Vector{String};
-   skipghosttype=true, maxamronly=false, verbose=false) -> celldata, vtkGhostType

Fill the DCCRG mesh with quantity of vars on all refinement levels.

Return arguments

  • celldata::Vector{Vector{Array}}: data for each variable on each AMR level.
  • vtkGhostType::Array{UInt8}: cell status (to be completed!).
source
Vlasiator.getRotationMatrixMethod
getRotationMatrix(e1::Matrix, e2::Matrix) -> SMatrix{3,3}

Obtain the rotation matrix from orthgonal base vectors e1 to e2, such that a vector $\mathbf{u}_1$ in e1 can be expressed as $\mathbf{u}_1 = M\cdot \mathbf{u}_2$, where $M$ is the rotation matrix and $\mathbf{u}_2$ is the same vector in e2.

Example

e1 = [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0]
+refineslice(meta, idlist::Vector{Int}, data::AbstractArray, dir::Int)

Generate data on the finest refinement level given cellids idlist and variable data on the slice perpendicular to normal. If data is 2D, then the first dimension is treated as vector components.

source
Vlasiator.write_vlsvMethod
write_vlsv(filein, fileout, newvars::Vector{Tuple{Vector, String, VarInfo}};
+   force=false)

Generate a new VLSV fileout based on filein, with newvars added. force=true overwrites the existing fileout.

source
Vlasiator.write_vtkMethod
write_vtk(meta::MetaVLSV; kwargs...)
+write_vtk(file::AbstractString; kwargs...)

Convert VLSV file to VTK format.

Keywords

  • vars::Vector{String}=[""]: select which variables to convert.
  • ascii::Bool=false: output stored in ASCII or compressed binary format.
  • maxamronly::Bool=false: generate image files on the highest refinement level only.
  • box::Vector: selected box range in 3D.
  • outdir::String="": output directory.
  • verbose::Bool=false: display logs during conversion.
source

PyPlot Wrapper APIs

Modules = [VlasiatorPyPlot]
+Pages   = ["VlasiatorPyPlot.jl"]

Private APIs

Base.ndimsMethod
ndims(meta::MetaVLSV) -> Int

Return the simulation spatial dimension of VLSV data.

source
Vlasiator.curlMethod
curl(A::AbstractArray{T,N}, dx:Union{Vector{U}, NTuple{3,U}}) where {T,N,U}

Calculate 2nd order cell-centered ∇×A where A is a 4D array of size (3, nx, ny, nz) and dx is a vector of grid intervals in each dimension.

source
Vlasiator.divergenceMethod
divergence(A::AbstractArray{T,N}, dx::Vector{U}=ones(T, 3)) where {T,N,U}

Calculate 2nd order cell-centered ∇⋅A where A is a 4D array of size (3, nx, ny, nz) and dx is a vector of grid intervals in each dimension.

source
Vlasiator.downsample_fgMethod
downsample_fg(meta::MetaVLSV, v_fg::Array)
+downsample_fg(meta::MetaVLSV, var::String)

Downsample a field solver array v_fg to the spatial grid associated with meta.

source
Vlasiator.fillmeshMethod
fillmesh(meta::MetaVLSV, vars::Vector{String};
+   skipghosttype=true, maxamronly=false, verbose=false) -> celldata, vtkGhostType

Fill the DCCRG mesh with quantity of vars on all refinement levels.

Return arguments

  • celldata::Vector{Vector{Array}}: data for each variable on each AMR level.
  • vtkGhostType::Array{UInt8}: cell status (to be completed!).
source
Vlasiator.getRotationMatrixMethod
getRotationMatrix(e1::Matrix, e2::Matrix) -> SMatrix{3,3}

Obtain the rotation matrix from orthgonal base vectors e1 to e2, such that a vector $\mathbf{u}_1$ in e1 can be expressed as $\mathbf{u}_1 = M\cdot \mathbf{u}_2$, where $M$ is the rotation matrix and $\mathbf{u}_2$ is the same vector in e2.

Example

e1 = [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0]
 e2 = [0.0 1.0 0.0; 1.0 0.0 0.0; 0.0 0.0 1.0]
-R = getRotationMatrix(e1, e2)
source
Vlasiator.getRotationMatrixMethod
getRotationMatrix(axis::AbstractVector, angle::Real) --> SMatrix{3,3}

Create a rotation matrix for rotating a 3D vector around a unit axis by an angle in radians. Reference: Rotation matrix from axis and angle

Example

using LinearAlgebra
 v = [-0.5, 1.0, 1.0]
 v̂ = normalize(v)
 θ = deg2rad(-74)
-R = getRotationMatrix(v̂, θ)
source
Vlasiator.get_axisMethod
get_axis(axisunit::AxisUnit, plotrange::NTuple{4,<:Real}, sizes::NTuple{2,<:Integer})
-get_axis(pArgs::PlotArgs)

Return x and y ranges for 2D.

source
Vlasiator.get_fg_array_cellMethod
get_fg_array_cell(meta::MetaVLSV, v_fg::Array, cid::Int)

Return a subarray of the field solver grid array, corresponding to the fsgrid covered by the spatial cell ID cid.

source
Vlasiator.get_fg_indices_subvolumeFunction
get_fg_indices_subvolume(meta::MetaVLSV, lower, upper, tol::Float64=1e-3)

Get indices for subarray of fsgrid variables, in a cuboid defined by lower and upper vertices. This is used for mapping a set of fsgrid cells to a given DCCRG cell. Shift the corners (lower, upper) inward by a distance controlled by tol. If direct low-inclusive behaviour is required, tol shall be set to 0.

source
Vlasiator.getdata2dMethod
getdata2d(meta::MetaVLSV, var::String)

Return 2d scalar/vector data. Nonpublic since it won't work with DCCRG AMR.

source
Vlasiator.gradientMethod
gradient(A::AbstractArray{T,N}, dx::Vector{U}) where {T,N,U}

Calculate 2nd order cell-centered ∇A where A is a scalar array and dx is a vector of grid intervals in each dimension.

Warning

The current implementation has issues at the boundary if gradient is taken multiple times.

source
Vlasiator.prep1dMethod
prep1d(meta::MetaVLSV, var::String; i1::Int=0, i2::Int=0, comp::Int=0) -> Array

Obtain a 1D slice from 2D meta of var. i1 is the index for the first dimension, and i2 is the index for the second dimension; only one of them is needed. Use comp to select vector components.

source
Vlasiator.prep2dFunction
prep2d(meta::MetaVLSV, var::String, comp::Union{Symbol, Int}=0) -> Array

Obtain data from meta of var for 2D plotting. Use comp to select vector components.

source
Vlasiator.prep2dsliceMethod
prep2dslice(meta::MetaVLSV, var::String, normal, comp, pArgs::PlotArgs)

Return data of var on a uniform 2D mesh on the finest AMR level. Use normal to select the plane orientation, and comp to select the component of a vector, same as in pcolormesh.

source
Vlasiator.prep_vdfMethod
prep_vdf(meta::MetaVLSV, location::AbstractVector; kwargs...)

Return the cell velocities v1, v2, bin ranges r1, r2, cell VDF values fweight, and strings of labels and titles for VDF plots.

Keywords

  • unit::AxisUnit: location unit in SI, EARTH.
  • unitv::String: velocity unit in ("km/s", "m/s").
  • limits::Vector{Real}: velocity space range given in [xmin, xmax, ymin, ymax].
  • slicetype: symbol for choosing the slice type from :xy, :xz, :yz, :bperp, :bpar1, :bpar2.
  • center: symbol for setting the reference frame from :bulk, :peak.
  • vslicethick: setting the velocity space slice thickness in the normal direction. If set to 0, the whole distribution along the normal direction is projected onto a plane. Currently this is only meaningful when center is set such that a range near the bulk/peak normal velocity is selected.
  • weight::Symbol: choosing distribution weights from phase space density or particle flux between :particle and :flux.
  • flimit: minimum VDF threshold for plotting.
  • verbose: display the selection process.
source
Vlasiator.read_variable_as_fgMethod
read_variable_as_fg(meta::MetaVLSV, var::String)

Interpolate DCCRG variable var to field solver grid size. This is an alternative method to fillmesh, but not optimized for performance.

source
Vlasiator.reconstructMethod
reconstruct(vmesh::VMeshInfo, vcellids::Vector{Int32}, vcellf::Vector{<:AbstractFloat})

Reconstruct the full VDFs in 3D. vcellids are raw indices of nonzero VDFs ordered by blocks, and vcellf are the corresponding values in each cell.

source
Vlasiator.reorderMethod
reorder(vmesh::VMeshInfo, vcellids::Vector{Int32}) -> vcellids_origin

Reorder vblock-organized VDF indexes into x–>y–>z indexes. vcellids are raw indices of nonzero VDFs ordered by blocks.

source
Vlasiator.rotateTensorToVectorZMethod
rotateTensorToVectorZ(tensor::AbstractMatrix, vector::AbstractVector) -> SMatrix{3,3}

Rotate tensor with a rotation matrix that aligns the 3rd direction with vector, which is equivalent to change the basis from (i,j,k) to (i′,j′,k′) where k′ ∥ vector. Reference: Tensor rotation

source
Vlasiator.save_imageFunction
save_image(meta::MetaVLSV, file, vars, data, vtkGhostType, level,
-   ascii=false, append=true, box=[-Inf, Inf, -Inf, Inf, -Inf, Inf])

Save data of name vars at AMR level into VTK image file of name file.

Arguments

  • file::String: output file name.
  • vars::Vector{String}: variable names to be saved.
  • data::Vector{Vector{Array}}: data for all the variables on each refinement level.
  • vtkGhostType::Array{UInt8}: array for visibility control.
  • level::Int: refinement level (0-based).
  • ascii::Bool=false: save output in ASCII or binary format.
  • append::Bool=true: determines whether to append data at the end of file or do in-block writing.
  • box::Vector: selected box range in 3D.
source
Vlasiator.set_argsMethod
set_args(meta::MetaVLSV, var::String, axisunit::AxisUnit;
-   normal::Symbol=:none, origin=0.0)

Set plot-related arguments of var in axisunit. normal and origin are used for 2D slices of 3D data, as specified in pcolormesh.

source
Vlasiator.set_limMethod
set_lim(vmin, vmax, data, colorscale=Linear)

Set colormap limits vmin, vmax for data under scale colorscale.

source
+R = getRotationMatrix(v̂, θ)
source
Vlasiator.get_axisMethod
get_axis(axisunit::AxisUnit, plotrange::NTuple{4,<:Real}, sizes::NTuple{2,<:Integer})
+get_axis(pArgs::PlotArgs)

Return x and y ranges for 2D.

source
Vlasiator.get_fg_array_cellMethod
get_fg_array_cell(meta::MetaVLSV, v_fg::Array, cid::Int)

Return a subarray of the field solver grid array, corresponding to the fsgrid covered by the spatial cell ID cid.

source
Vlasiator.get_fg_indices_subvolumeFunction
get_fg_indices_subvolume(meta::MetaVLSV, lower, upper, tol::Float64=1e-3)

Get indices for subarray of fsgrid variables, in a cuboid defined by lower and upper vertices. This is used for mapping a set of fsgrid cells to a given DCCRG cell. Shift the corners (lower, upper) inward by a distance controlled by tol. If direct low-inclusive behaviour is required, tol shall be set to 0.

source
Vlasiator.getdata2dMethod
getdata2d(meta::MetaVLSV, var::String)

Return 2d scalar/vector data. Nonpublic since it won't work with DCCRG AMR.

source
Vlasiator.gradientMethod
gradient(A::AbstractArray{T,N}, dx::Vector{U}) where {T,N,U}

Calculate 2nd order cell-centered ∇A where A is a scalar array and dx is a vector of grid intervals in each dimension.

Warning

The current implementation has issues at the boundary if gradient is taken multiple times.

source
Vlasiator.prep1dMethod
prep1d(meta::MetaVLSV, var::String; i1::Int=0, i2::Int=0, comp::Int=0) -> Array

Obtain a 1D slice from 2D meta of var. i1 is the index for the first dimension, and i2 is the index for the second dimension; only one of them is needed. Use comp to select vector components.

source
Vlasiator.prep2dFunction
prep2d(meta::MetaVLSV, var::String, comp::Union{Symbol, Int}=0) -> Array

Obtain data from meta of var for 2D plotting. Use comp to select vector components.

source
Vlasiator.prep2dsliceMethod
prep2dslice(meta::MetaVLSV, var::String, normal, comp, pArgs::PlotArgs)

Return data of var on a uniform 2D mesh on the finest AMR level. Use normal to select the plane orientation, and comp to select the component of a vector, same as in pcolormesh.

source
Vlasiator.prep_vdfMethod
prep_vdf(meta::MetaVLSV, location::AbstractVector; kwargs...)

Return the cell velocities v1, v2, bin ranges r1, r2, cell VDF values fweight, and strings of labels and titles for VDF plots.

Keywords

  • unit::AxisUnit: location unit in SI, EARTH.
  • unitv::String: velocity unit in ("km/s", "m/s").
  • limits::Vector{Real}: velocity space range given in [xmin, xmax, ymin, ymax].
  • slicetype: symbol for choosing the slice type from :xy, :xz, :yz, :bperp, :bpar1, :bpar2.
  • center: symbol for setting the reference frame from :bulk, :peak.
  • vslicethick: setting the velocity space slice thickness in the normal direction. If set to 0, the whole distribution along the normal direction is projected onto a plane. Currently this is only meaningful when center is set such that a range near the bulk/peak normal velocity is selected.
  • weight::Symbol: choosing distribution weights from phase space density or particle flux between :particle and :flux.
  • flimit: minimum VDF threshold for plotting.
  • verbose: display the selection process.
source
Vlasiator.read_variable_as_fgMethod
read_variable_as_fg(meta::MetaVLSV, var::String)

Interpolate DCCRG variable var to field solver grid size. This is an alternative method to fillmesh, but not optimized for performance.

source
Vlasiator.reconstructMethod
reconstruct(vmesh::VMeshInfo, vcellids::Vector{Int32}, vcellf::Vector{<:AbstractFloat})

Reconstruct the full VDFs in 3D. vcellids are raw indices of nonzero VDFs ordered by blocks, and vcellf are the corresponding values in each cell.

source
Vlasiator.reorderMethod
reorder(vmesh::VMeshInfo, vcellids::Vector{Int32}) -> vcellids_origin

Reorder vblock-organized VDF indexes into x–>y–>z indexes. vcellids are raw indices of nonzero VDFs ordered by blocks.

source
Vlasiator.rotateTensorToVectorZMethod
rotateTensorToVectorZ(tensor::AbstractMatrix, vector::AbstractVector) -> SMatrix{3,3}

Rotate tensor with a rotation matrix that aligns the 3rd direction with vector, which is equivalent to change the basis from (i,j,k) to (i′,j′,k′) where k′ ∥ vector. Reference: Tensor rotation

source
Vlasiator.save_imageFunction
save_image(meta::MetaVLSV, file, vars, data, vtkGhostType, level,
+   ascii=false, append=true, box=[-Inf, Inf, -Inf, Inf, -Inf, Inf])

Save data of name vars at AMR level into VTK image file of name file.

Arguments

  • file::String: output file name.
  • vars::Vector{String}: variable names to be saved.
  • data::Vector{Vector{Array}}: data for all the variables on each refinement level.
  • vtkGhostType::Array{UInt8}: array for visibility control.
  • level::Int: refinement level (0-based).
  • ascii::Bool=false: save output in ASCII or binary format.
  • append::Bool=true: determines whether to append data at the end of file or do in-block writing.
  • box::Vector: selected box range in 3D.
source
Vlasiator.set_argsMethod
set_args(meta::MetaVLSV, var::String, axisunit::AxisUnit;
+   normal::Symbol=:none, origin=0.0)

Set plot-related arguments of var in axisunit. normal and origin are used for 2D slices of 3D data, as specified in pcolormesh.

source
Vlasiator.set_limMethod
set_lim(vmin, vmax, data, colorscale=Linear)

Set colormap limits vmin, vmax for data under scale colorscale.

source
diff --git a/dev/log/index.html b/dev/log/index.html index 5bae9871..65af0c0c 100644 --- a/dev/log/index.html +++ b/dev/log/index.html @@ -3,4 +3,4 @@ rootpath = artifact"testdata" files = joinpath.(rootpath, ("bulk.1d.vlsv", "bulk.2d.vlsv", "bulk.amr.vlsv"))

These are also used in the standard test. These will be automatically downloaded from vlsv_data if you run the package test locally.

Performance

The VLSV loader inherits the basic structure from Analysator and is redesigned for performance.

For development, it is recommended to use PkgBenchmark.jl to run the test suite:

using PkgBenchmark, Vlasiator
-results = benchmarkpkg(Vlasiator)

or if you want to compare the current status of the package against a different git version

judge(Vlasiator, "97e3dca6b2474d7bdc5b62b5bf98ecf070516e5e")

To export results to Markdown,

export_markdown("testresult", results)

See more in the PkgBenchmark manual.

Precision

For post-processing and data analysis purposes, it makes less sense to stick to double precisions, so we mostly use Float32 in Vlasiator.jl for numerical arrays. Several exceptions are:

Int vs. UInt

Integers but not unsigned integers shall be used for indexing, even though unsigned integers are tempting.

Memory

Vlasiator output files can be large. If we have limited memory relative to the file size, Vlasiator.jl provide direct hard disk mapping through mmap in Julia. With this mechanism you never need to worry about unable to process data with small free memory. Besides, we found that proper usage of mmap can also speed up reading and reduce memory comsumption. However, without reinterpret we may encounter the alignment issue!

Parallelism

The current design choice is to achieve optimal serial performance per file, and apply parallel processing across individual files. In most common cases, the time it takes for post-processing one snapshot is reasonably short, but the number of snapshots are large. Julia's built-in support for all kinds of parallelism paradigm (multithreading, multiprocessing, channel) and external support from packages (MPI.jl, Polyester.jl) can be relatively easily incorported to make the whole workflow parallel.

See more in the examples.

VTK

VLSV is just an uncompressed binary format. If we convert VLSV to VTK through write_vtk, the generated VTK files, even the highest resolution one with every coarse cell mapping to the finest level, can be several times smaller than the original VLSV file.

One drawback of this conversion is that it cannot deal with phase space outputs, i.e. VDFs.

+results = benchmarkpkg(Vlasiator)

or if you want to compare the current status of the package against a different git version

judge(Vlasiator, "97e3dca6b2474d7bdc5b62b5bf98ecf070516e5e")

To export results to Markdown,

export_markdown("testresult", results)

See more in the PkgBenchmark manual.

Precision

For post-processing and data analysis purposes, it makes less sense to stick to double precisions, so we mostly use Float32 in Vlasiator.jl for numerical arrays. Several exceptions are:

Int vs. UInt

Integers but not unsigned integers shall be used for indexing, even though unsigned integers are tempting.

Memory

Vlasiator output files can be large. If we have limited memory relative to the file size, Vlasiator.jl provide direct hard disk mapping through mmap in Julia. With this mechanism you never need to worry about unable to process data with small free memory. Besides, we found that proper usage of mmap can also speed up reading and reduce memory comsumption. However, without reinterpret we may encounter the alignment issue!

Parallelism

The current design choice is to achieve optimal serial performance per file, and apply parallel processing across individual files. In most common cases, the time it takes for post-processing one snapshot is reasonably short, but the number of snapshots are large. Julia's built-in support for all kinds of parallelism paradigm (multithreading, multiprocessing, channel) and external support from packages (MPI.jl, Polyester.jl) can be relatively easily incorported to make the whole workflow parallel.

See more in the examples.

VTK

VLSV is just an uncompressed binary format. If we convert VLSV to VTK through write_vtk, the generated VTK files, even the highest resolution one with every coarse cell mapping to the finest level, can be several times smaller than the original VLSV file.

One drawback of this conversion is that it cannot deal with phase space outputs, i.e. VDFs.

diff --git a/dev/manual/index.html b/dev/manual/index.html index 9b939e6d..5ff8b887 100644 --- a/dev/manual/index.html +++ b/dev/manual/index.html @@ -47,4 +47,4 @@ push!(vars, (pa, "panisotropy", VarInfo("", "", "", ""))) write_vlsv("bulk.1d.vlsv", "bulk.1d_new.vlsv", vars)
Note

Writing new FsGrid variables is not supported. All quantities from the original file is maintained.

Converting to VTK

We can convert VLSV files into VTK format. Since DCCRG is Cartesian based with uniform spacing, each level of mesh refinement corresponds to a VTK image file, and the cell refinement relationships are stored in vtkGhostType as well as the vthb file.

To convert a VLSV file into VTK,

write_vtk(file)

This function accepts either string of file names or MetaVLSV.

To see the full list of options, please refer to the documentation in API Reference. Example usage can be found here.

Warning

As of ParaView 5.9.1, there are display issues with VTKOverlappingAMR. However, we can read the generated image files directly. There is also an keyword argument for write_vtk called maxamronly: when it is set to true, then only the image file at the highest refinement level is generated. This part is experimental and subject to change in the future.

Tracking log files

The runtime performance per iteration can be monitored through log files:

file = "logfile.txt"
-timestamps, speed = readlog(file)

Here is a live demo.

Examples

More examples are provided about

Feel free to check those out and try on your data!

+timestamps, speed = readlog(file)

Here is a live demo.

Examples

More examples are provided about

Feel free to check those out and try on your data!

diff --git a/dev/python/index.html b/dev/python/index.html index e4b341dd..02205a01 100644 --- a/dev/python/index.html +++ b/dev/python/index.html @@ -20,4 +20,4 @@ jl = Julia(compiled_modules=False) jl.eval('include("examples/demo_2dplot_pyplot.jl")') import matplotlib.pyplot as plt -plt.show()
Note

This approach is for you to have a taste of the package with a Python frontend. The workaround shown above for handling the static python libraries makes it slow for regular use. An alternative solution would be creating system images, but as of Julia 1.6 the user experience is not smooth. For better integrated experience with its full power, it is recommended to use the package inside Julia.

+plt.show()
Note

This approach is for you to have a taste of the package with a Python frontend. The workaround shown above for handling the static python libraries makes it slow for regular use. An alternative solution would be creating system images, but as of Julia 1.6 the user experience is not smooth. For better integrated experience with its full power, it is recommended to use the package inside Julia.

diff --git a/dev/search/index.html b/dev/search/index.html index e3f1b002..9c4d426e 100644 --- a/dev/search/index.html +++ b/dev/search/index.html @@ -1,2 +1,2 @@ -Search · Vlasiator.jl

Loading search...

    +Search · Vlasiator.jl

    Loading search...

      diff --git a/dev/search_index.js b/dev/search_index.js index f3988607..600a22e4 100644 --- a/dev/search_index.js +++ b/dev/search_index.js @@ -1,3 +1,3 @@ var documenterSearchIndex = {"docs": -[{"location":"examples/postprocess/demo_em_extract_slice/#demo_em_slice","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"","category":"section"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"To save Epar, Eperp, B in a selected slice region from 3D VLSV outputs,","category":"page"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"using Vlasiator, Glob\nusing JLD2: jldsave\nusing StaticArrays\nusing LinearAlgebra: norm\n\nfunction getvars(meta::MetaVLSV, pArgs::Vlasiator.PlotArgs, normal::Symbol, range1, range2)\n (;origin, idlist, indexlist) = pArgs\n\n B = readvariable(meta, \"vg_b_vol\")\n\n Bout = @views refineslice(meta, idlist, B[:,indexlist], normal)[:, range1, range2]\n\n ncells = meta.ncells .* 2^meta.maxamr\n if normal == :x\n dir = 1\n elseif normal == :y\n dir = 2\n elseif normal == :z\n dir = 3\n else\n @error \"Unknown normal direction $normal\"\n end\n\n sliceratio = (origin - meta.coordmin[dir]) / (meta.coordmax[dir] - meta.coordmin[dir])\n 0.0 ≤ sliceratio ≤ 1.0 || error(\"slice plane index out of bound!\")\n # Find the cut plane index for each refinement level\n icut = floor(Int, sliceratio*ncells[dir]) + 1\n\n E = readvariable(meta, \"fg_e\", true, true)\n\n E = if normal == :x\n E[:,icut,range1,range2]\n elseif normal == :y\n E[:,range1,icut,range2]\n elseif normal == :z\n E[:,range1,range2,icut]\n end\n\n n2D = meta[\"n\"][indexlist]\n\n n = refineslice(meta, idlist, n2D, normal)[range1, range2]\n\n v2D = meta[\"proton/vg_v\"][:,indexlist]\n v = @views refineslice(meta, idlist, v2D, normal)[:, range1, range2]\n\n p2D = meta[\"P\"][indexlist]\n p = refineslice(meta, idlist, p2D, normal)[range1, range2]\n\n E, Bout, n, v, p\nend\n\nfunction main()\n # Parameters\n directory = \"/home/hongyang/runs/3D/EGI/bulk/dense_cold_hall1e5_afterRestart374/\"\n outdir = \"EM/\"\n outfile = \"EM.jld2\"\n\n files = glob(\"bulk1.*vlsv\", directory)\n # Only orthogonal slices are supported\n normal = :y # (:x, :y, :z)\n origin = 0.0\n var = \"e\"\n axisunit = EARTH\n\n meta = load(files[1])\n\n pArgs = Vlasiator.set_args(meta, var, axisunit; normal, origin)\n\n x1, x2 = Vlasiator.get_axis(pArgs)\n\n extent = [-23., 12., -10., 10.]\n\n range1, range2 =\n searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2]),\n searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\n\n E = zeros(Float32, 3, length(range1), length(range2), length(files))\n B = zeros(Float32, 3, length(range1), length(range2), length(files))\n n = zeros(Float32, length(range1), length(range2), length(files))\n v = zeros(Float32, 3, length(range1), length(range2), length(files))\n p = zeros(Float32, length(range1), length(range2), length(files))\n\n for i in eachindex(files)\n meta = load(files[i])\n E[:,:,:,i], B[:,:,:,i], n[:,:,i], v[:,:,:,i], p[:,:,i] =\n getvars(meta, pArgs, normal, range1, range2)\n end\n\n # Save into binary file\n jldsave(outdir*outfile; E, B, n, v, p)\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"","category":"page"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/#demo_2d_contour_streamline_levels","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"","category":"section"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"This demo shows how to plot 2D colored contour in a region of interest with streamlines and levels.","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"using VlasiatorPyPlot\nusing Vlasiator: RE\n\nfunction main(file::String, varname::String)\n meta = load(file)\n\n fig, ax = plt.subplots(1,1; figsize=(8,6), constrained_layout=true)\n\n pcolormesh(meta, varname, ax)\n streamplot(meta, \"rho_v\", ax; comp=\"xy\", color=\"w\", density=2.0)\n\n cbar = ax.collections[end].colorbar\n boxcoords = Float64[0, 20, -15, 15]\n ax.set_xlim([boxcoords[1],boxcoords[2]])\n ax.set_ylim([boxcoords[3],boxcoords[4]])\n\n # Contour line at a specific level\n pArgs = Vlasiator.set_args(meta, varname, EARTH)\n x, y = Vlasiator.get_axis(pArgs)\n data = Vlasiator.prep2d(meta, varname)'\n CS = plt.contour(x, y, data, levels = [1e7],\n colors=(\"k\",),linestyles=(\"-\",),linewidths=(0.5,))\n\n # Add a rectangular box region\n boxrange = (250:299, 200:249)\n\n x = LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\n y = LinRange(meta.coordmin[2], meta.coordmax[2], meta.ncells[2])\n # Construct the patch\n rect = matplotlib.patches.Rectangle((x[boxrange[1][1]]/RE, y[boxrange[2][1]]/RE),\n (x[boxrange[1][end]] - x[boxrange[1][1]])/RE,\n (y[boxrange[2][end]] - y[boxrange[2][1]])/RE,\n linewidth=1, edgecolor=\"r\", facecolor=\"none\")\n\n ax.add_patch(rect)\nend\n\n\nfile = \"bulk.0000501.vlsv\"\nnameρ = \"rho\"\n\nmain(file, nameρ)","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/#demo_energy_spectrum","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"","category":"section"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"This demo shows how to plot energy spectrum of oscillations at a fixed point.","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"using FFTW, JLD2, CurveFit, PyPlot\nusing Vlasiator: RE\n\nfunction main()\n file = \"satellites_uniform_sampled.jld2\"\n data = JLD2.load(file)\n\n nSatellite = length(data[\"t\"])\n nI, nJ = size(data[\"rho\"])[2:3]\n\n t = data[\"t\"]\n # Select spatial point\n i, j = 5, 5\n var = data[\"rho\"][:,i,j]\n\n dt = t[2] - t[1] # uniform sample interval [s]\n Fs = 1 / dt # sample frequency, [Hz]\n Fn = Fs / 2 # Nyquist frequency, [Hz]\n\n ## Frequency calculation\n nPoints = length(var)\n nFFT = nPoints\n df = Fs / nFFT\n freq_fullrange = -Fn:df:Fn\n\n freq = freq_fullrange[(nPoints ÷ 2 + 1):end-1]\n\n var_freq = fft(var)\n var_power = abs.(fftshift(var_freq))[(nPoints ÷ 2 + 1):end]\n\n # k is the exponential coefficient\n a, k = @views power_fit(freq[10:end], var_power[10:end])\n\n figure(figsize=(6,8))\n loglog(freq, var_power)\n axis(\"scaled\")\n\n min_power, max_power = extrema(@view var_power[10:end])\n xlim(freq[8], Fs)\n ylim(min_power * 0.75, max_power * 2.0)\n\n xlabel(\"Frequency [Hz]\"; fontsize=14)\n ylabel(\"Power Density \"; fontsize=14)\n title(string(round.(data[\"locations\"][i,j]./RE, digits=1))*\"Re\"; fontsize=14)\n\n loglog(freq[10:end], a.*freq[10:end].^k, label=\"k = $(round(k, digits=1))\")\n\n legend()\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/#demo_track_waves","page":"Track waves","title":"Track waves","text":"","category":"section"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"This demo shows how to track wave and plot the dispersion relation On a equatorial plane, B ∥ ẑ, we can choose an arbitrary line in-plane. On a meridional plane, B is in-plane, we can find a local line region ∥ B and ⟂ B.","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"Currently it only works on a equatorial plane.","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"julia -t 4 demo_wave_tracing_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"or","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"JULIA_NUM_THREADS=4 julia demo_wave_tracing_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"using Vlasiator, VlasiatorPyPlot\nusing Vlasiator: qᵢ, μ₀, c, mᵢ, ϵ₀, RE\nusing Glob, DSP, FFTW, ImageFiltering, Interpolations\nusing Statistics: mean\nusing LinearAlgebra\n\n## Types\n\nstruct Variables\n varnames::Vector{String}\n varnames_print::Vector{String}\n components::Vector{Int}\nend\n\n## Methods\n\nispolar(meta::MetaVLSV) = findfirst(==(1), meta.ncells) == 2\n\n\"Extract `component` of variable `varname` at `cellids` from `files`.\"\nfunction extract_var(files, varname, cellids, distances, component=0)\n sample_loc = range(distances[1], distances[end], length=length(distances))\n\n var = zeros(length(distances), length(files))\n\n Threads.@threads for i in eachindex(files)\n meta = load(files[i])\n if component == 0\n var_line = readvariable(meta, varname, cellids)[:]\n else\n var_line = readvariable(meta, varname, cellids)[component,:]\n end\n #TODO: do we need high order interpolations?\n interp_linear = LinearInterpolation(distances, var_line)\n var_line_resample = interp_linear.(sample_loc)\n var_line_smooth = imfilter(var_line_resample, Kernel.gaussian((3,)))\n\n var[:,i] = var_line_smooth\n end\n var\nend\n\n\"CFL constrained normalized frequency.\"\ndispersion_CFL(k, dx, dt, di, ωci) = dx/dt * abs(k) /(di * ωci)\n\n\"Normalized frequency of fast magnetosonic waves along angle `θ` with Doppler shift.\"\nfunction dispersion_fast_perp(k, θ, vS, vA, v, di, ωci)\n ω = zeros(length(k))\n\n turnindex = findfirst(>=(0), k)\n\n vbulkpar = v[1]*cos(θ) + v[2]*sin(θ)\n\n dv1 = √(vS^2 + vA^2) + vbulkpar # propagate along +θ direction\n dv2 = -√(vS^2 + vA^2) + vbulkpar # propagate along -θ direction\n\n if dv1 < 0; dv1 = 0.0; end\n if dv2 > 0; dv2 = 0.0; end\n\n for i in 1:turnindex-1\n ω[i] = dv2*k[i] /(di * ωci)\n end\n\n for i in turnindex:length(k)\n ω[i] = dv1*k[i] /(di * ωci)\n end\n ω\nend\n\n\"Normalized frequency of bulk flow along tilted angle `θ`.\"\nfunction dispersion_bulk_flow(k, θ, v, di, ωci)\n ω = zeros(length(k))\n turnindex = findfirst(>=(0), k)\n vbulkpar = v[1]*cos(θ) + v[2]*sin(θ)\n irange = vbulkpar > 0 ? (turnindex:length(k)) : (1:turnindex)\n for i in irange # otherwise 0\n ω[i] = vbulkpar*k[i] /(di * ωci)\n end\n ω\nend\n\n\"Return the index in sorted `vec` with value closest to `x`.\"\nfunction searchsortednearest(vec, x)\n idx = searchsortedfirst(vec, x)\n if idx == 1\n return idx\n elseif idx > length(vec)\n return length(vec)\n elseif vec[idx] == x\n return idx\n elseif abs(vec[idx]-x) < abs(vec[idx-1]-x)\n return idx\n else\n return idx-1\n end\nend\n\n\"Obtain fast mode and bulk speed along line `angle` w.r.t. x-axis for cell ID `cid` in\n`meta`.\"\nfunction getCharacteristicSpeeds(meta, cid, angle)\n n = readvariable(meta, \"proton/vg_rho\", cid)\n B = readvariable(meta, \"vg_b_vol\", cid)\n p = readvariable(meta, \"vg_pressure\", cid)\n v = readvariable(meta, \"proton/vg_v\", cid)\n\n Bmag = norm.(eachcol(B))\n\n vA = @. Bmag / √(μ₀ * n * mᵢ) # Alfven speed, [m/s]\n vS = @. √(γ * p / (n * mᵢ)) # sonic speed, [m/s]\n\n vFast = @. √(vA^2 + vS^2)\n vBulk = @. v[1,:]*cos(angle) + v[2,:]*sin(angle)\n\n vFast, vBulk\nend\n\n\"Trace along line with `angle` w.r.t. x-axis at possible wave speeds.\"\nfunction tracewave(xstart, angle, files, dtfile, t, cellids, distances)\n\n x1 = zeros(length(t)); x1[1] = xstart\n x2 = copy(x1)\n x3 = copy(x1)\n\n tfile = let\n tfilefirst = getproperty(load(files[1]), :time)\n tfilelast = getproperty(load(files[end]), :time)\n tfilefirst:dtfile:tfilelast\n end\n\n ifile = 1 # file index tracker\n\n dt = t[2] - t[1] # timestep\n\n for it in eachindex(t)[1:end-1]\n # Find the closest output saving time to t[it], 0th order interpolation\n for i = ifile:length(tfile)\n if abs(tfile[i] - t[it]) < 0.5*dtfile\n ifile = i\n break\n end\n end\n meta = load(files[ifile])\n # Find the closest cell to the wave location\n cid = let\n c1 = searchsortednearest(distances, x1[it])\n c2 = searchsortednearest(distances, x2[it])\n c3 = searchsortednearest(distances, x3[it])\n cellids[c1], cellids[c2], cellids[c3]\n end\n vFast, vBulk = getCharacteristicSpeeds(meta, cid, angle)\n x1[it+1] = x1[it] + dt * vBulk[1]\n x2[it+1] = x2[it] + dt * (vBulk[2] + vFast[2])\n x3[it+1] = x3[it] + dt * (vBulk[3] - vFast[3])\n end\n\n x1, x2, x3\nend\n\n\"Evaluate the average quantities at `cellids` at the middle of `files`.\"\nfunction estimate_meanstates(files, cellids)\n # Select the snapshot in the middle\n nfile = length(files)\n meta = load(files[nfile÷2+1])\n\n n = readvariable(meta, \"proton/vg_rho\", cellids)\n v = readvariable(meta, \"proton/vg_v\", cellids)\n p = readvariable(meta, \"vg_pressure\", cellids)\n\n if hasvariable(meta, \"vg_b_vol\")\n B = readvariable(meta, \"vg_b_vol\", cellids)\n elseif hasvariable(meta, \"fg_b\")\n B = readvariable(meta, \"fg_b\", cellids)\n else\n B = readvariable(meta, \"b\", cellids)\n end\n\n vperp = @view v[1:2,:]\n vpar = @view v[3,:]\n\n # Obtain average states\n n̄ = mean(n)\n p̄ = mean(p)\n v̄par = mean(vpar)\n v̄perp = @views [mean(vperp[1,:]), mean(vperp[2,:])]\n\n # Characteristic parameters\n Bnorm = @views abs(mean(B[3,:]))\n di = √(mᵢ*ϵ₀/(n̄))*c/qᵢ # ion inertial length, [m]\n ωci = qᵢ*Bnorm/mᵢ # [/s]\n v̄A = Bnorm / √(μ₀ * n̄ * mᵢ) # Alfven speed, [m/s]\n v̄S = √(γ * p̄ / (n̄ * mᵢ)) # sonic speed, [m/s]\n\n println(\"--------------------------------------------------\")\n println(\"* Average states along the line at the middle snapshot\")\n println(\"Density : \", rpad(round(n̄/1e6; digits=2), 8), \"amu/cc\")\n println(\"Pressure : \", rpad(round(p̄*1e9; digits=3), 8), \"nPa\")\n println(\"Parallel velocity : \", rpad(round(v̄par/1e3; digits=2), 8), \"km/s\")\n println(\"Perpendicular velocity: \", rpad(round.(v̄perp/1e3; digits=2), 8), \"km/s\")\n println(\"Flow angle : \", rpad(round(atand(v̄perp[2], v̄perp[1]); digits=2), 8),\n \"degrees\")\n println(\"Ion inertial length : \", rpad(round(di/1e3; digits=2), 8), \"km\")\n println(\"Gyrofrequency : \", rpad(round(ωci; digits=2), 8), \"Hz\")\n println(\"Alfven speed : \", rpad(round(v̄A/1e3; digits=2), 8), \"km/s\")\n println(\"Sonic speed : \", rpad(round(v̄S/1e3; digits=2), 8), \"km/s\")\n println(\"--------------------------------------------------\")\n\n di, ωci, v̄A, v̄S, v̄perp\nend\n\n\"Plot the process of wave checks.\"\nfunction plot_dispersion(files, vars, cellids, distances, coords, meanstates, dtfile, Δt,\n outdir)\n\n # Parameters\n nfile = length(files)\n npoints = length(cellids)\n nt = nfile ÷ 2 + 1\n\n varnames = vars.varnames\n varnames_print = vars.varnames_print\n components = vars.components\n\n di, ωci, v̄A, v̄S, v̄perp = meanstates\n\n tfile1st = load(files[1]).time\n # Output timestamps\n t = [dtfile * ifile + tfile1st for ifile in 0:nfile-1]\n # Selected line tilted angle ∈ [-π, π]\n θ = atan(coords[2,end] - coords[2,1], coords[1,end] - coords[1,1])\n # Sample width, [m]\n dx = norm(coords[:,end] .- coords[:,1]) /(npoints - 1)\n println(\"spatial resolution: \", round(dx/1e3; digits=2), \" km\")\n\n # Trace wave along the line in a space-time domain\n twave = let\n tstart = 400.0\n tend = 430.0\n tstart:200Δt:tend\n end\n xwave = tracewave(distances[npoints÷2+1], θ, files, dtfile, twave, cellids, distances)\n\n twave2 = let\n tstart = 600.0\n tend = 630.0\n tstart:200Δt:tend\n end\n xwave2 = tracewave(distances[npoints÷2+1], θ, files, dtfile, twave2, cellids, distances)\n\n # Dispersion plotting ranges\n kmin = -π / dx * di # minimum wave number\n kmax = π / dx * di # maximum wave number\n ωmin = 0 # minimum angular frequency\n ωmax = π / dtfile / ωci # maximum angular frequency\n\n # Only the 1st quadrature\n krange = range(kmin, kmax, length=npoints)\n ωrange = range(ωmin, ωmax, length=nt)\n\n axisunit = EARTH\n\n # Precalculated lines\n ωCFL = dispersion_CFL.(krange, dx, Δt, di, ωci)\n ωfast = dispersion_fast_perp(krange, θ, v̄S, v̄A, v̄perp, di, ωci)\n ωbulk = dispersion_bulk_flow(krange, θ, v̄perp, di, ωci)\n # Window filtering for avoiding spectral leakage\n window = hanning(npoints) * hanning(nfile)'\n\n meta = load(files[end])\n\n for i in eachindex(varnames)\n println(\"variable name: \", varnames[i])\n var = extract_var(files, varnames[i], cellids, distances, components[i])\n\n # 2DFFT\n F̃ = window .* var |> fft |> fftshift\n\n # Visualization\n fig = figure(figsize=(12,12), constrained_layout=false)\n ax = [subplot(221), subplot(223), subplot(222), subplot(224, projection=\"3d\")]\n\n dispersion = reverse!(abs.(F̃.*F̃)[:, end-nt+1:end]', dims=1)\n im1 = ax[1].pcolormesh(krange, ωrange, dispersion, norm=matplotlib.colors.LogNorm())\n\n ax[1].plot([krange[1], 0.0, krange[end]], [ωCFL[1], 0.0, ωCFL[end]], \"--\",\n linewidth=1.0, color=\"k\", label=\"CFL Condition\")\n ax[1].plot(krange, ωfast, \"--\",\n linewidth=1.2, color=\"#d62728\", label=\"Fast Mode\")\n ax[1].plot(krange, ωbulk, \"--\",\n linewidth=1.2, color=\"#9467bd\", label=\"Flow Speed\")\n\n ax[1].set_xlim(kmin, kmax)\n ax[1].set_ylim(ωmin, ωmax)\n\n cb = colorbar(im1; ax=ax[1])\n cb.ax.tick_params(direction=\"in\")\n ax[1].legend(;fontsize=\"x-small\")\n ax[1].set_xlabel(L\"$k_\\perp \\cdot d_i$\")\n ax[1].set_ylabel(L\"$\\omega/\\Omega_{ci}$\")\n ax[1].set_title(L\"$k_\\perp$ angle w.r.t. x = %$θ\")\n\n im2 = ax[2].pcolormesh((distances .+ coords[1,1])./RE, t, var')\n\n ax[2].plot((xwave[1] .+ coords[1,1])./RE, twave, \".--\",\n color=\"#d62728\", label=L\"$V_{bulk}$\")\n ax[2].plot((xwave[2] .+ coords[1,1])./RE, twave, \".--\",\n color=\"#9467bd\", label=L\"$V_{bulk} + V_{fast}$\")\n ax[2].plot((xwave[3] .+ coords[1,1])./RE, twave, \".--\",\n color=\"#ff7f0e\", label=L\"$V_{bulk} - V_{fast}$\")\n\n ax[2].plot((xwave2[1] .+ coords[1,1])./RE, twave2, \".--\",\n color=\"#d62728\")\n ax[2].plot((xwave2[2] .+ coords[1,1])./RE, twave2, \".--\",\n color=\"#9467bd\")\n ax[2].plot((xwave2[3] .+ coords[1,1])./RE, twave2, \".--\",\n color=\"#ff7f0e\")\n\n cb = colorbar(im2; ax=ax[2])\n cb.ax.tick_params(direction=\"in\")\n\n ax[2].set_xlim(coords[1,1]/RE, coords[1,end]/RE)\n\n ax[2].legend(loc=\"upper center\", bbox_to_anchor=(0.5, -0.13),\n fancybox=true, shadow=true, ncol=3)\n ax[2].set_xlabel(L\"x [$R_E$]\")\n ax[2].set_ylabel(L\"time [s]\")\n ax[2].set_title(\"$(varnames_print[i])_$(components[i])\")\n\n pArgs = Vlasiator.set_args(meta, varnames[i], axisunit; normal=:none)\n x, y = Vlasiator.get_axis(pArgs)\n data = Vlasiator.prep2d(meta, varnames[i], components[i])'\n cnorm, cticks = set_colorbar(Linear, -Inf, Inf, data)\n cmesh = ax[3].pcolormesh(x, y, data, norm=cnorm)\n\n ax[3].set_xlabel(pArgs.strx)\n ax[3].set_ylabel(pArgs.stry)\n ax[3].set_aspect(1)\n\n cb = colorbar(cmesh; ax=ax[3], ticks=cticks, fraction=0.046, pad=0.04)\n cb.ax.set_ylabel(pArgs.cb_title)\n cb.ax.tick_params(direction=\"in\")\n\n @views ax[3].scatter(coords[1,:]./RE, coords[2,:]./RE; s=0.2, color=\"k\")\n\n xCoord = (distances .+ coords[1,1])./RE\n # meshgrid\n X = [x for _ in t, x in xCoord]\n Y = [y for y in t, _ in xCoord]\n\n ax[4].view_init(elev=40., azim=-30.)\n ax[4].plot_surface(X, Y, var', cmap=matplotlib.cm.turbo, antialiased=false)\n\n ax[4].set_xlabel(L\"x [$R_E$]\"; fontsize=\"small\")\n ax[4].set_ylabel(\"time [s]\"; fontsize=\"small\")\n #ax[4].set_zlabel(pArgs.cb_title)\n ax[4].tick_params(labelsize=\"small\")\n\n outname = \"dispersion_$(varnames_print[i])_$(components[i]).png\"\n savefig(joinpath(outdir, outname), bbox_inches=\"tight\")\n close(fig)\n end\n\nend\n\nfunction main()\n outdir = \"../out/\"\n γ = 5 / 3\n\n xStart = [10.0, 0.0, 0.0].*RE\n xEnd = [13.3, 0.0, 0.0].*RE\n\n varnames = [\"proton/vg_rho\", \"vg_b_vol\", \"vg_e_vol\", \"vg_pressure\"]\n varnames_print = [\"rho\", \"b\", \"e\", \"p\"]\n components = [0, 3, 1, 0] # 0 for scalar, 1-3 for vector components\n\n dir = \"../run_rho2_bz-5_timevarying_startfrom300s\"\n files = glob(\"bulk.*.vlsv\", dir)\n\n vars = Variables(varnames, varnames_print, components)\n\n dtfile = 0.5 # output interval, [s]\n Δt = 0.0147176 # discrete time step from runlog, [s]\n\n meta = load(files[1])\n\n if ispolar(meta) # polar plane\n @error \"not implemented!\"\n end\n\n cellids, distances, coords = getcellinline(meta, xStart, xEnd)\n\n meanstates = estimate_meanstates(files, cellids)\n\n println(\"number of extracted points: \", length(cellids))\n println(\"xStart: \", xStart)\n println(\"xEnd: \", xEnd)\n tbegin = load(files[1]).time\n tend = load(files[end]).time\n println(\"time from $tbegin to $tend s\")\n\n @time plot_dispersion(files, vars, cellids, distances, coords, meanstates, dtfile, Δt,\n outdir)\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_pointextracting/#demo_virtual_sat","page":"Virtual satellite","title":"Virtual satellite","text":"","category":"section"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"This demo shows how to extract data for a virtual satellite. Outputs are stored in CSV format for sharing data.","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"julia -t nthreads demo_virtual_satellite.jl","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"or","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"JULIA_NUM_THREADS=nthreads julia demo_virtual_satellite.jl","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"using Glob, DelimitedFiles, Vlasiator, DataFrames\nusing Vlasiator: RE # Earth radius [m]\n\nfunction extract_vars(files, loc)\n nfiles = length(files)\n # variables to be extracted\n t = zeros(Float32, nfiles)\n rho = zeros(Float32, nfiles)\n v = zeros(Float32, 3, nfiles)\n p = zeros(Float32, nfiles)\n b = zeros(Float32, 3, nfiles)\n e = zeros(Float32, 3, nfiles)\n\n id = load(files[1]) do meta\n getcell(meta, loc)\n end\n\n # Extract data from each frame\n Threads.@threads for i = eachindex(files)\n meta = load(files[i])\n t[i] = meta.time\n rho[i] = readvariable(meta, \"proton/vg_rho\", id)[1]\n v[:,i] = readvariable(meta, \"proton/vg_v\", id)\n p[i] = readvariable(meta, \"vg_pressure\", id)[1]\n b[:,i] = readvariable(meta, \"vg_b_vol\", id)\n e[:,i] = readvariable(meta, \"vg_e_vol\", id)\n end\n\n df = DataFrame(t = t, rho = rho, v = v, p = p, b = b, e = e)\n # Save into text file\n writedlm(\"satellite.csv\", Iterators.flatten(([names(df)], eachrow(df))), ',')\nend\n\n#####\n\nfiles = glob(\"bulk*.vlsv\", \"./\")\n\n# virtual satellite location\nconst loc = Float64[12, 0, 0] .* RE\n\nprintln(\"Number of files: $(length(files))\")\nprintln(\"Extracting location: $loc\")\nprintln(\"Running with $(Threads.nthreads()) threads...\")\n\n@time extract_vars(files, loc)\n\nprintln(\"Virtual satellite extraction done!\")\n\n## Visualization\n#=\nusing PyPlot, DelimitedFiles\n\ndata = readdlm(\"satellite.csv\", ','; header=true)\n\nfig, ax = subplots(figsize=(8,10), 5,1, sharex=true, constrained_layout=true)\n\nax[1].plot(data[1][:,1], data[1][:,2] ./ 1e6, label=\"density\")\nax[2].plot(data[1][:,1], data[1][:,3] ./ 1e3, label=\"vx\")\nax[2].plot(data[1][:,1], data[1][:,4] ./ 1e3, label=\"vy\")\nax[3].plot(data[1][:,1], data[1][:,5] .* 1e9, label=\"p\")\nax[4].plot(data[1][:,1], data[1][:,6] .* 1e9, label=\"bz\")\nax[5].plot(data[1][:,1], data[1][:,7] .* 1e3, label=\"ex\")\nax[5].plot(data[1][:,1], data[1][:,8] .* 1e3, label=\"ey\")\n\nfor a in ax\n a.grid(true)\n a.legend()\nend\n\nax[1].set_ylabel(\"density [amu/cc]\", fontsize=14)\nax[2].set_ylabel(\"velocity [km/s]\", fontsize=14)\nax[3].set_ylabel(\"pressure [nPa]\", fontsize=14)\nax[4].set_ylabel(\"magnetic field [nT]\", fontsize=14)\nax[5].set_ylabel(\"electric field [mV/m]\", fontsize=14)\nax[5].set_xlabel(\"time [s]\", fontsize=14)\n\nfig.suptitle(\"Density Pulse Run, location = [12, 0, 0]\", fontsize=\"xx-large\")\n\nsavefig(\"virtual_satellite.png\", bbox_inches=\"tight\")\n=#","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/#demo_2d_virtual_sats","page":"Virtual satellites","title":"Virtual satellites","text":"","category":"section"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"This demo shows how to extract data for virtual satellites at uniformly sampled locations on a 2D plane. Outputs are stored in binary format for sharing within Julia.","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"using Glob, Vlasiator\nusing JLD2: jldsave\n\n\"Select cells in 2D `meta` with uniform distance `dx`.\"\nfunction sample(meta, dx)\n dcell = floor(Int, dx ÷ meta.dcoord[1])\n\n cellid = sort(collect(keys(meta.celldict)))\n cellid = reshape(cellid, meta.ncells[1], meta.ncells[2])\n cellid_select = cellid[1+dcell:dcell:end-dcell, 1+dcell:dcell:end-dcell]\nend\n\nfunction extract_vars(files, dx)\n nfiles = length(files)\n\n meta = load(files[1])\n ids = sample(meta, dx)\n locations = [getcellcoordinates(meta, id) for id in ids]\n\n nsize = size(ids)\n println(\"Number of virtual satellites: $(length(ids))\")\n\n # variables to be extracted\n t = zeros(Float32, nfiles)\n rho = zeros(Float32, nfiles, nsize[1], nsize[2])\n vx = zeros(Float32, nfiles, nsize[1], nsize[2])\n vy = zeros(Float32, nfiles, nsize[1], nsize[2])\n vz = zeros(Float32, nfiles, nsize[1], nsize[2])\n p = zeros(Float32, nfiles, nsize[1], nsize[2])\n bx = zeros(Float32, nfiles, nsize[1], nsize[2])\n by = zeros(Float32, nfiles, nsize[1], nsize[2])\n bz = zeros(Float32, nfiles, nsize[1], nsize[2])\n ex = zeros(Float32, nfiles, nsize[1], nsize[2])\n ey = zeros(Float32, nfiles, nsize[1], nsize[2])\n ez = zeros(Float32, nfiles, nsize[1], nsize[2])\n\n # Extract data from each frame\n for i = eachindex(files)\n meta = load(files[i])\n t[i] = meta.time\n rho[i,:,:] = readvariable(meta, \"proton/vg_rho\", ids)\n v = readvariable(meta, \"proton/vg_v\", ids)\n vx[i,:,:] = v[1,:]\n vy[i,:,:] = v[2,:]\n vz[i,:,:] = v[3,:]\n p[i,:,:] = readvariable(meta, \"vg_pressure\", ids)\n b = readvariable(meta, \"vg_b_vol\", ids)\n bx[i,:,:] = b[1,:]\n by[i,:,:] = b[2,:]\n bz[i,:,:] = b[3,:]\n e = readvariable(meta, \"vg_e_vol\", ids)\n ex[i,:,:] = e[1,:]\n ey[i,:,:] = e[2,:]\n ez[i,:,:] = e[3,:]\n end\n\n # Save into binary file\n jldsave(\"satellites_uniform_sampled.jld2\";\n locations, t, rho, vx, vy, vz, p, bx, by, bz, ex, ey, ez)\nend\n\n#####\n\nfiles = glob(\"bulk*.vlsv\", \"./\")\n\nconst dx = 5RE # uniform sampling distance [m]\n\nprintln(\"Number of files: $(length(files))\")\nprintln(\"Running with $(Threads.nthreads()) threads...\")\n\n@time extract_vars(files, dx)\n\nprintln(\"Virtual satellite extraction done!\")","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/#demo_2d_bowshock","page":"Extract bow shock location","title":"Extract bow shock location","text":"","category":"section"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"(Image: Author) (Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"This demo shows how to extract the bow shock location from a 2D equatorial run and plot.","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"using Vlasiator, PyPlot\n\n# Upstream solar wind temperature\nconst Tsw = 0.5e6 #[K]\n\nconst file = \"bulk.0001347.vlsv\"\nmeta = load(file)\n# NonAMR\nconst x = LinRange{Float32}(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\nconst y = LinRange{Float32}(meta.coordmin[2], meta.coordmax[2], meta.ncells[2])\n\n# Obtain thermal temperature\nT = meta[\"T\"]\nT = reshape(T, meta.ncells[1], meta.ncells[2])\n\nconst x_crossing = zeros(Float32, meta.ncells[2])\nconst y_crossing = y\n\n# Extract bow shock location from the 1st point which fulfills the threshold: T > 4 * Tsw\n# Note: this won't work if the bow shock does not cover the whole domain y extension!\nfor j in 1:meta.ncells[2] # scan in y direction\n ind_ = findlast(>(4*Tsw), @view T[:,j]) # count from upstream\n x_crossing[j] = x[ind_]\nend\n\n# Julia is column-major, while Python is row-major\nimshow(T', extent=(x[1], x[end], y[1], y[end]), origin=\"lower\", cmap=plt.get_cmap(\"ocean\"))\nplot(x_crossing, y_crossing, \"r\")\naxis(\"scaled\")\nsavefig(\"bs_temp_test.png\")","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/#demo_vdfs","page":"VDFs along a line","title":"VDFs along a line","text":"","category":"section"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"This demo shows how to plot velocity distribution functions along a line.","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"using VlasiatorPyPlot, JLD2\nusing Vlasiator: RE # Earth radius [m]\n\nfunction main()\n ## Plot velocity space distributions\n xloc = range(7.0, 10.0, step=2.35)\n yloc = range(-0.0, 5.0, step=2.35)\n zloc = 0.0\n\n CIs = CartesianIndices((1:length(xloc), 1:length(yloc)))\n\n fig, axs = plt.subplots(length(xloc), length(yloc), sharex=true, sharey=true)\n\n for i in CIs\n loc = RE .* [xloc[i[1]], yloc[i[2]], zloc]\n vdfslice(meta, loc, axs[i]; verbose=false)\n end\n\n for a in axs[end,:] a.set_xlabel(\"vx [km/s]\") end\n for a in axs[: ,1] a.set_ylabel(\"vy [km/s]\") end\n\n ## Subtract data of cells with VDF\n\n file = \"test/data/bulk.1d.vlsv\"\n meta = load(file)\n\n cells = getcellwithvdf(meta)\n\n ρ = zeros(Float64, size(cells))\n v = zeros(Float64, 3, size(cells)...)\n p = zeros(Float64, size(cells))\n\n vsize = meta.meshes[\"proton\"].vblock_size .* meta.meshes[\"proton\"].vblocks\n vcellids = [Int[] for _ in cells]\n vcellf = [Float64[] for _ in cells]\n\n for (i, cell) in enumerate(cells)\n ρ[i] = readvariable(meta, \"proton/vg_rho\", cell)[1]\n v[i] = readvariable(meta, \"proton/vg_v\", cell)[1]\n p[i] = readvariable(meta, \"vg_pressure\", cell)[1]\n\n vcellids[i], vcellf[i] = readvcells(meta, cell)\n end\n\n jldopen(\"example.jld2\", \"a+\") do file\n file[\"file1/density\"] = ρ\n file[\"file1/velocity\"] = v\n file[\"file1/pressure\"] = p\n file[\"file1/VDF\"] = vcellf\n end\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/#demo_xpoints","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"","category":"section"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"This example shows how to find X-points in a 2D magnetic reconnection configuration and save the coordinates as well as extracted reconnection rate Ey from multiple outputs. Here we assume a X-Z plane.","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"using JLD2: jldsave\nusing Vlasiator, Glob, ProgressMeter\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n\n nG = 2 # number of ghost cells\n\n x, z, dx = load(files[1]) do meta\n LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1]) ./ Vlasiator.RE,\n LinRange(meta.coordmin[3], meta.coordmax[3], meta.ncells[3]) ./ Vlasiator.RE,\n [meta.dcoord[1], meta.dcoord[3]]\n end\n\n xmin_ = searchsortedfirst(x, 7.0)\n xmax_ = searchsortedlast(x, 9.0)\n zmin_ = searchsortedfirst(z, -4.0)\n zmax_ = searchsortedlast(z, 4.0)\n\n x_points_x = Vector{Vector{eltype(x)}}(undef, 0)\n x_points_z = similar(x_points_x)\n\n @showprogress 5 \"Finding X-points...\" for ifile in eachindex(files)\n meta = load(files[ifile])\n b = meta[\"vg_b_vol\"]\n b = reshape(b, 3, meta.ncells[1], meta.ncells[3])\n\n flux = compute_flux_function(b, dx, nG)\n indices_x, _ = find_reconnection_points(flux[xmin_:xmax_,zmin_:zmax_], 5e-3)\n\n push!(x_points_x, x[indices_x[1,:].+xmin_.-1])\n push!(x_points_z, z[indices_x[2,:].+zmin_.-1])\n end\n\n ## Extract Ey at X-points\n ey = Vector{Vector{Float32}}(undef, 0)\n\n for it in eachindex(x_points_x)\n meta = load(files[it])\n ids = Vector{Int}(undef, length(x_points_x[it]))\n for ip in eachindex(x_points_x[it])\n loc = [x_points_x[it][ip], 0.0, x_points_z[it][ip]] .* Vlasiator.RE\n ids[ip] = getcell(meta, loc)\n end\n ey_now = readvariable(meta, \"vg_e_vol\", ids)[2,:]\n push!(ey, ey_now)\n end\n\n # save\n jldsave(\"x_point_locations.jld2\"; x_points_x, x_points_z, ey)\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"internal/#Internal","page":"API Reference","title":"Internal","text":"","category":"section"},{"location":"internal/#Public-APIs","page":"API Reference","title":"Public APIs","text":"","category":"section"},{"location":"internal/","page":"API Reference","title":"API Reference","text":"Modules = [Vlasiator]\nPrivate = false\nOrder = [:constant, :type, :function]","category":"page"},{"location":"internal/#Vlasiator.MetaVLSV","page":"API Reference","title":"Vlasiator.MetaVLSV","text":"VLSV meta data.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Vlasiator.VarInfo","page":"API Reference","title":"Vlasiator.VarInfo","text":"Variable information from the VLSV footer.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Vlasiator.check_plasma_characteristics-NTuple{4, Any}","page":"API Reference","title":"Vlasiator.check_plasma_characteristics","text":"check_plasma_characteristics(n, v, T, B)\n\nDisplay characteristic plasma parameters given density n, bulk velocity v, temperature T, and magnetic field strength B in SI units.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.compute_flux_function-Union{Tuple{N}, Tuple{T}, Tuple{AbstractArray{T, N}, Vector{T}}, Tuple{AbstractArray{T, N}, Vector{T}, Int64}} where {T, N}","page":"API Reference","title":"Vlasiator.compute_flux_function","text":"compute_flux_function(b::AbstractArray{T,N}, Δ::Vector{T}, nG::Int=2) where {T,N}\n\nCalculate the 2D magnetic flux function ψ from the magnetic field b and discrete steps Δ. nG is the number of ghost cells along each dimension in the vector field. ψ is defined as psi = int B_x dz = - int B_z dx from mathbfB = hatytimesnablapsi in the X-Z plane and Y is the out-of-plane direction. This is strictly true if B is divergence-free and the guide field By is constant. However, numerically there will be errors. The current implementation calculates ψ by integrating along -z boundary first, and then going along z. Reference: Flux function\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.extractsat-Tuple{AbstractVector{String}, String, Int64}","page":"API Reference","title":"Vlasiator.extractsat","text":"extractsat(files::AbstractVector{String}, var::String, cid::Int)\n\nMulti-threaded extraction of var at a fixed cell ID cid from files. This assumes that files come from the same grid structure.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.find_reconnection_points-Union{Tuple{Matrix{T}}, Tuple{T}} where T","page":"API Reference","title":"Vlasiator.find_reconnection_points","text":"find_reconnection_points(ψ::Array{T,2}; retol::Float64=1e-4,\n method::Int=1) -> indices_x, indices_o\n\nFind X-point and O-point indices in 2D magnetic field topology from flux function ψ. The current implementation does not work for the 3 layers near the boundary.\n\nKeywords\n\nretol=1e-1: determines the relative tolerance of the ratio w.r.t. |∇ψ|² to accept a gradient as 0.\nmethod=1: method 1 compute the cell-centered 1st and 2nd order derivatives and check the Hessian matrix; method 2 check the flux function at each point against its 8 neighbors, which is more deterministic.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getKLdivergence-Tuple{MetaVLSV, Array{<:AbstractFloat}}","page":"API Reference","title":"Vlasiator.getKLdivergence","text":"getKLdivergence(meta, VDF; species=\"proton\")\ngetKLdivergence(meta, vcellids, vcellf; species=\"proton\")\n\nObtain the KL-divergence ∫ f*log(f/g)dv, where f is the VDF from Vlasiator and g is the analytical Maxwellian distribution that generates the same density as f. The value ranges from [0, +∞], with 0 meaning perfect Maxwellian. Usually the values are quite small. Alternatively, one can pass original vcellids and vcellf directly.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getcell-Tuple{MetaVLSV, AbstractVector{<:AbstractFloat}}","page":"API Reference","title":"Vlasiator.getcell","text":"getcell(meta::MetaVLSV, location:::AbstractVector{<:AbstractFloat}) -> Int\n\nReturn cell ID containing the given spatial location in meter, excluding domain boundaries. Only accept 3D location.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getcellcoordinates-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getcellcoordinates","text":"getcellcoordinates(meta::MetaVLSV, cid::Int) -> SVector{3,Float64}\n\nReturn a given cell's spatial coordinates.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getcellinline-Union{Tuple{T}, Tuple{MetaVLSV, Vector{T}, Vector{T}}} where T","page":"API Reference","title":"Vlasiator.getcellinline","text":"getcellinline(meta, point1::Vector, point2::Vector) -> cellids, distances, coords\n\nReturns cell IDs, distances and coordinates for every cell in a line between two given points point1 and point2. TODO: preallocation?\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getcellwithvdf","page":"API Reference","title":"Vlasiator.getcellwithvdf","text":"getcellwithvdf(meta, species::String=\"proton\") -> cellids\n\nGet all the cell IDs with VDF saved associated with meta.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.getchildren-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getchildren","text":"getchildren(meta::MetaVLSV, cid::Int) -> Vector{Int}\n\nReturn direct children of cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getdensity-Union{Tuple{T}, Tuple{MetaVLSV, Array{T}}} where T<:AbstractFloat","page":"API Reference","title":"Vlasiator.getdensity","text":"getdensity(meta, VDF; species=\"proton\")\ngetdensity(meta, vcellf; species=\"proton\")\ngetdensity(vmesh::VMeshInfo, vcellf)\n\nGet density from VDF of species associated with meta, n = ∫ f(r,v) dV. Alternatively, one can directly pass vcellids as original indices of nonzero VDFs and vcellf as their corresponding values.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getheatfluxvector-Union{Tuple{T}, Tuple{MetaVLSV, Array{T}}} where T<:AbstractFloat","page":"API Reference","title":"Vlasiator.getheatfluxvector","text":"getheatfluxvector(meta, VDF; species=\"proton\")\ngetheatfluxvector(meta, vcellids, vcellf; species=\"proton\")\ngetheatfluxvector(vmesh::VMeshInfo, vcellids, vcellf)\n\nGet heat flux vector (3 components) of species from VDF associated with meta, qᵢ = m/2 * ∫ (v - u)²(v - u)ᵢ * f(r,v) dV. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getlevel-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getlevel","text":"getlevel(meta::MetaVLSV, cid::Int) -> Int\n\nReturn the AMR level of a given cell ID cid.\n\nwarning: Warning\nThis function does not check if the VLSV file of meta actually contains cid; it may be shadowed by refined children.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getmaxwellianity-Tuple{MetaVLSV, Array{<:AbstractFloat}}","page":"API Reference","title":"Vlasiator.getmaxwellianity","text":"getmaxwellianity(meta, VDF; species=\"proton\")\ngetmaxwellianity(meta, vcellids, vcellf; species=\"proton\")\n\nObtain the Maxwellian similarity factor -log(1/(2n) * ∫ |f - g| dv), where f is the VDF from Vlasiator and g is the analytical Maxwellian distribution that generates the same density as f. The value ranges from [0, +∞], with 0 meaning not Maxwellian-distributed at all, and +∞ a perfect Maxwellian distribution. Alternatively, one can pass original vcellids and vcellf directly.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getnearestcellwithvdf","page":"API Reference","title":"Vlasiator.getnearestcellwithvdf","text":"getnearestcellwithvdf(meta, id::Int, species::String=\"proton\") -> Int\n\nFind the nearest spatial cell with VDF saved for species of a given cell id associated with meta.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.getparent-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getparent","text":"getparent(meta::MetaVLSV, cid::Int) -> Int\n\nReturn the parent cell ID of given child cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getpressure-Union{Tuple{T}, Tuple{MetaVLSV, Array{T}}} where T<:AbstractFloat","page":"API Reference","title":"Vlasiator.getpressure","text":"getpressure(meta, VDF; species=\"proton\")\ngetpressure(meta, vcellids, vcellf; species=\"proton\")\ngetpressure(vmesh::VMeshInfo, vcellids, vcellf)\n\nGet pressure tensor (6 components: Pxx, Pyy, Pzz, Pyz, Pzx, Pxy) of species from VDF associated with meta, pᵢⱼ = m * ∫ (v - u)ᵢ(v - u)ⱼ * f(r,v) dV. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getsiblings-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getsiblings","text":"getsiblings(meta::MetaVLSV, cid::Int) -> Vector{Int}\n\nReturn sibling cells of a given cid, including itself.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getslicecell-Tuple{MetaVLSV, Float64, Int64, Float64, Float64}","page":"API Reference","title":"Vlasiator.getslicecell","text":"getslicecell(meta, sliceoffset, dir, minCoord, maxCoord) -> idlist, indexlist\n\nFind the cell IDs idlist which are needed to plot a 2d cut through of a 3d mesh, in a direction dir at sliceoffset, and the indexlist, which is a mapping from original order to the cut plane and can be used to select data onto the plane.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getvcellcoordinates-Tuple{MetaVLSV, Vector{Int32}}","page":"API Reference","title":"Vlasiator.getvcellcoordinates","text":"getvcellcoordinates(meta::MetaVLSV, vcellids::Vector; species=\"proton\")\n\nReturn velocity cells' coordinates of species and vcellids.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getvelocity-Union{Tuple{T}, Tuple{MetaVLSV, Array{T}}} where T<:AbstractFloat","page":"API Reference","title":"Vlasiator.getvelocity","text":"getvelocity(meta, VDF; species=\"proton\")\ngetvelocity(meta, vcellids, vcellf; species=\"proton\")\ngetvelocity(vmesh::VMeshInfo, vcellids, vcellf)\n\nGet bulk velocity from VDF of species, u = ∫ v * f(r,v) dV / n. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.hasname-Tuple{SubArray{XML.Node, 1, Vector{XML.Node}, Tuple{UnitRange{Int64}}, true}, String}","page":"API Reference","title":"Vlasiator.hasname","text":"Check if the XML nodes ns contain a node of name.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.hasparameter-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.hasparameter","text":"hasparameter(meta::MetaVLSV, param::String) -> Bool\n\nCheck if the VLSV file contains a certain parameter param.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.hasvariable-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.hasvariable","text":"hasvariable(meta::MetaVLSV, var::String) -> Bool\n\nCheck if the VLSV file associated with meta contains a variable var.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.isparent-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.isparent","text":"isparent(meta::MetaVLSV, cid::Int) -> Bool\n\nCheck if cid is a parent cell.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.issame","page":"API Reference","title":"Vlasiator.issame","text":"issame(file1, file2, tol=1e-4; strict=true, verbose=false) -> Bool\n\nCheck if two VLSV files file1 and file2 are approximately identical, under relative tolerance tol. If strict=true, the file size difference should be less than 1%.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.load-Tuple{AbstractString}","page":"API Reference","title":"Vlasiator.load","text":"load(file::AbstractString)) -> MetaVLSV\n\nGenerate a MetaVLSV object from file of VLSV format.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readlog-Tuple{AbstractString}","page":"API Reference","title":"Vlasiator.readlog","text":"readlog(file::AbstractString)\n\nRead the run log file, check the iteration status and return the timestamps (exluding the last) as well as the model running speed in physical seconds per simulated seconds.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readparameter-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.readparameter","text":"readparameter(meta::MetaVLSV, param::String)\n\nReturn the parameter value from the VLSV file associated with meta.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvariable","page":"API Reference","title":"Vlasiator.readvariable","text":"readvariable(meta::MetaVLSV, var::String, sorted::Bool=true, usemmap::Bool=false) -> Array\n\nReturn variable value of var from the VLSV file associated with meta. By default for DCCRG variables are sorted by cell ID. usemmap decides whether to use memory-mapped IO, which is especially useful for large arrays.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.readvariable-Tuple{MetaVLSV, String, Int64}","page":"API Reference","title":"Vlasiator.readvariable","text":"readvariable(meta::MetaVLSV, var::String, cid::Int) -> Array\n\nRead variable var in cell cid associated with meta.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvariable-Tuple{MetaVLSV, String, Vector{Int64}}","page":"API Reference","title":"Vlasiator.readvariable","text":"readvariable(meta::MetaVLSV, var::String, ids::Vector{Int}) -> Array\n\nRead variable var in a collection of cells ids associated with meta. if ids is empty, return the whole sorted array of var.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvariablemeta-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.readvariablemeta","text":"readvariablemeta(meta, var) -> VarInfo\n\nReturn VarInfo of var in the VLSV file associated with meta.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvcells-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.readvcells","text":"readvcells(meta::MetaVLSV, cid::Int; species=\"proton\") -> vcellids, vcellf\n\nRead velocity cells of species from a spatial cell of ID cid associated with meta, and return a map of velocity cell ids vcellids and corresponding value vcellf.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.refineslice-Tuple{MetaVLSV, Vector{Int64}, AbstractVector, Symbol}","page":"API Reference","title":"Vlasiator.refineslice","text":"refineslice(meta, idlist::Vector{Int}, data::AbstractVector, normal::Symbol) -> Vector\nrefineslice(meta, idlist::Vector{Int}, data::AbstractMatrix, normal::Symbol) -> Matrix\nrefineslice(meta, idlist::Vector{Int}, data::AbstractArray, dir::Int)\n\nGenerate data on the finest refinement level given cellids idlist and variable data on the slice perpendicular to normal. If data is 2D, then the first dimension is treated as vector components.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.write_vlsv-Tuple{AbstractString, AbstractString, Vector{Tuple{VecOrMat, String, VarInfo}}}","page":"API Reference","title":"Vlasiator.write_vlsv","text":"write_vlsv(filein, fileout, newvars::Vector{Tuple{Vector, String, VarInfo}};\n force=false)\n\nGenerate a new VLSV fileout based on filein, with newvars added. force=true overwrites the existing fileout.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.write_vtk-Tuple{MetaVLSV}","page":"API Reference","title":"Vlasiator.write_vtk","text":"write_vtk(meta::MetaVLSV; kwargs...)\nwrite_vtk(file::AbstractString; kwargs...)\n\nConvert VLSV file to VTK format.\n\nKeywords\n\nvars::Vector{String}=[\"\"]: select which variables to convert.\nascii::Bool=false: output stored in ASCII or compressed binary format.\nmaxamronly::Bool=false: generate image files on the highest refinement level only.\nbox::Vector: selected box range in 3D.\noutdir::String=\"\": output directory.\nverbose::Bool=false: display logs during conversion.\n\n\n\n\n\n","category":"method"},{"location":"internal/#PyPlot-Wrapper-APIs","page":"API Reference","title":"PyPlot Wrapper APIs","text":"","category":"section"},{"location":"internal/","page":"API Reference","title":"API Reference","text":"Modules = [VlasiatorPyPlot]\nPages = [\"VlasiatorPyPlot.jl\"]","category":"page"},{"location":"internal/#Private-APIs","page":"API Reference","title":"Private APIs","text":"","category":"section"},{"location":"internal/","page":"API Reference","title":"API Reference","text":"Modules = [Vlasiator]\nPublic = false","category":"page"},{"location":"internal/#Vlasiator.AxisUnit","page":"API Reference","title":"Vlasiator.AxisUnit","text":"Axis unit type. Currently supported: SI, EARTH.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Vlasiator.ColorScale","page":"API Reference","title":"Vlasiator.ColorScale","text":"Color scales type for 2D plots. Currently supported: Log, Linear, SymLog.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Vlasiator.PlotArgs","page":"API Reference","title":"Vlasiator.PlotArgs","text":"Plotting arguments.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Vlasiator.VMeshInfo","page":"API Reference","title":"Vlasiator.VMeshInfo","text":"Velocity mesh information.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Base.isopen-Tuple{MetaVLSV}","page":"API Reference","title":"Base.isopen","text":"Determine whether meta is not yet closed.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Base.ndims-Tuple{MetaVLSV}","page":"API Reference","title":"Base.ndims","text":"ndims(meta::MetaVLSV) -> Int\n\nReturn the simulation spatial dimension of VLSV data.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Base.size-Tuple{MetaVLSV}","page":"API Reference","title":"Base.size","text":"File size in bytes.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.curl-Union{Tuple{U}, Tuple{N}, Tuple{T}, Tuple{AbstractArray{T, N}, Union{Vector{U}, Tuple{U, U, U}}}} where {T, N, U}","page":"API Reference","title":"Vlasiator.curl","text":"curl(A::AbstractArray{T,N}, dx:Union{Vector{U}, NTuple{3,U}}) where {T,N,U}\n\nCalculate 2nd order cell-centered ∇×A where A is a 4D array of size (3, nx, ny, nz) and dx is a vector of grid intervals in each dimension.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.divergence-Union{Tuple{AbstractArray{T, N}}, Tuple{U}, Tuple{N}, Tuple{T}, Tuple{AbstractArray{T, N}, Vector{U}}} where {T, N, U}","page":"API Reference","title":"Vlasiator.divergence","text":"divergence(A::AbstractArray{T,N}, dx::Vector{U}=ones(T, 3)) where {T,N,U}\n\nCalculate 2nd order cell-centered ∇⋅A where A is a 4D array of size (3, nx, ny, nz) and dx is a vector of grid intervals in each dimension.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.downsample_fg-Tuple{MetaVLSV, Array}","page":"API Reference","title":"Vlasiator.downsample_fg","text":"downsample_fg(meta::MetaVLSV, v_fg::Array)\ndownsample_fg(meta::MetaVLSV, var::String)\n\nDownsample a field solver array v_fg to the spatial grid associated with meta.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.downsample_fg_cell-Tuple{MetaVLSV, Array, Int64}","page":"API Reference","title":"Vlasiator.downsample_fg_cell","text":"Return a field solver grid subarray contained inside spatial cell cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.fillmesh-Tuple{MetaVLSV, Vector{String}}","page":"API Reference","title":"Vlasiator.fillmesh","text":"fillmesh(meta::MetaVLSV, vars::Vector{String};\n skipghosttype=true, maxamronly=false, verbose=false) -> celldata, vtkGhostType\n\nFill the DCCRG mesh with quantity of vars on all refinement levels.\n\nReturn arguments\n\ncelldata::Vector{Vector{Array}}: data for each variable on each AMR level.\nvtkGhostType::Array{UInt8}: cell status (to be completed!).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.findindex-Tuple{Int32, Tuple{Int64, Int64, Int64}, Tuple{Int64, Int64, Int64}, Int64, Tuple{Int64, Int64, Int64}, Int64, Int64}","page":"API Reference","title":"Vlasiator.findindex","text":"Get the original vcell index without blocks from raw vcell index i (0-based).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get1stcell-Tuple{Int64, Int64}","page":"API Reference","title":"Vlasiator.get1stcell","text":"Return the first cell ID on mylevel given ncells on this level.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getDomainDecomposition-Tuple{Any, Any}","page":"API Reference","title":"Vlasiator.getDomainDecomposition","text":"getDomainDecomposition(globalsize, nprocs)\n\nObtain decomposition of this grid over the given number of processors. Reference: fsgrid.hpp\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getObjInfo-Tuple{Vector{XML.Node}, String, String, String}","page":"API Reference","title":"Vlasiator.getObjInfo","text":"General inquiry of element tag with tagname and attr.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getRotationMatrix-Tuple{AbstractMatrix, AbstractMatrix}","page":"API Reference","title":"Vlasiator.getRotationMatrix","text":"getRotationMatrix(e1::Matrix, e2::Matrix) -> SMatrix{3,3}\n\nObtain the rotation matrix from orthgonal base vectors e1 to e2, such that a vector mathbfu_1 in e1 can be expressed as mathbfu_1 = Mcdot mathbfu_2, where M is the rotation matrix and mathbfu_2 is the same vector in e2.\n\nExample\n\ne1 = [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0]\ne2 = [0.0 1.0 0.0; 1.0 0.0 0.0; 0.0 0.0 1.0]\nR = getRotationMatrix(e1, e2)\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getRotationMatrix-Tuple{AbstractVector{<:AbstractFloat}, Real}","page":"API Reference","title":"Vlasiator.getRotationMatrix","text":"getRotationMatrix(axis::AbstractVector, angle::Real) --> SMatrix{3,3}\n\nCreate a rotation matrix for rotating a 3D vector around a unit axis by an angle in radians. Reference: Rotation matrix from axis and angle\n\nExample\n\nusing LinearAlgebra\nv = [-0.5, 1.0, 1.0]\nv̂ = normalize(v)\nθ = deg2rad(-74)\nR = getRotationMatrix(v̂, θ)\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_axis-Tuple{Vlasiator.AxisUnit, NTuple{4, var\"#s166\"} where var\"#s166\"<:Real, Tuple{var\"#s165\", var\"#s165\"} where var\"#s165\"<:Integer}","page":"API Reference","title":"Vlasiator.get_axis","text":"get_axis(axisunit::AxisUnit, plotrange::NTuple{4,<:Real}, sizes::NTuple{2,<:Integer})\nget_axis(pArgs::PlotArgs)\n\nReturn x and y ranges for 2D.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_fg_array_cell-Tuple{MetaVLSV, Array, Int64}","page":"API Reference","title":"Vlasiator.get_fg_array_cell","text":"get_fg_array_cell(meta::MetaVLSV, v_fg::Array, cid::Int)\n\nReturn a subarray of the field solver grid array, corresponding to the fsgrid covered by the spatial cell ID cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_fg_indices-Tuple{MetaVLSV, StaticArraysCore.SVector{3, Float64}}","page":"API Reference","title":"Vlasiator.get_fg_indices","text":"Return the field solver grid cell indexes containing coords (low-inclusive).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_fg_indices_cell-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.get_fg_indices_cell","text":"Returns a slice tuple of fsgrid indices that are contained in the spatial cell cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_fg_indices_subvolume","page":"API Reference","title":"Vlasiator.get_fg_indices_subvolume","text":"get_fg_indices_subvolume(meta::MetaVLSV, lower, upper, tol::Float64=1e-3)\n\nGet indices for subarray of fsgrid variables, in a cuboid defined by lower and upper vertices. This is used for mapping a set of fsgrid cells to a given DCCRG cell. Shift the corners (lower, upper) inward by a distance controlled by tol. If direct low-inclusive behaviour is required, tol shall be set to 0.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.getdata2d-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.getdata2d","text":"getdata2d(meta::MetaVLSV, var::String)\n\nReturn 2d scalar/vector data. Nonpublic since it won't work with DCCRG AMR.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getfooter-Tuple{IOStream}","page":"API Reference","title":"Vlasiator.getfooter","text":"Return the XML footer of opened VLSV file.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getindexes-NTuple{5, Int64}","page":"API Reference","title":"Vlasiator.getindexes","text":"Compute x, y and z index of cell id on a given refinement level ilevel(0-based).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getindexes-Tuple{Int64, Int64, Int64, Int64, AbstractVector{Int64}}","page":"API Reference","title":"Vlasiator.getindexes","text":"Compute x, y and z indexes of all cell ids on the given refinement level (0-based).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.gradient-Union{Tuple{U}, Tuple{N}, Tuple{T}, Tuple{AbstractArray{T, N}, Vector{U}}} where {T, N, U}","page":"API Reference","title":"Vlasiator.gradient","text":"gradient(A::AbstractArray{T,N}, dx::Vector{U}) where {T,N,U}\n\nCalculate 2nd order cell-centered ∇A where A is a scalar array and dx is a vector of grid intervals in each dimension.\n\nwarning: Warning\nThe current implementation has issues at the boundary if gradient is taken multiple times.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.isextrema-Tuple{Any}","page":"API Reference","title":"Vlasiator.isextrema","text":"Check if the center point in a 3x3 matrix ψ is an extrema point.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.issaddle-Tuple{Any}","page":"API Reference","title":"Vlasiator.issaddle","text":"Check if the center point in a 3x3 matrix ψ is a saddle point.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.prep1d-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.prep1d","text":"prep1d(meta::MetaVLSV, var::String; i1::Int=0, i2::Int=0, comp::Int=0) -> Array\n\nObtain a 1D slice from 2D meta of var. i1 is the index for the first dimension, and i2 is the index for the second dimension; only one of them is needed. Use comp to select vector components.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.prep2d","page":"API Reference","title":"Vlasiator.prep2d","text":"prep2d(meta::MetaVLSV, var::String, comp::Union{Symbol, Int}=0) -> Array\n\nObtain data from meta of var for 2D plotting. Use comp to select vector components.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.prep2dslice-Tuple{MetaVLSV, String, Symbol, Union{Int64, Symbol}, Vlasiator.PlotArgs}","page":"API Reference","title":"Vlasiator.prep2dslice","text":"prep2dslice(meta::MetaVLSV, var::String, normal, comp, pArgs::PlotArgs)\n\nReturn data of var on a uniform 2D mesh on the finest AMR level. Use normal to select the plane orientation, and comp to select the component of a vector, same as in pcolormesh.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.prep_vdf-Tuple{MetaVLSV, AbstractVector}","page":"API Reference","title":"Vlasiator.prep_vdf","text":"prep_vdf(meta::MetaVLSV, location::AbstractVector; kwargs...)\n\nReturn the cell velocities v1, v2, bin ranges r1, r2, cell VDF values fweight, and strings of labels and titles for VDF plots.\n\nKeywords\n\nunit::AxisUnit: location unit in SI, EARTH.\nunitv::String: velocity unit in (\"km/s\", \"m/s\").\nlimits::Vector{Real}: velocity space range given in [xmin, xmax, ymin, ymax].\nslicetype: symbol for choosing the slice type from :xy, :xz, :yz, :bperp, :bpar1, :bpar2.\ncenter: symbol for setting the reference frame from :bulk, :peak.\nvslicethick: setting the velocity space slice thickness in the normal direction. If set to 0, the whole distribution along the normal direction is projected onto a plane. Currently this is only meaningful when center is set such that a range near the bulk/peak normal velocity is selected.\nweight::Symbol: choosing distribution weights from phase space density or particle flux between :particle and :flux.\nflimit: minimum VDF threshold for plotting.\nverbose: display the selection process.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.read_variable_as_fg-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.read_variable_as_fg","text":"read_variable_as_fg(meta::MetaVLSV, var::String)\n\nInterpolate DCCRG variable var to field solver grid size. This is an alternative method to fillmesh, but not optimized for performance.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readmesh-Tuple{IOStream, Vector{XML.Node}}","page":"API Reference","title":"Vlasiator.readmesh","text":"Return spatial mesh information.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvector-Union{Tuple{T}, Tuple{IOStream, Type{T}, Int64, Int64, Int64, Val{false}}} where T","page":"API Reference","title":"Vlasiator.readvector","text":"Return vector of name from the VLSV file associated with stream fid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvmesh-Tuple{IOStream, Vector{XML.Node}, String}","page":"API Reference","title":"Vlasiator.readvmesh","text":"Return velocity mesh information.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.reconstruct-Tuple{Vlasiator.VMeshInfo, Vector{Int32}, Vector{<:AbstractFloat}}","page":"API Reference","title":"Vlasiator.reconstruct","text":"reconstruct(vmesh::VMeshInfo, vcellids::Vector{Int32}, vcellf::Vector{<:AbstractFloat})\n\nReconstruct the full VDFs in 3D. vcellids are raw indices of nonzero VDFs ordered by blocks, and vcellf are the corresponding values in each cell.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.reorder-Tuple{Vlasiator.VMeshInfo, Vector{Int32}}","page":"API Reference","title":"Vlasiator.reorder","text":"reorder(vmesh::VMeshInfo, vcellids::Vector{Int32}) -> vcellids_origin\n\nReorder vblock-organized VDF indexes into x–>y–>z indexes. vcellids are raw indices of nonzero VDFs ordered by blocks.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.rotateTensorToVectorZ-Union{Tuple{T}, Tuple{AbstractMatrix{T}, AbstractVector{T}}} where T","page":"API Reference","title":"Vlasiator.rotateTensorToVectorZ","text":"rotateTensorToVectorZ(tensor::AbstractMatrix, vector::AbstractVector) -> SMatrix{3,3}\n\nRotate tensor with a rotation matrix that aligns the 3rd direction with vector, which is equivalent to change the basis from (i,j,k) to (i′,j′,k′) where k′ ∥ vector. Reference: Tensor rotation\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.save_image","page":"API Reference","title":"Vlasiator.save_image","text":"save_image(meta::MetaVLSV, file, vars, data, vtkGhostType, level,\n ascii=false, append=true, box=[-Inf, Inf, -Inf, Inf, -Inf, Inf])\n\nSave data of name vars at AMR level into VTK image file of name file.\n\nArguments\n\nfile::String: output file name.\nvars::Vector{String}: variable names to be saved.\ndata::Vector{Vector{Array}}: data for all the variables on each refinement level.\nvtkGhostType::Array{UInt8}: array for visibility control.\nlevel::Int: refinement level (0-based).\nascii::Bool=false: save output in ASCII or binary format.\nappend::Bool=true: determines whether to append data at the end of file or do in-block writing.\nbox::Vector: selected box range in 3D.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.set_args-Tuple{MetaVLSV, String, Vlasiator.AxisUnit}","page":"API Reference","title":"Vlasiator.set_args","text":"set_args(meta::MetaVLSV, var::String, axisunit::AxisUnit;\n normal::Symbol=:none, origin=0.0)\n\nSet plot-related arguments of var in axisunit. normal and origin are used for 2D slices of 3D data, as specified in pcolormesh.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.set_lim-Union{Tuple{T}, Tuple{T, T, Any}, Tuple{T, T, Any, Vlasiator.ColorScale}} where T","page":"API Reference","title":"Vlasiator.set_lim","text":"set_lim(vmin, vmax, data, colorscale=Linear)\n\nSet colormap limits vmin, vmax for data under scale colorscale.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.upsample_fsgrid_subarray!-Union{Tuple{T}, Tuple{MetaVLSV, Any, Int64, Array{T, 4}}} where T","page":"API Reference","title":"Vlasiator.upsample_fsgrid_subarray!","text":"Set the elements of the fsgrid array to the value of corresponding cell ID cid.\n\n\n\n\n\n","category":"method"},{"location":"examples/visualization/demo_B_fieldline_pyplot/#demo_2d_fieldlines","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"","category":"section"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"This demo shows how to plot field lines with handpicked seeds.","category":"page"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"using VlasiatorPyPlot, FieldTracer\nusing Vlasiator: RE # Earth radius, [m]\n\nfunction main()\n file = \"../../bulk.0000999.vlsv\"\n meta = load(file)\n (;coordmin, coordmax, ncells) = meta\n pcolormesh(meta, \"proton/vg_rho\", colorscale=Linear)\n\n dim_ =\n if ncells[2] == 1\n (1,3)\n elseif ncells[3] == 1\n (1,2)\n else\n @error \"Not implemented for ncells = $ncells.\"\n end\n\n # NonAMR Cartesian mesh\n grid1 = range(coordmin[dim_[1]], coordmax[dim_[1]], length=ncells[dim_[1]])\n grid2 = range(coordmin[dim_[2]], coordmax[dim_[2]], length=ncells[dim_[2]])\n\n ns1 = 14 # number of seeding points on the dayside\n ns2 = 10 # number of seeding points on the nightside\n ns4 = 4 # number of seeding points in the polar region\n seeds = Matrix{Float64}(undef, 2, ns1+2*ns2+2*ns4)\n\n for i in 1:ns1\n seeds[1,i] = coordmax[dim_[1]] / ns1 * (i - 1)\n seeds[2,i] = 0.0\n end\n\n for i in 1:ns2\n seeds[1,ns1+i] = -10RE\n seeds[2,ns1+i] = coordmin[dim_[2]] +\n (coordmax[dim_[2]] - coordmin[dim_[2]]) / ns2 * (i - 1)\n seeds[1,ns1+ns2+i] = -30RE\n seeds[2,ns1+ns2+i] = coordmin[dim_[2]] +\n (coordmax[dim_[2]] - coordmin[dim_[2]]) / ns2 * (i - 1)\n end\n\n for i in 1:ns4\n seeds[1,ns1+2*ns2+i] = -20RE + 10RE*(i - 1)\n seeds[2,ns1+2*ns2+i] = 30RE\n seeds[1,ns1+2*ns2+ns4+i] = -20RE + 10RE*(i - 1)\n seeds[2,ns1+2*ns2+ns4+i] = -30RE\n end\n\n b = meta[\"vg_b_vol\"]\n b1 = reshape(b[dim_[1],:], ncells[dim_[1]], ncells[dim_[2]])\n b2 = reshape(b[dim_[2],:], ncells[dim_[1]], ncells[dim_[2]])\n\n for i = axes(seeds,2)\n startx, starty = seeds[:,i]\n x1, y1 = trace(b1, b2, startx, starty, grid1, grid2;\n ds=0.5, maxstep=3000, gridtype=\"ndgrid\")\n x1 ./= RE\n y1 ./= RE\n if length(x1) < 5; continue; end\n line = plot(x1, y1, color=\"w\")\n add_arrow(line[1])\n end\n\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"","category":"page"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/#demo_2d_trace","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"","category":"section"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"This demo shows how to trace streamlines in a 2D uniform field.","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"using VlasiatorPyPlot, FieldTracer\nusing Vlasiator: RE # Earth radius, [m]\n\nfunction main()\n file = \"bulk.0000501.vlsv\"\n nameρ = \"rho\"\n nameV = \"rho_v\"\n\n meta = load(file)\n\n pcolormesh(meta, nameρ)\n\n v = readvariable(meta, nameV)\n vx = reshape(v[1,:], meta.ncells[1], meta.ncells[2])\n vy = reshape(v[2,:], meta.ncells[1], meta.ncells[2])\n # tracing starting point\n xstart, ystart = 12RE, 0RE\n # regular Cartesian mesh\n x = range(meta.coordmin[1], meta.coordmax[1], length=meta.ncells[1])\n y = range(meta.coordmin[2], meta.coordmax[2], length=meta.ncells[2])\n\n # RK4 scheme by default\n x1, y1 = trace2d(vx, vy, xstart, ystart, x, y;\n ds=0.5, maxstep=3000, gridType=\"ndgrid\")\n x1 ./= RE\n y1 ./= RE\n\n plot(x1, y1)\n\n streamplot(meta, nameV, comp=\"xy\", color=\"w\", density=1.0)\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/#demo_line_extract_mp","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"","category":"section"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"This demos shows how to extract multiple variables alone a line across multiple frames with multi-processing.","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"tip: Tip\nThis can be made faster by updating the data without deleting the lines.","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"Usage:","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"julia -p $ncores demo_vars_extracting_mp.jl","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"using Distributed, ParallelDataTransfer, Glob\nusing Vlasiator: RE\n@everywhere using Vlasiator, PyPlot, Printf\n\n@everywhere function init_figure(x1, x2)\n fig, axs = plt.subplots(4, 1; num=myid(),\n figsize=(10, 15), sharex=true, constrained_layout=true)\n\n axs[end].set_xlim(x1, x2)\n\n axs[1].set_ylim(ρmin, ρmax)\n axs[2].set_ylim(vmin, vmax)\n axs[3].set_ylim(pmin, pmax)\n axs[4].set_ylim(bmin, bmax)\n for ax in axs\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axs[end].set_xlabel(\"x [RE]\"; fontsize)\n axs[1].set_ylabel(\"Density [amu/cc]\"; fontsize)\n axs[2].set_ylabel(\"Velocity [km/s]\"; fontsize)\n axs[3].set_ylabel(\"Pressure [nPa]\"; fontsize)\n axs[4].set_ylabel(\"Magnetic field [nT]\"; fontsize)\n return fig, axs\nend\n\n@everywhere function process(axs, file, cellids)\n isfile(\"out/\"*file[end-8:end-5]*\".png\") && return\n\n println(\"file = $file\")\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1e9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1e9 # [nPa]\n\n bz = readvariable(meta, \"vg_b_vol\", cellids)[3,:] .* 1e9 #[nT]\n\n imagnetopause_ = findfirst(<(0.0), bz)\n\n axs[1].plot(loc, rho_extract ./ 1e6, label=\"Proton density\", color=\"#1f77b4\")\n vl1 = axs[1].vlines(loc[imagnetopause_], ρmin, ρmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[2].plot(loc, v_extract[1,:] ./ 1e3, label=\"Vx\", color=\"#1f77b4\")\n vl2 = axs[2].vlines(loc[imagnetopause_], vmin, vmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[3].plot(loc, pram_extract, label=\"Ram\", color=\"#1f77b4\")\n axs[3].plot(loc, p_extract, label=\"Thermal\", color=\"#ff7f0e\")\n vl3 = axs[3].vlines(loc[imagnetopause_], pmin, pmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[4].plot(loc, bz, label=\"Bz\", color=\"#1f77b4\")\n hl4 = axs[4].hlines(0.0, loc[1], loc[end], colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n vl4 = axs[4].vlines(loc[imagnetopause_], bmin, bmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n str_title = @sprintf \"t= %4.1fs\" meta.time\n axs[1].set_title(str_title; fontsize)\n\n axs[2].legend(;loc=\"upper right\", fontsize)\n axs[3].legend(;loc=\"upper left\", fontsize)\n axs[4].legend(;loc=\"upper right\", fontsize)\n\n savefig(\"out/\"*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n\n for ax in axs\n for line in ax.get_lines()\n line.remove()\n end\n end\n for line in (vl1, vl2, vl3, vl4, hl4)\n line.remove()\n end\n return\nend\n\nfunction make_jobs(files)\n for f in files\n put!(jobs, f)\n end\nend\n\n@everywhere function do_work(jobs, results)\n fig, axs = init_figure(x1, x2)\n while true\n file = take!(jobs)\n process(axs, file, cellids)\n put!(results, true)\n end\n close(fig)\nend\n\n################################################################################\nfiles = glob(\"bulk*.vlsv\", \".\")\nnfile = length(files)\n\nconst x1, x2 = 8.0, 29.0\nconst point1 = [x1, 0, 0] .* RE\nconst point2 = [x2, 0, 0] .* RE\n\nmeta = load(files[1])\ncellids, _, _ = getcellinline(meta, point1, point2)\nclose(meta.fid)\n\npassobj(1, workers(), [:x1, :x2, :cellids])\n\n@broadcast begin\n const loc = range(x1, x2, length=length(cellids))\n\n const ρmin, ρmax = 0.0, 10.0 # [amu/cc]\n const vmin, vmax = -640.0, 0.0 # [km/s]\n const pmin, pmax = 0.0, 1.82 # [nPa]\n const bmin, bmax = -25.0, 60.0 # [nT]\n\n const fontsize = 14\nend\n\nconst jobs = RemoteChannel(()->Channel{String}(nfile))\nconst results = RemoteChannel(()->Channel{Bool}(nworkers()))\n\nprintln(\"Total number of files: $nfile\")\nprintln(\"Running with $(nworkers()) workers...\")\n\n@async make_jobs(files) # Feed the jobs channel with all files to process.\n\n@sync for p in workers()\n @async remote_do(do_work, p, jobs, results)\nend\n\nlet n = nfile\n t = @elapsed while n > 0 # wait for all jobs to complete\n take!(results)\n n -= 1\n end\n println(\"Finished in $(round(t, digits=2))s.\")\nend","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/#demo_extractline","page":"Extract variables along a line","title":"Extract variables along a line","text":"","category":"section"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"To extract variables along a line across multiple frames using multithreads,","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"using Vlasiator, Glob\nusing JLD2: jldsave\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n nfile = length(files)\n # Define end points of the line in Earth radius\n x1, x2 = 6.0, 20.0\n point1 = [x1, 0, 0] .* Vlasiator.RE\n point2 = [x2, 0, 0] .* Vlasiator.RE\n # Extract cell info along the line\n cellids, distances, coords =\n load(files[1]) do meta\n getcellinline(meta, point1, point2)\n end\n # WARNING: this may not be exact due to round-off errors in output time stamps!\n t = let tstart = load(files[1]).time, tend = load(files[end]).time\n range(round(tstart,digits=1), round(tend, digits=1), length=nfile)\n end\n\n n = zeros(Float32, length(cellids), nfile)\n v = zeros(Float32, 3, length(cellids), nfile)\n p = zeros(Float32, 6, length(cellids), nfile)\n b = similar(v)\n e = similar(v)\n\n Threads.@threads for i in eachindex(files)\n println(\"i = $i/$nfile, file = $(files[i])\")\n local meta = load(files[i])\n\n n[:,i] = readvariable(meta, \"proton/vg_rho\", cellids)\n v[:,:,i] = readvariable(meta, \"proton/vg_v\", cellids)\n p[1:3,:,i] = readvariable(meta, \"proton/vg_ptensor_diagonal\", cellids)\n p[4:6,:,i] = readvariable(meta, \"proton/vg_ptensor_offdiagonal\", cellids)\n b[:,:,i] = readvariable(meta, \"vg_b_vol\", cellids)\n e[:,:,i] = readvariable(meta, \"vg_e_vol\", cellids)\n end\n\n # Save into binary file\n jldsave(\"vars_sun_earth_line.jld2\"; x1, x2, t, n, v, p, b, e)\n\n println(\"Line extraction finished!\")\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_x_o_points/#demo_x_o_points","page":"Find X- and O-points","title":"Find X- and O-points","text":"","category":"section"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"This demo shows how to find X-points and O-points in a 2D magnetic reconnection configuration. Here we assume a X-Z meridional plane.","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"note: Note\nThe input B field domain matters for computing the flux function, but I don't knowwhy there are differences.In identifying the X-points and O-points, we currently provide two methods: method 1needs to set the relative tolerance, while method 2 does not.","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"using VlasiatorPyPlot\n\nfunction main()\n file = \"bulk.0001657.vlsv\"\n meta = load(file)\n\n ndims(meta) != 2 && @error \"Flux function only works for 2D simulations!\"\n\n meta.ncells[3] == 1 && @error \"equatorial plane, no reconnection!\"\n\n b = meta[\"vg_b_vol\"]\n b = reshape(b, 3, meta.ncells[1], meta.ncells[3])\n dx = [meta.dcoord[1], meta.dcoord[3]]\n\n x = LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1]) ./ Vlasiator.RE\n z = LinRange(meta.coordmin[3], meta.coordmax[3], meta.ncells[3]) ./ Vlasiator.RE\n\n xmin_ = searchsortedfirst(x, 7.0)\n xmax_ = searchsortedlast(x, 9.5)\n zmin_ = searchsortedfirst(z, -5.0)\n zmax_ = searchsortedlast(z, 5.0)\n\n # meshgrid for plotting\n X = [a for a in x[xmin_:xmax_], _ in z[zmin_:zmax_]]\n Z = [b for _ in x[xmin_:xmax_], b in z[zmin_:zmax_]]\n\n flux = compute_flux_function(view(b,:,xmin_:xmax_,zmin_:zmax_), dx)\n\n fig, ax = plt.subplots(subplot_kw=Dict(\"projection\"=>\"3d\"))\n\n ax.plot_surface(X, Z, flux;\n cmap=matplotlib.cm.turbo,\n linewidth=0, antialiased=false)\n\n indices_x, indices_o = find_reconnection_points(flux; retol=1e-4, method=2)\n\n fig, ax = subplots(figsize=(6,10), constrained_layout=true)\n\n pcolormesh(meta, \"proton/vg_v\", ax;\n comp=:z, extent=[5, 10, -7.5, 7.5],\n cmap=matplotlib.cm.RdBu_r)\n s1 = ax.scatter(x[indices_x[1,:].+xmin_.-1], z[indices_x[2,:].+zmin_.-1];\n s=50, marker=\"x\", color=\"tab:gray\")\n s2 = ax.scatter(x[indices_o[1,:].+xmin_.-1], z[indices_o[2,:].+zmin_.-1];\n s=12, marker=\"o\", color=\"tab:brown\")\n\n ax.legend([s1, s2], [\"X-point\", \"O-point\"])\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/#demo_1d_animation","page":"1D animation","title":"1D animation","text":"","category":"section"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"This example demonstrates 1D plot animation. ffmpeg is required to be installed for saving into mp4.","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"using Vlasiator, Glob, PyPlot, Printf\n\nfiles = glob(\"bulk.*.vlsv\", \".\")\n# Choose plotting variable\nconst var = \"proton/vg_rho\"\nconst comp = 0 # component of vector, if used\n\nfig = plt.figure(constrained_layout=true)\n# Fix axis limits according to data range\nax = plt.axes(xlim=(-10, 10), ylim=(0, 4))\n\nline, = ax.plot([], [], lw=3, marker=\"*\")\n\nfunction animate(i::Int, files::Vector{String}, var::String, comp::Int, ax, line)\n meta = load(files[i+1])\n x = LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\n d = readvariable(meta, var)\n y = ndims(d) == 1 ? d : d[comp,:]\n line.set_data(x, y)\n\n t = readparameter(meta, \"time\")\n str_title = @sprintf \"t = %4.1fs, var = %s\" t var\n ax.set_title(str_title)\n\n return (line,)\nend\n\n# https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html\nanim = matplotlib.animation.FuncAnimation(fig, animate, fargs=(files, var, comp, ax, line),\n frames=length(files), blit=true,\n repeat_delay=1000, interval=200)\n# Make sure ffmpeg is available!\nanim.save(\"line.mp4\", writer=\"ffmpeg\", fps=30)","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/#demo_3d_trace","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"","category":"section"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"This demo shows how to trace along a field line and extract variables from 3D AMR grid.","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"warning: Warning\nThis is a proof of concept, which is memory-bound in 3D and may be quite inefficient!","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"using Vlasiator, FieldTracer, PyPlot\nusing StaticArrays\nusing Vlasiator: RE\n\nfunction get_cell_along_B(meta::MetaVLSV, seed::Vector{T};\n ds::Float64=0.2, maxstep::Int=20000, direction::String=\"both\") where T\n B = Vlasiator.fillmesh(meta, [\"vg_b_vol\"]; maxamronly=true)[1][1][1]\n\n nx, ny, nz = size(B)[2:4]\n\n xrange = LinRange(meta.coordmin[1], meta.coordmax[1], nx)\n yrange = LinRange(meta.coordmin[2], meta.coordmax[2], ny)\n zrange = LinRange(meta.coordmin[3], meta.coordmax[3], nz)\n\n bx = @view B[1,:,:,:]\n by = @view B[2,:,:,:]\n bz = @view B[3,:,:,:]\n xs, ys, zs = seed\n\n x, y, z = trace(bx, by, bz, xs, ys, zs, xrange, yrange, zrange; ds, maxstep, direction)\n\n cellids = [getcell(meta, SVector(x[1], y[1], z[1]))]\n\n for i in eachindex(x)[2:end]\n cellidnew = getcell(meta, SVector(x[i], y[i], z[i]))\n if cellidnew != cellids[end]\n push!(cellids, cellidnew)\n end\n end\n\n cellids\nend\n\nfunction main()\n file = \"bulk1.0001000.vlsv\"\n meta = load(file)\n\n seed = [-5.0, 0., 3.5] .* RE\n # For EGI, ds=1.0 is between 1-2 steps per finest cell.\n cellids = get_cell_along_B(meta, seed; ds=1.0, maxstep=100, direction=\"backward\")\n\n #n = readvariable(meta, \"proton/vg_rho\", cellids)\n #v = readvariable(meta, \"proton/vg_v\", cellids)\n #E = readvariable(meta, \"fg_e\", cellids) # Not available for now!\n\n x = zeros(Float64, length(cellids))\n y = zeros(Float64, length(cellids))\n z = zeros(Float64, length(cellids))\n\n for i in eachindex(cellids)\n coords = getcellcoordinates(meta, cellids[i])\n x[i], y[i], z[i] = coords\n end\n\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"3d\")\n\n ax.set_xlabel(\"x [RE]\")\n ax.set_ylabel(\"y [RE]\")\n ax.set_zlabel(\"z [RE]\")\n\n ax.set_box_aspect([1,1,1])\n ax.set_xlim3d([-20.0, -5.0])\n ax.set_ylim3d([0.0, 0.5])\n ax.set_zlim3d([-2.0, 3.0])\n\n ax.plot3D(x./RE, y./RE, z./RE)\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/#demo_line_extract","page":"Extract variable along a line","title":"Extract variable along a line","text":"","category":"section"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"This demo shows how to extract data alone a line across frames.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"tip: Tip\nThis can be made faster by updating the data without deleting the lines.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"using Vlasiator, Glob, PyPlot, Printf\nusing Vlasiator: RE # Earth radius, [m]\n\nfunction main()\n files = glob(\"run4/bulk*.vlsv\")\n\n point1 = [0e8, 0, 0]\n point2 = [1.9e8, 0, 0]\n\n cellids, distances, coords =\n let meta = load(files[1])\n getcellinline(meta, point1, point2)\n end\n\n # time density temperature vx\n inputs = [\n 0.0 2.0e6 1.0e5 -5.0e5;\n 99.0 2.0e6 1.0e5 -5.0e5;\n 100.0 2.0e6 1.0e5 -8.0e5;\n 200.0 2.0e6 1.0e5 -8.0e5;\n 201.0 1.0e6 1.0e5 -8.0e5;\n 499.0 1.0e6 1.0e5 -8.0e5;\n 500.0 2.0e6 1.0e5 -5.0e5]\n\n ndigits = 4\n\n lim_rho = [0.0, 4.0e6]\n lim_v = [-2e5, 10e5]\n\n fig, ax = plt.subplots(2,1, figsize=(12,5))\n\n for (i, file) in enumerate(files)\n fileout = lpad(i, ndigits, '0')*\".png\"\n\n meta = load(file)\n rho = readvariable(meta, \"proton/vg_rho\", cellids)\n v = readvariable(meta, \"proton/vg_v\", cellids)\n vx = Vector{Float64}(undef, size(v,1))\n\n for k in axes(v,1)\n vx[k] = v[k][1]\n end\n\n t = readparameter(meta, \"time\")\n\n ax[1].plot(coords[1,:] ./ RE, rho, label=\"rho\")\n ax[1].set_ylim(lim_rho)\n ax[1].legend()\n ax[1].minorticks_on()\n\n ax[2].plot(coords[1,:] ./ RE, abs.(vx), label=\"vx\")\n ax[2].set_ylim(lim_v)\n ax[2].legend()\n ax[2].minorticks_on()\n\n xlabel(\"X\")\n\n j = searchsortedfirst(inputs[:,1], t) - 1\n if j == 0; j = 1; end\n str_title =\n @sprintf \"t=%4.1fs, rho=%4.1f/cc, vx=%4.1fkm/s\" t inputs[j,2]/1e6 inputs[j,4]/1e3\n fig.suptitle(str_title, fontsize=14)\n\n savefig(fileout, bbox_inches=\"tight\")\n\n ax[1].cla()\n ax[2].cla()\n end\n\n close(fig)\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"manual/#Manual","page":"User Guide","title":"Manual","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Here we demonstrate some basic usages of processing Vlasiator output. A quick self-contained demo is shown with Pluto. For complete description of the arguments, please refer to the API documents or type ?function_name to display help message in the REPL.","category":"page"},{"location":"manual/#Common-physical-constants","page":"User Guide","title":"Common physical constants","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"A bunch of physical constants are predefined in Vlasiator.jl. To use them, you need to import explicitly, e.g. using Vlasiator: RE or prepend the module name like Vlasiator.RE.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Physical constant Value Meaning\nqₑ -1.60217662e-19 electron charge, [C]\nmₑ 9.10938356e-31 electron mass, [kg]\nqᵢ 1.60217662e-19 proton mass, [C]\nmᵢ 1.673557546e-27 proton mass, [kg]\nc 299792458. speed of light, [m/s]\nμ₀ 4π*1e-7 Vacuum permeability, [H/m]\nϵ₀ 1/(c^2*μ₀) Vacuum permittivity, [F/m]\nkB 1.38064852e-23 Boltzmann constant, [m²kg/(s²K)]\nRE 6.371e6 Earth radius, [m]","category":"page"},{"location":"manual/#Loading-VLSV-data","page":"User Guide","title":"Loading VLSV data","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"A quick way to obtain small test data can be found in F&Q. Larger open-access data can be found from the references in Vlasiator publications, e.g. Takahashi+ 2020. In this tutorial we are using the 2D test file bulk.2d.vlsv from vlsv_data if not specified.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Read meta data","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"file = \"bulk.2d.vlsv\"\nmeta = load(file)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The VLSV meta data contains information of file name, variable names, ordinary cell ID list, mesh sizes, species, and velocity cell structures. It is often the first argument for methods defined in Vlasiator.jl.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Read parameter","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"For convenience we support the do-block syntax that automatically closes the file stream.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"t = load(file) do meta\n readparameter(meta, \"time\")\nend","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Read variable meta data","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"readvariablemeta(meta, \"proton/vg_rho\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"A list of utility functions has been implemented for checking variable status. See here for the full list.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Read variable","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"data = meta[\"CellID\"]\n# Or equivalently\ndata = readvariable(meta, \"CellID\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The variable reading is designed for cells, which takes cell ID(s) as the 3rd argument if specified. The same interface works for both DCCRG grid (for storing cell centered quantities like plasma moments) and FS grid (for storing field solver related quantities on a uniform high resolution mesh) variables. By default the returned DCCRG variable array is sorted by cell IDs. If in any case you want the original unsorted version as being stored in the file, use readvariable(meta, var, false).","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Get variable at a given location","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"loc = [2.0, 0.0, 0.0]\nid = getcell(meta, loc)\nreadvariable(meta, \"CellID\", id)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Get variable along a line between two points","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"using Vlasiator: RE # Earth radii\npoint1 = [12RE, 0, 0]\npoint2 = [15RE, 0, 0]\ncellids, distances, coords = getcellinline(meta, point1, point2)\nvar_extract = readvariable(meta, \"VA\", cellids)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Extract variable at a static cell ID from a sequence of files under the same grid","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"files = [\"bulk.2d.vlsv\"]\nvar = \"CellID\"\nid = 1\nextractsat(files, var, id)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Downsample field solver variable to DCCRG grid","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vlasiator.downsample_fg(meta, \"fg_e\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Upsample DCCRG variable to field solver grid","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"data = Vlasiator.read_variable_as_fg(meta, \"proton/vg_rho\")\n# Equivalent to the above, but faster\ndata = let\n tmp = Vlasiator.fillmesh(meta, [\"proton/vg_rho\"]; maxamronly=true)[1][1][1]\n reshape(tmp, size(tmp)[2:end])\nend","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"This is useful when corresponding DCCRG variables are not saved, or a uniform mesh is required for further analysis.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Compare VLSV files","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"One may want to check if two vlsv files are identical. This is tricky because","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"the structure of VLSV format does not guarantee the writing order in parallel processing;\nnumerical error accumulates with floating point representation, especially with fastmath option.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The issame method does not check quantities that are related to the MPI writing sequence: for some reasons, even file sizes may vary depending on the number of MPI processes!","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"issame(file1, file2)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"There is an optional third argument to issame for setting the relative difference tolerance, with default being 1e-4. In practice relative difference works better for \"large\" numbers, and absolute difference works better for \"small\" numbers.","category":"page"},{"location":"manual/#Computing-derived-quantities","page":"User Guide","title":"Computing derived quantities","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vlasiator.jl is capable of computing plasma moments and some predefined derived quantities and saving them directly into VLSV files. To avoid confusion about variable names, the conventions are","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"raw quantities are all lowercases;\nall predefined derived variable names start with a capital letter;\nexceptions are for aliases (e.g. \"n\").","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To obtain a derived quantity, use either a key of string or symbol,","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"beta = meta[\"Beta\"]\nVA = meta[:VA]","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Here is a full list of available quantities[1]:","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Derived variable name Meaning Required variable[2]\nBmag magnetic field magnitude vg_b_vol\nEmag electric field magnitude vg_e_vol\nVmag bulk speed vg_v\nBhat unit magnetic field vg_b_vol\nVS sound speed vg_ptensor_diagonal; vg_rho\nVA Alfvén speed vg_rho; Bmag\nMA Alfvén Mach number Vmag; VA\nMS Sonic Mach number Vmag; VS\nEpar mathbfE_parallel vg_e_vol; Bhat\nEperp mathbfE_perp vg_e_vol; Bhat\nVpar bulk velocity parallelmathbfB vg_v; vg_b_vol\nVperp bulk velocity perp mathbfB vg_v; vg_b_vol\nVth proton thermal velocity P; vg_rho\nP scalar thermal pressure vg_ptensor_diagonal\nPpar pressure parallelmathbfB vg_ptensor_diagonal; vg_b_vol\nPperp pressure perp mathbfB vg_ptensor_offdiagonal; vg_b_vol\nT scalar temperature P; vg_rho\nTpar temperature parallelmathbfB vg_rho; vg_ptensor_diagonal; vg_b_vol\nTperp temperature perp mathbfB vg_rho; vg_ptensor_offdiagonal; vg_b_vol\nTanisotropy T_perp T_parallel Tpar; Tperp\nJ current density vg_b_vol\nJpar j_parallel vg_b_vol\nJperp j_perp vg_b_vol\nProtated pressure tensor with widehatz parallel mathbfB vg_b_vol; vg_ptensor_diagonal; vg_ptensor_offdiagonal\nPanisotropy P_perp P_parallel ptensor; B\nPram dynamic ram pressure vg_rho; Vmag\nPb magnetic pressure vg_b_vol\nPoynting Poynting flux E; B\nBeta plasma beta, P P_B P; vg_b_vol\nBetaStar modified beta, (P+P_ram)P_B P; Pram; vg_b_vol\nIonInertial proton inertial length vg_rho\nLarmor proton Larmor radius Vth; Bmag\nGyroperiod proton gyroperiod Bmag\nPlasmaPeriod plasma oscillation period vg_rho\nGyrofrequency proton gyro-frequency Bmag\nOmegap plasma frequency (proton) vg_rho\nMagneticTension magnetic tension force vg_b_vol\nn proton number density vg_rho","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"which can also be found as keys of dictionary in vlsvvariables.jl.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"[1]: For species specific variables, you need to add the species name at the front, separated by a slash. For example, the proton bulk velocity is a string proton/vg_v.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"[2]: If a required variable exists in the VLSV file, we try to use it directly instead of calculating from other variables. The interpolated FS grid variables onto DCCRG grid are preferred over original FS grid variables.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"note: Note\nIn Vlasiator, the cells inside the inner boundary (which is usually a sphere/circle) are filled with zero density values. This is then used to identify the inner boundary for all other quantities. Therefore, if you are manipulating directly on data, make sure that the nonsense values inside the inner boundary are excluded. One way to do this can be found in vlsvvariables.jl.","category":"page"},{"location":"manual/#Velocity-space-moments","page":"User Guide","title":"Velocity space moments","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"We can also calculate plasma moments from the saved VLSV velocity space distributions.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.1d.vlsv\")\ncellid = 5\n# VDF cell indexes and values, with sparsity\nvcellids, vcellf = readvcells(meta, cellid; species=\"proton\")\n\ngetdensity(meta, vcellf)\n\ngetvelocity(meta, vcellids, vcellf)\n# pressure tensor components Pxx, Pyy, Pzz, Pyz, Pzx, Pxy\ngetpressure(meta, vcellids, vcellf)\n# heat flux components qⱼⱼᵢ\ngetheatfluxvector(meta, vcellids, vcellf)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To obtain the original ordering of velocity cells,","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vcellids_original = Vlasiator.reorder(meta.meshes[\"proton\"], vcellids)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Non-Maxwellianity represents the deviation from a Maxwellian distribution. Currently we have implemented a monitor quantity named \"Maxwellianity\", which is defined as -ln big 1(2n) int f(v) - g(v) dv big, where n is the density, f(vᵢ) is the actual VDF value at velocity cell i, and g(vᵢ) is the analytical Maxwellian (or strictly speaking, normal) distribution with the same density, bulk velocity and scalar pressure as f.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"getmaxwellianity(meta, vcellids, vcellf)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The value ranges from [0, +∞], with 0 meaning not Maxwellian-distributed at all, and +∞ a perfect Maxwellian distribution. An alternative measure is the KL-divergence borrowed from statistics, where we select the reference distribution g to be again a Maxwellian derived from the actual distribution f:","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"getKLdivergence(meta, vcellids, vcellf)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"In this case, 0 indicates perfect Maxwellian while +∞ indicates largest deviation. There is no unique definition of non-Maxwellianity, and we are still trying to see which one works better for describing plasma behaviors.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Sometimes it may be useful to recover the full 3D array of VDFs:","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"f = Vlasiator.reconstruct(meta.meshes[\"proton\"], vcellids, vcellf)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"However, usually in practice there would be only about 1% nonzero values. The moments and maxwellianity calculations above all have an alternative form of using reconstructed VDFs as inputs.","category":"page"},{"location":"manual/#Plotting","page":"User Guide","title":"Plotting","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vlasiator.jl does not include any plotting library as explicit dependency, but it offers plotting recipes/wrappers once the target plotting package is used.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Currently PyPlot provides the most complete and fine-tuned plotting capabilities. Plotting with PyPlot by accepting MetaVLSV as the first argument is supported via VlasiatorPyPlot. Plots is a collection of plotting libraries with a uniform frontend, but it lacks fine-tuned supports and consistent APIs between different backends. Makie, a native Julia plotting library, is also supported via VlasiatorMakie.jl. Without generating an system image from PackageCompiler, it would take ~20s for the first plot on Julia 1.9. However, Makie has made nice progress in layouts, widgets, docs, and all the tiny things, which makes it a strong candidate for the de facto plotting library in the future.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"More examples of customized plots can be found in the repository.","category":"page"},{"location":"manual/#PyPlot-Backend","page":"User Guide","title":"PyPlot Backend","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To trigger Matplotlib plotting that supports MetaVLSV, using VlasiatorPyPlot. All the functions with identical names as in Matplotlib accept all possible keyword arguments supported by Matplotlib, e.g. font width, font size, colormap, etc. For detailed adjustment of plots, please refer to the Matplotlib documentation for details.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"warning: Warning\nThe method call to certain axes is not dispatched, e.g. ax.plot; as an alternative, one needs to pass ax as the third argument to the functions, e.g. plot(meta, \"rho\", ax). See Matplotlib's two interfaces for the history of the interfaces.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Scalar colored contour from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pcolormesh(meta, \"n\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vector z-component colored contour from 2D simulation in a manually set range","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pcolormesh(meta, \"n\", comp=:z, colorscale=Log, axisunit=EARTH, vmin=1e6, vmax=2e6)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vz colored contour from 2D simulation with prescribed colormap","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pcolormesh(meta, \"proton/vg_v\", comp=:z, colorscale=Linear, cmap=matplotlib.cm.RdBu_r)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Derived quantity colored contour from 2D simulation (as long as the input variable is in the predefined dictionary)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pcolormesh(meta, \"Bmag\", comp=:z, colorscale=Linear, axisunit=SI)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Streamline from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"streamplot(meta, \"proton/vg_v\", comp=\"xy\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Quiver from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"quiver(meta, \"proton/vg_v\", comp=\"xy\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The comp option is used to specify the two vector components.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"You can choose to use a linear/log/symlog color scale by setting keyword colorscale to Linear, Log, or SymLog, plot vector components by setting keyword op to :x, :y, :z, 1, 2, 3, 0 or :mag, and set axisunit to EARTH or SI etc.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Mesh denoted by cell centers","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"plotmesh(meta; projection=\"z\", color=\"k\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Cut slice colored contour from 3D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.amr.vlsv\")\npcolormesh(meta, \"proton/vg_rho\", normal=:y, origin=0.0)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Velocity distribution slice plot near a given spatial location","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.1d.vlsv\")\ncoordinates = [0.0, 0.0, 0.0]\nvdfslice(meta, coordinates)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Quick interactive REPL-based function for data inspection","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pui(meta)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Or pass filename directly like pui(file).","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"note: Note\nThis is an experimental feature. We plan to have GUI-based plotting support in the future.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"For a full list available optional arguments, please refer to the doc for each method","category":"page"},{"location":"manual/#Plots-Backend","page":"User Guide","title":"Plots Backend","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To trigger Plots.jl plotting, using Plots. This backend supports all available attributes provided by Plots.jl. By default it uses GR, but many other plotting libraries are also supported.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Scaler colored contour from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"var = \"n\"\nheatmap(meta, var, aspect_ratio=:equal, c=:turbo)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Scaler colored contour with lines from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"var = \"n\"\ncontourf(meta, var)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"VDF projected slice in a normal direction","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.1d.vlsv\")\nlocation = [0.0, 0.0, 0.0]\nvdfslice(meta, location)","category":"page"},{"location":"manual/#Makie-Backend","page":"User Guide","title":"Makie Backend","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"A standalone package VlasiatorMakie.jl is designed for plotting with Makie. To trigger Makie plotting with OpenGL, using VlasiatorMakie, GLMakie. You can either use intrinsic Makie plotting methods like","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"lines(meta, var) # 1D\nheatmap(meta, var) # 2D","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"or use full recipes provided by VlasiatorMakie","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vlheatmap(meta, var)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"For quick inspection of data, we have","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"2D slices of 3D AMR data","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vlslice(meta, var; normal=:x)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Orthognal slices of 3D AMR data","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vlslices(meta, var)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"2D slice of VDFs at a spatial cell","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"VlasiatorMakie.vdfslice(meta, location)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Orthognal slices of VDFs at a spatial cell","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vdfslices(meta, location)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"3D scatter of VDFs at a spatial cell","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vdfvolume(meta, location)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The interactive plots are available through the OpenGL backend of Makie GLMakie. For noninteractive high fidelity plots, we can also use the Cairo backend of Makie CairoMakie. Other options can be found at Makie Ecosystem.","category":"page"},{"location":"manual/#Appending-to-VLSV","page":"User Guide","title":"Appending to VLSV","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"We are able to compute derived quantities from an original VLSV file and generate a new VLSV output with new quantities included.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.1d.vlsv\")\nvmag = readvariable(meta, \"Vmag\")\npa = readvariable(meta, \"Panisotropy\")\nvars = Vector{Tuple{VecOrMat, String, VarInfo}}(undef, 0)\nusing LaTeXStrings\npush!(vars, (vmag, \"vmag\", VarInfo(\"m/s\", L\"$\\mathrm{m}/mathrm{s}$\", L\"$V$\", \"\")))\npush!(vars, (pa, \"panisotropy\", VarInfo(\"\", \"\", \"\", \"\")))\n\nwrite_vlsv(\"bulk.1d.vlsv\", \"bulk.1d_new.vlsv\", vars)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"note: Note\nWriting new FsGrid variables is not supported. All quantities from the original file is maintained.","category":"page"},{"location":"manual/#Converting-to-VTK","page":"User Guide","title":"Converting to VTK","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"We can convert VLSV files into VTK format. Since DCCRG is Cartesian based with uniform spacing, each level of mesh refinement corresponds to a VTK image file, and the cell refinement relationships are stored in vtkGhostType as well as the vthb file.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To convert a VLSV file into VTK,","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"write_vtk(file)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"This function accepts either string of file names or MetaVLSV.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To see the full list of options, please refer to the documentation in API Reference. Example usage can be found here.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"warning: Warning\nAs of ParaView 5.9.1, there are display issues with VTKOverlappingAMR. However, we can read the generated image files directly. There is also an keyword argument for write_vtk called maxamronly: when it is set to true, then only the image file at the highest refinement level is generated. This part is experimental and subject to change in the future.","category":"page"},{"location":"manual/#Tracking-log-files","page":"User Guide","title":"Tracking log files","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The runtime performance per iteration can be monitored through log files:","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"file = \"logfile.txt\"\ntimestamps, speed = readlog(file)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Here is a live demo.","category":"page"},{"location":"manual/#Examples","page":"User Guide","title":"Examples","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"More examples are provided about","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Plotting with PyPlot\nPlotting with Plots\nExtracing variable along a line\nField line tracing\nSimulation log file tracking\nConverting VLSV to VTK format\nParallel post-processing\nFinding X-points and O-points in 2D reconnections","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Feel free to check those out and try on your data!","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/#demo_2d_contour","page":"2D contour plots","title":"2D contour plots","text":"","category":"section"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"This script creates contours from a series of input files with a fixed color range. Combined with ffmpeg, we can easily make animations from data.","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"using Vlasiator, Glob, VlasiatorPyPlot, Printf\n\nfiles = glob(\"bulk*.vlsv\")\nnfile = length(files)\n# Set output directory\nconst outdir = \"out/\"\n\nmeta = load(files[1])\nconst varname = \"proton/vg_rho\"\n\nfig, ax = plt.subplots()\n\nconst comp = :z # vector component for plotting (if applicable)\nconst axisunit = EARTH\nconst colorscale = Log\nconst addcolorbar = true\n# Choose colormap\nconst cmap = matplotlib.cm.turbo\n# Set data plotting range\nconst vmin = 7.0e4\nconst vmax = 2.5e6\n\npArgs = Vlasiator.set_args(meta, varname, axisunit; normal=:none)\n\nx1, x2 = Vlasiator.get_axis(pArgs)\n\nnorm, ticks = set_colorbar(colorscale, vmin, vmax)\n\nfakedata = zeros(Float32, length(x2), length(x1))\n\nc = ax.pcolormesh(x1, x2, fakedata; norm, cmap)\n\nVlasiator.set_plot(c, ax, pArgs, ticks, addcolorbar)\n\nfor (i, file) in enumerate(files)\n @info \"$i out of $nfile\"\n local meta = load(file)\n\n var = meta[varname]\n t = readparameter(meta, \"time\")\n\n data = Vlasiator.prep2d(meta, varname, comp)'\n c.set_array(data)\n\n str_title = @sprintf \"t= %4.1fs\" t\n ax.set_title(str_title)\n\n savefig(outdir*lpad(i, 4, '0')*\".png\", bbox_inches=\"tight\", dpi=100)\nend\n\nclose()","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/#examples","page":"Examples","title":"Examples","text":"","category":"section"},{"location":"examples/","page":"Examples","title":"Examples","text":"This section contains thorough examples for using Vlasiator.jl.","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"","category":"page"},{"location":"examples/#Postprocess","page":"Examples","title":"Postprocess","text":"","category":"section"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to convert VLSV to VTK","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Converting to VTK","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract data for a virtual satellite","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Virtual satellite","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract data for virtual satellites","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Virtual satellites","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract data for virtual satellites","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Virtual satellites","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract EM fields on a selected 2D slice","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract EM fields on a slice","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract variables along a line across multiple frames","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract variables along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract logfile.txt information","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Log tracking","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to find X-points in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Find X-points in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract variables along the magnetopause","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract variables along the magnetopause","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to identify EMIC and mirror modes","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Identify EMIC and mirror modes","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to search for waves","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Search waves","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to track waves and plot the dispersion relation","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Track waves","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to find X/O-points","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Find X- and O-points","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to find X-points in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Find X-points in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/#Visualization","page":"Examples","title":"Visualization","text":"","category":"section"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to create animation for 1D plots","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"1D animation","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate complex plots with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Combined plots with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate complex plots","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Combined plots","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate 2D colored contour animation","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plot animation","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate 2D colored contours with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plots with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate 2D colored contours","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plots","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot 2D colored contour with streamlines","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plot with streamlines","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot 2D colored contour with streamlines and levels","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plot with streamlines and levels","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot 2D colored contour slices for 3D data","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Orthogonal slices","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot field lines with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Field lines with customized seeds via multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot field lines with handpicked seeds.","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Field lines with customized seeds","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract the bow shock location and save into file","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract bow shock location","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract the bow shock location and plot","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract bow shock location","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract difference between grids","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract differences between FsGrid and DCCRG variables","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot energy spectrum at a fixed point","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Energy spectrum at a fixed point","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to trace streamlines in a 2D field","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Trace field lines in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to trace streamlines in a 3D field","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Trace field lines in 3D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract variables along a line with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract variables along a line with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract a variable along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract variable along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot variable along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Plot variable along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot variables along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Plot variables along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot mesh","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Plot mesh","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot across nodes","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Plot with multi-nodes","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract poynting flux on a subdomain","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Poynting flux","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot pressure tensor","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Pressure tensor","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot velocity distribution function","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"VDF","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot velocity distribution functions","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"VDFs along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot vector components","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Vector components","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/#demo_identify_EMIC_mirror","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"","category":"section"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"This demo shows how to identify EMIC and mirror modes in two frequency bands from single satellite data. For EMIC mode we check δB⟂ vs. δv⟂; for mirror mode we check δB∥ vs. δn. The moving box window size is decided empirically.","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"julia -t 4 demo_wave_satellite_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"or","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"JULIA_NUM_THREADS=4 julia demo_wave_satellite_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"using Statistics: mean\nusing LinearAlgebra: ⋅, normalize!, norm\nusing DSP, PyPlot, Glob\nusing Vlasiator\nusing Vlasiator: μ₀, mᵢ, RE\nusing Polyester\n\n\"Extract variables at `loc` from VLSV `files`.\"\nfunction extract_vars(files, loc)\n nfiles = length(files)\n\n t = zeros(Float32, nfiles)\n n = zeros(Float32, nfiles)\n v = zeros(Float32, 3, nfiles)\n b = zeros(Float32, 3, nfiles)\n e = zeros(Float32, 3, nfiles)\n\n id = load(files[1]) do meta\n getcell(meta, loc)\n end\n\n # Extract data from each frame\n @batch for i = eachindex(files)\n meta = load(files[i])\n t[i] = meta.time\n n[i] = readvariable(meta, \"proton/vg_rho\", id)[1]\n v[:,i] = readvariable(meta, \"proton/vg_v\", id)\n b[:,i] = readvariable(meta, \"vg_b_vol\", id)\n e[:,i] = readvariable(meta, \"vg_e_vol\", id)\n end\n\n t, n, v, e, b\nend\n\nfunction moving_average(g::AbstractVector{<:AbstractFloat}, n::Int)\n nbackward = div(n,2)\n nforward = isodd(n) ? nbackward : nbackward - 1\n len = length(g)\n g_avg = similar(g)\n @inbounds @batch for i = 1:len\n lo = max(1, i - nbackward)\n hi = min(len, i + nforward)\n g_avg[i] = mean(@view g[lo:hi])\n end\n g_avg\nend\n\nfunction moving_average(g::AbstractMatrix{<:AbstractFloat}, n::Int)\n nbackward = div(n,2)\n nforward = isodd(n) ? nbackward : nbackward - 1\n len = size(g,2)\n g_avg = similar(g)\n for icomp = axes(g,1)\n @inbounds @batch for i = 1:len\n lo = max(1, i - nbackward)\n hi = min(len, i + nforward)\n g_avg[icomp,i] = mean(@view g[icomp, lo:hi])\n end\n end\n g_avg\nend\n\nfunction detrend(v::AbstractVector{<:AbstractFloat}; nbox=length(v)÷12)\n v̄ = moving_average(v, nbox)\n dv = v .- v̄\nend\n\nfunction detrend(v::AbstractMatrix{<:AbstractFloat}; nbox=size(v,2)÷12)\n v̄ = similar(v)\n for i in axes(v,1)\n v̄[i,:] = @views moving_average(v[i,:], nbox)\n end\n dv = v .- v̄\nend\n\nfunction align_yaxis(ax1, ax2)\n y_lims = [ax.get_ylim() for ax in [ax1, ax2]]\n\n # normalize both axes\n y_mags = ntuple(i -> y_lims[i][2] - y_lims[i][1], Val(2))\n y_lims_normalized = ntuple(i -> y_lims[i] ./ y_mags[i], Val(2))\n\n # find combined range\n y_new_lims_normalized = (min(y_lims_normalized[1][1],y_lims_normalized[2][1]),\n max(y_lims_normalized[1][2], y_lims_normalized[2][2]))\n\n # denormalize combined range to get new axes\n new_lim1 = y_new_lims_normalized .* y_mags[1]\n new_lim2 = y_new_lims_normalized .* y_mags[2]\n ax1.set_ylim(new_lim1)\n ax2.set_ylim(new_lim2)\n return\nend\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n\n # virtual satellite location\n loc = [12Vlasiator.RE, 0, 0]\n\n nbox = 40 # moving box size, [# of indices]\n fs = 2.0 # sampling rate, [Hz]\n\n println(\"Running with $(Threads.nthreads()) threads...\")\n println(\"Number of files: $(length(files))\")\n println(\"Extracting location: $loc [m]\")\n println(\"Sampling rate: $fs [Hz]\")\n println(\"Moving box window size: $(nbox / fs) [s]\")\n\n t, n, v, e, b = extract_vars(files, loc)\n\n bmag = [hypot(b[1,i], b[2,i], b[3,i]) for i in eachindex(n)]\n\n # Detrend before filtering to remove the lowest frequency changes\n dn = detrend(n; nbox)\n dbmag = detrend(bmag; nbox)\n\n n̄ = moving_average(n, nbox)\n b̄mag = moving_average(bmag, nbox)\n\n v̄a = @. b̄mag / sqrt(μ₀ * mᵢ * n̄)\n\n dv = detrend(v; nbox) # [m/s]\n db = detrend(b; nbox) # [T]\n\n # Decompose into parallel and perpendicular vector components\n b̂₀ = moving_average(b, nbox)\n for i in axes(b̂₀, 2)\n normalize!(@view b̂₀[:,i])\n end\n\n # δB∥\n db_par = [db[:,i] ⋅ b̂₀[:,i] for i in axes(db, 2)]\n # δB⟂\n db_perp = [norm(db[:,i] .- db_par[i] .* b̂₀[:,i]) for i in axes(db, 2)]\n # δv∥\n dv_par = [dv[:,i] ⋅ b̂₀[:,i] for i in axes(dv, 2)]\n # δv⟂\n dv_perp = [norm(dv[:,i] .- dv_par[i] .* b̂₀[:,i]) for i in axes(dv, 2)]\n\n designmethod = Butterworth(5)\n\n responsetype = Highpass(0.1; fs)\n dn_high = filtfilt(digitalfilter(responsetype, designmethod), dn)\n dbpar_high = filtfilt(digitalfilter(responsetype, designmethod), db_par)\n dbperp_high = filtfilt(digitalfilter(responsetype, designmethod), db_perp)\n dvperp_high = filtfilt(digitalfilter(responsetype, designmethod), dv_perp)\n\n responsetype = Bandpass(0.02, 0.067; fs)\n dn_low = filtfilt(digitalfilter(responsetype, designmethod), dn)\n dbpar_low = filtfilt(digitalfilter(responsetype, designmethod), db_par)\n\n color1 = \"tab:blue\"\n color2 = \"tab:red\"\n\n fig, axs = plt.subplots(3, 1; figsize=(13, 9), sharex=true, constrained_layout=true)\n\n fig.suptitle(\"Virtual satellite at $(string(round.(loc./RE, digits=2))) \"*L\"R_E\";\n fontsize=\"x-large\")\n\n axs[1].plot(t, dn_low ./ n̄, color1, label=L\"\\delta n, 0.02-0.067\\, Hz\")\n ax12 = axs[1].twinx()\n ax12.plot(t, dbpar_low ./ b̄mag, color=color2, label=L\"\\delta B, 0.02-0.067\\, Hz\")\n\n axs[2].plot(t, (dn_high ./ n̄), color1, label=L\"\\delta n, 0.1-1.0\\, Hz\")\n ax22 = axs[2].twinx()\n ax22.plot(t, (dbpar_high ./ b̄mag), color=color2, label=L\"\\delta B, 0.1-1.0\\, Hz\")\n\n axs[3].plot(t, dvperp_high ./ v̄a, color1, label=L\"\\delta v_\\perp, 0.1-1.0\\, Hz\")\n ax32 = axs[3].twinx()\n ax32.plot(t, dbperp_high ./ b̄mag, color=color2, label=L\"\\delta B, 0.1-1.0\\, Hz\")\n\n axs[3].set_xlabel(\"time [s]\"; fontsize=\"large\")\n\n n_str = (L\"\\delta n /n\", L\"\\delta n / n\", L\"\\delta v_\\perp / V_A\")\n\n for (i, a) in enumerate(axs)\n a.hlines(0.0, t[1], t[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.3)\n a.tick_params(axis=\"y\", labelcolor=color1)\n a.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n a.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n a.grid(true)\n a.set_ylabel(n_str[i], color=color1, fontsize=14)\n end\n\n axtwin = (ax12, ax22, ax32)\n b_str = ( L\"\\delta B_\\parallel / B_0\", L\"\\delta B_\\parallel / B_0\", L\"\\delta B_\\perp / B_0\")\n\n for (i, a) in enumerate(axtwin)\n a.tick_params(axis=\"y\", labelcolor=color2)\n a.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n a.set_ylabel(b_str[i], color=color2, fontsize=\"large\")\n align_yaxis(axs[i], a)\n end\n\n AnchoredText = matplotlib.offsetbox.AnchoredText\n\n at = AnchoredText(\n \"[0.02, 0.067] Hz band\", prop=Dict(\"size\"=>\"medium\"), frameon=true, loc=\"lower left\")\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n axs[1].add_artist(at)\n\n at = AnchoredText(\n \"[0.1, 1.0] Hz band\", prop=Dict(\"size\"=>\"medium\"), frameon=true, loc=\"lower left\")\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n axs[2].add_artist(at)\n\n at = AnchoredText(\n \"[0.1, 1.0] Hz band\", prop=Dict(\"size\"=>\"medium\"), frameon=true, loc=\"lower left\")\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n axs[3].add_artist(at)\n\n savefig(\"virtual_satellite_wave.png\"; dpi=300)\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/#demo_2d_contour_streamline","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"","category":"section"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"This demos shows how to reading 2D simulation data, zoom-in to a region of interest, and add streamlines on top of colored mesh.","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"using Vlasiator, Plots\n\nfile = \"bulk.0000501.vlsv\"\nnameρ = \"rho\"\nnameV = \"rho_v\"\n\nboxcoords = Float64[0, 20, -15, 15]\n\nmeta = load(file)\n\nheatmap(meta, nameρ,\n xlim=(boxcoords[1], boxcoords[2]),\n ylim=(boxcoords[3], boxcoords[4]),\n aspect_ratio=:equal,\n c=:turbo)\n\n#=\n# Attributes can be modified afterwards, but it's slower.\nheatmap(meta, nameρ, c=:turbo)\nxlims!(boxcoords[1], boxcoords[2])\nylims!(boxcoords[3], boxcoords[4])\n=#\n\nstreamplot(meta, nameV, comp=\"xy\", color=\"w\", density=2.0)","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/#demo_3d_cuts","page":"Orthogonal slices","title":"Orthogonal slices","text":"","category":"section"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"This demo shows how to plot 2D colored contour slices for 3D data.","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"using VlasiatorPyPlot, PyCall\n\naxes_grid1 = pyimport(\"mpl_toolkits.axes_grid1\")\nImageGrid = axes_grid1.ImageGrid\n\nfile = \"bulk1.0001000.vlsv\"\nnameρ = \"proton/vg_rho\"\ncolorscale = Log\naddcolorbar = false\n\nmeta = load(file)\n\n# normal cuts in the x,y,z directions\nfig = plt.figure(figsize=(12, 4))\ngrid = ImageGrid(fig, 111,\n nrows_ncols=(1, 3),\n axes_pad=0.85,\n cbar_mode=\"single\",\n cbar_location=\"right\",\n cbar_pad=0.1,\n label_mode=\"all\"\n )\n\nc1 = pcolormesh(meta, nameρ, grid[1]; normal=:x, addcolorbar, colorscale)\nc2 = pcolormesh(meta, nameρ, grid[2]; normal=:y, addcolorbar, colorscale)\nc3 = pcolormesh(meta, nameρ, grid[3]; normal=:z, addcolorbar, colorscale)\n\ncb = fig.colorbar(c3, cax=grid.cbar_axes[1])\ndatainfo = readvariablemeta(meta, nameρ)\n\ncb_title_str = datainfo.variableLaTeX\ncb_title_str *= \",[\"*datainfo.unitLaTeX*\"]\"\ncb_title = cb.ax.set_title(cb_title_str, fontsize=14, fontweight=\"bold\")\n\nplt.savefig(\"test.png\", bbox_inches=\"tight\")","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/#demo_plot_multinode","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"","category":"section"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"This demos shows how to plot complex figures with more than one node using ClusterManagers. A progress bar is added for tracking.","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"Usage:","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"sbatch job.slurm","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"# Sample Slurm job script\n#!/bin/bash -l\n# -*- mode: julia -*-\n#SBATCH --nodes=2\n#SBATCH --ntasks-per-node=1\n#SBATCH --time=00:03:00\n#SBATCH --mem-per-cpu=2G\n#SBATCH --partition=test\n#SBATCH --output=%x_%j.log\n#SBATCH --job-name=pmap\n\njulia demo_mp_progressbar.jl","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"using Distributed, ProgressMeter, Glob\nusing Vlasiator: RE # Earth radius [m]\nusing ClusterManagers\naddprocs(SlurmManager(parse(Int, ENV[\"SLURM_NTASKS\"])),\n partition=ENV[\"SLURM_JOB_PARTITION\"],\n time=\"00:03:00\", # No environment variable for time limit\n mem_per_cpu=ENV[\"SLURM_MEM_PER_CPU\"])\n\n@everywhere begin\n using ParallelDataTransfer\n using Vlasiator, VlasiatorPyPlot, Printf, LaTeXStrings\n using Vlasiator: set_args, prep2d\nend\n\n@assert matplotlib.__version__ ≥ \"3.4\" \"Require Matplotlib version 3.4+ to use subfigure!\"\n\n@everywhere function init_figure(x1, x2)\n fig = plt.figure(myid(), constrained_layout=true, figsize=(12, 12))\n subfigs = fig.subfigures(1, 2, wspace=0.05)\n\n axsL = subfigs[1].subplots(4, 1, sharex=true)\n axsR = subfigs[2].subplots(2, 1, sharex=true, sharey=true)\n\n # Set line plots' axes\n axsL[end].set_xlim(x1, x2)\n\n axsL[1].set_ylim(ρmin, ρmax)\n axsL[2].set_ylim(vmin, vmax)\n axsL[3].set_ylim(pmin, pmax)\n axsL[4].set_ylim(bmin, bmax)\n for ax in axsL\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axsL[end].set_xlabel(L\"x [$R_E$]\"; fontsize)\n axsL[1].set_ylabel(\"Density [amu/cc]\"; fontsize)\n axsL[2].set_ylabel(\"Velocity [km/s]\"; fontsize)\n axsL[3].set_ylabel(\"Pressure [nPa]\"; fontsize)\n axsL[4].set_ylabel(\"Magnetic field [nT]\"; fontsize)\n\n fakeline = loc\n l1 = axsL[1].plot(loc, fakeline, label=\"Proton density\", color=\"#1f77b4\")\n l2 = axsL[2].plot(loc, fakeline, label=\"Vx\", color=\"#1f77b4\")\n l3 = axsL[3].plot(loc, fakeline, label=\"Ram\", color=\"#1f77b4\")\n l4 = axsL[3].plot(loc, fakeline, label=\"Thermal\", color=\"#ff7f0e\")\n l5 = axsL[4].plot(loc, fakeline, label=\"Bz\", color=\"#1f77b4\")\n\n ls = (l1, l2, l3, l4, l5)\n\n axsL[2].legend(;loc=\"upper right\", fontsize)\n axsL[3].legend(;loc=\"lower right\", fontsize)\n axsL[4].legend(;loc=\"upper right\", fontsize)\n\n vl1 = axsL[1].vlines(loc[imagnetopause_], ρmin, ρmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n vl2 = axsL[2].vlines(loc[imagnetopause_], vmin, vmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n vl3 = axsL[3].vlines(loc[imagnetopause_], pmin, pmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n vl4 = axsL[4].vlines(loc[imagnetopause_], bmin, bmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n hl4 = axsL[4].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n\n vlines = (vl1, vl2, vl3, vl4)\n\n for ax in axsR\n ax.set_aspect(\"equal\")\n\n # Set border line widths\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\n edge = get(ax.spines, loc, nothing)\n edge.set_linewidth(2.0)\n end\n ax.xaxis.set_tick_params(width=2.0, length=3)\n ax.yaxis.set_tick_params(width=2.0, length=3)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n\n ax.set_ylabel(L\"Y [$R_E$]\"; fontsize)\n end\n\n axsR[2].set_xlabel(L\"X [$R_E$]\"; fontsize)\n\n axsR[1].set_title(\"Alfven speed\", fontsize=\"x-large\")\n axsR[2].set_title(\"Sound speed\", fontsize=\"x-large\")\n\n x, y = Vlasiator.get_axis(pArgs1)\n\n fakedata = zeros(Float32, length(y), length(x))\n\n c1 = axsR[1].pcolormesh(x, y, fakedata, norm=cnorm1, cmap=cmap)\n c2 = axsR[2].pcolormesh(x, y, fakedata, norm=cnorm2, cmap=cmap)\n\n cb1 = colorbar(c1; ax=axsR[1], ticks=cticks1, fraction=0.046, pad=0.04)\n cb2 = colorbar(c2; ax=axsR[2], ticks=cticks2, fraction=0.046, pad=0.04)\n\n cs = (c1, c2)\n\n for cb in (cb1, cb2)\n cb.ax.set_ylabel(\"[km/s]\"; fontsize)\n cb.outline.set_linewidth(1.0)\n end\n\n fig.suptitle(\"Density Pulse Run\", fontsize=\"xx-large\")\n\n return fig, subfigs, ls, vlines, cs\nend\n\nfunction update_vline(h, x)\n seg_old = h.get_segments()\n ymin = seg_old[1][1, 2]\n ymax = seg_old[1][2, 2]\n\n seg_new = [[[x, ymin] [x, ymax]]]\n\n h.set_segments(seg_new)\nend\n\n@everywhere function process(subfigs, ls, vlines, cs, file, cellids)\n isfile(\"../out/\"*file[end-8:end-5]*\".png\") && return\n\n println(\"file = $(basename(file))\")\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1e9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1e9 # [nPa]\n\n bz = readvariable(meta, \"vg_b_vol\", cellids)[3,:] .* 1e9 #[nT]\n\n ls[1][1].set_ydata(rho_extract ./ 1e6)\n ls[2][1].set_ydata(v_extract[1,:] ./ 1e3)\n ls[3][1].set_ydata(pram_extract)\n ls[4][1].set_ydata(p_extract)\n ls[5][1].set_ydata(bz)\n\n imagnetopause_ = findfirst(<(0.0), bz)\n for vline in vlines\n update_vline(vline, loc[imagnetopause_])\n end\n\n str_title = @sprintf \"Sun-Earth line, t= %4.1fs\" meta.time\n subfigs[1].suptitle(str_title, fontsize=\"x-large\")\n\n data = prep2d(meta, \"VA\")'\n cs[1].set_array(data ./ 1e3)\n\n data = prep2d(meta, \"VS\")'\n cs[2].set_array(data ./ 1e3)\n\n savefig(\"../out/\"*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n return\nend\n\n## Parameters\n\nfiles = glob(\"bulk*.vlsv\", \"../run_rho2_bz-5_timevarying_startfrom300s\")\nnfiles = length(files)\n\nconst p = Progress(nfiles; showspeed=true)\nconst channel = RemoteChannel(()->Channel{Bool}(), 1)\n\n@passobj 1 workers() files\n\n@broadcast begin # on all workers\n const isinit = true\n # Set contour plots' axes and colorbars\n const cmap = matplotlib.cm.turbo\n colorscale = Linear\n axisunit = EARTH\n\n # Upper/lower limits for each variable\n const ρmin, ρmax = 0.0, 10.0 # [amu/cc]\n const vmin, vmax = -640.0, 0.0 # [km/s]\n const pmin, pmax = 0.0, 1.82 # [nPa]\n const bmin, bmax = -25.0, 60.0 # [nT]\n const vamin, vamax = 0.0, 250.0 # [km/s]\n const vsmin, vsmax = 30.0, 350.0 # [km/s]\n\n meta = load(files[1])\n\n const pArgs1 = set_args(meta, \"VA\", axisunit; normal=:none)\n const cnorm1, cticks1 = set_colorbar(colorscale, vamin, vamax)\n const cnorm2, cticks2 = set_colorbar(colorscale, vsmin, vsmax)\n\n const fontsize = 14\nend\n\nconst x1, x2 = 8.0, 29.0\nconst point1 = [x1, 0, 0] .* RE\nconst point2 = [x2, 0, 0] .* RE\n\nmeta = load(files[1])\ncellids, _, _ = getcellinline(meta, point1, point2)\npassobj(1, workers(), [:x1, :x2, :cellids])\n@broadcast const loc = range(x1, x2, length=length(cellids))\n\n## Execution\n\n@broadcast begin\n # initialize figure, axes, lines, and contours\n fig, subfigs, ls, vlines, cs = init_figure(x1, x2)\nend\n\n@sync begin # start two tasks which will be synced in the very end\n # the first task updates the progress bar\n @async while take!(channel)\n next!(p)\n end\n\n # the second task does the computation\n @async begin\n pmap(1:nfiles) do i\n process(subfigs, ls, vlines, cs, files[i], cellids)\n put!(channel, true) # trigger a progress bar update\n end\n put!(channel, false) # this tells the printing task to finish\n end\nend","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/#demo_plot_mesh","page":"Plot mesh","title":"Plot mesh","text":"","category":"section"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"This demo shows how to plot mesh. The cell centers are represented by the markers.","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"using VlasiatorPyPlot\n\nconst file = \"test/data/bulk.amr.vlsv\"\nmeta = load(file)\n# 3D mesh\nfig = plt.figure()\nax = fig.add_subplot(projection=\"3d\")\n\nplotmesh(meta, marker=\"+\")\n\n# 2D mesh\nfig = plt.figure()\n\npcolormesh(meta, \"proton/vg_rho\"; axisunit=SI)\nplotmesh(meta, projection=\"y\"; color=\"w\")","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/#demo_poynting","page":"Poynting flux","title":"Poynting flux","text":"","category":"section"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"This demo shows how to extract the Poynting flux on a subdomain from 2D and plot.","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"Usage:","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"julia -t 4 demo_poynting_mt_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"or","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"JULIA_NUM_THREADS=4 julia demo_poynting_mt_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"using Statistics: mean, normalize\nusing LinearAlgebra: ×, ⋅\nusing Vlasiator\nusing Vlasiator: μ₀, prep2d, prep2dslice\nusing Glob, DSP, Polyester, Printf, PyPlot\n\n\"\"\"\n extract_EM(files, range1, range2, pArgs, ndim=2; normal=:y, verbose=true)\n\nExtract time-series of EM fields from `files` within `range1` in the 1st dim and `range1` in\nthe 2nd dim.\n\"\"\"\nfunction extract_EM(files, range1, range2, pArgs, ndim=2; normal=:y, verbose=true)\n @assert ndim ∈ (2,3) \"Only support extracting EM fields from 2D/3D runs.\"\n nfile = length(files)\n e = zeros(Float32, 3, length(range1), length(range2), nfile)\n b = zeros(Float32, 3, length(range1), length(range2), nfile)\n\n if ndim == 2\n @batch for i in eachindex(files)\n verbose && println(\"i = $i/$nfile, file = $(files[i])\")\n meta = load(files[i])\n\n e[1,:,:,i] = prep2d(meta, \"vg_e_vol\", 1)[range1, range2]\n e[2,:,:,i] = prep2d(meta, \"vg_e_vol\", 2)[range1, range2]\n e[3,:,:,i] = prep2d(meta, \"vg_e_vol\", 3)[range1, range2]\n b[1,:,:,i] = prep2d(meta, \"vg_b_vol\", 1)[range1, range2]\n b[2,:,:,i] = prep2d(meta, \"vg_b_vol\", 2)[range1, range2]\n b[3,:,:,i] = prep2d(meta, \"vg_b_vol\", 3)[range1, range2]\n end\n else\n @batch for i in eachindex(files)\n verbose && println(\"i = $i/$nfile, file = $(files[i])\")\n meta = load(files[i])\n\n e[1,:,:,i] = prep2dslice(meta, \"vg_e_vol\", normal, 1, pArgs)[range1, range2]\n e[2,:,:,i] = prep2dslice(meta, \"vg_e_vol\", normal, 2, pArgs)[range1, range2]\n e[3,:,:,i] = prep2dslice(meta, \"vg_e_vol\", normal, 3, pArgs)[range1, range2]\n b[1,:,:,i] = prep2dslice(meta, \"vg_b_vol\", normal, 1, pArgs)[range1, range2]\n b[2,:,:,i] = prep2dslice(meta, \"vg_b_vol\", normal, 2, pArgs)[range1, range2]\n b[3,:,:,i] = prep2dslice(meta, \"vg_b_vol\", normal, 3, pArgs)[range1, range2]\n end\n end\n e, b\nend\n\n\"Moving box average of vector `g` with box size `n`.\"\nfunction moving_average(g::AbstractVector{<:AbstractFloat}, n::Int)\n nbackward = div(n,2)\n nforward = isodd(n) ? div(n,2) : div(n,2) - 1\n len = length(g)\n g_avg = similar(g)\n @inbounds @batch for i = 1:len\n lo = max(1, i - nbackward)\n hi = min(len, i + nforward)\n g_avg[i] = mean(@view g[lo:hi])\n end\n g_avg\nend\n\n\"Extract the perturbation from vector `v` with moving box size `nbox`.\"\nfunction detrend(v::AbstractVector{<:AbstractFloat}; nbox=length(v)÷12)\n v̄ = moving_average(v, nbox)\n dv = v .- v̄\nend\n\n\"Extract the perturbation from 4D array `v` along the last dim with moving box size `nbox`.\"\nfunction detrend(v::AbstractArray{<:AbstractFloat}; nbox=size(v,4)÷12)\n v̄ = similar(v)\n for idim = 1:3\n for j in axes(v, 3), i in axes(v, 2)\n v̄[idim,i,j,:] = @views moving_average(v[idim,i,j,:], nbox)\n end\n end\n dv = v .- v̄\n dv, v̄\nend\n\n\"Band pass filter for vector field `var`.\"\nfunction band_pass_filter(var, responsetype, designmethod)\n\n filter = digitalfilter(responsetype, designmethod)\n\n var_filtered = zeros(eltype(var), size(var,4), 3, size(var,2), size(var,3))\n\n for idim = 1:3\n for j in axes(var, 3), i in axes(var, 2)\n var_filtered[:,idim,i,j] = filtfilt(filter, var[idim,i,j,:])\n end\n end\n var_filtered\nend\n\n\"\"\"\n calc_poynting(de, db, b̄, it)\n\nReturn full Poynting vector, also parallel and perpendicular Poynting vector components to\nthe magnetic field. The perpendicular components are in-plane.\n\"\"\"\nfunction calc_poynting(de, db, b̄, it)\n\n s = zeros(3, size(de,3), size(de,4))\n # parallel and perpendicular Poynting vector magnitudes\n s_par = zeros(size(de,3), size(de,4))\n s_perp = zeros(size(de,3), size(de,4))\n\n @views for j in axes(de,4), i in axes(de,3)\n # Poynting vector = dE × dB\n s[:,i,j] = de[it,:,i,j] × db[it,:,i,j] / μ₀\n\n # Transform into parallel and perpendicular direction w.r.t. B\n b̂ = normalize(b̄[:,i,j,it])\n s_par[i,j] = s[:,i,j] ⋅ b̂\n #s_perp[i,j] = norm(s[:,i,j] .- s_par[i,j] .* b̂)\n # in-plane perpendicular component only\n s_perp[i,j] = sqrt((s[1,i,j] - s_par[i,j]*b̂[1])^2 + (s[3,i,j] - s_par[i,j]*b̂[3])^2)\n end\n\n s, s_par, s_perp\nend\n\n\"Output figures of Poynting vectors for each snapshot.\"\nfunction plot_poynting(de_filtered, db_filtered, b̄, x1, x2, frequency_range)\n\n nt = size(de_filtered, 1)\n\n norm1 = let\n sparmax = frequency_range == \"high\" ? 5e-7 : 1e-5\n sparmin = -sparmax\n levels = matplotlib.ticker.MaxNLocator(nbins=255).tick_values(sparmin, sparmax)\n matplotlib.colors.BoundaryNorm(levels, ncolors=256, clip=true)\n end\n\n norm2 = let\n sperpmax = frequency_range == \"high\" ? 5e-7 : 1e-5\n sperpmin = 0.0\n levels = matplotlib.ticker.MaxNLocator(nbins=255).tick_values(sperpmin, sperpmax)\n matplotlib.colors.BoundaryNorm(levels, ncolors=256, clip=true)\n end\n\n stride = 10 # number of strides for quivers\n\n s, s_par, s_perp = calc_poynting(de_filtered, db_filtered, b̄, 1)\n\n\n fig, axs = plt.subplots(1, 2; figsize=(11,6), sharex=true, sharey=true,\n constrained_layout=true)\n\n axs[1].set_title(L\"S_\\parallel\"; fontsize=\"large\")\n axs[2].set_title(L\"S_\\perp\"; fontsize=\"large\")\n\n for ax in axs\n ax.set_aspect(\"equal\")\n ax.set_xlabel(L\"x1 [R_E]\"; fontsize=\"large\")\n ax.set_ylabel(L\"x2 [R_E]\"; fontsize=\"large\")\n end\n\n c1 = axs[1].pcolormesh(x1, x2, s_par';\n cmap=matplotlib.cm.RdBu_r,\n shading=\"nearest\",\n norm=norm1,\n )\n\n cb1 = colorbar(c1; ax=axs[1], extend=\"both\")\n cb1.ax.set_ylabel(L\"[W/m^2]\"; fontsize=\"large\")\n\n c2 = axs[2].pcolormesh(x1, x2, s_perp';\n cmap=matplotlib.cm.turbo,\n shading=\"nearest\",\n norm=norm2,\n )\n\n cb2 = colorbar(c2; ax=axs[2], extend=\"max\")\n cb2.ax.set_ylabel(L\"[W/m^2]\"; fontsize=\"large\")\n\n s1 = @views (s[1,:,:] ./ hypot.(s[1,:,:], s[3,:,:]))[1:stride:end, 1:stride:end]'\n s2 = @views (s[3,:,:] ./ hypot.(s[1,:,:], s[3,:,:]))[1:stride:end, 1:stride:end]'\n\n q = axs[1].quiver(x1[1:stride:end], x2[1:stride:end], s1, s2; color=\"k\")\n\n b1 = @views (b̄[1,:,:,1] ./ hypot.(b̄[1,:,:,1], b̄[3,:,:,1]))[1:stride:end, 1:stride:end]'\n b2 = @views (b̄[3,:,:,1] ./ hypot.(b̄[1,:,:,1], b̄[3,:,:,1]))[1:stride:end, 1:stride:end]'\n\n qb = axs[1].quiver(x1[1:stride:end], x2[1:stride:end], b1, b2; color=\"tab:purple\")\n\n if frequency_range == \"high\"\n fig.suptitle(\"t = $(t[1]) s, [0.1, 1.0] Hz\";\n fontsize=\"xx-large\")\n else\n fig.suptitle(\"t = $(t[1]) s, [$(responsetype.w1), $(responsetype.w2)] Hz\";\n fontsize=\"xx-large\")\n end\n\n for it = 1:nt\n @info \"it = $it\"\n local s, s_par, s_perp\n outname = \"poynting/poynting_$(lpad(it, 4, '0'))_band$frequency_range.png\"\n isfile(outname) && continue\n s, s_par, s_perp = calc_poynting(de_filtered, db_filtered, b̄, it)\n\n c1.set_array(s_par')\n c2.set_array(s_perp')\n\n ŝx = @views @. s[1,:,:] / hypot(s[1,:,:], s[3,:,:])\n ŝz = @views @. s[3,:,:] / hypot(s[1,:,:], s[3,:,:])\n\n q.set_UVC(ŝx[1:stride:end, 1:stride:end]', ŝz[1:stride:end, 1:stride:end]')\n\n b̂x = @views @. b̄[1,:,:,it] / hypot(b̄[1,:,:,it], b̄[3,:,:,it])\n b̂z = @views @. b̄[3,:,:,it] / hypot(b̄[1,:,:,it], b̄[3,:,:,it])\n\n qb.set_UVC(b̂x[1:stride:end, 1:stride:end]', b̂z[1:stride:end, 1:stride:end]')\n\n if frequency_range == \"high\"\n fig.suptitle(\"t = $(t[it]) s, [0.1, 1.0] Hz\";\n fontsize=\"xx-large\")\n else\n fig.suptitle(\"t = $(t[it]) s, [$(responsetype.w1), $(responsetype.w2)] Hz\";\n fontsize=\"xx-large\")\n end\n savefig(outname; dpi=300, bbox_inches=\"tight\")\n end\nend\n\n########## Main\n\nfiles = glob(\"bulk*.vlsv\", \".\")\nnfile = length(files)\n\nconst frequency_range = \"low\" # filtered frequency range ∈ (\"low\", \"high\")\nconst extent = [6., 16., -7., 7.] # [RE], default: [-Inf32, Inf32, -Inf32, Inf32]\nconst normal = :none # plane normal direction for 3D data, (:none, :x, :y, :z)\nconst fs = 2.0 # sampling frequency, [Hz]\n\n# WARNING: t may not be exact due to round-off errors in output time stamps!\nndim, pArgs, t, range1, range2 = let meta = load(files[1])\n pArgs = Vlasiator.set_args(meta, \"vg_e_vol\", EARTH; normal=:none)\n x1, x2 = Vlasiator.get_axis(pArgs)\n\n tstart = meta.time\n tend = load(files[end]).time\n\n ndims(meta), pArgs,\n range(round(tstart,digits=1), round(tend, digits=1), length=nfile),\n searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2]),\n searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\nend\n\n@assert ndim == 3 \"3D not working yet!\"\n\ne, b = extract_EM(files, range1, range2, pArgs, ndim; normal, verbose=true)\n\ndesignmethod = Butterworth(5)\nif frequency_range == \"high\"\n responsetype = Highpass(0.1; fs)\n nbox = 40\nelseif frequency_range == \"low\"\n responsetype = Bandpass(0.02, 0.067; fs)\n nbox = 200\nend\n\nde, _ = detrend(e; nbox)\ndb, b̄ = detrend(b; nbox)\n\nde_filtered = band_pass_filter(de, responsetype, designmethod)\ndb_filtered = band_pass_filter(db, responsetype, designmethod)\n\nx1 = range(extent[1], extent[2], length=length(range1))\nx2 = range(extent[3], extent[4], length=length(range2))\n\nplot_poynting(de_filtered, db_filtered, b̄, x1, x2, frequency_range)","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/#demo_tensor","page":"Pressure tensor","title":"Pressure tensor","text":"","category":"section"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"This demo shows how to plot the pressure tensor from one snapshot.","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"using Vlasiator, VlasiatorPyPlot, LaTeXStrings, Printf\n\nfunction main()\n file = \"bulk.0001582.vlsv\"\n\n axisunit = EARTH\n colorscale = Linear\n cmap = matplotlib.cm.turbo\n\n vars = [\"proton/vg_ptensor_diagonal\", \"proton/vg_ptensor_offdiagonal\"]\n\n #####\n meta = load(file)\n\n pArgs1 = Vlasiator.set_args(meta, vars[1], axisunit; normal=:none)\n pArgs2 = Vlasiator.set_args(meta, vars[2], axisunit; normal=:none)\n\n x, y = Vlasiator.get_axis(pArgs1)\n # [nPa]\n pxx = Vlasiator.prep2d(meta, vars[1], :x)' .* 1e9\n pyy = Vlasiator.prep2d(meta, vars[1], :y)' .* 1e9\n pzz = Vlasiator.prep2d(meta, vars[1], :z)' .* 1e9\n pyz = Vlasiator.prep2d(meta, vars[2], :1)' .* 1e9\n pxz = Vlasiator.prep2d(meta, vars[2], :2)' .* 1e9\n pxy = Vlasiator.prep2d(meta, vars[2], :3)' .* 1e9\n\n P = (pxx, pyy, pzz, pyz, pxz, pxy)\n P_str = (\"Pxx\", \"Pyy\", \"Pzz\", \"Pyz\", \"Pxz\", \"Pxy\")\n\n vmin = minimum(minimum.(P))\n vmax = maximum(maximum.(P))\n\n cnorm1, cticks1 = set_colorbar(colorscale, vmin, vmax)\n\n fig, axs = subplots(3,2,\n figsize=(6, 12), sharex=true, sharey=true, constrained_layout=true)\n\n c1 = axs[1].pcolormesh(x, y, pxx; norm=cnorm1, cmap)\n\n for i in eachindex(axs)[2:end]\n axs[i].pcolormesh(x, y, P[i]; norm=cnorm1, cmap)\n end\n\n for (i, ax) in enumerate(axs)\n ax.set_aspect(\"equal\")\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.set_title(P_str[i])\n end\n\n for ax in axs[3,:]\n ax.set_xlabel(L\"x [$R_E$]\")\n end\n\n for ax in axs[:,1]\n ax.set_ylabel(L\"y [$R_E$]\")\n end\n\n # One colorbar for all subplots\n cb1 = colorbar(c1; ax=axs, ticks=cticks1, fraction=0.046, pad=0.04)\n cb1.ax.set_ylabel(\"[nPa]\")\n cb1.outline.set_linewidth(1.0)\n\n str_title = @sprintf \"Pressure Tensor at t = %4.1fs\" meta.time\n\n fig.suptitle(str_title, fontsize=\"xx-large\")\n\n savefig(\"ptensor.png\", bbox_inches=\"tight\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"python/#Interoperability-Between-Julia-and-Python","page":"Calling from Python","title":"Interoperability Between Julia and Python","text":"","category":"section"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"There are currently two ways to call Julia from Python and vice versa, which are described below. When converting from Julia to Python, there are two most important differences:","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"Julia is column-major, while Python is row-major.\nJulia adopts by default 1-based indexing, while Python adopts 0-based indexing.","category":"page"},{"location":"python/#JuliaCall","page":"Calling from Python","title":"JuliaCall","text":"","category":"section"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"Vlasiator.jl can be called from Python via JuliaCall. JuliaCall will link to the first Julia version in the system path. If Vlasiator.jl has been installed, we can use it directly; otherwise we need to state it in the juliacalldeps.json file.","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"from juliacall import Main as jl\njl.seval(\"using Vlasiator\")\nfile = \"bulk.1d.vlsv\"\nmeta = jl.load(file)","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"Matplotlib can then be used to visualize the data.","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"from matplotlib import pyplot as plt\nimport numpy as np\nrho = jl.readvariable(meta, \"proton/vg_rho\")\nx = np.arange(meta.coordmin[0], meta.coordmax[0], meta.dcoord[0])\nplt.plot(x, rho)\nplt.show()","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"warn: Warn\nThere is an issue that JuliaCall may decide to check pkg installation every time for a new session. We need to first make sure that PythonCall is installed in Julia; then make sure your PYTHONPATH is properly set. See this issue for more information.","category":"page"},{"location":"python/#PyJulia","page":"Calling from Python","title":"PyJulia","text":"","category":"section"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"Vlasiator.jl can also be called from Python with the aid of PyJulia. Following the installation steps described in the manual[1], and then inside Python REPL:","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"# Handling initialization issue for Conda\nfrom julia.api import Julia\njl = Julia(compiled_modules=False)\n\nfrom julia import Vlasiator\nfile = \"bulk1.0001000.vlsv\"\nmeta = Vlasiator.load(file)\nvar = \"proton/vg_rho\"\ndata = Vlasiator.readvariable(meta, var)","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"To run a Julia script in Python,","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"# Handling initialization issue for Conda\nfrom julia.api import Julia\njl = Julia(compiled_modules=False)\njl.eval('include(\"examples/demo_2dplot_pyplot.jl\")')\nimport matplotlib.pyplot as plt\nplt.show()","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"note: Note\nThis approach is for you to have a taste of the package with a Python frontend. The workaround shown above for handling the static python libraries makes it slow for regular use. An alternative solution would be creating system images, but as of Julia 1.6 the user experience is not smooth. For better integrated experience with its full power, it is recommended to use the package inside Julia.","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"[1]: For Debian-based Linux distributions, it gets a little bit tricky. Please refer to Troubleshooting for details.","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/#demo_search_waves","page":"Search waves","title":"Search waves","text":"","category":"section"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"This demo shows how to search for wave-like structures and plot spatial-temporal distributions.","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"Procedures:","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"Extract variables in all cells from all snapshots.\nFor each cell and time interval, count time-series local peaks.\nPlot the peak occurrence frequencies across the whole domain as an indicator for waves.","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"note: Note\nWhen dealing with multiple variables, it is recommended to handle one variable at atime through the whole process due to memory considerations. With large number of frame counts, the current procedure is still memory-consuming.It assumes uniform sampling in time.\nPeak-finding is threaded, but plotting is still serial.","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"julia -t 4 demo_wave_search_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"or","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"JULIA_NUM_THREADS=4 julia demo_wave_search_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"using Glob, Vlasiator, PyPlot, LaTeXStrings\n\n\"Extract time series variable\"\nfunction extract_var(files, ncells, varname, component=0)\n nfiles = length(files)\n var = zeros(Float32, ncells[1], ncells[2], nfiles)\n\n # Extract data from each frame\n if component == 0 # scalar\n Threads.@threads for i = eachindex(files)\n meta = load(files[i])\n var[:,:,i] = meta[varname]\n end\n else # vector component\n Threads.@threads for i = eachindex(files)\n meta = load(files[i])\n var[:,:,i] = meta[varname][component,:]\n end\n end\n\n return var\nend\n\n\"Count local maxima of vector `y` with moving box length `n`.\"\nfunction countpeaks(y, n; interval=1)\n maxs = Int[]\n if interval == 1\n for i in 2:length(y)-1\n if y[i-1] < y[i] > y[i+1]\n push!(maxs, i)\n end\n end\n elseif interval == 2\n for i in 3:length(y)-2\n if y[i-2] ≤ y[i-1] < y[i] > y[i+1] ≥ y[i+2]\n push!(maxs, i)\n end\n end\n elseif interval == 3\n for i in 4:length(y)-3\n if y[i-3] ≤ y[i-2] ≤ y[i-1] < y[i] > y[i+1] ≥ y[i+2] > y[i+3]\n push!(maxs, i)\n end\n end\n else\n error(\"interval = $interval not implemented!\")\n end\n nCounts = zeros(Int, length(y)-n+1)\n nCounts[1] = count(i->(1 ≤ i ≤ n), maxs)\n for i in 1:length(y)-n\n nCounts[i+1] = nCounts[i]\n if i ∈ maxs\n nCounts[i+1] -= 1\n end\n if i+n-1 ∈ maxs\n nCounts[i+1] += 1\n end\n end\n nCounts\nend\n\n\"Check wave-like occurrence frequencies within box length `n` of output interval `dt`.\"\nfunction checkwaves_sma(var, dt=0.5, n::Int=size(var,3); interval=1)\n nPeaks = zeros(Int, size(var,3)-n+1, size(var,1), size(var,2))\n\n Threads.@threads for j in axes(var, 2)\n for i in axes(var, 1)\n var_series = @view var[i,j,:]\n nPeaks[:,i,j] = countpeaks(var_series, n; interval)\n end\n end\n nPeaks ./ (n*dt)\nend\n\nfunction plot_dist(files, varnames, varnames_print, components, Δt, nboxlength;\n interval=1, nplotstride=1)\n @assert nboxlength ≥ 3 && isodd(nboxlength) \"Expect odd box length ≥ 3!\"\n if (local nfiles = length(files)) < nboxlength\n @warn \"Set moving box length to the number of files...\"\n nboxlength = nfiles\n end\n local x, y, tStart, tEnd, ncells\n let RE = Vlasiator.RE\n meta = load(files[1])\n tStart = meta.time\n ncells = meta.ncells\n x = LinRange{Float32}(meta.coordmin[1]/RE, meta.coordmax[1]/RE, meta.ncells[1])\n y = LinRange{Float32}(meta.coordmin[2]/RE, meta.coordmax[2]/RE, meta.ncells[2])\n meta = load(files[end])\n tEnd = meta.time\n end\n\n fig, ax = plt.subplots(figsize=(16,9))\n fontsize = 14\n vmin, vmax = 0.0, 0.5\n levels = matplotlib.ticker.MaxNLocator(nbins=255).tick_values(vmin, vmax)\n norm = matplotlib.colors.BoundaryNorm(levels, ncolors=256, clip=true)\n ticks = range(vmin, vmax, length=11)\n\n fakedata = zeros(Float32, length(x), length(y))\n im = ax.pcolormesh(y, x, fakedata; norm)\n\n ax.set_aspect(\"equal\")\n ax.set_xlabel(L\"y [$R_E$]\"; fontsize, weight=\"black\")\n ax.set_ylabel(L\"x [$R_E$]\"; fontsize, weight=\"black\")\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true, color=\"grey\", linestyle=\"-\")\n\n cb = fig.colorbar(im; ax, ticks, pad=0.02)\n cb.ax.set_ylabel(\"Frequency of local maxima occurrence, [#/s]\"; fontsize)\n\n for i in eachindex(varnames)\n outdir = \"../out/$(lowercase(varnames_print[i]))\"\n !isdir(outdir) && mkdir(outdir)\n length(glob(\"spatial*.png\", outdir)) == length(files) - nboxlength + 1 && continue\n\n # Obtain time series data\n var = extract_var(files, ncells, varnames[i], components[i])\n # Count local peak occuring frequencies at each location\n fPeaks = checkwaves_sma(var, Δt, nboxlength; interval)\n\n for it in 1:nplotstride:size(fPeaks,1) # Iterate over time\n outname = joinpath(outdir,\n \"spatial_perturbation_distribution_$(lpad(it, 4, '0')).png\")\n isfile(outname) && continue\n # Update plot\n im.set_array(fPeaks[it,:,:])\n ax.set_title(\"$(varnames_print[i]) Perturbation Detection, \"*\n \"t = $(round(tStart+(it-1)*Δt, digits=1)) ~ \"*\n \"$(round(tStart+(it+nboxlength-1)*Δt, digits=1))s\";\n fontsize, fontweight=\"bold\")\n\n savefig(outname, bbox_inches=\"tight\")\n end\n end\nend\n\nfunction main()\n varnames = [\"proton/vg_rho\", \"vg_pressure\", \"proton/vg_v\", \"proton/vg_v\", \"vg_b_vol\",\n \"vg_e_vol\", \"vg_e_vol\"]\n varnames_print = [\"Density\", \"Thermal Pressure\", \"Vx\", \"Vy\", \"Bz\", \"Ex\", \"Ey\"]\n components = [0, 0, 1, 2, 3, 1, 2] # 0: scalar; 1: x, 2: y, 3: z\n Δt = 0.5 # output time interval [s]\n nboxlength = 101 # moving box average length\n interval = 2 # local peak gap minimal interval\n nplotstride = 50 # plot intervals in frames\n dir = \"./\" # data directory\n\n files = glob(\"bulk*.vlsv\", dir)\n\n println(\"Total number of snapshots: $(length(files))\")\n println(\"Running with $(Threads.nthreads()) threads...\")\n\n @time plot_dist(files, varnames, varnames_print, components, Δt, nboxlength;\n interval, nplotstride)\n\n println(\"Virtual satellite extraction done!\")\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"","page":"Home","title":"Home","text":"CurrentModule = Vlasiator","category":"page"},{"location":"#Vlasiator.jl","page":"Home","title":"Vlasiator.jl","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"Vlasiator.jl is a data processing and analyzing tool for the numerical model for collisionless ion-kinetic plasma physics Vlasiator. This lightweight package is built upon its sister in Python Analysator and carefully designed for performance, capability and ease of use. It can be easily integrated with external packages like FieldTracer.jl and TestParticle.jl to do all kinds of in-depth analysis.","category":"page"},{"location":"","page":"Home","title":"Home","text":"Vlasiator.jl contains the following features:","category":"page"},{"location":"","page":"Home","title":"Home","text":"Reading VLSV format data.\nCalculating derived quantities from raw VLSV outputs.\nExtracting quantities at a given point/line/plane/box.\nPlotting 1D curves/2D cuts of saved/derived variables and phase space distributions.\nAnalyzing velocity distribution functions.\nAppending DCCRG arrays to VLSV files.\nConverting selected domain and variables from VLSV into VTK format for data analysis and visualization in ParaView and VisIt.\nMonitoring Vlasiator run log files.","category":"page"},{"location":"","page":"Home","title":"Home","text":"warning: Warning\nThis package mostly aims at supporting Vlasiator 5.0+. Older versions of Vlasiator has different naming standards for outputs, and is not guaranteed to work. The full naming standards are described in the analysator wiki page.","category":"page"},{"location":"#What-is-Vlasiator","page":"Home","title":"What is Vlasiator","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"Vlasiator solves the Vlasov–Maxwell system of equations for ions while assuming massless electrons under quasi-neutrality. The fundamental description of charged particle motion in an electromagnetic field is given by the Vlasov equation","category":"page"},{"location":"","page":"Home","title":"Home","text":"fracpartial f_alphapartial t + mathbfvcdotfracpartial f_alphapartial mathbfr + fracq_alpham_alpha(mathbfE+mathbfvtimesmathbfB)cdot fracpartial f_alphapartial mathbfv = 0","category":"page"},{"location":"","page":"Home","title":"Home","text":"where alpha denotes the particle species, mathbfr and mathbfv are the spatial and velocity coordinates, f_alpha(mathbfrmathbfvt) is the six-dimensional phase-space density of a particle species with mass m_alpha and charge q_alpha, and acceleration mathbfa is given by the Lorentz force with mathbfE and mathbfB are the electric and magnetic field, respectively.","category":"page"},{"location":"","page":"Home","title":"Home","text":"The zeroth and first moments of plasma, ion density n_alpha and velocity mathbfu_alpha, are obtained as integrals of the ion velocity distribution function","category":"page"},{"location":"","page":"Home","title":"Home","text":"beginaligned\nn_alpha = int f_alpha(mathbfrmathbfvt)mathrmdmathbfv \nmathbfu_alpha = frac1n_alphaint mathbfvf_alpha(mathbfrmathbfvt)mathrmdmathbfv\nendaligned","category":"page"},{"location":"","page":"Home","title":"Home","text":"The magnetic field is updated using Faraday's law:","category":"page"},{"location":"","page":"Home","title":"Home","text":"nabla times mathbfE = -fracpartial mathbfBpartial t","category":"page"},{"location":"","page":"Home","title":"Home","text":"and the electric field is given by the generalized Ohm's law:","category":"page"},{"location":"","page":"Home","title":"Home","text":"mathbfE = -mathbfu_alpha timesmathbfB + frac1n_alpha q_alphamathbfjtimesmathbfB - frac1n_alpha q_alphanablacdotoverleftrightarrowP_e + eta mathbfj","category":"page"},{"location":"","page":"Home","title":"Home","text":"The four terms on the right-handed side are the convection term, the Hall term, the electron pressure gradient term, and the resistive term, respectively. The total current density mathbfj is obtained from Ampère's law where the displacement current has been neglected:","category":"page"},{"location":"","page":"Home","title":"Home","text":"nablatimesmathbfB = mu_0 mathbfj","category":"page"},{"location":"","page":"Home","title":"Home","text":"Finally, by determining the electron pressure tensor by using an appropriate equation of state, the evolution of the system can be followed in time. For example, let overleftrightarrowP_e = p_e overleftrightarrowI where p_e is the isotropic scalar electron pressure. In an isothermal process,","category":"page"},{"location":"","page":"Home","title":"Home","text":"p_e = n_e k_B T_e","category":"page"},{"location":"","page":"Home","title":"Home","text":"where n_e approx n_i and T_e is a constant. In an adiabatic process with index gamma,","category":"page"},{"location":"","page":"Home","title":"Home","text":"p_e n_e^gamma = textconst","category":"page"},{"location":"","page":"Home","title":"Home","text":"The different processes can be generalized into the polytropic process:","category":"page"},{"location":"","page":"Home","title":"Home","text":"p_e n_e^n = textconst","category":"page"},{"location":"","page":"Home","title":"Home","text":"When the ideal gas law applies, the polytropic index n=1 for an isothermal process, and n=gamma for an adiabatic process.","category":"page"},{"location":"","page":"Home","title":"Home","text":"For more details, please refer to Vlasov methods in space physics and astrophysics.","category":"page"},{"location":"#Getting-started","page":"Home","title":"Getting started","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"To install,","category":"page"},{"location":"","page":"Home","title":"Home","text":"julia> ]\npkg> add Vlasiator","category":"page"},{"location":"","page":"Home","title":"Home","text":"You can then use the package via","category":"page"},{"location":"","page":"Home","title":"Home","text":"julia> using Vlasiator","category":"page"},{"location":"#Visualization","page":"Home","title":"Visualization","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"PyPlot","category":"page"},{"location":"","page":"Home","title":"Home","text":"If you aim at using Matplotlib, besides adding PyPlot and the Vlasiator specific wrapper VlasiatorPyPlot, you should also link to a preinstalled Python version by setting the environment variable and building the PyCall package","category":"page"},{"location":"","page":"Home","title":"Home","text":"ENV[\"PYTHON\"]=\"your python executable\"\nPkg.build(\"PyCall\")","category":"page"},{"location":"","page":"Home","title":"Home","text":"If ENV[\"PYTHON\"] = \"\" before building, a private Python distribution will be installed via Miniconda. Details are described in automated matplotlib installation.","category":"page"},{"location":"","page":"Home","title":"Home","text":"Makie","category":"page"},{"location":"","page":"Home","title":"Home","text":"You can add Makie.jl and VlasiatorMakie.jl through the pkg manger. The sub-package VlasiatorMakie provides user recipes for Makie.","category":"page"},{"location":"","page":"Home","title":"Home","text":"Plots","category":"page"},{"location":"","page":"Home","title":"Home","text":"Add Plots.jl through the pkg manager. Built-in user recipes for Plots are provided.","category":"page"},{"location":"#Author","page":"Home","title":"Author","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"This module is written by Hongyang Zhou. For citing Vlasiator.jl, please refer to (Image: DOI).","category":"page"},{"location":"contributing/#Contributing","page":"Contributing","title":"Contributing","text":"","category":"section"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"Try to explain your contribution with simple language.\nReferences are always welcome.\nFollow the coding standards in the source.","category":"page"},{"location":"contributing/#Reporting-issues","page":"Contributing","title":"Reporting issues","text":"","category":"section"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"If you are experiencing issues or have discovered a bug, please report it on GitHub. To make the resolution process easier, please include the version of Julia and Vlasiator.jl in your writeup. These can be found with two commands:","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"julia> versioninfo()\njulia> using Pkg; Pkg.status()","category":"page"},{"location":"contributing/#Feature-requests","page":"Contributing","title":"Feature requests","text":"","category":"section"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"If you have suggestions of improvement or algorithms that you would like to see implemented in Vlasiator.jl, please open an issue on GitHub. Suggestions as well as feature requests are very welcome.","category":"page"},{"location":"contributing/#Code-contribution","page":"Contributing","title":"Code contribution","text":"","category":"section"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"If you have code that you would like to contribute to Vlasiator.jl, that is awesome! Please open an issue before you create the pull request on GitHub so that we make sure your idea is aligned with our goals for the project.","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"After your idea is discussed and revised by maintainers, please get the development version of the project by typing the following in the package manager:","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"] activate @dev","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"This will create a fresh environment called @dev where you can play with the project components without compromising your normal user environment.","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"] dev Vlasiator","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"This will clone all the project components in your ~/.julia folder so that you can modify it and submit a pull request on GitHub later. Don't hesitate to ask questions. We are looking forward to your contributions.","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/#demo_extract_magnetopause","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"","category":"section"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"This demo shows how to extract variables along the magnetopause defined by Bz == 0 from multiple frames.","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"julia -t 4 demo_magnetopause_2d_mt.jl","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"or","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"JULIA_NUM_THREADS=4 julia demo_magnetopause_2d_mt.jl","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"using Vlasiator, Glob\nusing Vlasiator: RE # Earth radius, [m]\nusing JLD2: jldsave\n\n\"\"\"\n extract_magnetopause_var(files; zmin=-4RE, zmax=4RE, verbose=true)\n\nExtract variables on the magnetopause defined by ``B_z = 0``.\n\"\"\"\nfunction extract_magnetopause_var(files; zmin=-4RE, zmax=4RE, verbose=true)\n nfiles = length(files)\n\n verbose && println(\"Number of files: $nfiles\")\n\n meta = load(files[1])\n\n x = LinRange{Float32}(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\n z = LinRange{Float32}(meta.coordmin[3], meta.coordmax[3], meta.ncells[3])\n\n z_range = let zmin_ = searchsortedfirst(z, zmin), zmax_ = searchsortedlast(z, zmax)\n zmin_:zmax_\n end\n\n x_crossing = zeros(Float32, length(z_range))\n z_crossing = z[z_range]\n\n cellids = Vector{Int}(undef, length(z_range))\n\n x_crossings = zeros(length(z_range), nfiles)\n v = zeros(3, length(z_range), nfiles)\n ey = zeros(length(z_range), nfiles)\n\n Threads.@threads for ifile in eachindex(files)\n verbose && println(\"$(files[ifile]) on thread $(Threads.threadid())\")\n meta = load(files[ifile])\n\n # Obtain thermal temperature\n b = meta[\"vg_b_vol\"]\n b = reshape(b, 3, meta.ncells[1], meta.ncells[3])\n\n # Extract the last point from right to left which fulfills Bz < 0\n for (i,k) in enumerate(z_range) # scan in z direction\n ind_ = findlast(>(0), @view b[3,:,k]) + 1 # count from upstream\n isnothing(ind_) && (ind_ = 1) # if not found then set to 1\n x_crossing[i] = x[ind_]\n end\n\n cellids = [ getcell(meta, [x_crossing[i], 0, z_crossing[i]])\n for i in eachindex(x_crossing, z_crossing) ]\n\n x_crossings[:,ifile] = x_crossing\n v[:,:,ifile] = readvariable(meta, \"proton/vg_v\", cellids)\n ey[:,ifile] = readvariable(meta, \"vg_e_vol\", cellids)[2,:]\n end\n\n z_crossing, x_crossings, v, ey\nend\n\n######\n\nfiles = glob(\"bulk*.vlsv\", \".\")\n\n@time z,x,v,ey = extract_magnetopause_var(files)\n\njldsave(\"magnetopause.jld2\"; z,x,v,ey)","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_log/#demo_log","page":"Log tracking","title":"Log tracking","text":"","category":"section"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"This is an example of extracting log file timing information and visualize them.","category":"page"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"using Vlasiator, Dates, Plots\n\n# plotly is nice for scanning through data interactively\nplotly()\n\nconst file = \"logfile.txt\"\n\ntimestamps, speed = readlog(file)\n\nscatter(timestamps, speed,\n markershape=:circle,\n #yaxis=:log10,\n xlabel=\"Time\", ylabel=\"Time per simulated second [s]\")","category":"page"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"","category":"page"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/#demo_plot_line2","page":"Plot variables along a line","title":"Plot variables along a line","text":"","category":"section"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"This demo shows how to plot variables along a line.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"using Vlasiator, PyPlot, Glob, Printf\nusing Vlasiator: RE # Earth radius [m]\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n nfiles = length(files)\n\n x1, x2 = 8.0, 29.0\n point1 = [x1, 0, 0] .* RE\n point2 = [x2, 0, 0] .* RE\n\n cellids, distances, coords =\n let meta = load(files[1])\n getcellinline(meta, point1, point2)\n end\n\n loc = range(x1, x2, length=length(cellids))\n\n ρmin, ρmax = 0.0, 10.0 # [amu/cc]\n vmin, vmax = -640.0, 0.0 # [km/s]\n pmin, pmax = 0.0, 1.82 # [nPa]\n bmin, bmax = -25.0, 60.0 # [nT]\n\n fontsize = 14\n\n fig, axs = plt.subplots(4, 1, figsize=(10, 15), sharex=true, constrained_layout=true)\n\n axs[end].set_xlim(x1, x2)\n\n axs[1].set_ylim(ρmin, ρmax)\n axs[2].set_ylim(vmin, vmax)\n axs[3].set_ylim(pmin, pmax)\n axs[4].set_ylim(bmin, bmax)\n for ax in axs\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axs[end].set_xlabel(\"x [Re]\"; fontsize)\n axs[1].set_ylabel(\"Density [amu/cc]\"; fontsize)\n axs[2].set_ylabel(\"Velocity [km/s]\"; fontsize)\n axs[3].set_ylabel(\"Pressure [nPa]\"; fontsize)\n axs[4].set_ylabel(\"Magnetic field [nT]\"; fontsize)\n\n # Loop over snapshots\n for (i, file) in enumerate(files)\n isfile(\"out/\"*file[end-8:end-5]*\".png\") && continue\n\n println(\"i = $i/$nfiles, file = $file\")\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1e9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1e9 # [nPa]\n\n bz = readvariable(meta, \"vg_b_vol\", cellids)[3,:] .* 1e9 #[nT]\n\n imagnetopause_ = findfirst(<(0.0), bz)\n\n axs[1].plot(loc, rho_extract ./ 1e6, label=\"Proton density\", color=\"#1f77b4\")\n vl1 = axs[1].vlines(loc[imagnetopause_], ρmin, ρmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[2].plot(loc, v_extract[1,:] ./ 1e3, label=\"Vx\", color=\"#1f77b4\")\n vl2 = axs[2].vlines(loc[imagnetopause_], vmin, vmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[3].plot(loc, pram_extract, label=\"Ram\", color=\"#1f77b4\")\n axs[3].plot(loc, p_extract, label=\"Thermal\", color=\"#ff7f0e\")\n vl3 = axs[3].vlines(loc[imagnetopause_], pmin, pmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[4].plot(loc, bz, label=\"Bz\", color=\"#1f77b4\")\n hl4 = axs[4].hlines(0.0, loc[1], loc[end], colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n vl4 = axs[4].vlines(loc[imagnetopause_], bmin, bmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n str_title = @sprintf \"t= %4.1fs\" meta.time\n axs[1].set_title(str_title; fontsize)\n\n axs[2].legend(;loc=\"upper right\", fontsize)\n axs[3].legend(;loc=\"upper left\", fontsize)\n axs[4].legend(;loc=\"upper right\", fontsize)\n\n savefig(\"out/\"*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n\n for ax in axs\n for line in ax.get_lines()\n line.remove()\n end\n end\n for line in (vl1, vl2, vl3, vl4, hl4)\n line.remove()\n end\n end\n\n close(fig)\n println(\"Finished!\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/#demo_2d_bowshock_mt","page":"Extract bow shock location","title":"Extract bow shock location","text":"","category":"section"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"This demo shows how to extract the bow shock location from 2D equatorial run outputs and save into file. To run in multi-threading mode,","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"julia -t nthreads demo_bowshock_2d_mt.jl","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"or alternatively","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"JULIA_NUM_THREADS=$nthreads julia demo_bowshock_2d_mt.jl","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"using Vlasiator, Glob\nusing Vlasiator: RE # Earth radius, [m]\nusing JLD2: jldsave\n\n# Upstream solar wind temperature\nconst Tsw = 0.5e6 #[K]\n\nfunction extract_bowshock_position(files; verbose=true)\n nfiles = length(files)\n\n verbose && println(\"Number of files: $nfiles\")\n\n meta = load(files[1])\n\n x = LinRange{Float32}(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\n y = LinRange{Float32}(meta.coordmin[2], meta.coordmax[2], meta.ncells[2])\n\n close(meta.fid)\n\n # Only extract bow shock location near the front between y = ±20RE\n ymin_ = findlast(<(-20RE), y)\n ymax_ = findfirst(>(20RE), y)\n\n x_crossing = zeros(Float32, ymax_-ymin_+1, nfiles)\n y_crossing = y[ymin_:ymax_]\n\n Threads.@threads for ifile = 1:nfiles\n verbose && println(\"$(files[ifile]) on thread $(Threads.threadid())\")\n f = load(files[ifile])\n # Obtain thermal temperature\n T = f[\"T\"]\n close(f.fid)\n T = reshape(T, f.ncells[1], f.ncells[2])\n # Extract bow shock location from the 1st point which fulfills\n # the threshold: T > 4 * Tsw\n for (i,j) in enumerate(ymin_:ymax_) # scan in y direction\n ind_ = findlast(>(4*Tsw), @view T[:,j]) # count from upstream\n x_crossing[i,ifile] = x[ind_]\n end\n end\n\n return x_crossing, y_crossing\nend\n\n#####\nfiles = glob(\"bulk*.vlsv\", \".\")\n\n@time x_crossing, y_crossing = extract_bowshock_position(files)\n\njldsave(\"example.jld2\"; x_crossing, y_crossing)","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/#demo_vdf","page":"VDF","title":"VDF","text":"","category":"section"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"This demo shows how to plot the phase space density (i.e. velocity distribution function) near a given spatial location.","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"using VlasiatorPyPlot\nusing Vlasiator: RE # Earth radius [m]\n\nfunction main()\n file = \"bulk.0001347.vlsv\"\n meta = load(file)\n\n coordinates = [0.0, 0.0, 0.0]\n\n vdfslice(meta, coordinates; verbose=true)\n\n # Show the spatial distribution of cells with saved VDF\n cellswithVDF = getcellwithvdf(meta)\n locations = [getcellcoordinates(meta, cid) for cid in cellswithVDF]\n\n xcell = zeros(size(locations))\n ycell = similar(xcell)\n\n for i in eachindex(locations)\n xcell[i] = locations[i][1] / RE\n ycell[i] = locations[i][2] / RE\n end\n\n figure()\n pcolormesh(meta, \"vg_pressure\", colorscale=Linear)\n ax = plt.gca()\n ax.scatter(xcell, ycell, marker=\"+\", color=\"w\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_diff_extracting/#demo_3d_grid_diff","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"","category":"section"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"This demos shows how to extract differences between FsGrid and DCCRG variables from 3D data.","category":"page"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"using Vlasiator, PyPlot\nimport Vlasiator: RE\n\nfunction main()\n directory = \"./\"\n file = \"bulk1.0001284.vlsv\"\n # Box range for variation diff extraction\n extent = [0.0, 12.0, -7.0, 7.0] # default [-Inf, Inf, -Inf, Inf]\n\n normal = :y\n origin = 0.0\n axisunit = EARTH\n comp = 2\n\n meta = load(directory*file)\n\n pArgs = Vlasiator.set_args(meta, \"fg_e\", axisunit; normal, origin)\n e_fg = Vlasiator.prep2dslice(meta, \"fg_e\", normal, comp, pArgs)\n\n pArgs = Vlasiator.set_args(meta, \"vg_e_vol\", axisunit; normal, origin)\n e_vg = Vlasiator.prep2dslice(meta, \"vg_e_vol\", normal, comp, pArgs)\n\n x1, x2 = Vlasiator.get_axis(pArgs)\n\n range1, range2 =\n if axisunit == EARTH\n searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2]),\n searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\n else\n searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2]),\n searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\n end\n\n ## Visualization\n fig, ax = plt.subplots()\n\n diff = (e_fg[range1,range2] - e_vg[range1,range2])'\n\n c = ax.pcolormesh(x1[range1], x2[range2], diff,\n norm=matplotlib.colors.CenteredNorm(),\n cmap=matplotlib.cm.RdBu_r)\n\n if comp == 1\n fig.colorbar(c; ax, label=\"E_fg_x - E_vg_x [V/m]\")\n elseif comp == 2\n fig.colorbar(c; ax, label=\"E_fg_y - E_vg_y [V/m]\")\n elseif comp == 3\n fig.colorbar(c; ax, label=\"E_fg_z - E_vg_z [V/m]\")\n end\n\n ax.set_title(file)\n\n #savefig(\"test_diff.png\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"","category":"page"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"log/#FAQ","page":"FAQ","title":"FAQ","text":"","category":"section"},{"location":"log/#Test-Data","page":"FAQ","title":"Test Data","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"If you don't have VLSV data at hand, Vlasiator.jl provides some test data for you to begin with.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"using LazyArtifacts\n\nrootpath = artifact\"testdata\"\nfiles = joinpath.(rootpath, (\"bulk.1d.vlsv\", \"bulk.2d.vlsv\", \"bulk.amr.vlsv\"))","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"These are also used in the standard test. These will be automatically downloaded from vlsv_data if you run the package test locally.","category":"page"},{"location":"log/#Performance","page":"FAQ","title":"Performance","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"The VLSV loader inherits the basic structure from Analysator and is redesigned for performance.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"For general data reading, a dictionary is constructed for cell IDs and orderings for O(1) timings.\nIt is faster to read a bunch of cell IDs together, if possible, than to read each cell one-by-one.\nSpecific methods are provided for targeted tasks that are much faster than the generic approaches. For instance, extractsat for multi-frame static satellite extraction can be more than 10x faster than first reading the metadata and then extracting variables for each frame.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"For development, it is recommended to use PkgBenchmark.jl to run the test suite:","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"using PkgBenchmark, Vlasiator\nresults = benchmarkpkg(Vlasiator)","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"or if you want to compare the current status of the package against a different git version","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"judge(Vlasiator, \"97e3dca6b2474d7bdc5b62b5bf98ecf070516e5e\")","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"To export results to Markdown,","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"export_markdown(\"testresult\", results)","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"See more in the PkgBenchmark manual.","category":"page"},{"location":"log/#Precision","page":"FAQ","title":"Precision","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"For post-processing and data analysis purposes, it makes less sense to stick to double precisions, so we mostly use Float32 in Vlasiator.jl for numerical arrays. Several exceptions are:","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"physical constants are defined in Float64, since single precision only resolves up to ±3.4E+38, and it may go out of bound in the middle of calculation (e.g. plasma frequency).","category":"page"},{"location":"log/#Int-vs.-UInt","page":"FAQ","title":"Int vs. UInt","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"Integers but not unsigned integers shall be used for indexing, even though unsigned integers are tempting.","category":"page"},{"location":"log/#Memory","page":"FAQ","title":"Memory","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"Vlasiator output files can be large. If we have limited memory relative to the file size, Vlasiator.jl provide direct hard disk mapping through mmap in Julia. With this mechanism you never need to worry about unable to process data with small free memory. Besides, we found that proper usage of mmap can also speed up reading and reduce memory comsumption. However, without reinterpret we may encounter the alignment issue!","category":"page"},{"location":"log/#Parallelism","page":"FAQ","title":"Parallelism","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"The current design choice is to achieve optimal serial performance per file, and apply parallel processing across individual files. In most common cases, the time it takes for post-processing one snapshot is reasonably short, but the number of snapshots are large. Julia's built-in support for all kinds of parallelism paradigm (multithreading, multiprocessing, channel) and external support from packages (MPI.jl, Polyester.jl) can be relatively easily incorported to make the whole workflow parallel.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"multi-threading with @threads (recommended when working within one node)\nmulti-processing with pmap\nmulti-processing with RemoteChannel\nClusterManagers for multi-node jobs","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"See more in the examples.","category":"page"},{"location":"log/#VTK","page":"FAQ","title":"VTK","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"VLSV is just an uncompressed binary format. If we convert VLSV to VTK through write_vtk, the generated VTK files, even the highest resolution one with every coarse cell mapping to the finest level, can be several times smaller than the original VLSV file.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"One drawback of this conversion is that it cannot deal with phase space outputs, i.e. VDFs.","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/#demo_1d2d_mp","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"","category":"section"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"This is an example for generating combined 1D/2D plots across multiple frames with multi-processing. To run on a single node,","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"julia -p $ncores demo_1d2d_mp_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"using Distributed, Glob\n@everywhere using Vlasiator, VlasiatorPyPlot, Printf, LaTeXStrings\n\n@assert matplotlib.__version__ ≥ \"3.4\" \"Require Matplotlib version 3.4+ to use subfigure!\"\n\n@everywhere struct Varminmax{T}\n \"Density, [amu/cc]\"\n ρmin::T\n ρmax::T\n \"Velocity, [km/s]\"\n vmin::T\n vmax::T\n \"Pressure, [nPa]\"\n pmin::T\n pmax::T\n \"Magnetic field, [nT]\"\n bmin::T\n bmax::T\n \"Electric field, [nT]\"\n emin::T\n emax::T\nend\n\n@everywhere function init_figure(loc, norms, ticks, pArgs1, varminmax)\n fig = plt.figure(myid(), constrained_layout=true, figsize=(12, 7.2))\n subfigs = fig.subfigures(1, 2, wspace=0.01, width_ratios=[2,1])\n\n axsL = subfigs[1].subplots(5, 1, sharex=true)\n axsR = subfigs[2].subplots(2, 1, sharex=true)\n\n # Set line plots' axes\n axsL[end].set_xlim(loc[1], loc[end])\n\n (;ρmin, ρmax, vmin, vmax, pmin, pmax, bmin, bmax, emin, emax) = varminmax\n\n axsL[1].set_ylim(ρmin, ρmax)\n axsL[2].set_ylim(vmin, vmax)\n axsL[3].set_ylim(pmin, pmax)\n axsL[4].set_ylim(bmin, bmax)\n axsL[5].set_ylim(emin, emax)\n for ax in axsL\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axsL[end].set_xlabel(L\"x [$R_E$]\"; fontsize=14)\n axsL[1].set_ylabel(\"n [amu/cc]\"; fontsize=14)\n axsL[2].set_ylabel(\"V [km/s]\"; fontsize=14)\n axsL[3].set_ylabel(\"P [nPa]\"; fontsize=14)\n axsL[4].set_ylabel(\"B [nT]\"; fontsize=14)\n axsL[5].set_ylabel(\"E [mV/m]\"; fontsize=14)\n\n fakeline = loc\n l1 = axsL[1].plot(loc, fakeline, label=\"Proton density\", color=\"#1f77b4\")\n l2 = axsL[2].plot(loc, fakeline, label=\"Vx\", color=\"#1f77b4\")\n l3 = axsL[2].plot(loc, fakeline, label=\"Vy\", color=\"#ff7f0e\")\n l4 = axsL[2].plot(loc, fakeline, label=\"Vz\", color=\"#2ca02c\")\n l5 = axsL[3].plot(loc, fakeline, label=\"Ram\", color=\"#1f77b4\")\n l6 = axsL[3].plot(loc, fakeline, label=\"Thermal\", color=\"#ff7f0e\")\n l7 = axsL[4].plot(loc, fakeline, label=\"Bx\", color=\"#1f77b4\")\n l8 = axsL[4].plot(loc, fakeline, label=\"By\", color=\"#ff7f0e\")\n l9 = axsL[4].plot(loc, fakeline, label=\"Bz\", color=\"#2ca02c\")\n l10= axsL[5].plot(loc, fakeline, label=\"Ex\", color=\"#1f77b4\")\n l11= axsL[5].plot(loc, fakeline, label=\"Ey\", color=\"#ff7f0e\")\n l12= axsL[5].plot(loc, fakeline, label=\"Ez\", color=\"#2ca02c\")\n\n ls = (l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12)\n\n axsL[2].legend(;loc=\"lower left\", ncol=3, frameon=false, fontsize=12)\n axsL[3].legend(;loc=\"upper right\", ncol=2, frameon=false, fontsize=12)\n axsL[4].legend(;loc=\"upper right\", ncol=3, frameon=false, fontsize=12)\n axsL[5].legend(;loc=\"lower right\", ncol=3, frameon=false, fontsize=12)\n\n vl1 = axsL[1].vlines(loc[1], ρmin, ρmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl2 = axsL[2].vlines(loc[1], vmin, vmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl3 = axsL[3].vlines(loc[1], pmin, pmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl4 = axsL[4].vlines(loc[1], bmin, bmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl5 = axsL[5].vlines(loc[1], emin, emax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n hl2 = axsL[2].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n hl4 = axsL[4].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n hl5 = axsL[5].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n\n vlines = (vl1, vl2, vl3, vl4, vl5)\n\n for ax in axsR\n ax.set_aspect(\"equal\")\n\n # Set border line widths\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\n edge = get(ax.spines, loc, nothing)\n edge.set_linewidth(2.0)\n end\n ax.xaxis.set_tick_params(width=2.0, length=3)\n ax.yaxis.set_tick_params(width=2.0, length=3)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n\n ax.set_ylabel(pArgs1.stry; fontsize=14)\n end\n\n axsR[2].set_xlabel(pArgs1.strx; fontsize=14)\n\n axsR[1].set_title(\"Alfvén speed\", fontsize=14)\n axsR[2].set_title(\"Sound speed\", fontsize=14)\n\n x, y = Vlasiator.get_axis(pArgs1)\n fakedata = fill(NaN32, length(y), length(x))\n\n c1 = axsR[1].pcolormesh(x, y, fakedata, norm=norms[1], cmap=matplotlib.cm.turbo)\n c2 = axsR[2].pcolormesh(x, y, fakedata, norm=norms[2], cmap=matplotlib.cm.turbo)\n\n rInner = 31.8e6 # [m]\n circle1 = plt.Circle((0, 0), rInner/Vlasiator.RE, facecolor=\"w\", edgecolor=\"tab:purple\")\n circle2 = plt.Circle((0, 0), rInner/Vlasiator.RE, facecolor=\"w\", edgecolor=\"tab:purple\")\n axsR[1].add_patch(circle1)\n axsR[2].add_patch(circle2)\n\n im_ratio = length(y)/length(x)\n fraction = 0.046 * im_ratio\n\n cb1 = colorbar(c1; ax=axsR[1], ticks=ticks[1], fraction, pad=0.02, extend=\"max\")\n cb1.ax.set_ylabel(\"[km/s]\"; fontsize=14)\n\n cb2 = colorbar(c2; ax=axsR[2], ticks=ticks[2], fraction, pad=0.02, extend=\"max\")\n cb2.ax.set_ylabel(\"[km/s]\"; fontsize=14)\n\n fig.suptitle(\"Density Pulse Run\", fontsize=\"x-large\")\n\n cs = (c1, c2)\n\n return fig, subfigs, ls, vlines, cs\nend\n\n@everywhere function update_vline(h, x)\n seg_old = h.get_segments()\n ymin = seg_old[1][1, 2]\n ymax = seg_old[1][2, 2]\n\n seg_new = [[x ymin; x ymax]]\n\n h.set_segments(seg_new)\nend\n\n@everywhere function update_plot!(subfigs, ls, vlines, cs, outdir, file, cellids, loc)\n isfile(outdir*file[end-8:end-5]*\".png\") && return\n\n println(\"file = $(basename(file))\")\n meta = load(file)\n\n rho = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v = readvariable(meta, \"proton/vg_v\", cellids)\n p = readvariable(meta, \"vg_pressure\", cellids) .* 1f9 |> vec # [nPa]\n\n vmag2 = sum(x -> x*x, v, dims=1) |> vec\n pram = rho .* Vlasiator.mᵢ .* vmag2 .* 1f9 # [nPa]\n\n b = readvariable(meta, \"vg_b_vol\", cellids) .* 1f9 #[nT]\n e = readvariable(meta, \"vg_e_vol\", cellids) .* 1f3 #[mV/m]\n\n ls[1][1].set_ydata(rho ./ 1f6)\n ls[2][1].set_ydata(@views v[1,:] ./ 1f3)\n ls[3][1].set_ydata(@views v[2,:] ./ 1f3)\n ls[4][1].set_ydata(@views v[3,:] ./ 1f3)\n ls[5][1].set_ydata(pram)\n ls[6][1].set_ydata(p)\n ls[7][1].set_ydata(@view b[1,:])\n ls[8][1].set_ydata(@view b[2,:])\n ls[9][1].set_ydata(@view b[3,:])\n ls[10][1].set_ydata(@view e[1,:])\n ls[11][1].set_ydata(@view e[2,:])\n ls[12][1].set_ydata(@view e[3,:])\n\n imagnetopause_ = findfirst(<(0.0), @views b[3,:])\n for vline in vlines\n update_vline(vline, loc[imagnetopause_])\n end\n\n str_title = @sprintf \"Sun-Earth line, t= %4.1fs\" meta.time\n subfigs[1].suptitle(str_title, fontsize=\"x-large\")\n\n data = Vlasiator.prep2d(meta, \"VA\", :z)'\n cs[1].set_array(data ./ 1f3)\n\n data = Vlasiator.prep2d(meta, \"VS\", :z)'\n cs[2].set_array(data ./ 1f3)\n\n savefig(outdir*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n return\nend\n\nfunction make_jobs(files)\n for f in files\n put!(jobs, f)\n end\nend\n\n@everywhere function do_work(jobs, status,\n outdir, loc, norms, ticks, pArgs1, cellids, varminmax)\n\n fig, subfigs, ls, vlines, cs = init_figure(loc, norms, ticks, pArgs1, varminmax)\n while true\n file = take!(jobs)\n update_plot!(subfigs, ls, vlines, cs, outdir, file, cellids, loc)\n put!(status, true)\n end\n close(fig)\nend\n\n################################################################################\nfiles = glob(\"bulk*.vlsv\", \".\")\n\nnfile = length(files)\n# Set output directory\nconst outdir = \"1d2d/\"\n\n# Set contour plots' axes\naxisunit = EARTH\n# Upper/lower limits for each variable\nρmin, ρmax = 0.0, 14.0 # [amu/cc]\nvmin, vmax = -620.0, 150.0 # [km/s]\npmin, pmax = 0.0, 2.8 # [nPa]\nbmin, bmax = -60.0, 60.0 # [nT]\nemin, emax = -8.0, 8.0 # [mV/m]\nvamin, vamax = 50.0, 600.0 # [km/s]\nvsmin, vsmax = 50.0, 600.0 # [km/s]\n\nvarminmax = Varminmax(ρmin, ρmax, vmin, vmax, pmin, pmax, bmin, bmax, emin, emax)\n\nmeta = load(files[1])\n\npArgs1 = Vlasiator.set_args(meta, \"VA\", axisunit; normal=:none)\nnorm1, ticks1 = set_colorbar(Linear, vamin, vamax)\nnorm2, ticks2 = set_colorbar(Linear, vsmin, vsmax)\n\nconst norms = (norm1, norm2)\nconst ticks = (ticks1, ticks2)\n\nconst jobs = RemoteChannel(()->Channel{String}(nfile))\nconst status = RemoteChannel(()->Channel{Bool}(nworkers()))\n\nxmin, xmax = 7.0, 17.0 # Earth radii\npoint1 = [xmin, 0, 0] .* Vlasiator.RE\npoint2 = [xmax, 0, 0] .* Vlasiator.RE\n\nmeta = load(files[1])\ncellids, _, _ = getcellinline(meta, point1, point2)\nloc = range(xmin, xmax, length=length(cellids))\n\nprintln(\"Total number of files: $nfile\")\nprintln(\"Running with $(nworkers()) workers...\")\n\n@async make_jobs(files) # Feed the jobs channel with all files to process.\n\n@sync for p in workers()\n @async remote_do(do_work, p, jobs, status,\n outdir, loc, norms, ticks, pArgs1, cellids, varminmax)\nend\n\nlet n = nfile\n t = @elapsed while n > 0 # wait for all jobs to complete\n take!(status)\n n -= 1\n end\n println(\"Finished in $(round(t, digits=2))s.\")\nend","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/#demo_virtual_sats","page":"Virtual satellites","title":"Virtual satellites","text":"","category":"section"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"This demo shows how to extract data for virtual satellites at multiple locations. Outputs are stored in binary format for sharing within Julia.","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"julia -t nthreads demo_pointsextracting.jl","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"or","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"JULIA_NUM_THREADS=nthreads julia demo_pointsextracting.jl","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"using Glob, Vlasiator\nusing Vlasiator: RE # Earth radius, [m]\nusing JLD2: jldsave\n\nfunction extract_vars(files, locations)\n nfiles = length(files)\n nlocs = length(locations)\n # variables to be extracted\n t = zeros(Float32, nfiles)\n rho = zeros(Float32, nlocs, nfiles)\n v = zeros(Float32, 3, nlocs, nfiles)\n p = zeros(Float32, nlocs, nfiles)\n b = zeros(Float32, 3, nlocs, nfiles)\n e = zeros(Float32, 3, nlocs, nfiles)\n\n ids = Vector{Int}(undef, nlocs)\n load(files[1]) do meta\n for iloc in eachindex(locations)\n ids[iloc] = getcell(meta, locations[iloc])\n end\n end\n\n # Extract data from each frame\n Threads.@threads for i = eachindex(files)\n meta = load(files[i])\n t[i] = meta.time\n rho[:,i] = readvariable(meta, \"proton/vg_rho\", ids)\n v[:,:,i] = readvariable(meta, \"proton/vg_v\", ids)\n p[ :,i] = readvariable(meta, \"vg_pressure\", ids)\n b[:,:,i] = readvariable(meta, \"vg_b_vol\", ids)\n e[:,:,i] = readvariable(meta, \"vg_e_vol\", ids)\n end\n\n # Save into binary file\n jldsave(\"satellites.jld2\"; locations, t, rho, v, p, b, e)\nend\n\n#####\n\nfiles = glob(\"bulk*.vlsv\", \"./\")\n\n# virtual satellite locations\nconst locations = [[7RE, 0, 0], [9RE, 0, 0], [11RE, 0, 0], [12RE, 0, 0],\n [13RE, 0, 0], [14RE, 0, 0], [15RE, 0, 0], [16RE, 0, 0], [17RE, 0, 0],\n [29.3RE, 0, 0]]\n\nprintln(\"Number of files: $(length(files))\")\nprintln(\"Number of virtual satellites: $(length(locations))\")\nprintln(\"Running with $(Threads.nthreads()) threads...\")\n\n@time extract_vars(files, locations)\n\nprintln(\"Virtual satellite extraction done!\")","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_convert2vti/#demo_convertvtk","page":"Converting to VTK","title":"Converting to VTK","text":"","category":"section"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"To convert VLSV time series files to VTK image files using multithreads,","category":"page"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"using Vlasiator, Glob\n\nfiles = glob(\"*.vlsv\")\n\nThreads.@threads for file in files\n @info file, Threads.threadid()\n write_vtk(file; vti=true)\nend","category":"page"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"","category":"page"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/#demo_2d_contour_mp","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"","category":"section"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"This demo shows how to generate 2D colored contours with multi-processing. To run on a single node,","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"julia -p $ncores demo_2d_mp_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"using Distributed, ParallelDataTransfer, Glob\r\n@everywhere using Vlasiator, VlasiatorPyPlot, Printf, LaTeXStrings\r\n\r\n@everywhere function init_figure(cmaps, norms, ticks, pArgs1, extent)\r\n fig, axs = plt.subplots(2, 3; num=myid(),\r\n figsize=(13.5, 9.5), sharex=true, sharey=true, constrained_layout=true)\r\n\r\n for ax in axs\r\n ax.set_aspect(\"equal\")\r\n # Set border line widths\r\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\r\n edge = get(ax.spines, loc, nothing)\r\n edge.set_linewidth(2.0)\r\n end\r\n ax.xaxis.set_tick_params(width=2.0, length=3)\r\n ax.yaxis.set_tick_params(width=2.0, length=3)\r\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\r\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\r\n end\r\n\r\n for ax in axs[end,:]\r\n ax.set_xlabel(pArgs1.strx; fontsize)\r\n end\r\n for ax in axs[:,1]\r\n ax.set_ylabel(pArgs1.stry; fontsize)\r\n end\r\n\r\n titles = (\"Density\", \"Pth\", \"Vx\", \"Bz\", \"Vz\", \"E\")\r\n\r\n for (ax, title) in zip(axs, titles)\r\n ax.set_title(title; fontsize)\r\n end\r\n\r\n x1, x2 = Vlasiator.get_axis(pArgs1)\r\n\r\n range1 = searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2])\r\n range2 = searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\r\n\r\n fakedata = zeros(Float32, length(range2), length(range1))\r\n\r\n c1 = axs[1,1].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[1], cmap=cmaps[1])\r\n c2 = axs[1,2].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[2], cmap=cmaps[2])\r\n c3 = axs[1,3].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[3], cmap=cmaps[2])\r\n c4 = axs[2,1].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[4], cmap=cmaps[1])\r\n c5 = axs[2,2].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[5], cmap=cmaps[2])\r\n c6 = axs[2,3].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[6], cmap=cmaps[1])\r\n\r\n cs = (c1, c2, c3, c4, c5, c6)\r\n\r\n format = matplotlib.ticker.FormatStrFormatter(\"%.1f\")\r\n\r\n cb1 = colorbar(c1; ax=axs[1,1], ticks=ticks[1], format)\r\n cb2 = colorbar(c2; ax=axs[1,2], ticks=ticks[2])\r\n cb3 = colorbar(c3; ax=axs[1,3], ticks=ticks[3])\r\n cb4 = colorbar(c4; ax=axs[2,1], ticks=ticks[4], format)\r\n cb5 = colorbar(c5; ax=axs[2,2], ticks=ticks[5], format, extend=\"both\")\r\n cb6 = colorbar(c6; ax=axs[2,3], ticks=ticks[6], extend=\"max\")\r\n\r\n ylabels = (\"[amu/cc]\", \"[km/s]\", \"[km/s]\", \"[nPa]\", \"[nT]\", \"[mV/m]\")\r\n\r\n for (i, cb) in enumerate((cb1, cb2, cb3, cb4, cb5, cb6))\r\n cb.ax.set_ylabel(ylabels[i]; fontsize)\r\n cb.outline.set_linewidth(1.0)\r\n end\r\n\r\n return fig, cs, range1, range2\r\nend\r\n\r\n@everywhere function update_plot!(fig, cs, range1, range2, outdir, file)\r\n isfile(outdir*file[end-8:end-5]*\".png\") && return\r\n\r\n println(\"file = $file\")\r\n meta = load(file)\r\n\r\n data = Vlasiator.prep2d(meta, \"proton/vg_rho\", :mag)'\r\n cs[1].set_array(data[range2,range1] ./ 1f6)\r\n\r\n data = Vlasiator.prep2d(meta, \"proton/vg_v\", :x)'\r\n cs[2].set_array(data[range2,range1] ./ 1f3)\r\n\r\n data = Vlasiator.prep2d(meta, \"proton/vg_v\", :z)'\r\n cs[3].set_array(data[range2,range1] ./ 1f3)\r\n\r\n data = Vlasiator.prep2d(meta, \"vg_pressure\", :mag)'\r\n cs[4].set_array(data[range2,range1] .* 1f9)\r\n\r\n data = Vlasiator.prep2d(meta, \"vg_b_vol\", :z)'\r\n cs[5].set_array(data[range2,range1] .* 1f9)\r\n\r\n data = Vlasiator.prep2d(meta, \"vg_e_vol\", :mag)'\r\n cs[6].set_array(data[range2,range1] .* 1f3)\r\n\r\n str_title = @sprintf \"Density pulse run, t= %4.1fs\" meta.time\r\n fig.suptitle(str_title; fontsize=\"xx-large\")\r\n\r\n savefig(outdir*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\r\nend\r\n\r\nfunction make_jobs(files)\r\n for f in files\r\n put!(jobs, f)\r\n end\r\nend\r\n\r\n@everywhere function do_work(jobs, status, outdir, cmaps, norms, ticks, pArgs1, extent)\r\n fig, cs, range1, range2 = init_figure(cmaps, norms, ticks, pArgs1, extent)\r\n while true\r\n file = take!(jobs)\r\n update_plot!(fig, cs, range1, range2, outdir, file)\r\n put!(status, true)\r\n end\r\n close(fig)\r\nend\r\n\r\n################################################################################\r\nfiles = glob(\"bulk*.vlsv\", \".\")\r\n\r\nnfile = length(files)\r\n# Set output directory\r\nconst outdir = \"contour/\"\r\n\r\n# Set colormaps for continuous and divergent data\r\nconst cmaps = (matplotlib.cm.turbo, matplotlib.cm.RdBu_r)\r\nconst axisunit = EARTH\r\nconst extent = [0., 20., -20., 20.] # [RE], default: [-Inf32, Inf32, -Inf32, Inf32]\r\n\r\n# Plotting range for each variable\r\nconst ρmin, ρmax = 0.1, 15.0 # [amu/cc]\r\nconst vxmin, vxmax = -650.0, 650.0 # [km/s]\r\nconst vzmin, vzmax = -500.0, 500.0 # [km/s]\r\nconst pmin, pmax = 0.0, 3.6 # [nPa]\r\nconst bmin, bmax = -60.0, 60. # [nT]\r\nconst emin, emax = 0.0, 20. # [mV/m]\r\n\r\nmeta = load(files[1])\r\n\r\npArgs1 = Vlasiator.set_args(meta, \"proton/vg_rho\", axisunit; normal=:none)\r\n\r\nnorm1, ticks1 = set_colorbar(Linear, ρmin, ρmax)\r\nnorm2, ticks2 = set_colorbar(Linear, vxmin, vxmax)\r\nnorm3, ticks3 = set_colorbar(Linear, vzmin, vzmax)\r\nnorm4, ticks4 = set_colorbar(Linear, pmin, pmax)\r\nnorm5, ticks5 = set_colorbar(Linear, bmin, bmax)\r\nnorm6, ticks6 = set_colorbar(Linear, emin, emax)\r\n\r\nconst norms = (norm1, norm2, norm3, norm4, norm5, norm6)\r\nconst ticks = (ticks1, ticks2, ticks3, ticks4, ticks5, ticks6)\r\n\r\nconst jobs = RemoteChannel(()->Channel{String}(nfile))\r\nconst status = RemoteChannel(()->Channel{Bool}(nworkers()))\r\n\r\n@broadcast begin\r\n const fontsize = \"x-large\"\r\nend\r\n\r\nprintln(\"Total number of files: $nfile\")\r\nprintln(\"Running with $(nworkers()) workers...\")\r\n\r\n@async make_jobs(files) # Feed the jobs channel with all files to process.\r\n\r\n@sync for p in workers()\r\n @async remote_do(do_work, p, jobs, status, outdir, cmaps, norms, ticks, pArgs1, extent)\r\nend\r\n\r\nlet n = nfile\r\n t = @elapsed while n > 0 # wait for all jobs to complete\r\n take!(status)\r\n n -= 1\r\n end\r\n println(\"Finished in $(round(t, digits=2))s.\")\r\nend","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/#demo_2d_contour_animation","page":"2D contour plot animation","title":"2D contour plot animation","text":"","category":"section"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"This example shows how to plot 2D colored contours with pcolormesh. ffmpeg is required to be installed for saving into mp4.","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"using Vlasiator, Glob, VlasiatorPyPlot, Printf\n\nfiles = glob(\"bulk*.vlsv\", \".\")\nconst var = \"proton/vg_rho\"\nconst comp = 0 # vector component for plotting (if applicable)\n\nfig = plt.figure(figsize=(6.4,5.1), constrained_layout=true)\n\nax = plt.axes()\n\nconst axisunit = EARTH\nconst colorscale = Log\nconst addcolorbar = true\n# Choose colormap\nconst cmap = matplotlib.cm.turbo\n# Set data plotting range\nconst vmin = 7.0e4\nconst vmax = 2.5e6\n\nmeta = load(files[1])\n\npArgs = Vlasiator.set_args(meta, var, axisunit; normal=:none)\n\nnorm, ticks = set_colorbar(colorscale, vmin, vmax)\n\nc = let\n x1, x2 = Vlasiator.get_axis(pArgs)\n fakedata = zeros(Float32, length(x2), length(x1))\n ax.pcolormesh(x1, x2, fakedata; norm, cmap)\nend\n\nVlasiator.set_plot(c, ax, pArgs, ticks, addcolorbar)\n\nfunction animate(i::Int, files::Vector{String}, var::String, comp::Int, c)\n meta = load(files[i+1])\n t = readparameter(meta, \"time\")\n data = Vlasiator.prep2d(meta, var, comp)'\n c.set_array(data)\n\n str_title = @sprintf \"t= %4.1fs\" t\n ax.set_title(str_title, fontweight=\"bold\")\n\n return (c,)\nend\n\n# https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html\nanim = matplotlib.animation.FuncAnimation(fig, animate, fargs=(files, var, comp, c),\n frames=length(files), blit=true,\n repeat_delay=1000, interval=50)\n# Make sure ffmpeg is available!\nanim.save(\"contour.mp4\", writer=\"ffmpeg\", fps=30)","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/#demo_1d2d","page":"Combined plots","title":"Combined plots","text":"","category":"section"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"To generate combined 1D/2D plots across multiple frames,","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"using Vlasiator, VlasiatorPyPlot, Glob, Printf, LaTeXStrings\nusing Vlasiator: set_args, prep2d\n\n@assert VERSION ≥ v\"1.7.0\" \"Compatible with Julia v1.7+!\"\n@assert matplotlib.__version__ >= \"3.4\" \"Require Matplotlib version 3.4+ to use subfigure!\"\n\n\nstruct Varminmax{T}\n \"Density, [amu/cc]\"\n ρmin::T\n ρmax::T\n \"Velocity, [km/s]\"\n vmin::T\n vmax::T\n \"Pressure, [nPa]\"\n pmin::T\n pmax::T\n \"Magnetic field, [nT]\"\n bmin::T\n bmax::T\n \"Electric field, [nT]\"\n emin::T\n emax::T\n \"Alfven speed, [km/s]\"\n vamin::T\n vamax::T\n \"Sonic speed, [km/s]\"\n vsmin::T\n vsmax::T\nend\n\nfunction init_figure(varminmax, loc, pArgs)\n (; ρmin, ρmax, vmin, vmax, pmin, pmax, bmin, bmax, emin, emax,\n vamin, vamax, vsmin, vsmax) = varminmax\n\n fig = plt.figure(constrained_layout=true, figsize=(12, 7.2))\n subfigs = fig.subfigures(1, 2, wspace=0.01, width_ratios=[2,1])\n\n axsL = subfigs[1].subplots(5, 1, sharex=true)\n axsR = subfigs[2].subplots(2, 1, sharex=true)\n\n # Set line plots' axes\n axsL[end].set_xlim(loc[1], loc[end])\n\n axsL[1].set_ylim(ρmin, ρmax)\n axsL[2].set_ylim(vmin, vmax)\n axsL[3].set_ylim(pmin, pmax)\n axsL[4].set_ylim(bmin, bmax)\n axsL[5].set_ylim(emin, emax)\n for ax in axsL\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axsL[end].set_xlabel(L\"x [$R_E$]\"; fontsize=14)\n axsL[1].set_ylabel(\"n [amu/cc]\"; fontsize=14)\n axsL[2].set_ylabel(\"V [km/s]\"; fontsize=14)\n axsL[3].set_ylabel(\"P [nPa]\"; fontsize=14)\n axsL[4].set_ylabel(\"B [nT]\"; fontsize=14)\n axsL[5].set_ylabel(\"E [mV/m]\"; fontsize=14)\n\n fakeline = loc\n l1 = axsL[1].plot(loc, fakeline, label=\"Proton density\", color=\"#1f77b4\")\n l2 = axsL[2].plot(loc, fakeline, label=\"Vx\", color=\"#1f77b4\")\n l3 = axsL[2].plot(loc, fakeline, label=\"Vy\", color=\"#ff7f0e\")\n l4 = axsL[2].plot(loc, fakeline, label=\"Vz\", color=\"#2ca02c\")\n l5 = axsL[3].plot(loc, fakeline, label=\"Ram\", color=\"#1f77b4\")\n l6 = axsL[3].plot(loc, fakeline, label=\"Thermal\", color=\"#ff7f0e\")\n l7 = axsL[4].plot(loc, fakeline, label=\"Bx\", color=\"#1f77b4\")\n l8 = axsL[4].plot(loc, fakeline, label=\"By\", color=\"#ff7f0e\")\n l9 = axsL[4].plot(loc, fakeline, label=\"Bz\", color=\"#2ca02c\")\n l10= axsL[5].plot(loc, fakeline, label=\"Ex\", color=\"#1f77b4\")\n l11= axsL[5].plot(loc, fakeline, label=\"Ey\", color=\"#ff7f0e\")\n l12= axsL[5].plot(loc, fakeline, label=\"Ez\", color=\"#2ca02c\")\n\n ls = (l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12)\n\n axsL[2].legend(;loc=\"lower left\", ncol=3, frameon=false, fontsize=12)\n axsL[3].legend(;loc=\"upper left\", ncol=2, frameon=false, fontsize=12)\n axsL[4].legend(;loc=\"upper right\", ncol=3, frameon=false, fontsize=12)\n axsL[5].legend(;loc=\"lower right\", ncol=3, frameon=false, fontsize=12)\n\n vl1 = axsL[1].vlines(loc[1], ρmin, ρmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl2 = axsL[2].vlines(loc[1], vmin, vmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl3 = axsL[3].vlines(loc[1], pmin, pmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl4 = axsL[4].vlines(loc[1], bmin, bmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl5 = axsL[5].vlines(loc[1], emin, emax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n hl2 = axsL[2].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n hl4 = axsL[4].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n hl5 = axsL[5].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n\n vlines = (vl1, vl2, vl3, vl4, vl5)\n\n for ax in axsR\n ax.set_aspect(\"equal\")\n\n # Set border line widths\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\n edge = get(ax.spines, loc, nothing)\n edge.set_linewidth(2.0)\n end\n ax.xaxis.set_tick_params(width=2.0, length=3)\n ax.yaxis.set_tick_params(width=2.0, length=3)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n\n ax.set_ylabel(L\"Y [$R_E$]\"; fontsize=14)\n end\n\n axsR[2].set_xlabel(L\"X [$R_E$]\"; fontsize=14)\n\n axsR[1].set_title(\"Alfven speed\", fontsize=14)\n axsR[2].set_title(\"Sound speed\", fontsize=14)\n\n x, y = Vlasiator.get_axis(pArgs)\n fakedata = fill(NaN32, length(y), length(x))\n\n cnorm1, cticks1 = set_colorbar(Linear, vamin, vamax)\n cnorm2, cticks2 = set_colorbar(Linear, vsmin, vsmax)\n cmap = matplotlib.cm.turbo\n\n c1 = axsR[1].pcolormesh(x, y, fakedata; norm=cnorm1, cmap)\n c2 = axsR[2].pcolormesh(x, y, fakedata; norm=cnorm2, cmap)\n\n rInner = 31.8e6 # [m]\n circle1 = plt.Circle((0, 0), rInner/Vlasiator.RE, color=\"w\")\n circle2 = plt.Circle((0, 0), rInner/Vlasiator.RE, color=\"w\")\n axsR[1].add_patch(circle1)\n axsR[2].add_patch(circle2)\n\n cb1 = colorbar(c1; ax=axsR[1], ticks=cticks1, fraction=0.046, pad=0.04, extend=\"max\")\n cb1.ax.set_ylabel(\"[km/s]\"; fontsize=14)\n\n cb2 = colorbar(c2; ax=axsR[2], ticks=cticks2, fraction=0.046, pad=0.04)\n cb2.ax.set_ylabel(\"[km/s]\"; fontsize=14)\n\n #fig.suptitle(\"Density Pulse Run\", fontsize=\"xx-large\")\n\n cs = (c1, c2)\n\n return fig, subfigs, ls, vlines, cs\nend\n\n\n\"Update frame.\"\nfunction update_plot!(plotargs, outdir, file)\n isfile(outdir*file[end-8:end-5]*\".png\") && return\n\n fig, subfigs, ls, vlines, cs = plotargs\n\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1f9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1f9 # [nPa]\n\n bz = readvariable(meta, \"vg_b_vol\", cellids)[3,:] .* 1f9 #[nT]\n\n ls[1][1].set_ydata(rho_extract ./ 1f6)\n ls[2][1].set_ydata(v_extract[1,:] ./ 1f3)\n ls[3][1].set_ydata(pram_extract)\n ls[4][1].set_ydata(p_extract)\n ls[5][1].set_ydata(bz)\n\n imagnetopause_ = findfirst(<(0.0), bz)\n for vline in vlines\n update_vline(vline, loc[imagnetopause_])\n end\n\n str_title = @sprintf \"Sun-Earth line, t= %4.1fs\" meta.time\n subfigs[1].suptitle(str_title, fontsize=14)\n\n data = prep2d(meta, \"VA\", :z)'\n cs[1].update(Dict(\"array\" => data ./ 1e3))\n\n data = prep2d(meta, \"VS\", :z)'\n cs[2].update(Dict(\"array\" => data ./ 1e3))\n\n savefig(outdir*file[end-8:end-5]*\".png\", bbox_inches=\"tight\", dpi=100)\n return\nend\n\nfunction update_vline(h, x)\n seg_old = h.get_segments()\n ymin = seg_old[1][1, 2]\n ymax = seg_old[1][2, 2]\n\n seg_new = [[x ymin; x ymax]]\n\n h.set_segments(seg_new)\nend\n\n####### Main\n\nfiles = glob(\"bulk*.vlsv\", \".\")\nnfile = length(files)\n# Set output directory\nconst outdir = \"out/\"\n\nmeta = load(files[1])\n\nconst x1, x2 = 7.0, 18.0 # Earth radii\nconst point1 = [x1, 0, 0] .* Vlasiator.RE\nconst point2 = [x2, 0, 0] .* Vlasiator.RE\n\ncellids, distances, coords = getcellinline(meta, point1, point2)\n\nloc = range(x1, x2, length=length(cellids))\n\npArgs = set_args(meta, \"fakename\", RE; normal=:none)\n\n# Upper/lower limits for each variable\nρmin, ρmax = 0.0, 10.0 # [amu/cc]\nvmin, vmax = -640.0, 100.0 # [km/s]\npmin, pmax = 0.0, 1.82 # [nPa]\nbmin, bmax = -25.0, 60.0 # [nT]\nemin, emax = -5.0, 5.0 # [mV/m]\nvamin, vamax = 0.0, 250.0 # [km/s]\nvsmin, vsmax = 0.0, 400.0 # [km/s]\n\nvarminmax =\n Varminmax(ρmin, ρmax, vmin, vmax, pmin, pmax, bmin, bmax, emin, emax,\n vamin, vamax, vsmin, vsmax)\n\n\nplotargs = init_figure(varminmax, loc, pArgs)\n\n# Loop over snapshots\nfor (i, file) in enumerate(files)\n println(\"i = $i/$nfile, file = $(basename(file))\")\n update_plot!(plotargs, outdir, file)\nend\n\nclose(plotargs[1])\nprintln(\"Finished!\")","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"gallery/#Gallery","page":"Gallery","title":"Gallery","text":"","category":"section"},{"location":"gallery/#PyPlot","page":"Gallery","title":"PyPlot","text":"","category":"section"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density in a laminar flow with points denoting cell centers. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density of Earth's magnetosphere in the meridional cut from 2D simulation, with fieldlines through fixed seeding points. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density of Earth's magnetosphere in the meridional plane from 3D simulation.","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density of Earth's magnetosphere in the equatorial plane from 2D simulation, zoomed in to the magnetosheath and foreshock region, with streamlines and density contour at 10 amu/cc. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density of Earth's magnetosphere in the normal cut planes from 3D simulation. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton phase space distribution projected onto the X-Z plane. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/#Makie","page":"Gallery","title":"Makie","text":"","category":"section"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Demos can be found in the Usage section of VlasiatorMakie.","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Various colored contours from 2D equatorial run","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Interactive proton density slice from 3D AMR run","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Three orthogonal slices of proton density from 3D AMR run","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Isosurface of Bz = 0 from 3D AMR run","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton phase space distribution projected onto the X-Z plane","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Interactive proton phase space distribution in the three orthogonal planes","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton phase space distribution","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/#ParaView","page":"Gallery","title":"ParaView","text":"","category":"section"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"VLSV files can be converted to the structured VTK format, and then visualized in ParaView.","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"2D slice contour of density in the meriodional plane with streamlines","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"2D slices of density viewing from upstream","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/#demo_2d_fieldlines_mp","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"","category":"section"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"This demo shows how to plot field lines with handpicked seeds via multi-processing. To run on a single node,","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"julia -p $ncores demo_fieldline_mp_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"using Distributed, ParallelDataTransfer, Glob\n@everywhere using Vlasiator, VlasiatorPyPlot, PyCall, Printf, LaTeXStrings, FieldTracer\n@everywhere using Vlasiator: RE\n\nfunction generate_seeds(coordmin, coordmax, dim_, nseeds)\n seeds = Matrix{Float64}(undef, 2, nseeds)\n for i in 1:nseeds\n seeds[1,i] = coordmin[dim_[1]] +\n (coordmax[dim_[1]] - coordmin[dim_[1]]) / nseeds * (i - 1)\n seeds[2,i] = -20RE\n end\n seeds\nend\n\n@everywhere function init_figure(pArgs, norm, ticks, seeds, extent)\n fig, ax = plt.subplots(1, 1; num=myid(),\n figsize=(6, 8), constrained_layout=true)\n\n fontsize = \"x-large\"\n\n ax.set_aspect(\"equal\")\n # Set border line widths\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\n edge = get(ax.spines, loc, nothing)\n edge.set_linewidth(2.0)\n end\n ax.xaxis.set_tick_params(width=2.0, length=3)\n ax.yaxis.set_tick_params(width=2.0, length=3)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n\n ax.set_xlabel(pArgs.strx; fontsize)\n ax.set_ylabel(pArgs.stry; fontsize)\n\n ax.set_title(\"Density\"; fontsize)\n\n x1, x2 = Vlasiator.get_axis(pArgs)\n\n range1 = searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2])\n range2 = searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\n\n fakedata = zeros(Float32, length(range2), length(range1))\n c = ax.pcolormesh(x1[range1], x2[range2], fakedata; norm, cmap=matplotlib.cm.turbo)\n\n format = matplotlib.ticker.FormatStrFormatter(\"%.1f\")\n cb1 = colorbar(c; ax, ticks, format)\n cb1.ax.set_ylabel(\"[amu/cc]\"; fontsize)\n cb1.outline.set_linewidth(1.0)\n\n fakeline = [0.0, 1.0]\n ls = [ax.plot(fakeline, fakeline, color=\"w\") for _ in 1:size(seeds,2)]\n\n return fig, ax, c, ls, range1, range2\nend\n\n@everywhere function update_plot!(ax, c, ls, range1, range2, dim_, seeds, grid1, grid2,\n outdir, file)\n isfile(outdir*file[end-8:end-5]*\".png\") && return\n\n println(\"file = $file\")\n meta = load(file)\n\n data = Vlasiator.prep2d(meta, \"proton/vg_rho\", :mag)'\n c.set_array(data[range2,range1] ./ 1f6)\n\n str_title = @sprintf \"Density pulse run, t= %4.1fs\" meta.time\n ax.set_title(str_title; fontsize=\"x-large\")\n\n b = meta[\"vg_b_vol\"]\n b1 = reshape(b[dim_[1],:], meta.ncells[dim_[1]], meta.ncells[dim_[2]])\n b2 = reshape(b[dim_[2],:], meta.ncells[dim_[1]], meta.ncells[dim_[2]])\n # Find existing arrow annotations\n annotations = [child for child in ax.get_children() if\n pybuiltin(:isinstance)(child, matplotlib.text.Annotation)]\n # Remove existing arrows\n for a in annotations\n a.remove()\n end\n # Add new arrows along field lines\n for i in axes(seeds,2)\n startx, starty = seeds[:,i]\n x1, y1 = trace(b1, b2, startx, starty, grid1, grid2;\n ds=0.5, maxstep=4000, gridtype=\"ndgrid\")\n x1 ./= RE\n y1 ./= RE\n if length(x1) < 5; continue; end\n ls[i][1].set_xdata(x1)\n ls[i][1].set_ydata(y1)\n add_arrow(ls[i][1])\n end\n\n savefig(outdir*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\nend\n\nfunction make_jobs(files)\n for f in files\n put!(jobs, f)\n end\nend\n\n@everywhere function do_work(jobs, status,\n outdir, pArgs, norm, ticks, grid1, grid2, dim_, seeds, extent)\n\n fig, ax, c, ls, range1, range2 = init_figure(pArgs, norm, ticks, seeds, extent)\n\n while true\n file = take!(jobs)\n update_plot!(ax, c, ls, range1, range2, dim_, seeds, grid1, grid2, outdir, file)\n put!(status, true)\n end\n close(fig)\nend\n\n################################################################################\nfiles = glob(\"bulk*.vlsv\", \".\")\n\nnfile = length(files)\n# Set output directory\nconst outdir = \"out/\"\n\nconst jobs = RemoteChannel(()->Channel{String}(nfile))\nconst status = RemoteChannel(()->Channel{Bool}(nworkers()))\n\nconst axisunit = EARTH # contour plot axes unit\nconst extent = [0., 20., -20., 20.] # [RE], default: [-Inf32, Inf32, -Inf32, Inf32]\n\n# Upper/lower limits for each variable\nconst ρmin, ρmax = 0.0, 11.0 # [amu/cc]\n\nmeta = load(files[1])\n# Construct pieces for plotting\npArgs = Vlasiator.set_args(meta, \"proton/vg_rho\", axisunit; normal=:none)\nnorm, ticks = set_colorbar(Linear, ρmin, ρmax)\n\n# Mark spatial dimensions\nconst dim_ = pArgs.stry[1] == 'Z' ? (1,3) : (1,2)\n\n(;coordmin, coordmax, ncells) = meta\n\n# Generate regular Cartesian range\ngrid1 = range(coordmin[dim_[1]], coordmax[dim_[1]], length=ncells[dim_[1]])\ngrid2 = range(coordmin[dim_[2]], coordmax[dim_[2]], length=ncells[dim_[2]])\n# Generate seeds for in-plane field line tracing\nconst nseeds = 10\nseeds = generate_seeds(coordmin, coordmax, dim_, nseeds)\n\n\nprintln(\"Total number of files: $nfile\")\nprintln(\"Running with $(nworkers()) workers...\")\n\n@async make_jobs(files) # Feed the jobs channel with all files to process.\n\n@sync for p in workers()\n @async remote_do(do_work, p, jobs, status,\n outdir, pArgs, norm, ticks, grid1, grid2, dim_, seeds, extent)\nend\n\nlet n = nfile\n t = @elapsed while n > 0 # wait for all jobs to complete\n take!(status)\n n -= 1\n end\n println(\"Finished in $(round(t, digits=2))s.\")\nend","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"benchmark/#Benchmarks","page":"Benchmarks","title":"Benchmarks","text":"","category":"section"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"The test file information are listed below:","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Index Filename Number of Cells Dimension AMR Public\n1 1d_single.vlsv 20 1 No Yes\n2 bulk.2d.vlsv 6,300 1 No Yes\n3 2d_double.vlsv 51,200 2 No Yes\n4 2d_AFC.vlsv 4,612,500 2 No Yes\n5 3d_EGI.vlsv 3,966,580 3 Yes No","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Access to the public data can be found from vlsv_data.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"note: Note\nThe numbers shown here are comparisons between Analysator v0.9 and Vlasiator.jl v0.9.32 running Python 3.6.9/3.9.7 and Julia 1.8.3 with the scripts perf.jl and perf.py. The timings are collected from a i5-10210U @ 1.6GHz CPU with 16 GB RAM if not specified.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Loading meta data[1]","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Julia [ms] Python [ms] Ratio\n1 0.18 1.19 6.6\n2 0.51 1.66 3.1\n3 2.33 3.11 1.3\n4 506 277 0.5\n5 549 283 0.5","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[1]: See the issue about sorting. The performance of EzXML is also not ideal: we may need to find a better XML parser in Julia.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Reading DCCRG grid variables","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Julia [ms] Python [ms] Ratio\n1 0.004 0.07 17\n2 0.02[2] 0.08 4\n3 0.17[2] 0.21 1.2\n4 20[2] 23 1.1\n5 11[2] 11 1.0","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[2]: Vlasiator.jl can be faster if there is no conversion from Float64 to Float32. See Precision.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Reading field solver grid variables[3]","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Size Julia [s] Julia, mmap [s] Python [s] Ratio\n5 6.2 GiB Float32 18 8 56 7","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[3]: The field solver grid is a regular Cartesian grid at the finest refinement level introduced after Vlasiator 5. Therefore fsgrid variables are quite large for 3D AMR runs: with limited memory (e.g. 16 GB RAM) you may encounter out-of-memory issues when reading fg_b more than once. In Vlasiator.jl, we provide the option usemmap=true for reading large arrays –- see Memory for more.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Plotting 2D density contours on a uniform mesh (no GUI)","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Julia [s] Python [s] Ratio\n4 0.5 5.4 11","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Plotting 2D density slices from a 3D AMR mesh (no GUI)","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Julia [s][4] Python [s] Ratio\n5 0.5 3.1 6.2","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[4]: The first time execution will be slower due to JIT compilation (which is excluded in the timing here). This is known as \"Time-To-First-X\" in the Julia community.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Static virtual satellite tracking from 3D AMR data (26G per frame, 32 MB Cell IDs) on a cluster[5]","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Frames Julia, 1 thread [s] Julia, 2 threads [s] Python [s]\n845 45 34 1220","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[5]: University of Helsinki cluster Vorna with Intel Xeon E5-2697 @ 2.70GHz.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/#demo_plot_line","page":"Plot variable along a line","title":"Plot variable along a line","text":"","category":"section"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"This demo shows how to plot pressure along a line across multiple frames.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"using Vlasiator, PyPlot, Glob, Printf\nusing Vlasiator: RE # Earth radius [m]\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n nfile = length(files)\n\n x1, x2 = 8.0, 29.0\n point1 = [x1, 0, 0] .* RE\n point2 = [x2, 0, 0] .* RE\n\n cellids, distances, coords =\n load(files[1]) do meta\n getcellinline(meta, point1, point2)\n end\n\n fig, ax = plt.subplots(figsize=(8, 4.8))\n\n for (i, file) in enumerate(files)\n println(\"i = $i/$nfile, file = $file\")\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1e9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1e9 # [nPa]\n loc = range(x1, x2, length=length(rho_extract))\n\n ax.plot(loc, pram_extract, label=\"ram\")\n ax.plot(loc, p_extract, label=\"thermal\")\n\n ax.set_xlim(x1, x2)\n ax.set_ylim(0.0, 1.8)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n grid(true)\n\n xlabel(\"x [Re]\", fontsize=14)\n ylabel(\"Pressure [nPa]\", fontsize=14)\n str_title = @sprintf \"t= %4.1fs\" meta.time\n title(str_title, fontsize=14)\n legend(loc=\"upper left\", fontsize=14)\n savefig(\"out/\"*meta.name[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n ax.cla()\n end\n\n close(fig)\n println(\"plot finished!\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/#demo_vector_comps","page":"Vector components","title":"Vector components","text":"","category":"section"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"This demo shows how to plot the components of a vector from one snapshot.","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"using Vlasiator, VlasiatorPyPlot, LaTeXStrings, Printf\n\nfunction main()\n file = \"/wrk/group/spacephysics/vlasiator/2D/ABA/bulk/bulk.0001000.vlsv\"\n\n axisunit = EARTH\n colorscale = Linear\n cmap = matplotlib.cm.RdBu\n\n var = \"B_vol\"\n\n #####\n meta = load(file)\n\n pArgs = Vlasiator.set_args(meta, var, axisunit; normal=:none)\n\n x, y = Vlasiator.get_axis(pArgs)\n\n B = meta[\"B_vol\"] # [T]\n bx = @views B[1,:].*1e9\n bx = reshape(bx, meta.ncells[1], meta.ncells[2])\n by = @views B[2,:].*1e9\n by = reshape(by, meta.ncells[1], meta.ncells[2])\n bz = @views B[3,:].*1e9\n bz = reshape(bz, meta.ncells[1], meta.ncells[2])\n\n V = (bx, by, bz)\n V_str = (\"Bx\", \"By\", \"Bz\")\n\n # Symmetric range for diverging colormap\n vmin = minimum(minimum.(V))\n vmax = -vmin\n\n cnorm1, cticks1 = set_colorbar(colorscale, vmin, vmax)\n\n fig, axs = subplots(1,3,\n figsize=(10, 4), sharex=true, sharey=true, constrained_layout=true)\n\n c1 = axs[1].pcolormesh(x, y, V[1]'; norm=cnorm1, cmap)\n\n for i in eachindex(axs)[2:end]\n axs[i].pcolormesh(x, y, V[i]'; norm=cnorm1, cmap)\n end\n\n for (i, ax) in enumerate(axs)\n ax.set_aspect(\"equal\")\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.set_title(V_str[i])\n ax.set_xlabel(L\"x [$R_E$]\")\n end\n\n axs[1].set_ylabel(L\"y [$R_E$]\")\n\n # One colorbar for all subplots\n cb1 = colorbar(c1; ax=axs, ticks=cticks1, fraction=0.046, pad=0.04)\n cb1.ax.set_ylabel(\"[nT]\")\n cb1.outline.set_linewidth(1.0)\n\n str_title = @sprintf \"B at t = %4.1fs\" meta.time\n\n fig.suptitle(str_title, fontsize=\"xx-large\")\n\n savefig(\"Bvector.png\", bbox_inches=\"tight\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"This page was generated using DemoCards.jl.","category":"page"}] +[{"location":"examples/postprocess/demo_em_extract_slice/#demo_em_slice","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"","category":"section"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"To save Epar, Eperp, B in a selected slice region from 3D VLSV outputs,","category":"page"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"using Vlasiator, Glob\nusing JLD2: jldsave\nusing StaticArrays\nusing LinearAlgebra: norm\n\nfunction getvars(meta::MetaVLSV, pArgs::Vlasiator.PlotArgs, normal::Symbol, range1, range2)\n (;origin, idlist, indexlist) = pArgs\n\n B = readvariable(meta, \"vg_b_vol\")\n\n Bout = @views refineslice(meta, idlist, B[:,indexlist], normal)[:, range1, range2]\n\n ncells = meta.ncells .* 2^meta.maxamr\n if normal == :x\n dir = 1\n elseif normal == :y\n dir = 2\n elseif normal == :z\n dir = 3\n else\n @error \"Unknown normal direction $normal\"\n end\n\n sliceratio = (origin - meta.coordmin[dir]) / (meta.coordmax[dir] - meta.coordmin[dir])\n 0.0 ≤ sliceratio ≤ 1.0 || error(\"slice plane index out of bound!\")\n # Find the cut plane index for each refinement level\n icut = floor(Int, sliceratio*ncells[dir]) + 1\n\n E = readvariable(meta, \"fg_e\", true, true)\n\n E = if normal == :x\n E[:,icut,range1,range2]\n elseif normal == :y\n E[:,range1,icut,range2]\n elseif normal == :z\n E[:,range1,range2,icut]\n end\n\n n2D = meta[\"n\"][indexlist]\n\n n = refineslice(meta, idlist, n2D, normal)[range1, range2]\n\n v2D = meta[\"proton/vg_v\"][:,indexlist]\n v = @views refineslice(meta, idlist, v2D, normal)[:, range1, range2]\n\n p2D = meta[\"P\"][indexlist]\n p = refineslice(meta, idlist, p2D, normal)[range1, range2]\n\n E, Bout, n, v, p\nend\n\nfunction main()\n # Parameters\n directory = \"/home/hongyang/runs/3D/EGI/bulk/dense_cold_hall1e5_afterRestart374/\"\n outdir = \"EM/\"\n outfile = \"EM.jld2\"\n\n files = glob(\"bulk1.*vlsv\", directory)\n # Only orthogonal slices are supported\n normal = :y # (:x, :y, :z)\n origin = 0.0\n var = \"e\"\n axisunit = EARTH\n\n meta = load(files[1])\n\n pArgs = Vlasiator.set_args(meta, var, axisunit; normal, origin)\n\n x1, x2 = Vlasiator.get_axis(pArgs)\n\n extent = [-23., 12., -10., 10.]\n\n range1, range2 =\n searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2]),\n searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\n\n E = zeros(Float32, 3, length(range1), length(range2), length(files))\n B = zeros(Float32, 3, length(range1), length(range2), length(files))\n n = zeros(Float32, length(range1), length(range2), length(files))\n v = zeros(Float32, 3, length(range1), length(range2), length(files))\n p = zeros(Float32, length(range1), length(range2), length(files))\n\n for i in eachindex(files)\n meta = load(files[i])\n E[:,:,:,i], B[:,:,:,i], n[:,:,i], v[:,:,:,i], p[:,:,i] =\n getvars(meta, pArgs, normal, range1, range2)\n end\n\n # Save into binary file\n jldsave(outdir*outfile; E, B, n, v, p)\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"","category":"page"},{"location":"examples/postprocess/demo_em_extract_slice/","page":"Extract EM fields on a slice","title":"Extract EM fields on a slice","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/#demo_2d_contour_streamline_levels","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"","category":"section"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"This demo shows how to plot 2D colored contour in a region of interest with streamlines and levels.","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"using VlasiatorPyPlot\nusing Vlasiator: RE\n\nfunction main(file::String, varname::String)\n meta = load(file)\n\n fig, ax = plt.subplots(1,1; figsize=(8,6), constrained_layout=true)\n\n pcolormesh(meta, varname, ax)\n streamplot(meta, \"rho_v\", ax; comp=\"xy\", color=\"w\", density=2.0)\n\n cbar = ax.collections[end].colorbar\n boxcoords = Float64[0, 20, -15, 15]\n ax.set_xlim([boxcoords[1],boxcoords[2]])\n ax.set_ylim([boxcoords[3],boxcoords[4]])\n\n # Contour line at a specific level\n pArgs = Vlasiator.set_args(meta, varname, EARTH)\n x, y = Vlasiator.get_axis(pArgs)\n data = Vlasiator.prep2d(meta, varname)'\n CS = plt.contour(x, y, data, levels = [1e7],\n colors=(\"k\",),linestyles=(\"-\",),linewidths=(0.5,))\n\n # Add a rectangular box region\n boxrange = (250:299, 200:249)\n\n x = LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\n y = LinRange(meta.coordmin[2], meta.coordmax[2], meta.ncells[2])\n # Construct the patch\n rect = matplotlib.patches.Rectangle((x[boxrange[1][1]]/RE, y[boxrange[2][1]]/RE),\n (x[boxrange[1][end]] - x[boxrange[1][1]])/RE,\n (y[boxrange[2][end]] - y[boxrange[2][1]])/RE,\n linewidth=1, edgecolor=\"r\", facecolor=\"none\")\n\n ax.add_patch(rect)\nend\n\n\nfile = \"bulk.0000501.vlsv\"\nnameρ = \"rho\"\n\nmain(file, nameρ)","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"","category":"page"},{"location":"examples/visualization/demo_2dplot_pyplot/","page":"2D contour plot with streamlines and levels","title":"2D contour plot with streamlines and levels","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/#demo_energy_spectrum","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"","category":"section"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"This demo shows how to plot energy spectrum of oscillations at a fixed point.","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"using FFTW, JLD2, CurveFit, PyPlot\nusing Vlasiator: RE\n\nfunction main()\n file = \"satellites_uniform_sampled.jld2\"\n data = JLD2.load(file)\n\n nSatellite = length(data[\"t\"])\n nI, nJ = size(data[\"rho\"])[2:3]\n\n t = data[\"t\"]\n # Select spatial point\n i, j = 5, 5\n var = data[\"rho\"][:,i,j]\n\n dt = t[2] - t[1] # uniform sample interval [s]\n Fs = 1 / dt # sample frequency, [Hz]\n Fn = Fs / 2 # Nyquist frequency, [Hz]\n\n ## Frequency calculation\n nPoints = length(var)\n nFFT = nPoints\n df = Fs / nFFT\n freq_fullrange = -Fn:df:Fn\n\n freq = freq_fullrange[(nPoints ÷ 2 + 1):end-1]\n\n var_freq = fft(var)\n var_power = abs.(fftshift(var_freq))[(nPoints ÷ 2 + 1):end]\n\n # k is the exponential coefficient\n a, k = @views power_fit(freq[10:end], var_power[10:end])\n\n figure(figsize=(6,8))\n loglog(freq, var_power)\n axis(\"scaled\")\n\n min_power, max_power = extrema(@view var_power[10:end])\n xlim(freq[8], Fs)\n ylim(min_power * 0.75, max_power * 2.0)\n\n xlabel(\"Frequency [Hz]\"; fontsize=14)\n ylabel(\"Power Density \"; fontsize=14)\n title(string(round.(data[\"locations\"][i,j]./RE, digits=1))*\"Re\"; fontsize=14)\n\n loglog(freq[10:end], a.*freq[10:end].^k, label=\"k = $(round(k, digits=1))\")\n\n legend()\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"","category":"page"},{"location":"examples/visualization/demo_energy_spectrum/","page":"Energy spectrum at a fixed point","title":"Energy spectrum at a fixed point","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/#demo_track_waves","page":"Track waves","title":"Track waves","text":"","category":"section"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"This demo shows how to track wave and plot the dispersion relation On a equatorial plane, B ∥ ẑ, we can choose an arbitrary line in-plane. On a meridional plane, B is in-plane, we can find a local line region ∥ B and ⟂ B.","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"Currently it only works on a equatorial plane.","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"julia -t 4 demo_wave_tracing_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"or","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"JULIA_NUM_THREADS=4 julia demo_wave_tracing_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"using Vlasiator, VlasiatorPyPlot\nusing Vlasiator: qᵢ, μ₀, c, mᵢ, ϵ₀, RE\nusing Glob, DSP, FFTW, ImageFiltering, Interpolations\nusing Statistics: mean\nusing LinearAlgebra\n\n## Types\n\nstruct Variables\n varnames::Vector{String}\n varnames_print::Vector{String}\n components::Vector{Int}\nend\n\n## Methods\n\nispolar(meta::MetaVLSV) = findfirst(==(1), meta.ncells) == 2\n\n\"Extract `component` of variable `varname` at `cellids` from `files`.\"\nfunction extract_var(files, varname, cellids, distances, component=0)\n sample_loc = range(distances[1], distances[end], length=length(distances))\n\n var = zeros(length(distances), length(files))\n\n Threads.@threads for i in eachindex(files)\n meta = load(files[i])\n if component == 0\n var_line = readvariable(meta, varname, cellids)[:]\n else\n var_line = readvariable(meta, varname, cellids)[component,:]\n end\n #TODO: do we need high order interpolations?\n interp_linear = LinearInterpolation(distances, var_line)\n var_line_resample = interp_linear.(sample_loc)\n var_line_smooth = imfilter(var_line_resample, Kernel.gaussian((3,)))\n\n var[:,i] = var_line_smooth\n end\n var\nend\n\n\"CFL constrained normalized frequency.\"\ndispersion_CFL(k, dx, dt, di, ωci) = dx/dt * abs(k) /(di * ωci)\n\n\"Normalized frequency of fast magnetosonic waves along angle `θ` with Doppler shift.\"\nfunction dispersion_fast_perp(k, θ, vS, vA, v, di, ωci)\n ω = zeros(length(k))\n\n turnindex = findfirst(>=(0), k)\n\n vbulkpar = v[1]*cos(θ) + v[2]*sin(θ)\n\n dv1 = √(vS^2 + vA^2) + vbulkpar # propagate along +θ direction\n dv2 = -√(vS^2 + vA^2) + vbulkpar # propagate along -θ direction\n\n if dv1 < 0; dv1 = 0.0; end\n if dv2 > 0; dv2 = 0.0; end\n\n for i in 1:turnindex-1\n ω[i] = dv2*k[i] /(di * ωci)\n end\n\n for i in turnindex:length(k)\n ω[i] = dv1*k[i] /(di * ωci)\n end\n ω\nend\n\n\"Normalized frequency of bulk flow along tilted angle `θ`.\"\nfunction dispersion_bulk_flow(k, θ, v, di, ωci)\n ω = zeros(length(k))\n turnindex = findfirst(>=(0), k)\n vbulkpar = v[1]*cos(θ) + v[2]*sin(θ)\n irange = vbulkpar > 0 ? (turnindex:length(k)) : (1:turnindex)\n for i in irange # otherwise 0\n ω[i] = vbulkpar*k[i] /(di * ωci)\n end\n ω\nend\n\n\"Return the index in sorted `vec` with value closest to `x`.\"\nfunction searchsortednearest(vec, x)\n idx = searchsortedfirst(vec, x)\n if idx == 1\n return idx\n elseif idx > length(vec)\n return length(vec)\n elseif vec[idx] == x\n return idx\n elseif abs(vec[idx]-x) < abs(vec[idx-1]-x)\n return idx\n else\n return idx-1\n end\nend\n\n\"Obtain fast mode and bulk speed along line `angle` w.r.t. x-axis for cell ID `cid` in\n`meta`.\"\nfunction getCharacteristicSpeeds(meta, cid, angle)\n n = readvariable(meta, \"proton/vg_rho\", cid)\n B = readvariable(meta, \"vg_b_vol\", cid)\n p = readvariable(meta, \"vg_pressure\", cid)\n v = readvariable(meta, \"proton/vg_v\", cid)\n\n Bmag = norm.(eachcol(B))\n\n vA = @. Bmag / √(μ₀ * n * mᵢ) # Alfven speed, [m/s]\n vS = @. √(γ * p / (n * mᵢ)) # sonic speed, [m/s]\n\n vFast = @. √(vA^2 + vS^2)\n vBulk = @. v[1,:]*cos(angle) + v[2,:]*sin(angle)\n\n vFast, vBulk\nend\n\n\"Trace along line with `angle` w.r.t. x-axis at possible wave speeds.\"\nfunction tracewave(xstart, angle, files, dtfile, t, cellids, distances)\n\n x1 = zeros(length(t)); x1[1] = xstart\n x2 = copy(x1)\n x3 = copy(x1)\n\n tfile = let\n tfilefirst = getproperty(load(files[1]), :time)\n tfilelast = getproperty(load(files[end]), :time)\n tfilefirst:dtfile:tfilelast\n end\n\n ifile = 1 # file index tracker\n\n dt = t[2] - t[1] # timestep\n\n for it in eachindex(t)[1:end-1]\n # Find the closest output saving time to t[it], 0th order interpolation\n for i = ifile:length(tfile)\n if abs(tfile[i] - t[it]) < 0.5*dtfile\n ifile = i\n break\n end\n end\n meta = load(files[ifile])\n # Find the closest cell to the wave location\n cid = let\n c1 = searchsortednearest(distances, x1[it])\n c2 = searchsortednearest(distances, x2[it])\n c3 = searchsortednearest(distances, x3[it])\n cellids[c1], cellids[c2], cellids[c3]\n end\n vFast, vBulk = getCharacteristicSpeeds(meta, cid, angle)\n x1[it+1] = x1[it] + dt * vBulk[1]\n x2[it+1] = x2[it] + dt * (vBulk[2] + vFast[2])\n x3[it+1] = x3[it] + dt * (vBulk[3] - vFast[3])\n end\n\n x1, x2, x3\nend\n\n\"Evaluate the average quantities at `cellids` at the middle of `files`.\"\nfunction estimate_meanstates(files, cellids)\n # Select the snapshot in the middle\n nfile = length(files)\n meta = load(files[nfile÷2+1])\n\n n = readvariable(meta, \"proton/vg_rho\", cellids)\n v = readvariable(meta, \"proton/vg_v\", cellids)\n p = readvariable(meta, \"vg_pressure\", cellids)\n\n if hasvariable(meta, \"vg_b_vol\")\n B = readvariable(meta, \"vg_b_vol\", cellids)\n elseif hasvariable(meta, \"fg_b\")\n B = readvariable(meta, \"fg_b\", cellids)\n else\n B = readvariable(meta, \"b\", cellids)\n end\n\n vperp = @view v[1:2,:]\n vpar = @view v[3,:]\n\n # Obtain average states\n n̄ = mean(n)\n p̄ = mean(p)\n v̄par = mean(vpar)\n v̄perp = @views [mean(vperp[1,:]), mean(vperp[2,:])]\n\n # Characteristic parameters\n Bnorm = @views abs(mean(B[3,:]))\n di = √(mᵢ*ϵ₀/(n̄))*c/qᵢ # ion inertial length, [m]\n ωci = qᵢ*Bnorm/mᵢ # [/s]\n v̄A = Bnorm / √(μ₀ * n̄ * mᵢ) # Alfven speed, [m/s]\n v̄S = √(γ * p̄ / (n̄ * mᵢ)) # sonic speed, [m/s]\n\n println(\"--------------------------------------------------\")\n println(\"* Average states along the line at the middle snapshot\")\n println(\"Density : \", rpad(round(n̄/1e6; digits=2), 8), \"amu/cc\")\n println(\"Pressure : \", rpad(round(p̄*1e9; digits=3), 8), \"nPa\")\n println(\"Parallel velocity : \", rpad(round(v̄par/1e3; digits=2), 8), \"km/s\")\n println(\"Perpendicular velocity: \", rpad(round.(v̄perp/1e3; digits=2), 8), \"km/s\")\n println(\"Flow angle : \", rpad(round(atand(v̄perp[2], v̄perp[1]); digits=2), 8),\n \"degrees\")\n println(\"Ion inertial length : \", rpad(round(di/1e3; digits=2), 8), \"km\")\n println(\"Gyrofrequency : \", rpad(round(ωci; digits=2), 8), \"Hz\")\n println(\"Alfven speed : \", rpad(round(v̄A/1e3; digits=2), 8), \"km/s\")\n println(\"Sonic speed : \", rpad(round(v̄S/1e3; digits=2), 8), \"km/s\")\n println(\"--------------------------------------------------\")\n\n di, ωci, v̄A, v̄S, v̄perp\nend\n\n\"Plot the process of wave checks.\"\nfunction plot_dispersion(files, vars, cellids, distances, coords, meanstates, dtfile, Δt,\n outdir)\n\n # Parameters\n nfile = length(files)\n npoints = length(cellids)\n nt = nfile ÷ 2 + 1\n\n varnames = vars.varnames\n varnames_print = vars.varnames_print\n components = vars.components\n\n di, ωci, v̄A, v̄S, v̄perp = meanstates\n\n tfile1st = load(files[1]).time\n # Output timestamps\n t = [dtfile * ifile + tfile1st for ifile in 0:nfile-1]\n # Selected line tilted angle ∈ [-π, π]\n θ = atan(coords[2,end] - coords[2,1], coords[1,end] - coords[1,1])\n # Sample width, [m]\n dx = norm(coords[:,end] .- coords[:,1]) /(npoints - 1)\n println(\"spatial resolution: \", round(dx/1e3; digits=2), \" km\")\n\n # Trace wave along the line in a space-time domain\n twave = let\n tstart = 400.0\n tend = 430.0\n tstart:200Δt:tend\n end\n xwave = tracewave(distances[npoints÷2+1], θ, files, dtfile, twave, cellids, distances)\n\n twave2 = let\n tstart = 600.0\n tend = 630.0\n tstart:200Δt:tend\n end\n xwave2 = tracewave(distances[npoints÷2+1], θ, files, dtfile, twave2, cellids, distances)\n\n # Dispersion plotting ranges\n kmin = -π / dx * di # minimum wave number\n kmax = π / dx * di # maximum wave number\n ωmin = 0 # minimum angular frequency\n ωmax = π / dtfile / ωci # maximum angular frequency\n\n # Only the 1st quadrature\n krange = range(kmin, kmax, length=npoints)\n ωrange = range(ωmin, ωmax, length=nt)\n\n axisunit = EARTH\n\n # Precalculated lines\n ωCFL = dispersion_CFL.(krange, dx, Δt, di, ωci)\n ωfast = dispersion_fast_perp(krange, θ, v̄S, v̄A, v̄perp, di, ωci)\n ωbulk = dispersion_bulk_flow(krange, θ, v̄perp, di, ωci)\n # Window filtering for avoiding spectral leakage\n window = hanning(npoints) * hanning(nfile)'\n\n meta = load(files[end])\n\n for i in eachindex(varnames)\n println(\"variable name: \", varnames[i])\n var = extract_var(files, varnames[i], cellids, distances, components[i])\n\n # 2DFFT\n F̃ = window .* var |> fft |> fftshift\n\n # Visualization\n fig = figure(figsize=(12,12), constrained_layout=false)\n ax = [subplot(221), subplot(223), subplot(222), subplot(224, projection=\"3d\")]\n\n dispersion = reverse!(abs.(F̃.*F̃)[:, end-nt+1:end]', dims=1)\n im1 = ax[1].pcolormesh(krange, ωrange, dispersion, norm=matplotlib.colors.LogNorm())\n\n ax[1].plot([krange[1], 0.0, krange[end]], [ωCFL[1], 0.0, ωCFL[end]], \"--\",\n linewidth=1.0, color=\"k\", label=\"CFL Condition\")\n ax[1].plot(krange, ωfast, \"--\",\n linewidth=1.2, color=\"#d62728\", label=\"Fast Mode\")\n ax[1].plot(krange, ωbulk, \"--\",\n linewidth=1.2, color=\"#9467bd\", label=\"Flow Speed\")\n\n ax[1].set_xlim(kmin, kmax)\n ax[1].set_ylim(ωmin, ωmax)\n\n cb = colorbar(im1; ax=ax[1])\n cb.ax.tick_params(direction=\"in\")\n ax[1].legend(;fontsize=\"x-small\")\n ax[1].set_xlabel(L\"$k_\\perp \\cdot d_i$\")\n ax[1].set_ylabel(L\"$\\omega/\\Omega_{ci}$\")\n ax[1].set_title(L\"$k_\\perp$ angle w.r.t. x = %$θ\")\n\n im2 = ax[2].pcolormesh((distances .+ coords[1,1])./RE, t, var')\n\n ax[2].plot((xwave[1] .+ coords[1,1])./RE, twave, \".--\",\n color=\"#d62728\", label=L\"$V_{bulk}$\")\n ax[2].plot((xwave[2] .+ coords[1,1])./RE, twave, \".--\",\n color=\"#9467bd\", label=L\"$V_{bulk} + V_{fast}$\")\n ax[2].plot((xwave[3] .+ coords[1,1])./RE, twave, \".--\",\n color=\"#ff7f0e\", label=L\"$V_{bulk} - V_{fast}$\")\n\n ax[2].plot((xwave2[1] .+ coords[1,1])./RE, twave2, \".--\",\n color=\"#d62728\")\n ax[2].plot((xwave2[2] .+ coords[1,1])./RE, twave2, \".--\",\n color=\"#9467bd\")\n ax[2].plot((xwave2[3] .+ coords[1,1])./RE, twave2, \".--\",\n color=\"#ff7f0e\")\n\n cb = colorbar(im2; ax=ax[2])\n cb.ax.tick_params(direction=\"in\")\n\n ax[2].set_xlim(coords[1,1]/RE, coords[1,end]/RE)\n\n ax[2].legend(loc=\"upper center\", bbox_to_anchor=(0.5, -0.13),\n fancybox=true, shadow=true, ncol=3)\n ax[2].set_xlabel(L\"x [$R_E$]\")\n ax[2].set_ylabel(L\"time [s]\")\n ax[2].set_title(\"$(varnames_print[i])_$(components[i])\")\n\n pArgs = Vlasiator.set_args(meta, varnames[i], axisunit; normal=:none)\n x, y = Vlasiator.get_axis(pArgs)\n data = Vlasiator.prep2d(meta, varnames[i], components[i])'\n cnorm, cticks = set_colorbar(Linear, -Inf, Inf, data)\n cmesh = ax[3].pcolormesh(x, y, data, norm=cnorm)\n\n ax[3].set_xlabel(pArgs.strx)\n ax[3].set_ylabel(pArgs.stry)\n ax[3].set_aspect(1)\n\n cb = colorbar(cmesh; ax=ax[3], ticks=cticks, fraction=0.046, pad=0.04)\n cb.ax.set_ylabel(pArgs.cb_title)\n cb.ax.tick_params(direction=\"in\")\n\n @views ax[3].scatter(coords[1,:]./RE, coords[2,:]./RE; s=0.2, color=\"k\")\n\n xCoord = (distances .+ coords[1,1])./RE\n # meshgrid\n X = [x for _ in t, x in xCoord]\n Y = [y for y in t, _ in xCoord]\n\n ax[4].view_init(elev=40., azim=-30.)\n ax[4].plot_surface(X, Y, var', cmap=matplotlib.cm.turbo, antialiased=false)\n\n ax[4].set_xlabel(L\"x [$R_E$]\"; fontsize=\"small\")\n ax[4].set_ylabel(\"time [s]\"; fontsize=\"small\")\n #ax[4].set_zlabel(pArgs.cb_title)\n ax[4].tick_params(labelsize=\"small\")\n\n outname = \"dispersion_$(varnames_print[i])_$(components[i]).png\"\n savefig(joinpath(outdir, outname), bbox_inches=\"tight\")\n close(fig)\n end\n\nend\n\nfunction main()\n outdir = \"../out/\"\n γ = 5 / 3\n\n xStart = [10.0, 0.0, 0.0].*RE\n xEnd = [13.3, 0.0, 0.0].*RE\n\n varnames = [\"proton/vg_rho\", \"vg_b_vol\", \"vg_e_vol\", \"vg_pressure\"]\n varnames_print = [\"rho\", \"b\", \"e\", \"p\"]\n components = [0, 3, 1, 0] # 0 for scalar, 1-3 for vector components\n\n dir = \"../run_rho2_bz-5_timevarying_startfrom300s\"\n files = glob(\"bulk.*.vlsv\", dir)\n\n vars = Variables(varnames, varnames_print, components)\n\n dtfile = 0.5 # output interval, [s]\n Δt = 0.0147176 # discrete time step from runlog, [s]\n\n meta = load(files[1])\n\n if ispolar(meta) # polar plane\n @error \"not implemented!\"\n end\n\n cellids, distances, coords = getcellinline(meta, xStart, xEnd)\n\n meanstates = estimate_meanstates(files, cellids)\n\n println(\"number of extracted points: \", length(cellids))\n println(\"xStart: \", xStart)\n println(\"xEnd: \", xEnd)\n tbegin = load(files[1]).time\n tend = load(files[end]).time\n println(\"time from $tbegin to $tend s\")\n\n @time plot_dispersion(files, vars, cellids, distances, coords, meanstates, dtfile, Δt,\n outdir)\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"","category":"page"},{"location":"examples/postprocess/demo_wave_tracing_mt/","page":"Track waves","title":"Track waves","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_pointextracting/#demo_virtual_sat","page":"Virtual satellite","title":"Virtual satellite","text":"","category":"section"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"This demo shows how to extract data for a virtual satellite. Outputs are stored in CSV format for sharing data.","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"julia -t nthreads demo_virtual_satellite.jl","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"or","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"JULIA_NUM_THREADS=nthreads julia demo_virtual_satellite.jl","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"using Glob, DelimitedFiles, Vlasiator, DataFrames\nusing Vlasiator: RE # Earth radius [m]\n\nfunction extract_vars(files, loc)\n nfiles = length(files)\n # variables to be extracted\n t = zeros(Float32, nfiles)\n rho = zeros(Float32, nfiles)\n v = zeros(Float32, 3, nfiles)\n p = zeros(Float32, nfiles)\n b = zeros(Float32, 3, nfiles)\n e = zeros(Float32, 3, nfiles)\n\n id = load(files[1]) do meta\n getcell(meta, loc)\n end\n\n # Extract data from each frame\n Threads.@threads for i = eachindex(files)\n meta = load(files[i])\n t[i] = meta.time\n rho[i] = readvariable(meta, \"proton/vg_rho\", id)[1]\n v[:,i] = readvariable(meta, \"proton/vg_v\", id)\n p[i] = readvariable(meta, \"vg_pressure\", id)[1]\n b[:,i] = readvariable(meta, \"vg_b_vol\", id)\n e[:,i] = readvariable(meta, \"vg_e_vol\", id)\n end\n\n df = DataFrame(t = t, rho = rho, v = v, p = p, b = b, e = e)\n # Save into text file\n writedlm(\"satellite.csv\", Iterators.flatten(([names(df)], eachrow(df))), ',')\nend\n\n#####\n\nfiles = glob(\"bulk*.vlsv\", \"./\")\n\n# virtual satellite location\nconst loc = Float64[12, 0, 0] .* RE\n\nprintln(\"Number of files: $(length(files))\")\nprintln(\"Extracting location: $loc\")\nprintln(\"Running with $(Threads.nthreads()) threads...\")\n\n@time extract_vars(files, loc)\n\nprintln(\"Virtual satellite extraction done!\")\n\n## Visualization\n#=\nusing PyPlot, DelimitedFiles\n\ndata = readdlm(\"satellite.csv\", ','; header=true)\n\nfig, ax = subplots(figsize=(8,10), 5,1, sharex=true, constrained_layout=true)\n\nax[1].plot(data[1][:,1], data[1][:,2] ./ 1e6, label=\"density\")\nax[2].plot(data[1][:,1], data[1][:,3] ./ 1e3, label=\"vx\")\nax[2].plot(data[1][:,1], data[1][:,4] ./ 1e3, label=\"vy\")\nax[3].plot(data[1][:,1], data[1][:,5] .* 1e9, label=\"p\")\nax[4].plot(data[1][:,1], data[1][:,6] .* 1e9, label=\"bz\")\nax[5].plot(data[1][:,1], data[1][:,7] .* 1e3, label=\"ex\")\nax[5].plot(data[1][:,1], data[1][:,8] .* 1e3, label=\"ey\")\n\nfor a in ax\n a.grid(true)\n a.legend()\nend\n\nax[1].set_ylabel(\"density [amu/cc]\", fontsize=14)\nax[2].set_ylabel(\"velocity [km/s]\", fontsize=14)\nax[3].set_ylabel(\"pressure [nPa]\", fontsize=14)\nax[4].set_ylabel(\"magnetic field [nT]\", fontsize=14)\nax[5].set_ylabel(\"electric field [mV/m]\", fontsize=14)\nax[5].set_xlabel(\"time [s]\", fontsize=14)\n\nfig.suptitle(\"Density Pulse Run, location = [12, 0, 0]\", fontsize=\"xx-large\")\n\nsavefig(\"virtual_satellite.png\", bbox_inches=\"tight\")\n=#","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"","category":"page"},{"location":"examples/postprocess/demo_pointextracting/","page":"Virtual satellite","title":"Virtual satellite","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/#demo_2d_virtual_sats","page":"Virtual satellites","title":"Virtual satellites","text":"","category":"section"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"This demo shows how to extract data for virtual satellites at uniformly sampled locations on a 2D plane. Outputs are stored in binary format for sharing within Julia.","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"using Glob, Vlasiator\nusing JLD2: jldsave\n\n\"Select cells in 2D `meta` with uniform distance `dx`.\"\nfunction sample(meta, dx)\n dcell = floor(Int, dx ÷ meta.dcoord[1])\n\n cellid = sort(collect(keys(meta.celldict)))\n cellid = reshape(cellid, meta.ncells[1], meta.ncells[2])\n cellid_select = cellid[1+dcell:dcell:end-dcell, 1+dcell:dcell:end-dcell]\nend\n\nfunction extract_vars(files, dx)\n nfiles = length(files)\n\n meta = load(files[1])\n ids = sample(meta, dx)\n locations = [getcellcoordinates(meta, id) for id in ids]\n\n nsize = size(ids)\n println(\"Number of virtual satellites: $(length(ids))\")\n\n # variables to be extracted\n t = zeros(Float32, nfiles)\n rho = zeros(Float32, nfiles, nsize[1], nsize[2])\n vx = zeros(Float32, nfiles, nsize[1], nsize[2])\n vy = zeros(Float32, nfiles, nsize[1], nsize[2])\n vz = zeros(Float32, nfiles, nsize[1], nsize[2])\n p = zeros(Float32, nfiles, nsize[1], nsize[2])\n bx = zeros(Float32, nfiles, nsize[1], nsize[2])\n by = zeros(Float32, nfiles, nsize[1], nsize[2])\n bz = zeros(Float32, nfiles, nsize[1], nsize[2])\n ex = zeros(Float32, nfiles, nsize[1], nsize[2])\n ey = zeros(Float32, nfiles, nsize[1], nsize[2])\n ez = zeros(Float32, nfiles, nsize[1], nsize[2])\n\n # Extract data from each frame\n for i = eachindex(files)\n meta = load(files[i])\n t[i] = meta.time\n rho[i,:,:] = readvariable(meta, \"proton/vg_rho\", ids)\n v = readvariable(meta, \"proton/vg_v\", ids)\n vx[i,:,:] = v[1,:]\n vy[i,:,:] = v[2,:]\n vz[i,:,:] = v[3,:]\n p[i,:,:] = readvariable(meta, \"vg_pressure\", ids)\n b = readvariable(meta, \"vg_b_vol\", ids)\n bx[i,:,:] = b[1,:]\n by[i,:,:] = b[2,:]\n bz[i,:,:] = b[3,:]\n e = readvariable(meta, \"vg_e_vol\", ids)\n ex[i,:,:] = e[1,:]\n ey[i,:,:] = e[2,:]\n ez[i,:,:] = e[3,:]\n end\n\n # Save into binary file\n jldsave(\"satellites_uniform_sampled.jld2\";\n locations, t, rho, vx, vy, vz, p, bx, by, bz, ex, ey, ez)\nend\n\n#####\n\nfiles = glob(\"bulk*.vlsv\", \"./\")\n\nconst dx = 5RE # uniform sampling distance [m]\n\nprintln(\"Number of files: $(length(files))\")\nprintln(\"Running with $(Threads.nthreads()) threads...\")\n\n@time extract_vars(files, dx)\n\nprintln(\"Virtual satellite extraction done!\")","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"","category":"page"},{"location":"examples/postprocess/demo_pointsextracting_2d_uniform/","page":"Virtual satellites","title":"Virtual satellites","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/#demo_2d_bowshock","page":"Extract bow shock location","title":"Extract bow shock location","text":"","category":"section"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"(Image: Author) (Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"This demo shows how to extract the bow shock location from a 2D equatorial run and plot.","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"using Vlasiator, PyPlot\n\n# Upstream solar wind temperature\nconst Tsw = 0.5e6 #[K]\n\nconst file = \"bulk.0001347.vlsv\"\nmeta = load(file)\n# NonAMR\nconst x = LinRange{Float32}(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\nconst y = LinRange{Float32}(meta.coordmin[2], meta.coordmax[2], meta.ncells[2])\n\n# Obtain thermal temperature\nT = meta[\"T\"]\nT = reshape(T, meta.ncells[1], meta.ncells[2])\n\nconst x_crossing = zeros(Float32, meta.ncells[2])\nconst y_crossing = y\n\n# Extract bow shock location from the 1st point which fulfills the threshold: T > 4 * Tsw\n# Note: this won't work if the bow shock does not cover the whole domain y extension!\nfor j in 1:meta.ncells[2] # scan in y direction\n ind_ = findlast(>(4*Tsw), @view T[:,j]) # count from upstream\n x_crossing[j] = x[ind_]\nend\n\n# Julia is column-major, while Python is row-major\nimshow(T', extent=(x[1], x[end], y[1], y[end]), origin=\"lower\", cmap=plt.get_cmap(\"ocean\"))\nplot(x_crossing, y_crossing, \"r\")\naxis(\"scaled\")\nsavefig(\"bs_temp_test.png\")","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"","category":"page"},{"location":"examples/visualization/demo_bowshock_2dlocation/","page":"Extract bow shock location","title":"Extract bow shock location","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/#demo_vdfs","page":"VDFs along a line","title":"VDFs along a line","text":"","category":"section"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"This demo shows how to plot velocity distribution functions along a line.","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"using VlasiatorPyPlot, JLD2\nusing Vlasiator: RE # Earth radius [m]\n\nfunction main()\n ## Plot velocity space distributions\n xloc = range(7.0, 10.0, step=2.35)\n yloc = range(-0.0, 5.0, step=2.35)\n zloc = 0.0\n\n CIs = CartesianIndices((1:length(xloc), 1:length(yloc)))\n\n fig, axs = plt.subplots(length(xloc), length(yloc), sharex=true, sharey=true)\n\n for i in CIs\n loc = RE .* [xloc[i[1]], yloc[i[2]], zloc]\n vdfslice(meta, loc, axs[i]; verbose=false)\n end\n\n for a in axs[end,:] a.set_xlabel(\"vx [km/s]\") end\n for a in axs[: ,1] a.set_ylabel(\"vy [km/s]\") end\n\n ## Subtract data of cells with VDF\n\n file = \"test/data/bulk.1d.vlsv\"\n meta = load(file)\n\n cells = getcellwithvdf(meta)\n\n ρ = zeros(Float64, size(cells))\n v = zeros(Float64, 3, size(cells)...)\n p = zeros(Float64, size(cells))\n\n vsize = meta.meshes[\"proton\"].vblock_size .* meta.meshes[\"proton\"].vblocks\n vcellids = [Int[] for _ in cells]\n vcellf = [Float64[] for _ in cells]\n\n for (i, cell) in enumerate(cells)\n ρ[i] = readvariable(meta, \"proton/vg_rho\", cell)[1]\n v[i] = readvariable(meta, \"proton/vg_v\", cell)[1]\n p[i] = readvariable(meta, \"vg_pressure\", cell)[1]\n\n vcellids[i], vcellf[i] = readvcells(meta, cell)\n end\n\n jldopen(\"example.jld2\", \"a+\") do file\n file[\"file1/density\"] = ρ\n file[\"file1/velocity\"] = v\n file[\"file1/pressure\"] = p\n file[\"file1/VDF\"] = vcellf\n end\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"","category":"page"},{"location":"examples/visualization/demo_vdfs_pyplot/","page":"VDFs along a line","title":"VDFs along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/#demo_xpoints","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"","category":"section"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"This example shows how to find X-points in a 2D magnetic reconnection configuration and save the coordinates as well as extracted reconnection rate Ey from multiple outputs. Here we assume a X-Z plane.","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"using JLD2: jldsave\nusing Vlasiator, Glob, ProgressMeter\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n\n nG = 2 # number of ghost cells\n\n x, z, dx = load(files[1]) do meta\n LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1]) ./ Vlasiator.RE,\n LinRange(meta.coordmin[3], meta.coordmax[3], meta.ncells[3]) ./ Vlasiator.RE,\n [meta.dcoord[1], meta.dcoord[3]]\n end\n\n xmin_ = searchsortedfirst(x, 7.0)\n xmax_ = searchsortedlast(x, 9.0)\n zmin_ = searchsortedfirst(z, -4.0)\n zmax_ = searchsortedlast(z, 4.0)\n\n x_points_x = Vector{Vector{eltype(x)}}(undef, 0)\n x_points_z = similar(x_points_x)\n\n @showprogress 5 \"Finding X-points...\" for ifile in eachindex(files)\n meta = load(files[ifile])\n b = meta[\"vg_b_vol\"]\n b = reshape(b, 3, meta.ncells[1], meta.ncells[3])\n\n flux = compute_flux_function(b, dx, nG)\n indices_x, _ = find_reconnection_points(flux[xmin_:xmax_,zmin_:zmax_], 5e-3)\n\n push!(x_points_x, x[indices_x[1,:].+xmin_.-1])\n push!(x_points_z, z[indices_x[2,:].+zmin_.-1])\n end\n\n ## Extract Ey at X-points\n ey = Vector{Vector{Float32}}(undef, 0)\n\n for it in eachindex(x_points_x)\n meta = load(files[it])\n ids = Vector{Int}(undef, length(x_points_x[it]))\n for ip in eachindex(x_points_x[it])\n loc = [x_points_x[it][ip], 0.0, x_points_z[it][ip]] .* Vlasiator.RE\n ids[ip] = getcell(meta, loc)\n end\n ey_now = readvariable(meta, \"vg_e_vol\", ids)[2,:]\n push!(ey, ey_now)\n end\n\n # save\n jldsave(\"x_point_locations.jld2\"; x_points_x, x_points_z, ey)\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"","category":"page"},{"location":"examples/postprocess/demo_x_points_extracting/","page":"Find X-points in 2D","title":"Find X-points in 2D","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"internal/#Internal","page":"API Reference","title":"Internal","text":"","category":"section"},{"location":"internal/#Public-APIs","page":"API Reference","title":"Public APIs","text":"","category":"section"},{"location":"internal/","page":"API Reference","title":"API Reference","text":"Modules = [Vlasiator]\nPrivate = false\nOrder = [:constant, :type, :function]","category":"page"},{"location":"internal/#Vlasiator.MetaVLSV","page":"API Reference","title":"Vlasiator.MetaVLSV","text":"VLSV meta data.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Vlasiator.VarInfo","page":"API Reference","title":"Vlasiator.VarInfo","text":"Variable information from the VLSV footer.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Vlasiator.check_plasma_characteristics-NTuple{4, Any}","page":"API Reference","title":"Vlasiator.check_plasma_characteristics","text":"check_plasma_characteristics(n, v, T, B)\n\nDisplay characteristic plasma parameters given density n, bulk velocity v, temperature T, and magnetic field strength B in SI units.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.compute_flux_function-Union{Tuple{N}, Tuple{T}, Tuple{AbstractArray{T, N}, Vector{T}}, Tuple{AbstractArray{T, N}, Vector{T}, Int64}} where {T, N}","page":"API Reference","title":"Vlasiator.compute_flux_function","text":"compute_flux_function(b::AbstractArray{T,N}, Δ::Vector{T}, nG::Int=2) where {T,N}\n\nCalculate the 2D magnetic flux function ψ from the magnetic field b and discrete steps Δ. nG is the number of ghost cells along each dimension in the vector field. ψ is defined as psi = int B_x dz = - int B_z dx from mathbfB = hatytimesnablapsi in the X-Z plane and Y is the out-of-plane direction. This is strictly true if B is divergence-free and the guide field By is constant. However, numerically there will be errors. The current implementation calculates ψ by integrating along -z boundary first, and then going along z. Reference: Flux function\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.extractsat-Tuple{AbstractVector{String}, String, Int64}","page":"API Reference","title":"Vlasiator.extractsat","text":"extractsat(files::AbstractVector{String}, var::String, cid::Int)\n\nMulti-threaded extraction of var at a fixed cell ID cid from files. This assumes that files come from the same grid structure.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.find_reconnection_points-Union{Tuple{Matrix{T}}, Tuple{T}} where T","page":"API Reference","title":"Vlasiator.find_reconnection_points","text":"find_reconnection_points(ψ::Array{T,2}; retol::Float64=1e-4,\n method::Int=1) -> indices_x, indices_o\n\nFind X-point and O-point indices in 2D magnetic field topology from flux function ψ. The current implementation does not work for the 3 layers near the boundary.\n\nKeywords\n\nretol=1e-1: determines the relative tolerance of the ratio w.r.t. |∇ψ|² to accept a gradient as 0.\nmethod=1: method 1 compute the cell-centered 1st and 2nd order derivatives and check the Hessian matrix; method 2 check the flux function at each point against its 8 neighbors, which is more deterministic.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getKLdivergence-Tuple{MetaVLSV, Array{<:AbstractFloat}}","page":"API Reference","title":"Vlasiator.getKLdivergence","text":"getKLdivergence(meta, VDF; species=\"proton\")\ngetKLdivergence(meta, vcellids, vcellf; species=\"proton\")\n\nObtain the KL-divergence ∫ f*log(f/g)dv, where f is the VDF from Vlasiator and g is the analytical Maxwellian distribution that generates the same density as f. The value ranges from [0, +∞], with 0 meaning perfect Maxwellian. Usually the values are quite small. Alternatively, one can pass original vcellids and vcellf directly.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getcell-Tuple{MetaVLSV, AbstractVector{<:AbstractFloat}}","page":"API Reference","title":"Vlasiator.getcell","text":"getcell(meta::MetaVLSV, location:::AbstractVector{<:AbstractFloat}) -> Int\n\nReturn cell ID containing the given spatial location in meter, excluding domain boundaries. Only accept 3D location.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getcellcoordinates-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getcellcoordinates","text":"getcellcoordinates(meta::MetaVLSV, cid::Int) -> SVector{3,Float64}\n\nReturn a given cell's spatial coordinates.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getcellinline-Union{Tuple{T}, Tuple{MetaVLSV, Vector{T}, Vector{T}}} where T","page":"API Reference","title":"Vlasiator.getcellinline","text":"getcellinline(meta, point1::Vector, point2::Vector) -> cellids, distances, coords\n\nReturns cell IDs, distances and coordinates for every cell in a line between two given points point1 and point2. TODO: preallocation?\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getcellwithvdf","page":"API Reference","title":"Vlasiator.getcellwithvdf","text":"getcellwithvdf(meta, species::String=\"proton\") -> cellids\n\nGet all the cell IDs with VDF saved associated with meta.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.getchildren-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getchildren","text":"getchildren(meta::MetaVLSV, cid::Int) -> Vector{Int}\n\nReturn direct children of cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getdensity-Union{Tuple{T}, Tuple{MetaVLSV, Array{T}}} where T<:AbstractFloat","page":"API Reference","title":"Vlasiator.getdensity","text":"getdensity(meta, VDF; species=\"proton\")\ngetdensity(meta, vcellf; species=\"proton\")\ngetdensity(vmesh::VMeshInfo, vcellf)\n\nGet density from VDF of species associated with meta, n = ∫ f(r,v) dV. Alternatively, one can directly pass vcellids as original indices of nonzero VDFs and vcellf as their corresponding values.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getheatfluxvector-Union{Tuple{T}, Tuple{MetaVLSV, Array{T}}} where T<:AbstractFloat","page":"API Reference","title":"Vlasiator.getheatfluxvector","text":"getheatfluxvector(meta, VDF; species=\"proton\")\ngetheatfluxvector(meta, vcellids, vcellf; species=\"proton\")\ngetheatfluxvector(vmesh::VMeshInfo, vcellids, vcellf)\n\nGet heat flux vector (3 components) of species from VDF associated with meta, qᵢ = m/2 * ∫ (v - u)²(v - u)ᵢ * f(r,v) dV. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getlevel-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getlevel","text":"getlevel(meta::MetaVLSV, cid::Int) -> Int\n\nReturn the AMR level of a given cell ID cid.\n\nwarning: Warning\nThis function does not check if the VLSV file of meta actually contains cid; it may be shadowed by refined children.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getmaxwellianity-Tuple{MetaVLSV, Array{<:AbstractFloat}}","page":"API Reference","title":"Vlasiator.getmaxwellianity","text":"getmaxwellianity(meta, VDF; species=\"proton\")\ngetmaxwellianity(meta, vcellids, vcellf; species=\"proton\")\n\nObtain the Maxwellian similarity factor -log(1/(2n) * ∫ |f - g| dv), where f is the VDF from Vlasiator and g is the analytical Maxwellian distribution that generates the same density as f. The value ranges from [0, +∞], with 0 meaning not Maxwellian-distributed at all, and +∞ a perfect Maxwellian distribution. Alternatively, one can pass original vcellids and vcellf directly.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getnearestcellwithvdf","page":"API Reference","title":"Vlasiator.getnearestcellwithvdf","text":"getnearestcellwithvdf(meta, id::Int, species::String=\"proton\") -> Int\n\nFind the nearest spatial cell with VDF saved for species of a given cell id associated with meta.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.getparent-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getparent","text":"getparent(meta::MetaVLSV, cid::Int) -> Int\n\nReturn the parent cell ID of given child cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getpressure-Union{Tuple{T}, Tuple{MetaVLSV, Array{T}}} where T<:AbstractFloat","page":"API Reference","title":"Vlasiator.getpressure","text":"getpressure(meta, VDF; species=\"proton\")\ngetpressure(meta, vcellids, vcellf; species=\"proton\")\ngetpressure(vmesh::VMeshInfo, vcellids, vcellf)\n\nGet pressure tensor (6 components: Pxx, Pyy, Pzz, Pyz, Pzx, Pxy) of species from VDF associated with meta, pᵢⱼ = m * ∫ (v - u)ᵢ(v - u)ⱼ * f(r,v) dV. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getsiblings-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.getsiblings","text":"getsiblings(meta::MetaVLSV, cid::Int) -> Vector{Int}\n\nReturn sibling cells of a given cid, including itself.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getslicecell-Tuple{MetaVLSV, Float64, Int64, Float64, Float64}","page":"API Reference","title":"Vlasiator.getslicecell","text":"getslicecell(meta, sliceoffset, dir, minCoord, maxCoord) -> idlist, indexlist\n\nFind the cell IDs idlist which are needed to plot a 2d cut through of a 3d mesh, in a direction dir at sliceoffset, and the indexlist, which is a mapping from original order to the cut plane and can be used to select data onto the plane.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getvcellcoordinates-Tuple{MetaVLSV, Vector{Int32}}","page":"API Reference","title":"Vlasiator.getvcellcoordinates","text":"getvcellcoordinates(meta::MetaVLSV, vcellids::Vector; species=\"proton\")\n\nReturn velocity cells' coordinates of species and vcellids.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getvelocity-Union{Tuple{T}, Tuple{MetaVLSV, Array{T}}} where T<:AbstractFloat","page":"API Reference","title":"Vlasiator.getvelocity","text":"getvelocity(meta, VDF; species=\"proton\")\ngetvelocity(meta, vcellids, vcellf; species=\"proton\")\ngetvelocity(vmesh::VMeshInfo, vcellids, vcellf)\n\nGet bulk velocity from VDF of species, u = ∫ v * f(r,v) dV / n. Alternatively, one can directly pass vcellids, vcellf, as in getdensity.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.hasname-Tuple{SubArray{XML.Node, 1, Vector{XML.Node}, Tuple{UnitRange{Int64}}, true}, String}","page":"API Reference","title":"Vlasiator.hasname","text":"Check if the XML nodes ns contain a node of name.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.hasparameter-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.hasparameter","text":"hasparameter(meta::MetaVLSV, param::String) -> Bool\n\nCheck if the VLSV file contains a certain parameter param.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.hasvariable-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.hasvariable","text":"hasvariable(meta::MetaVLSV, var::String) -> Bool\n\nCheck if the VLSV file associated with meta contains a variable var.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.isparent-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.isparent","text":"isparent(meta::MetaVLSV, cid::Int) -> Bool\n\nCheck if cid is a parent cell.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.issame","page":"API Reference","title":"Vlasiator.issame","text":"issame(file1, file2, tol=1e-4; strict=true, verbose=false) -> Bool\n\nCheck if two VLSV files file1 and file2 are approximately identical, under relative tolerance tol. If strict=true, the file size difference should be less than 1%.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.load-Tuple{AbstractString}","page":"API Reference","title":"Vlasiator.load","text":"load(file::AbstractString)) -> MetaVLSV\n\nGenerate a MetaVLSV object from file of VLSV format.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readlog-Tuple{AbstractString}","page":"API Reference","title":"Vlasiator.readlog","text":"readlog(file::AbstractString)\n\nRead the run log file, check the iteration status and return the timestamps (exluding the last) as well as the model running speed in physical seconds per simulated seconds.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readparameter-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.readparameter","text":"readparameter(meta::MetaVLSV, param::String)\n\nReturn the parameter value from the VLSV file associated with meta.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvariable","page":"API Reference","title":"Vlasiator.readvariable","text":"readvariable(meta::MetaVLSV, var::String, sorted::Bool=true, usemmap::Bool=false) -> Array\n\nReturn variable value of var from the VLSV file associated with meta. By default for DCCRG variables are sorted by cell ID. usemmap decides whether to use memory-mapped IO, which is especially useful for large arrays.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.readvariable-Tuple{MetaVLSV, String, Int64}","page":"API Reference","title":"Vlasiator.readvariable","text":"readvariable(meta::MetaVLSV, var::String, cid::Int) -> Array\n\nRead variable var in cell cid associated with meta.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvariable-Tuple{MetaVLSV, String, Vector{Int64}}","page":"API Reference","title":"Vlasiator.readvariable","text":"readvariable(meta::MetaVLSV, var::String, ids::Vector{Int}) -> Array\n\nRead variable var in a collection of cells ids associated with meta. if ids is empty, return the whole sorted array of var.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvariablemeta-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.readvariablemeta","text":"readvariablemeta(meta, var) -> VarInfo\n\nReturn VarInfo of var in the VLSV file associated with meta.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvcells-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.readvcells","text":"readvcells(meta::MetaVLSV, cid::Int; species=\"proton\") -> vcellids, vcellf\n\nRead velocity cells of species from a spatial cell of ID cid associated with meta, and return a map of velocity cell ids vcellids and corresponding value vcellf.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.refineslice-Tuple{MetaVLSV, Vector{Int64}, AbstractVector, Symbol}","page":"API Reference","title":"Vlasiator.refineslice","text":"refineslice(meta, idlist::Vector{Int}, data::AbstractVector, normal::Symbol) -> Vector\nrefineslice(meta, idlist::Vector{Int}, data::AbstractMatrix, normal::Symbol) -> Matrix\nrefineslice(meta, idlist::Vector{Int}, data::AbstractArray, dir::Int)\n\nGenerate data on the finest refinement level given cellids idlist and variable data on the slice perpendicular to normal. If data is 2D, then the first dimension is treated as vector components.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.write_vlsv-Tuple{AbstractString, AbstractString, Vector{Tuple{VecOrMat, String, VarInfo}}}","page":"API Reference","title":"Vlasiator.write_vlsv","text":"write_vlsv(filein, fileout, newvars::Vector{Tuple{Vector, String, VarInfo}};\n force=false)\n\nGenerate a new VLSV fileout based on filein, with newvars added. force=true overwrites the existing fileout.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.write_vtk-Tuple{MetaVLSV}","page":"API Reference","title":"Vlasiator.write_vtk","text":"write_vtk(meta::MetaVLSV; kwargs...)\nwrite_vtk(file::AbstractString; kwargs...)\n\nConvert VLSV file to VTK format.\n\nKeywords\n\nvars::Vector{String}=[\"\"]: select which variables to convert.\nascii::Bool=false: output stored in ASCII or compressed binary format.\nmaxamronly::Bool=false: generate image files on the highest refinement level only.\nbox::Vector: selected box range in 3D.\noutdir::String=\"\": output directory.\nverbose::Bool=false: display logs during conversion.\n\n\n\n\n\n","category":"method"},{"location":"internal/#PyPlot-Wrapper-APIs","page":"API Reference","title":"PyPlot Wrapper APIs","text":"","category":"section"},{"location":"internal/","page":"API Reference","title":"API Reference","text":"Modules = [VlasiatorPyPlot]\nPages = [\"VlasiatorPyPlot.jl\"]","category":"page"},{"location":"internal/#Private-APIs","page":"API Reference","title":"Private APIs","text":"","category":"section"},{"location":"internal/","page":"API Reference","title":"API Reference","text":"Modules = [Vlasiator]\nPublic = false","category":"page"},{"location":"internal/#Vlasiator.AxisUnit","page":"API Reference","title":"Vlasiator.AxisUnit","text":"Axis unit type. Currently supported: SI, EARTH.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Vlasiator.ColorScale","page":"API Reference","title":"Vlasiator.ColorScale","text":"Color scales type for 2D plots. Currently supported: Log, Linear, SymLog.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Vlasiator.PlotArgs","page":"API Reference","title":"Vlasiator.PlotArgs","text":"Plotting arguments.\n\n\n\n\n\n","category":"type"},{"location":"internal/#Base.isopen-Tuple{MetaVLSV}","page":"API Reference","title":"Base.isopen","text":"Determine whether meta is not yet closed.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Base.ndims-Tuple{MetaVLSV}","page":"API Reference","title":"Base.ndims","text":"ndims(meta::MetaVLSV) -> Int\n\nReturn the simulation spatial dimension of VLSV data.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Base.size-Tuple{MetaVLSV}","page":"API Reference","title":"Base.size","text":"File size in bytes.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.curl-Union{Tuple{U}, Tuple{N}, Tuple{T}, Tuple{AbstractArray{T, N}, Union{Vector{U}, Tuple{U, U, U}}}} where {T, N, U}","page":"API Reference","title":"Vlasiator.curl","text":"curl(A::AbstractArray{T,N}, dx:Union{Vector{U}, NTuple{3,U}}) where {T,N,U}\n\nCalculate 2nd order cell-centered ∇×A where A is a 4D array of size (3, nx, ny, nz) and dx is a vector of grid intervals in each dimension.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.divergence-Union{Tuple{AbstractArray{T, N}}, Tuple{U}, Tuple{N}, Tuple{T}, Tuple{AbstractArray{T, N}, Vector{U}}} where {T, N, U}","page":"API Reference","title":"Vlasiator.divergence","text":"divergence(A::AbstractArray{T,N}, dx::Vector{U}=ones(T, 3)) where {T,N,U}\n\nCalculate 2nd order cell-centered ∇⋅A where A is a 4D array of size (3, nx, ny, nz) and dx is a vector of grid intervals in each dimension.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.downsample_fg-Tuple{MetaVLSV, Array}","page":"API Reference","title":"Vlasiator.downsample_fg","text":"downsample_fg(meta::MetaVLSV, v_fg::Array)\ndownsample_fg(meta::MetaVLSV, var::String)\n\nDownsample a field solver array v_fg to the spatial grid associated with meta.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.downsample_fg_cell-Tuple{MetaVLSV, Array, Int64}","page":"API Reference","title":"Vlasiator.downsample_fg_cell","text":"Return a field solver grid subarray contained inside spatial cell cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.fillmesh-Tuple{MetaVLSV, Vector{String}}","page":"API Reference","title":"Vlasiator.fillmesh","text":"fillmesh(meta::MetaVLSV, vars::Vector{String};\n skipghosttype=true, maxamronly=false, verbose=false) -> celldata, vtkGhostType\n\nFill the DCCRG mesh with quantity of vars on all refinement levels.\n\nReturn arguments\n\ncelldata::Vector{Vector{Array}}: data for each variable on each AMR level.\nvtkGhostType::Array{UInt8}: cell status (to be completed!).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.findindex-Tuple{Int32, Tuple{Int64, Int64, Int64}, Tuple{Int64, Int64, Int64}, Int64, Tuple{Int64, Int64, Int64}, Int64, Int64}","page":"API Reference","title":"Vlasiator.findindex","text":"Get the original vcell index without blocks from raw vcell index i (0-based).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get1stcell-Tuple{Int64, Int64}","page":"API Reference","title":"Vlasiator.get1stcell","text":"Return the first cell ID on mylevel given ncells on this level.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getDomainDecomposition-Tuple{Any, Any}","page":"API Reference","title":"Vlasiator.getDomainDecomposition","text":"getDomainDecomposition(globalsize, nprocs)\n\nObtain decomposition of this grid over the given number of processors. Reference: fsgrid.hpp\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getObjInfo-Tuple{Vector{XML.Node}, String, String, String}","page":"API Reference","title":"Vlasiator.getObjInfo","text":"General inquiry of element tag with tagname and attr.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getRotationMatrix-Tuple{AbstractMatrix, AbstractMatrix}","page":"API Reference","title":"Vlasiator.getRotationMatrix","text":"getRotationMatrix(e1::Matrix, e2::Matrix) -> SMatrix{3,3}\n\nObtain the rotation matrix from orthgonal base vectors e1 to e2, such that a vector mathbfu_1 in e1 can be expressed as mathbfu_1 = Mcdot mathbfu_2, where M is the rotation matrix and mathbfu_2 is the same vector in e2.\n\nExample\n\ne1 = [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0]\ne2 = [0.0 1.0 0.0; 1.0 0.0 0.0; 0.0 0.0 1.0]\nR = getRotationMatrix(e1, e2)\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getRotationMatrix-Tuple{AbstractVector{<:AbstractFloat}, Real}","page":"API Reference","title":"Vlasiator.getRotationMatrix","text":"getRotationMatrix(axis::AbstractVector, angle::Real) --> SMatrix{3,3}\n\nCreate a rotation matrix for rotating a 3D vector around a unit axis by an angle in radians. Reference: Rotation matrix from axis and angle\n\nExample\n\nusing LinearAlgebra\nv = [-0.5, 1.0, 1.0]\nv̂ = normalize(v)\nθ = deg2rad(-74)\nR = getRotationMatrix(v̂, θ)\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_axis-Tuple{Vlasiator.AxisUnit, NTuple{4, var\"#s176\"} where var\"#s176\"<:Real, Tuple{var\"#s175\", var\"#s175\"} where var\"#s175\"<:Integer}","page":"API Reference","title":"Vlasiator.get_axis","text":"get_axis(axisunit::AxisUnit, plotrange::NTuple{4,<:Real}, sizes::NTuple{2,<:Integer})\nget_axis(pArgs::PlotArgs)\n\nReturn x and y ranges for 2D.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_fg_array_cell-Tuple{MetaVLSV, Array, Int64}","page":"API Reference","title":"Vlasiator.get_fg_array_cell","text":"get_fg_array_cell(meta::MetaVLSV, v_fg::Array, cid::Int)\n\nReturn a subarray of the field solver grid array, corresponding to the fsgrid covered by the spatial cell ID cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_fg_indices-Tuple{MetaVLSV, StaticArraysCore.SVector{3, Float64}}","page":"API Reference","title":"Vlasiator.get_fg_indices","text":"Return the field solver grid cell indexes containing coords (low-inclusive).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_fg_indices_cell-Tuple{MetaVLSV, Int64}","page":"API Reference","title":"Vlasiator.get_fg_indices_cell","text":"Returns a slice tuple of fsgrid indices that are contained in the spatial cell cid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.get_fg_indices_subvolume","page":"API Reference","title":"Vlasiator.get_fg_indices_subvolume","text":"get_fg_indices_subvolume(meta::MetaVLSV, lower, upper, tol::Float64=1e-3)\n\nGet indices for subarray of fsgrid variables, in a cuboid defined by lower and upper vertices. This is used for mapping a set of fsgrid cells to a given DCCRG cell. Shift the corners (lower, upper) inward by a distance controlled by tol. If direct low-inclusive behaviour is required, tol shall be set to 0.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.getdata2d-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.getdata2d","text":"getdata2d(meta::MetaVLSV, var::String)\n\nReturn 2d scalar/vector data. Nonpublic since it won't work with DCCRG AMR.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getfooter-Tuple{IOStream}","page":"API Reference","title":"Vlasiator.getfooter","text":"Return the XML footer of opened VLSV file.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getindexes-NTuple{5, Int64}","page":"API Reference","title":"Vlasiator.getindexes","text":"Compute x, y and z index of cell id on a given refinement level ilevel(0-based).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.getindexes-Tuple{Int64, Int64, Int64, Int64, AbstractVector{Int64}}","page":"API Reference","title":"Vlasiator.getindexes","text":"Compute x, y and z indexes of all cell ids on the given refinement level (0-based).\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.gradient-Union{Tuple{U}, Tuple{N}, Tuple{T}, Tuple{AbstractArray{T, N}, Vector{U}}} where {T, N, U}","page":"API Reference","title":"Vlasiator.gradient","text":"gradient(A::AbstractArray{T,N}, dx::Vector{U}) where {T,N,U}\n\nCalculate 2nd order cell-centered ∇A where A is a scalar array and dx is a vector of grid intervals in each dimension.\n\nwarning: Warning\nThe current implementation has issues at the boundary if gradient is taken multiple times.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.isextrema-Tuple{Any}","page":"API Reference","title":"Vlasiator.isextrema","text":"Check if the center point in a 3x3 matrix ψ is an extrema point.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.issaddle-Tuple{Any}","page":"API Reference","title":"Vlasiator.issaddle","text":"Check if the center point in a 3x3 matrix ψ is a saddle point.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.prep1d-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.prep1d","text":"prep1d(meta::MetaVLSV, var::String; i1::Int=0, i2::Int=0, comp::Int=0) -> Array\n\nObtain a 1D slice from 2D meta of var. i1 is the index for the first dimension, and i2 is the index for the second dimension; only one of them is needed. Use comp to select vector components.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.prep2d","page":"API Reference","title":"Vlasiator.prep2d","text":"prep2d(meta::MetaVLSV, var::String, comp::Union{Symbol, Int}=0) -> Array\n\nObtain data from meta of var for 2D plotting. Use comp to select vector components.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.prep2dslice-Tuple{MetaVLSV, String, Symbol, Union{Int64, Symbol}, Vlasiator.PlotArgs}","page":"API Reference","title":"Vlasiator.prep2dslice","text":"prep2dslice(meta::MetaVLSV, var::String, normal, comp, pArgs::PlotArgs)\n\nReturn data of var on a uniform 2D mesh on the finest AMR level. Use normal to select the plane orientation, and comp to select the component of a vector, same as in pcolormesh.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.prep_vdf-Tuple{MetaVLSV, AbstractVector}","page":"API Reference","title":"Vlasiator.prep_vdf","text":"prep_vdf(meta::MetaVLSV, location::AbstractVector; kwargs...)\n\nReturn the cell velocities v1, v2, bin ranges r1, r2, cell VDF values fweight, and strings of labels and titles for VDF plots.\n\nKeywords\n\nunit::AxisUnit: location unit in SI, EARTH.\nunitv::String: velocity unit in (\"km/s\", \"m/s\").\nlimits::Vector{Real}: velocity space range given in [xmin, xmax, ymin, ymax].\nslicetype: symbol for choosing the slice type from :xy, :xz, :yz, :bperp, :bpar1, :bpar2.\ncenter: symbol for setting the reference frame from :bulk, :peak.\nvslicethick: setting the velocity space slice thickness in the normal direction. If set to 0, the whole distribution along the normal direction is projected onto a plane. Currently this is only meaningful when center is set such that a range near the bulk/peak normal velocity is selected.\nweight::Symbol: choosing distribution weights from phase space density or particle flux between :particle and :flux.\nflimit: minimum VDF threshold for plotting.\nverbose: display the selection process.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.read_variable_as_fg-Tuple{MetaVLSV, String}","page":"API Reference","title":"Vlasiator.read_variable_as_fg","text":"read_variable_as_fg(meta::MetaVLSV, var::String)\n\nInterpolate DCCRG variable var to field solver grid size. This is an alternative method to fillmesh, but not optimized for performance.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readmesh-Tuple{IOStream, Vector{XML.Node}}","page":"API Reference","title":"Vlasiator.readmesh","text":"Return spatial mesh information.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvector-Union{Tuple{T}, Tuple{IOStream, Type{T}, Int64, Int64, Int64, Val{false}}} where T","page":"API Reference","title":"Vlasiator.readvector","text":"Return vector of name from the VLSV file associated with stream fid.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.readvmesh-Tuple{IOStream, Vector{XML.Node}, String}","page":"API Reference","title":"Vlasiator.readvmesh","text":"Return velocity mesh information.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.reconstruct-Tuple{Vlasiator.VMeshInfo, Vector{Int32}, Vector{<:AbstractFloat}}","page":"API Reference","title":"Vlasiator.reconstruct","text":"reconstruct(vmesh::VMeshInfo, vcellids::Vector{Int32}, vcellf::Vector{<:AbstractFloat})\n\nReconstruct the full VDFs in 3D. vcellids are raw indices of nonzero VDFs ordered by blocks, and vcellf are the corresponding values in each cell.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.reorder-Tuple{Vlasiator.VMeshInfo, Vector{Int32}}","page":"API Reference","title":"Vlasiator.reorder","text":"reorder(vmesh::VMeshInfo, vcellids::Vector{Int32}) -> vcellids_origin\n\nReorder vblock-organized VDF indexes into x–>y–>z indexes. vcellids are raw indices of nonzero VDFs ordered by blocks.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.rotateTensorToVectorZ-Union{Tuple{T}, Tuple{AbstractMatrix{T}, AbstractVector{T}}} where T","page":"API Reference","title":"Vlasiator.rotateTensorToVectorZ","text":"rotateTensorToVectorZ(tensor::AbstractMatrix, vector::AbstractVector) -> SMatrix{3,3}\n\nRotate tensor with a rotation matrix that aligns the 3rd direction with vector, which is equivalent to change the basis from (i,j,k) to (i′,j′,k′) where k′ ∥ vector. Reference: Tensor rotation\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.save_image","page":"API Reference","title":"Vlasiator.save_image","text":"save_image(meta::MetaVLSV, file, vars, data, vtkGhostType, level,\n ascii=false, append=true, box=[-Inf, Inf, -Inf, Inf, -Inf, Inf])\n\nSave data of name vars at AMR level into VTK image file of name file.\n\nArguments\n\nfile::String: output file name.\nvars::Vector{String}: variable names to be saved.\ndata::Vector{Vector{Array}}: data for all the variables on each refinement level.\nvtkGhostType::Array{UInt8}: array for visibility control.\nlevel::Int: refinement level (0-based).\nascii::Bool=false: save output in ASCII or binary format.\nappend::Bool=true: determines whether to append data at the end of file or do in-block writing.\nbox::Vector: selected box range in 3D.\n\n\n\n\n\n","category":"function"},{"location":"internal/#Vlasiator.set_args-Tuple{MetaVLSV, String, Vlasiator.AxisUnit}","page":"API Reference","title":"Vlasiator.set_args","text":"set_args(meta::MetaVLSV, var::String, axisunit::AxisUnit;\n normal::Symbol=:none, origin=0.0)\n\nSet plot-related arguments of var in axisunit. normal and origin are used for 2D slices of 3D data, as specified in pcolormesh.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.set_lim-Union{Tuple{T}, Tuple{T, T, Any}, Tuple{T, T, Any, Vlasiator.ColorScale}} where T","page":"API Reference","title":"Vlasiator.set_lim","text":"set_lim(vmin, vmax, data, colorscale=Linear)\n\nSet colormap limits vmin, vmax for data under scale colorscale.\n\n\n\n\n\n","category":"method"},{"location":"internal/#Vlasiator.upsample_fsgrid_subarray!-Union{Tuple{T}, Tuple{MetaVLSV, Any, Int64, Array{T, 4}}} where T","page":"API Reference","title":"Vlasiator.upsample_fsgrid_subarray!","text":"Set the elements of the fsgrid array to the value of corresponding cell ID cid.\n\n\n\n\n\n","category":"method"},{"location":"examples/visualization/demo_B_fieldline_pyplot/#demo_2d_fieldlines","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"","category":"section"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"This demo shows how to plot field lines with handpicked seeds.","category":"page"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"using VlasiatorPyPlot, FieldTracer\nusing Vlasiator: RE # Earth radius, [m]\n\nfunction main()\n file = \"../../bulk.0000999.vlsv\"\n meta = load(file)\n (;coordmin, coordmax, ncells) = meta\n pcolormesh(meta, \"proton/vg_rho\", colorscale=Linear)\n\n dim_ =\n if ncells[2] == 1\n (1,3)\n elseif ncells[3] == 1\n (1,2)\n else\n @error \"Not implemented for ncells = $ncells.\"\n end\n\n # NonAMR Cartesian mesh\n grid1 = range(coordmin[dim_[1]], coordmax[dim_[1]], length=ncells[dim_[1]])\n grid2 = range(coordmin[dim_[2]], coordmax[dim_[2]], length=ncells[dim_[2]])\n\n ns1 = 14 # number of seeding points on the dayside\n ns2 = 10 # number of seeding points on the nightside\n ns4 = 4 # number of seeding points in the polar region\n seeds = Matrix{Float64}(undef, 2, ns1+2*ns2+2*ns4)\n\n for i in 1:ns1\n seeds[1,i] = coordmax[dim_[1]] / ns1 * (i - 1)\n seeds[2,i] = 0.0\n end\n\n for i in 1:ns2\n seeds[1,ns1+i] = -10RE\n seeds[2,ns1+i] = coordmin[dim_[2]] +\n (coordmax[dim_[2]] - coordmin[dim_[2]]) / ns2 * (i - 1)\n seeds[1,ns1+ns2+i] = -30RE\n seeds[2,ns1+ns2+i] = coordmin[dim_[2]] +\n (coordmax[dim_[2]] - coordmin[dim_[2]]) / ns2 * (i - 1)\n end\n\n for i in 1:ns4\n seeds[1,ns1+2*ns2+i] = -20RE + 10RE*(i - 1)\n seeds[2,ns1+2*ns2+i] = 30RE\n seeds[1,ns1+2*ns2+ns4+i] = -20RE + 10RE*(i - 1)\n seeds[2,ns1+2*ns2+ns4+i] = -30RE\n end\n\n b = meta[\"vg_b_vol\"]\n b1 = reshape(b[dim_[1],:], ncells[dim_[1]], ncells[dim_[2]])\n b2 = reshape(b[dim_[2],:], ncells[dim_[1]], ncells[dim_[2]])\n\n for i = axes(seeds,2)\n startx, starty = seeds[:,i]\n x1, y1 = trace(b1, b2, startx, starty, grid1, grid2;\n ds=0.5, maxstep=3000, gridtype=\"ndgrid\")\n x1 ./= RE\n y1 ./= RE\n if length(x1) < 5; continue; end\n line = plot(x1, y1, color=\"w\")\n add_arrow(line[1])\n end\n\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"","category":"page"},{"location":"examples/visualization/demo_B_fieldline_pyplot/","page":"Field lines with customized seeds","title":"Field lines with customized seeds","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/#demo_2d_trace","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"","category":"section"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"This demo shows how to trace streamlines in a 2D uniform field.","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"using VlasiatorPyPlot, FieldTracer\nusing Vlasiator: RE # Earth radius, [m]\n\nfunction main()\n file = \"bulk.0000501.vlsv\"\n nameρ = \"rho\"\n nameV = \"rho_v\"\n\n meta = load(file)\n\n pcolormesh(meta, nameρ)\n\n v = readvariable(meta, nameV)\n vx = reshape(v[1,:], meta.ncells[1], meta.ncells[2])\n vy = reshape(v[2,:], meta.ncells[1], meta.ncells[2])\n # tracing starting point\n xstart, ystart = 12RE, 0RE\n # regular Cartesian mesh\n x = range(meta.coordmin[1], meta.coordmax[1], length=meta.ncells[1])\n y = range(meta.coordmin[2], meta.coordmax[2], length=meta.ncells[2])\n\n # RK4 scheme by default\n x1, y1 = trace2d(vx, vy, xstart, ystart, x, y;\n ds=0.5, maxstep=3000, gridType=\"ndgrid\")\n x1 ./= RE\n y1 ./= RE\n\n plot(x1, y1)\n\n streamplot(meta, nameV, comp=\"xy\", color=\"w\", density=1.0)\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"","category":"page"},{"location":"examples/visualization/demo_field_tracing_2d/","page":"Trace field lines in 2D","title":"Trace field lines in 2D","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/#demo_line_extract_mp","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"","category":"section"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"This demos shows how to extract multiple variables alone a line across multiple frames with multi-processing.","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"tip: Tip\nThis can be made faster by updating the data without deleting the lines.","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"Usage:","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"julia -p $ncores demo_vars_extracting_mp.jl","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"using Distributed, ParallelDataTransfer, Glob\nusing Vlasiator: RE\n@everywhere using Vlasiator, PyPlot, Printf\n\n@everywhere function init_figure(x1, x2)\n fig, axs = plt.subplots(4, 1; num=myid(),\n figsize=(10, 15), sharex=true, constrained_layout=true)\n\n axs[end].set_xlim(x1, x2)\n\n axs[1].set_ylim(ρmin, ρmax)\n axs[2].set_ylim(vmin, vmax)\n axs[3].set_ylim(pmin, pmax)\n axs[4].set_ylim(bmin, bmax)\n for ax in axs\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axs[end].set_xlabel(\"x [RE]\"; fontsize)\n axs[1].set_ylabel(\"Density [amu/cc]\"; fontsize)\n axs[2].set_ylabel(\"Velocity [km/s]\"; fontsize)\n axs[3].set_ylabel(\"Pressure [nPa]\"; fontsize)\n axs[4].set_ylabel(\"Magnetic field [nT]\"; fontsize)\n return fig, axs\nend\n\n@everywhere function process(axs, file, cellids)\n isfile(\"out/\"*file[end-8:end-5]*\".png\") && return\n\n println(\"file = $file\")\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1e9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1e9 # [nPa]\n\n bz = readvariable(meta, \"vg_b_vol\", cellids)[3,:] .* 1e9 #[nT]\n\n imagnetopause_ = findfirst(<(0.0), bz)\n\n axs[1].plot(loc, rho_extract ./ 1e6, label=\"Proton density\", color=\"#1f77b4\")\n vl1 = axs[1].vlines(loc[imagnetopause_], ρmin, ρmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[2].plot(loc, v_extract[1,:] ./ 1e3, label=\"Vx\", color=\"#1f77b4\")\n vl2 = axs[2].vlines(loc[imagnetopause_], vmin, vmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[3].plot(loc, pram_extract, label=\"Ram\", color=\"#1f77b4\")\n axs[3].plot(loc, p_extract, label=\"Thermal\", color=\"#ff7f0e\")\n vl3 = axs[3].vlines(loc[imagnetopause_], pmin, pmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[4].plot(loc, bz, label=\"Bz\", color=\"#1f77b4\")\n hl4 = axs[4].hlines(0.0, loc[1], loc[end], colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n vl4 = axs[4].vlines(loc[imagnetopause_], bmin, bmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n str_title = @sprintf \"t= %4.1fs\" meta.time\n axs[1].set_title(str_title; fontsize)\n\n axs[2].legend(;loc=\"upper right\", fontsize)\n axs[3].legend(;loc=\"upper left\", fontsize)\n axs[4].legend(;loc=\"upper right\", fontsize)\n\n savefig(\"out/\"*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n\n for ax in axs\n for line in ax.get_lines()\n line.remove()\n end\n end\n for line in (vl1, vl2, vl3, vl4, hl4)\n line.remove()\n end\n return\nend\n\nfunction make_jobs(files)\n for f in files\n put!(jobs, f)\n end\nend\n\n@everywhere function do_work(jobs, results)\n fig, axs = init_figure(x1, x2)\n while true\n file = take!(jobs)\n process(axs, file, cellids)\n put!(results, true)\n end\n close(fig)\nend\n\n################################################################################\nfiles = glob(\"bulk*.vlsv\", \".\")\nnfile = length(files)\n\nconst x1, x2 = 8.0, 29.0\nconst point1 = [x1, 0, 0] .* RE\nconst point2 = [x2, 0, 0] .* RE\n\nmeta = load(files[1])\ncellids, _, _ = getcellinline(meta, point1, point2)\nclose(meta.fid)\n\npassobj(1, workers(), [:x1, :x2, :cellids])\n\n@broadcast begin\n const loc = range(x1, x2, length=length(cellids))\n\n const ρmin, ρmax = 0.0, 10.0 # [amu/cc]\n const vmin, vmax = -640.0, 0.0 # [km/s]\n const pmin, pmax = 0.0, 1.82 # [nPa]\n const bmin, bmax = -25.0, 60.0 # [nT]\n\n const fontsize = 14\nend\n\nconst jobs = RemoteChannel(()->Channel{String}(nfile))\nconst results = RemoteChannel(()->Channel{Bool}(nworkers()))\n\nprintln(\"Total number of files: $nfile\")\nprintln(\"Running with $(nworkers()) workers...\")\n\n@async make_jobs(files) # Feed the jobs channel with all files to process.\n\n@sync for p in workers()\n @async remote_do(do_work, p, jobs, results)\nend\n\nlet n = nfile\n t = @elapsed while n > 0 # wait for all jobs to complete\n take!(results)\n n -= 1\n end\n println(\"Finished in $(round(t, digits=2))s.\")\nend","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"","category":"page"},{"location":"examples/visualization/demo_lineextracting_mp_pyplot/","page":"Extract variables along a line with multi-processing","title":"Extract variables along a line with multi-processing","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/#demo_extractline","page":"Extract variables along a line","title":"Extract variables along a line","text":"","category":"section"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"To extract variables along a line across multiple frames using multithreads,","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"using Vlasiator, Glob\nusing JLD2: jldsave\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n nfile = length(files)\n # Define end points of the line in Earth radius\n x1, x2 = 6.0, 20.0\n point1 = [x1, 0, 0] .* Vlasiator.RE\n point2 = [x2, 0, 0] .* Vlasiator.RE\n # Extract cell info along the line\n cellids, distances, coords =\n load(files[1]) do meta\n getcellinline(meta, point1, point2)\n end\n # WARNING: this may not be exact due to round-off errors in output time stamps!\n t = let tstart = load(files[1]).time, tend = load(files[end]).time\n range(round(tstart,digits=1), round(tend, digits=1), length=nfile)\n end\n\n n = zeros(Float32, length(cellids), nfile)\n v = zeros(Float32, 3, length(cellids), nfile)\n p = zeros(Float32, 6, length(cellids), nfile)\n b = similar(v)\n e = similar(v)\n\n Threads.@threads for i in eachindex(files)\n println(\"i = $i/$nfile, file = $(files[i])\")\n local meta = load(files[i])\n\n n[:,i] = readvariable(meta, \"proton/vg_rho\", cellids)\n v[:,:,i] = readvariable(meta, \"proton/vg_v\", cellids)\n p[1:3,:,i] = readvariable(meta, \"proton/vg_ptensor_diagonal\", cellids)\n p[4:6,:,i] = readvariable(meta, \"proton/vg_ptensor_offdiagonal\", cellids)\n b[:,:,i] = readvariable(meta, \"vg_b_vol\", cellids)\n e[:,:,i] = readvariable(meta, \"vg_e_vol\", cellids)\n end\n\n # Save into binary file\n jldsave(\"vars_sun_earth_line.jld2\"; x1, x2, t, n, v, p, b, e)\n\n println(\"Line extraction finished!\")\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"","category":"page"},{"location":"examples/postprocess/demo_lineextracting_mt/","page":"Extract variables along a line","title":"Extract variables along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_x_o_points/#demo_x_o_points","page":"Find X- and O-points","title":"Find X- and O-points","text":"","category":"section"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"This demo shows how to find X-points and O-points in a 2D magnetic reconnection configuration. Here we assume a X-Z meridional plane.","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"note: Note\nThe input B field domain matters for computing the flux function, but I don't knowwhy there are differences.In identifying the X-points and O-points, we currently provide two methods: method 1needs to set the relative tolerance, while method 2 does not.","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"using VlasiatorPyPlot\n\nfunction main()\n file = \"bulk.0001657.vlsv\"\n meta = load(file)\n\n ndims(meta) != 2 && @error \"Flux function only works for 2D simulations!\"\n\n meta.ncells[3] == 1 && @error \"equatorial plane, no reconnection!\"\n\n b = meta[\"vg_b_vol\"]\n b = reshape(b, 3, meta.ncells[1], meta.ncells[3])\n dx = [meta.dcoord[1], meta.dcoord[3]]\n\n x = LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1]) ./ Vlasiator.RE\n z = LinRange(meta.coordmin[3], meta.coordmax[3], meta.ncells[3]) ./ Vlasiator.RE\n\n xmin_ = searchsortedfirst(x, 7.0)\n xmax_ = searchsortedlast(x, 9.5)\n zmin_ = searchsortedfirst(z, -5.0)\n zmax_ = searchsortedlast(z, 5.0)\n\n # meshgrid for plotting\n X = [a for a in x[xmin_:xmax_], _ in z[zmin_:zmax_]]\n Z = [b for _ in x[xmin_:xmax_], b in z[zmin_:zmax_]]\n\n flux = compute_flux_function(view(b,:,xmin_:xmax_,zmin_:zmax_), dx)\n\n fig, ax = plt.subplots(subplot_kw=Dict(\"projection\"=>\"3d\"))\n\n ax.plot_surface(X, Z, flux;\n cmap=matplotlib.cm.turbo,\n linewidth=0, antialiased=false)\n\n indices_x, indices_o = find_reconnection_points(flux; retol=1e-4, method=2)\n\n fig, ax = subplots(figsize=(6,10), constrained_layout=true)\n\n pcolormesh(meta, \"proton/vg_v\", ax;\n comp=:z, extent=[5, 10, -7.5, 7.5],\n cmap=matplotlib.cm.RdBu_r)\n s1 = ax.scatter(x[indices_x[1,:].+xmin_.-1], z[indices_x[2,:].+zmin_.-1];\n s=50, marker=\"x\", color=\"tab:gray\")\n s2 = ax.scatter(x[indices_o[1,:].+xmin_.-1], z[indices_o[2,:].+zmin_.-1];\n s=12, marker=\"o\", color=\"tab:brown\")\n\n ax.legend([s1, s2], [\"X-point\", \"O-point\"])\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"","category":"page"},{"location":"examples/postprocess/demo_x_o_points/","page":"Find X- and O-points","title":"Find X- and O-points","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/#demo_1d_animation","page":"1D animation","title":"1D animation","text":"","category":"section"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"This example demonstrates 1D plot animation. ffmpeg is required to be installed for saving into mp4.","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"using Vlasiator, Glob, PyPlot, Printf\n\nfiles = glob(\"bulk.*.vlsv\", \".\")\n# Choose plotting variable\nconst var = \"proton/vg_rho\"\nconst comp = 0 # component of vector, if used\n\nfig = plt.figure(constrained_layout=true)\n# Fix axis limits according to data range\nax = plt.axes(xlim=(-10, 10), ylim=(0, 4))\n\nline, = ax.plot([], [], lw=3, marker=\"*\")\n\nfunction animate(i::Int, files::Vector{String}, var::String, comp::Int, ax, line)\n meta = load(files[i+1])\n x = LinRange(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\n d = readvariable(meta, var)\n y = ndims(d) == 1 ? d : d[comp,:]\n line.set_data(x, y)\n\n t = readparameter(meta, \"time\")\n str_title = @sprintf \"t = %4.1fs, var = %s\" t var\n ax.set_title(str_title)\n\n return (line,)\nend\n\n# https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html\nanim = matplotlib.animation.FuncAnimation(fig, animate, fargs=(files, var, comp, ax, line),\n frames=length(files), blit=true,\n repeat_delay=1000, interval=200)\n# Make sure ffmpeg is available!\nanim.save(\"line.mp4\", writer=\"ffmpeg\", fps=30)","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"","category":"page"},{"location":"examples/visualization/demo_1d_animation_pyplot/","page":"1D animation","title":"1D animation","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/#demo_3d_trace","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"","category":"section"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"This demo shows how to trace along a field line and extract variables from 3D AMR grid.","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"warning: Warning\nThis is a proof of concept, which is memory-bound in 3D and may be quite inefficient!","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"using Vlasiator, FieldTracer, PyPlot\nusing StaticArrays\nusing Vlasiator: RE\n\nfunction get_cell_along_B(meta::MetaVLSV, seed::Vector{T};\n ds::Float64=0.2, maxstep::Int=20000, direction::String=\"both\") where T\n B = Vlasiator.fillmesh(meta, [\"vg_b_vol\"]; maxamronly=true)[1][1][1]\n\n nx, ny, nz = size(B)[2:4]\n\n xrange = LinRange(meta.coordmin[1], meta.coordmax[1], nx)\n yrange = LinRange(meta.coordmin[2], meta.coordmax[2], ny)\n zrange = LinRange(meta.coordmin[3], meta.coordmax[3], nz)\n\n bx = @view B[1,:,:,:]\n by = @view B[2,:,:,:]\n bz = @view B[3,:,:,:]\n xs, ys, zs = seed\n\n x, y, z = trace(bx, by, bz, xs, ys, zs, xrange, yrange, zrange; ds, maxstep, direction)\n\n cellids = [getcell(meta, SVector(x[1], y[1], z[1]))]\n\n for i in eachindex(x)[2:end]\n cellidnew = getcell(meta, SVector(x[i], y[i], z[i]))\n if cellidnew != cellids[end]\n push!(cellids, cellidnew)\n end\n end\n\n cellids\nend\n\nfunction main()\n file = \"bulk1.0001000.vlsv\"\n meta = load(file)\n\n seed = [-5.0, 0., 3.5] .* RE\n # For EGI, ds=1.0 is between 1-2 steps per finest cell.\n cellids = get_cell_along_B(meta, seed; ds=1.0, maxstep=100, direction=\"backward\")\n\n #n = readvariable(meta, \"proton/vg_rho\", cellids)\n #v = readvariable(meta, \"proton/vg_v\", cellids)\n #E = readvariable(meta, \"fg_e\", cellids) # Not available for now!\n\n x = zeros(Float64, length(cellids))\n y = zeros(Float64, length(cellids))\n z = zeros(Float64, length(cellids))\n\n for i in eachindex(cellids)\n coords = getcellcoordinates(meta, cellids[i])\n x[i], y[i], z[i] = coords\n end\n\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"3d\")\n\n ax.set_xlabel(\"x [RE]\")\n ax.set_ylabel(\"y [RE]\")\n ax.set_zlabel(\"z [RE]\")\n\n ax.set_box_aspect([1,1,1])\n ax.set_xlim3d([-20.0, -5.0])\n ax.set_ylim3d([0.0, 0.5])\n ax.set_zlim3d([-2.0, 3.0])\n\n ax.plot3D(x./RE, y./RE, z./RE)\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"","category":"page"},{"location":"examples/visualization/demo_field_tracing_3d/","page":"Trace field lines in 3D","title":"Trace field lines in 3D","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/#demo_line_extract","page":"Extract variable along a line","title":"Extract variable along a line","text":"","category":"section"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"This demo shows how to extract data alone a line across frames.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"tip: Tip\nThis can be made faster by updating the data without deleting the lines.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"using Vlasiator, Glob, PyPlot, Printf\nusing Vlasiator: RE # Earth radius, [m]\n\nfunction main()\n files = glob(\"run4/bulk*.vlsv\")\n\n point1 = [0e8, 0, 0]\n point2 = [1.9e8, 0, 0]\n\n cellids, distances, coords =\n let meta = load(files[1])\n getcellinline(meta, point1, point2)\n end\n\n # time density temperature vx\n inputs = [\n 0.0 2.0e6 1.0e5 -5.0e5;\n 99.0 2.0e6 1.0e5 -5.0e5;\n 100.0 2.0e6 1.0e5 -8.0e5;\n 200.0 2.0e6 1.0e5 -8.0e5;\n 201.0 1.0e6 1.0e5 -8.0e5;\n 499.0 1.0e6 1.0e5 -8.0e5;\n 500.0 2.0e6 1.0e5 -5.0e5]\n\n ndigits = 4\n\n lim_rho = [0.0, 4.0e6]\n lim_v = [-2e5, 10e5]\n\n fig, ax = plt.subplots(2,1, figsize=(12,5))\n\n for (i, file) in enumerate(files)\n fileout = lpad(i, ndigits, '0')*\".png\"\n\n meta = load(file)\n rho = readvariable(meta, \"proton/vg_rho\", cellids)\n v = readvariable(meta, \"proton/vg_v\", cellids)\n vx = Vector{Float64}(undef, size(v,1))\n\n for k in axes(v,1)\n vx[k] = v[k][1]\n end\n\n t = readparameter(meta, \"time\")\n\n ax[1].plot(coords[1,:] ./ RE, rho, label=\"rho\")\n ax[1].set_ylim(lim_rho)\n ax[1].legend()\n ax[1].minorticks_on()\n\n ax[2].plot(coords[1,:] ./ RE, abs.(vx), label=\"vx\")\n ax[2].set_ylim(lim_v)\n ax[2].legend()\n ax[2].minorticks_on()\n\n xlabel(\"X\")\n\n j = searchsortedfirst(inputs[:,1], t) - 1\n if j == 0; j = 1; end\n str_title =\n @sprintf \"t=%4.1fs, rho=%4.1f/cc, vx=%4.1fkm/s\" t inputs[j,2]/1e6 inputs[j,4]/1e3\n fig.suptitle(str_title, fontsize=14)\n\n savefig(fileout, bbox_inches=\"tight\")\n\n ax[1].cla()\n ax[2].cla()\n end\n\n close(fig)\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic1/","page":"Extract variable along a line","title":"Extract variable along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"manual/#Manual","page":"User Guide","title":"Manual","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Here we demonstrate some basic usages of processing Vlasiator output. A quick self-contained demo is shown with Pluto. For complete description of the arguments, please refer to the API documents or type ?function_name to display help message in the REPL.","category":"page"},{"location":"manual/#Common-physical-constants","page":"User Guide","title":"Common physical constants","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"A bunch of physical constants are predefined in Vlasiator.jl. To use them, you need to import explicitly, e.g. using Vlasiator: RE or prepend the module name like Vlasiator.RE.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Physical constant Value Meaning\nqₑ -1.60217662e-19 electron charge, [C]\nmₑ 9.10938356e-31 electron mass, [kg]\nqᵢ 1.60217662e-19 proton mass, [C]\nmᵢ 1.673557546e-27 proton mass, [kg]\nc 299792458. speed of light, [m/s]\nμ₀ 4π*1e-7 Vacuum permeability, [H/m]\nϵ₀ 1/(c^2*μ₀) Vacuum permittivity, [F/m]\nkB 1.38064852e-23 Boltzmann constant, [m²kg/(s²K)]\nRE 6.371e6 Earth radius, [m]","category":"page"},{"location":"manual/#Loading-VLSV-data","page":"User Guide","title":"Loading VLSV data","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"A quick way to obtain small test data can be found in F&Q. Larger open-access data can be found from the references in Vlasiator publications, e.g. Takahashi+ 2020. In this tutorial we are using the 2D test file bulk.2d.vlsv from vlsv_data if not specified.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Read meta data","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"file = \"bulk.2d.vlsv\"\nmeta = load(file)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The VLSV meta data contains information of file name, variable names, ordinary cell ID list, mesh sizes, species, and velocity cell structures. It is often the first argument for methods defined in Vlasiator.jl.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Read parameter","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"For convenience we support the do-block syntax that automatically closes the file stream.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"t = load(file) do meta\n readparameter(meta, \"time\")\nend","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Read variable meta data","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"readvariablemeta(meta, \"proton/vg_rho\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"A list of utility functions has been implemented for checking variable status. See here for the full list.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Read variable","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"data = meta[\"CellID\"]\n# Or equivalently\ndata = readvariable(meta, \"CellID\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The variable reading is designed for cells, which takes cell ID(s) as the 3rd argument if specified. The same interface works for both DCCRG grid (for storing cell centered quantities like plasma moments) and FS grid (for storing field solver related quantities on a uniform high resolution mesh) variables. By default the returned DCCRG variable array is sorted by cell IDs. If in any case you want the original unsorted version as being stored in the file, use readvariable(meta, var, false).","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Get variable at a given location","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"loc = [2.0, 0.0, 0.0]\nid = getcell(meta, loc)\nreadvariable(meta, \"CellID\", id)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Get variable along a line between two points","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"using Vlasiator: RE # Earth radii\npoint1 = [12RE, 0, 0]\npoint2 = [15RE, 0, 0]\ncellids, distances, coords = getcellinline(meta, point1, point2)\nvar_extract = readvariable(meta, \"VA\", cellids)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Extract variable at a static cell ID from a sequence of files under the same grid","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"files = [\"bulk.2d.vlsv\"]\nvar = \"CellID\"\nid = 1\nextractsat(files, var, id)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Downsample field solver variable to DCCRG grid","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vlasiator.downsample_fg(meta, \"fg_e\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Upsample DCCRG variable to field solver grid","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"data = Vlasiator.read_variable_as_fg(meta, \"proton/vg_rho\")\n# Equivalent to the above, but faster\ndata = let\n tmp = Vlasiator.fillmesh(meta, [\"proton/vg_rho\"]; maxamronly=true)[1][1][1]\n reshape(tmp, size(tmp)[2:end])\nend","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"This is useful when corresponding DCCRG variables are not saved, or a uniform mesh is required for further analysis.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Compare VLSV files","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"One may want to check if two vlsv files are identical. This is tricky because","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"the structure of VLSV format does not guarantee the writing order in parallel processing;\nnumerical error accumulates with floating point representation, especially with fastmath option.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The issame method does not check quantities that are related to the MPI writing sequence: for some reasons, even file sizes may vary depending on the number of MPI processes!","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"issame(file1, file2)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"There is an optional third argument to issame for setting the relative difference tolerance, with default being 1e-4. In practice relative difference works better for \"large\" numbers, and absolute difference works better for \"small\" numbers.","category":"page"},{"location":"manual/#Computing-derived-quantities","page":"User Guide","title":"Computing derived quantities","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vlasiator.jl is capable of computing plasma moments and some predefined derived quantities and saving them directly into VLSV files. To avoid confusion about variable names, the conventions are","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"raw quantities are all lowercases;\nall predefined derived variable names start with a capital letter;\nexceptions are for aliases (e.g. \"n\").","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To obtain a derived quantity, use either a key of string or symbol,","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"beta = meta[\"Beta\"]\nVA = meta[:VA]","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Here is a full list of available quantities[1]:","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Derived variable name Meaning Required variable[2]\nBmag magnetic field magnitude vg_b_vol\nEmag electric field magnitude vg_e_vol\nVmag bulk speed vg_v\nBhat unit magnetic field vg_b_vol\nVS sound speed vg_ptensor_diagonal; vg_rho\nVA Alfvén speed vg_rho; Bmag\nMA Alfvén Mach number Vmag; VA\nMS Sonic Mach number Vmag; VS\nEpar mathbfE_parallel vg_e_vol; Bhat\nEperp mathbfE_perp vg_e_vol; Bhat\nVpar bulk velocity parallelmathbfB vg_v; vg_b_vol\nVperp bulk velocity perp mathbfB vg_v; vg_b_vol\nVth proton thermal velocity P; vg_rho\nP scalar thermal pressure vg_ptensor_diagonal\nPpar pressure parallelmathbfB vg_ptensor_diagonal; vg_b_vol\nPperp pressure perp mathbfB vg_ptensor_offdiagonal; vg_b_vol\nT scalar temperature P; vg_rho\nTpar temperature parallelmathbfB vg_rho; vg_ptensor_diagonal; vg_b_vol\nTperp temperature perp mathbfB vg_rho; vg_ptensor_offdiagonal; vg_b_vol\nTanisotropy T_perp T_parallel Tpar; Tperp\nJ current density vg_b_vol\nJpar j_parallel vg_b_vol\nJperp j_perp vg_b_vol\nProtated pressure tensor with widehatz parallel mathbfB vg_b_vol; vg_ptensor_diagonal; vg_ptensor_offdiagonal\nPanisotropy P_perp P_parallel ptensor; B\nPram dynamic ram pressure vg_rho; Vmag\nPb magnetic pressure vg_b_vol\nPoynting Poynting flux E; B\nBeta plasma beta, P P_B P; vg_b_vol\nBetaStar modified beta, (P+P_ram)P_B P; Pram; vg_b_vol\nIonInertial proton inertial length vg_rho\nLarmor proton Larmor radius Vth; Bmag\nGyroperiod proton gyroperiod Bmag\nPlasmaPeriod plasma oscillation period vg_rho\nGyrofrequency proton gyro-frequency Bmag\nOmegap plasma frequency (proton) vg_rho\nMagneticTension magnetic tension force vg_b_vol\nn proton number density vg_rho","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"which can also be found as keys of dictionary in vlsvvariables.jl.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"[1]: For species specific variables, you need to add the species name at the front, separated by a slash. For example, the proton bulk velocity is a string proton/vg_v.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"[2]: If a required variable exists in the VLSV file, we try to use it directly instead of calculating from other variables. The interpolated FS grid variables onto DCCRG grid are preferred over original FS grid variables.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"note: Note\nIn Vlasiator, the cells inside the inner boundary (which is usually a sphere/circle) are filled with zero density values. This is then used to identify the inner boundary for all other quantities. Therefore, if you are manipulating directly on data, make sure that the nonsense values inside the inner boundary are excluded. One way to do this can be found in vlsvvariables.jl.","category":"page"},{"location":"manual/#Velocity-space-moments","page":"User Guide","title":"Velocity space moments","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"We can also calculate plasma moments from the saved VLSV velocity space distributions.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.1d.vlsv\")\ncellid = 5\n# VDF cell indexes and values, with sparsity\nvcellids, vcellf = readvcells(meta, cellid; species=\"proton\")\n\ngetdensity(meta, vcellf)\n\ngetvelocity(meta, vcellids, vcellf)\n# pressure tensor components Pxx, Pyy, Pzz, Pyz, Pzx, Pxy\ngetpressure(meta, vcellids, vcellf)\n# heat flux components qⱼⱼᵢ\ngetheatfluxvector(meta, vcellids, vcellf)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To obtain the original ordering of velocity cells,","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vcellids_original = Vlasiator.reorder(meta.meshes[\"proton\"], vcellids)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Non-Maxwellianity represents the deviation from a Maxwellian distribution. Currently we have implemented a monitor quantity named \"Maxwellianity\", which is defined as -ln big 1(2n) int f(v) - g(v) dv big, where n is the density, f(vᵢ) is the actual VDF value at velocity cell i, and g(vᵢ) is the analytical Maxwellian (or strictly speaking, normal) distribution with the same density, bulk velocity and scalar pressure as f.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"getmaxwellianity(meta, vcellids, vcellf)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The value ranges from [0, +∞], with 0 meaning not Maxwellian-distributed at all, and +∞ a perfect Maxwellian distribution. An alternative measure is the KL-divergence borrowed from statistics, where we select the reference distribution g to be again a Maxwellian derived from the actual distribution f:","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"getKLdivergence(meta, vcellids, vcellf)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"In this case, 0 indicates perfect Maxwellian while +∞ indicates largest deviation. There is no unique definition of non-Maxwellianity, and we are still trying to see which one works better for describing plasma behaviors.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Sometimes it may be useful to recover the full 3D array of VDFs:","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"f = Vlasiator.reconstruct(meta.meshes[\"proton\"], vcellids, vcellf)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"However, usually in practice there would be only about 1% nonzero values. The moments and maxwellianity calculations above all have an alternative form of using reconstructed VDFs as inputs.","category":"page"},{"location":"manual/#Plotting","page":"User Guide","title":"Plotting","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vlasiator.jl does not include any plotting library as explicit dependency, but it offers plotting recipes/wrappers once the target plotting package is used.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Currently PyPlot provides the most complete and fine-tuned plotting capabilities. Plotting with PyPlot by accepting MetaVLSV as the first argument is supported via VlasiatorPyPlot. Plots is a collection of plotting libraries with a uniform frontend, but it lacks fine-tuned supports and consistent APIs between different backends. Makie, a native Julia plotting library, is also supported via VlasiatorMakie.jl. Without generating an system image from PackageCompiler, it would take ~20s for the first plot on Julia 1.9. However, Makie has made nice progress in layouts, widgets, docs, and all the tiny things, which makes it a strong candidate for the de facto plotting library in the future.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"More examples of customized plots can be found in the repository.","category":"page"},{"location":"manual/#PyPlot-Backend","page":"User Guide","title":"PyPlot Backend","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To trigger Matplotlib plotting that supports MetaVLSV, using VlasiatorPyPlot. All the functions with identical names as in Matplotlib accept all possible keyword arguments supported by Matplotlib, e.g. font width, font size, colormap, etc. For detailed adjustment of plots, please refer to the Matplotlib documentation for details.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"warning: Warning\nThe method call to certain axes is not dispatched, e.g. ax.plot; as an alternative, one needs to pass ax as the third argument to the functions, e.g. plot(meta, \"rho\", ax). See Matplotlib's two interfaces for the history of the interfaces.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Scalar colored contour from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pcolormesh(meta, \"n\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vector z-component colored contour from 2D simulation in a manually set range","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pcolormesh(meta, \"n\", comp=:z, colorscale=Log, axisunit=EARTH, vmin=1e6, vmax=2e6)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Vz colored contour from 2D simulation with prescribed colormap","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pcolormesh(meta, \"proton/vg_v\", comp=:z, colorscale=Linear, cmap=matplotlib.cm.RdBu_r)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Derived quantity colored contour from 2D simulation (as long as the input variable is in the predefined dictionary)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pcolormesh(meta, \"Bmag\", comp=:z, colorscale=Linear, axisunit=SI)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Streamline from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"streamplot(meta, \"proton/vg_v\", comp=\"xy\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Quiver from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"quiver(meta, \"proton/vg_v\", comp=\"xy\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The comp option is used to specify the two vector components.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"You can choose to use a linear/log/symlog color scale by setting keyword colorscale to Linear, Log, or SymLog, plot vector components by setting keyword op to :x, :y, :z, 1, 2, 3, 0 or :mag, and set axisunit to EARTH or SI etc.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Mesh denoted by cell centers","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"plotmesh(meta; projection=\"z\", color=\"k\")","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Cut slice colored contour from 3D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.amr.vlsv\")\npcolormesh(meta, \"proton/vg_rho\", normal=:y, origin=0.0)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Velocity distribution slice plot near a given spatial location","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.1d.vlsv\")\ncoordinates = [0.0, 0.0, 0.0]\nvdfslice(meta, coordinates)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Quick interactive REPL-based function for data inspection","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"pui(meta)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Or pass filename directly like pui(file).","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"note: Note\nThis is an experimental feature. We plan to have GUI-based plotting support in the future.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"For a full list available optional arguments, please refer to the doc for each method","category":"page"},{"location":"manual/#Plots-Backend","page":"User Guide","title":"Plots Backend","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To trigger Plots.jl plotting, using Plots. This backend supports all available attributes provided by Plots.jl. By default it uses GR, but many other plotting libraries are also supported.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Scaler colored contour from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"var = \"n\"\nheatmap(meta, var, aspect_ratio=:equal, c=:turbo)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Scaler colored contour with lines from 2D simulation","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"var = \"n\"\ncontourf(meta, var)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"VDF projected slice in a normal direction","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.1d.vlsv\")\nlocation = [0.0, 0.0, 0.0]\nvdfslice(meta, location)","category":"page"},{"location":"manual/#Makie-Backend","page":"User Guide","title":"Makie Backend","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"A standalone package VlasiatorMakie.jl is designed for plotting with Makie. To trigger Makie plotting with OpenGL, using VlasiatorMakie, GLMakie. You can either use intrinsic Makie plotting methods like","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"lines(meta, var) # 1D\nheatmap(meta, var) # 2D","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"or use full recipes provided by VlasiatorMakie","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vlheatmap(meta, var)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"For quick inspection of data, we have","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"2D slices of 3D AMR data","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vlslice(meta, var; normal=:x)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Orthognal slices of 3D AMR data","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vlslices(meta, var)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"2D slice of VDFs at a spatial cell","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"VlasiatorMakie.vdfslice(meta, location)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Orthognal slices of VDFs at a spatial cell","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vdfslices(meta, location)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"3D scatter of VDFs at a spatial cell","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"vdfvolume(meta, location)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The interactive plots are available through the OpenGL backend of Makie GLMakie. For noninteractive high fidelity plots, we can also use the Cairo backend of Makie CairoMakie. Other options can be found at Makie Ecosystem.","category":"page"},{"location":"manual/#Appending-to-VLSV","page":"User Guide","title":"Appending to VLSV","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"We are able to compute derived quantities from an original VLSV file and generate a new VLSV output with new quantities included.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"meta = load(\"bulk.1d.vlsv\")\nvmag = readvariable(meta, \"Vmag\")\npa = readvariable(meta, \"Panisotropy\")\nvars = Vector{Tuple{VecOrMat, String, VarInfo}}(undef, 0)\nusing LaTeXStrings\npush!(vars, (vmag, \"vmag\", VarInfo(\"m/s\", L\"$\\mathrm{m}/mathrm{s}$\", L\"$V$\", \"\")))\npush!(vars, (pa, \"panisotropy\", VarInfo(\"\", \"\", \"\", \"\")))\n\nwrite_vlsv(\"bulk.1d.vlsv\", \"bulk.1d_new.vlsv\", vars)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"note: Note\nWriting new FsGrid variables is not supported. All quantities from the original file is maintained.","category":"page"},{"location":"manual/#Converting-to-VTK","page":"User Guide","title":"Converting to VTK","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"We can convert VLSV files into VTK format. Since DCCRG is Cartesian based with uniform spacing, each level of mesh refinement corresponds to a VTK image file, and the cell refinement relationships are stored in vtkGhostType as well as the vthb file.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To convert a VLSV file into VTK,","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"write_vtk(file)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"This function accepts either string of file names or MetaVLSV.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"To see the full list of options, please refer to the documentation in API Reference. Example usage can be found here.","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"warning: Warning\nAs of ParaView 5.9.1, there are display issues with VTKOverlappingAMR. However, we can read the generated image files directly. There is also an keyword argument for write_vtk called maxamronly: when it is set to true, then only the image file at the highest refinement level is generated. This part is experimental and subject to change in the future.","category":"page"},{"location":"manual/#Tracking-log-files","page":"User Guide","title":"Tracking log files","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"The runtime performance per iteration can be monitored through log files:","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"file = \"logfile.txt\"\ntimestamps, speed = readlog(file)","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Here is a live demo.","category":"page"},{"location":"manual/#Examples","page":"User Guide","title":"Examples","text":"","category":"section"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"More examples are provided about","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Plotting with PyPlot\nPlotting with Plots\nExtracing variable along a line\nField line tracing\nSimulation log file tracking\nConverting VLSV to VTK format\nParallel post-processing\nFinding X-points and O-points in 2D reconnections","category":"page"},{"location":"manual/","page":"User Guide","title":"User Guide","text":"Feel free to check those out and try on your data!","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/#demo_2d_contour","page":"2D contour plots","title":"2D contour plots","text":"","category":"section"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"This script creates contours from a series of input files with a fixed color range. Combined with ffmpeg, we can easily make animations from data.","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"using Vlasiator, Glob, VlasiatorPyPlot, Printf\n\nfiles = glob(\"bulk*.vlsv\")\nnfile = length(files)\n# Set output directory\nconst outdir = \"out/\"\n\nmeta = load(files[1])\nconst varname = \"proton/vg_rho\"\n\nfig, ax = plt.subplots()\n\nconst comp = :z # vector component for plotting (if applicable)\nconst axisunit = EARTH\nconst colorscale = Log\nconst addcolorbar = true\n# Choose colormap\nconst cmap = matplotlib.cm.turbo\n# Set data plotting range\nconst vmin = 7.0e4\nconst vmax = 2.5e6\n\npArgs = Vlasiator.set_args(meta, varname, axisunit; normal=:none)\n\nx1, x2 = Vlasiator.get_axis(pArgs)\n\nnorm, ticks = set_colorbar(colorscale, vmin, vmax)\n\nfakedata = zeros(Float32, length(x2), length(x1))\n\nc = ax.pcolormesh(x1, x2, fakedata; norm, cmap)\n\nVlasiator.set_plot(c, ax, pArgs, ticks, addcolorbar)\n\nfor (i, file) in enumerate(files)\n @info \"$i out of $nfile\"\n local meta = load(file)\n\n var = meta[varname]\n t = readparameter(meta, \"time\")\n\n data = Vlasiator.prep2d(meta, varname, comp)'\n c.set_array(data)\n\n str_title = @sprintf \"t= %4.1fs\" t\n ax.set_title(str_title)\n\n savefig(outdir*lpad(i, 4, '0')*\".png\", bbox_inches=\"tight\", dpi=100)\nend\n\nclose()","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"","category":"page"},{"location":"examples/visualization/demo_2dcontourseries_pyplot/","page":"2D contour plots","title":"2D contour plots","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/#examples","page":"Examples","title":"Examples","text":"","category":"section"},{"location":"examples/","page":"Examples","title":"Examples","text":"This section contains thorough examples for using Vlasiator.jl.","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"","category":"page"},{"location":"examples/#Postprocess","page":"Examples","title":"Postprocess","text":"","category":"section"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to convert VLSV to VTK","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Converting to VTK","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract data for a virtual satellite","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Virtual satellite","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract data for virtual satellites","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Virtual satellites","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract data for virtual satellites","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Virtual satellites","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract EM fields on a selected 2D slice","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract EM fields on a slice","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract variables along a line across multiple frames","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract variables along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract logfile.txt information","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Log tracking","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to find X-points in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Find X-points in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract variables along the magnetopause","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract variables along the magnetopause","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to identify EMIC and mirror modes","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Identify EMIC and mirror modes","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to search for waves","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Search waves","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to track waves and plot the dispersion relation","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Track waves","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to find X/O-points","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Find X- and O-points","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to find X-points in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Find X-points in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/#Visualization","page":"Examples","title":"Visualization","text":"","category":"section"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to create animation for 1D plots","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"1D animation","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate complex plots with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Combined plots with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate complex plots","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Combined plots","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate 2D colored contour animation","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plot animation","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate 2D colored contours with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plots with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to generate 2D colored contours","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plots","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot 2D colored contour with streamlines","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plot with streamlines","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot 2D colored contour with streamlines and levels","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"2D contour plot with streamlines and levels","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot 2D colored contour slices for 3D data","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Orthogonal slices","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot field lines with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Field lines with customized seeds via multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot field lines with handpicked seeds.","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Field lines with customized seeds","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract the bow shock location and save into file","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract bow shock location","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract the bow shock location and plot","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract bow shock location","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract difference between grids","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract differences between FsGrid and DCCRG variables","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot energy spectrum at a fixed point","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Energy spectrum at a fixed point","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to trace streamlines in a 2D field","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Trace field lines in 2D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to trace streamlines in a 3D field","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Trace field lines in 3D","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract variables along a line with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract variables along a line with multi-processing","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract a variable along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Extract variable along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot variable along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Plot variable along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot variables along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Plot variables along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot mesh","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Plot mesh","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot across nodes","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Plot with multi-nodes","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to extract poynting flux on a subdomain","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Poynting flux","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot pressure tensor","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Pressure tensor","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot velocity distribution function","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"VDF","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot velocity distribution functions","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"VDFs along a line","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"This demo shows how to plot vector components","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"(Image: card-cover-image)","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"Vector components","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      \n
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"
      ","category":"page"},{"location":"examples/","page":"Examples","title":"Examples","text":"","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/#demo_identify_EMIC_mirror","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"","category":"section"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"This demo shows how to identify EMIC and mirror modes in two frequency bands from single satellite data. For EMIC mode we check δB⟂ vs. δv⟂; for mirror mode we check δB∥ vs. δn. The moving box window size is decided empirically.","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"julia -t 4 demo_wave_satellite_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"or","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"JULIA_NUM_THREADS=4 julia demo_wave_satellite_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"using Statistics: mean\nusing LinearAlgebra: ⋅, normalize!, norm\nusing DSP, PyPlot, Glob\nusing Vlasiator\nusing Vlasiator: μ₀, mᵢ, RE\nusing Polyester\n\n\"Extract variables at `loc` from VLSV `files`.\"\nfunction extract_vars(files, loc)\n nfiles = length(files)\n\n t = zeros(Float32, nfiles)\n n = zeros(Float32, nfiles)\n v = zeros(Float32, 3, nfiles)\n b = zeros(Float32, 3, nfiles)\n e = zeros(Float32, 3, nfiles)\n\n id = load(files[1]) do meta\n getcell(meta, loc)\n end\n\n # Extract data from each frame\n @batch for i = eachindex(files)\n meta = load(files[i])\n t[i] = meta.time\n n[i] = readvariable(meta, \"proton/vg_rho\", id)[1]\n v[:,i] = readvariable(meta, \"proton/vg_v\", id)\n b[:,i] = readvariable(meta, \"vg_b_vol\", id)\n e[:,i] = readvariable(meta, \"vg_e_vol\", id)\n end\n\n t, n, v, e, b\nend\n\nfunction moving_average(g::AbstractVector{<:AbstractFloat}, n::Int)\n nbackward = div(n,2)\n nforward = isodd(n) ? nbackward : nbackward - 1\n len = length(g)\n g_avg = similar(g)\n @inbounds @batch for i = 1:len\n lo = max(1, i - nbackward)\n hi = min(len, i + nforward)\n g_avg[i] = mean(@view g[lo:hi])\n end\n g_avg\nend\n\nfunction moving_average(g::AbstractMatrix{<:AbstractFloat}, n::Int)\n nbackward = div(n,2)\n nforward = isodd(n) ? nbackward : nbackward - 1\n len = size(g,2)\n g_avg = similar(g)\n for icomp = axes(g,1)\n @inbounds @batch for i = 1:len\n lo = max(1, i - nbackward)\n hi = min(len, i + nforward)\n g_avg[icomp,i] = mean(@view g[icomp, lo:hi])\n end\n end\n g_avg\nend\n\nfunction detrend(v::AbstractVector{<:AbstractFloat}; nbox=length(v)÷12)\n v̄ = moving_average(v, nbox)\n dv = v .- v̄\nend\n\nfunction detrend(v::AbstractMatrix{<:AbstractFloat}; nbox=size(v,2)÷12)\n v̄ = similar(v)\n for i in axes(v,1)\n v̄[i,:] = @views moving_average(v[i,:], nbox)\n end\n dv = v .- v̄\nend\n\nfunction align_yaxis(ax1, ax2)\n y_lims = [ax.get_ylim() for ax in [ax1, ax2]]\n\n # normalize both axes\n y_mags = ntuple(i -> y_lims[i][2] - y_lims[i][1], Val(2))\n y_lims_normalized = ntuple(i -> y_lims[i] ./ y_mags[i], Val(2))\n\n # find combined range\n y_new_lims_normalized = (min(y_lims_normalized[1][1],y_lims_normalized[2][1]),\n max(y_lims_normalized[1][2], y_lims_normalized[2][2]))\n\n # denormalize combined range to get new axes\n new_lim1 = y_new_lims_normalized .* y_mags[1]\n new_lim2 = y_new_lims_normalized .* y_mags[2]\n ax1.set_ylim(new_lim1)\n ax2.set_ylim(new_lim2)\n return\nend\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n\n # virtual satellite location\n loc = [12Vlasiator.RE, 0, 0]\n\n nbox = 40 # moving box size, [# of indices]\n fs = 2.0 # sampling rate, [Hz]\n\n println(\"Running with $(Threads.nthreads()) threads...\")\n println(\"Number of files: $(length(files))\")\n println(\"Extracting location: $loc [m]\")\n println(\"Sampling rate: $fs [Hz]\")\n println(\"Moving box window size: $(nbox / fs) [s]\")\n\n t, n, v, e, b = extract_vars(files, loc)\n\n bmag = [hypot(b[1,i], b[2,i], b[3,i]) for i in eachindex(n)]\n\n # Detrend before filtering to remove the lowest frequency changes\n dn = detrend(n; nbox)\n dbmag = detrend(bmag; nbox)\n\n n̄ = moving_average(n, nbox)\n b̄mag = moving_average(bmag, nbox)\n\n v̄a = @. b̄mag / sqrt(μ₀ * mᵢ * n̄)\n\n dv = detrend(v; nbox) # [m/s]\n db = detrend(b; nbox) # [T]\n\n # Decompose into parallel and perpendicular vector components\n b̂₀ = moving_average(b, nbox)\n for i in axes(b̂₀, 2)\n normalize!(@view b̂₀[:,i])\n end\n\n # δB∥\n db_par = [db[:,i] ⋅ b̂₀[:,i] for i in axes(db, 2)]\n # δB⟂\n db_perp = [norm(db[:,i] .- db_par[i] .* b̂₀[:,i]) for i in axes(db, 2)]\n # δv∥\n dv_par = [dv[:,i] ⋅ b̂₀[:,i] for i in axes(dv, 2)]\n # δv⟂\n dv_perp = [norm(dv[:,i] .- dv_par[i] .* b̂₀[:,i]) for i in axes(dv, 2)]\n\n designmethod = Butterworth(5)\n\n responsetype = Highpass(0.1; fs)\n dn_high = filtfilt(digitalfilter(responsetype, designmethod), dn)\n dbpar_high = filtfilt(digitalfilter(responsetype, designmethod), db_par)\n dbperp_high = filtfilt(digitalfilter(responsetype, designmethod), db_perp)\n dvperp_high = filtfilt(digitalfilter(responsetype, designmethod), dv_perp)\n\n responsetype = Bandpass(0.02, 0.067; fs)\n dn_low = filtfilt(digitalfilter(responsetype, designmethod), dn)\n dbpar_low = filtfilt(digitalfilter(responsetype, designmethod), db_par)\n\n color1 = \"tab:blue\"\n color2 = \"tab:red\"\n\n fig, axs = plt.subplots(3, 1; figsize=(13, 9), sharex=true, constrained_layout=true)\n\n fig.suptitle(\"Virtual satellite at $(string(round.(loc./RE, digits=2))) \"*L\"R_E\";\n fontsize=\"x-large\")\n\n axs[1].plot(t, dn_low ./ n̄, color1, label=L\"\\delta n, 0.02-0.067\\, Hz\")\n ax12 = axs[1].twinx()\n ax12.plot(t, dbpar_low ./ b̄mag, color=color2, label=L\"\\delta B, 0.02-0.067\\, Hz\")\n\n axs[2].plot(t, (dn_high ./ n̄), color1, label=L\"\\delta n, 0.1-1.0\\, Hz\")\n ax22 = axs[2].twinx()\n ax22.plot(t, (dbpar_high ./ b̄mag), color=color2, label=L\"\\delta B, 0.1-1.0\\, Hz\")\n\n axs[3].plot(t, dvperp_high ./ v̄a, color1, label=L\"\\delta v_\\perp, 0.1-1.0\\, Hz\")\n ax32 = axs[3].twinx()\n ax32.plot(t, dbperp_high ./ b̄mag, color=color2, label=L\"\\delta B, 0.1-1.0\\, Hz\")\n\n axs[3].set_xlabel(\"time [s]\"; fontsize=\"large\")\n\n n_str = (L\"\\delta n /n\", L\"\\delta n / n\", L\"\\delta v_\\perp / V_A\")\n\n for (i, a) in enumerate(axs)\n a.hlines(0.0, t[1], t[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.3)\n a.tick_params(axis=\"y\", labelcolor=color1)\n a.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n a.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n a.grid(true)\n a.set_ylabel(n_str[i], color=color1, fontsize=14)\n end\n\n axtwin = (ax12, ax22, ax32)\n b_str = ( L\"\\delta B_\\parallel / B_0\", L\"\\delta B_\\parallel / B_0\", L\"\\delta B_\\perp / B_0\")\n\n for (i, a) in enumerate(axtwin)\n a.tick_params(axis=\"y\", labelcolor=color2)\n a.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n a.set_ylabel(b_str[i], color=color2, fontsize=\"large\")\n align_yaxis(axs[i], a)\n end\n\n AnchoredText = matplotlib.offsetbox.AnchoredText\n\n at = AnchoredText(\n \"[0.02, 0.067] Hz band\", prop=Dict(\"size\"=>\"medium\"), frameon=true, loc=\"lower left\")\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n axs[1].add_artist(at)\n\n at = AnchoredText(\n \"[0.1, 1.0] Hz band\", prop=Dict(\"size\"=>\"medium\"), frameon=true, loc=\"lower left\")\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n axs[2].add_artist(at)\n\n at = AnchoredText(\n \"[0.1, 1.0] Hz band\", prop=Dict(\"size\"=>\"medium\"), frameon=true, loc=\"lower left\")\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n axs[3].add_artist(at)\n\n savefig(\"virtual_satellite_wave.png\"; dpi=300)\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"","category":"page"},{"location":"examples/postprocess/demo_wave_satellite_mt/","page":"Identify EMIC and mirror modes","title":"Identify EMIC and mirror modes","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/#demo_2d_contour_streamline","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"","category":"section"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"This demos shows how to reading 2D simulation data, zoom-in to a region of interest, and add streamlines on top of colored mesh.","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"using Vlasiator, Plots\n\nfile = \"bulk.0000501.vlsv\"\nnameρ = \"rho\"\nnameV = \"rho_v\"\n\nboxcoords = Float64[0, 20, -15, 15]\n\nmeta = load(file)\n\nheatmap(meta, nameρ,\n xlim=(boxcoords[1], boxcoords[2]),\n ylim=(boxcoords[3], boxcoords[4]),\n aspect_ratio=:equal,\n c=:turbo)\n\n#=\n# Attributes can be modified afterwards, but it's slower.\nheatmap(meta, nameρ, c=:turbo)\nxlims!(boxcoords[1], boxcoords[2])\nylims!(boxcoords[3], boxcoords[4])\n=#\n\nstreamplot(meta, nameV, comp=\"xy\", color=\"w\", density=2.0)","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"","category":"page"},{"location":"examples/visualization/demo_2dplot_plots/","page":"2D contour plot with streamlines","title":"2D contour plot with streamlines","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/#demo_3d_cuts","page":"Orthogonal slices","title":"Orthogonal slices","text":"","category":"section"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"This demo shows how to plot 2D colored contour slices for 3D data.","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"using VlasiatorPyPlot, PyCall\n\naxes_grid1 = pyimport(\"mpl_toolkits.axes_grid1\")\nImageGrid = axes_grid1.ImageGrid\n\nfile = \"bulk1.0001000.vlsv\"\nnameρ = \"proton/vg_rho\"\ncolorscale = Log\naddcolorbar = false\n\nmeta = load(file)\n\n# normal cuts in the x,y,z directions\nfig = plt.figure(figsize=(12, 4))\ngrid = ImageGrid(fig, 111,\n nrows_ncols=(1, 3),\n axes_pad=0.85,\n cbar_mode=\"single\",\n cbar_location=\"right\",\n cbar_pad=0.1,\n label_mode=\"all\"\n )\n\nc1 = pcolormesh(meta, nameρ, grid[1]; normal=:x, addcolorbar, colorscale)\nc2 = pcolormesh(meta, nameρ, grid[2]; normal=:y, addcolorbar, colorscale)\nc3 = pcolormesh(meta, nameρ, grid[3]; normal=:z, addcolorbar, colorscale)\n\ncb = fig.colorbar(c3, cax=grid.cbar_axes[1])\ndatainfo = readvariablemeta(meta, nameρ)\n\ncb_title_str = datainfo.variableLaTeX\ncb_title_str *= \",[\"*datainfo.unitLaTeX*\"]\"\ncb_title = cb.ax.set_title(cb_title_str, fontsize=14, fontweight=\"bold\")\n\nplt.savefig(\"test.png\", bbox_inches=\"tight\")","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"","category":"page"},{"location":"examples/visualization/demo_3dcuts_pyplot/","page":"Orthogonal slices","title":"Orthogonal slices","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/#demo_plot_multinode","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"","category":"section"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"This demos shows how to plot complex figures with more than one node using ClusterManagers. A progress bar is added for tracking.","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"Usage:","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"sbatch job.slurm","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"# Sample Slurm job script\n#!/bin/bash -l\n# -*- mode: julia -*-\n#SBATCH --nodes=2\n#SBATCH --ntasks-per-node=1\n#SBATCH --time=00:03:00\n#SBATCH --mem-per-cpu=2G\n#SBATCH --partition=test\n#SBATCH --output=%x_%j.log\n#SBATCH --job-name=pmap\n\njulia demo_mp_progressbar.jl","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"using Distributed, ProgressMeter, Glob\nusing Vlasiator: RE # Earth radius [m]\nusing ClusterManagers\naddprocs(SlurmManager(parse(Int, ENV[\"SLURM_NTASKS\"])),\n partition=ENV[\"SLURM_JOB_PARTITION\"],\n time=\"00:03:00\", # No environment variable for time limit\n mem_per_cpu=ENV[\"SLURM_MEM_PER_CPU\"])\n\n@everywhere begin\n using ParallelDataTransfer\n using Vlasiator, VlasiatorPyPlot, Printf, LaTeXStrings\n using Vlasiator: set_args, prep2d\nend\n\n@assert matplotlib.__version__ ≥ \"3.4\" \"Require Matplotlib version 3.4+ to use subfigure!\"\n\n@everywhere function init_figure(x1, x2)\n fig = plt.figure(myid(), constrained_layout=true, figsize=(12, 12))\n subfigs = fig.subfigures(1, 2, wspace=0.05)\n\n axsL = subfigs[1].subplots(4, 1, sharex=true)\n axsR = subfigs[2].subplots(2, 1, sharex=true, sharey=true)\n\n # Set line plots' axes\n axsL[end].set_xlim(x1, x2)\n\n axsL[1].set_ylim(ρmin, ρmax)\n axsL[2].set_ylim(vmin, vmax)\n axsL[3].set_ylim(pmin, pmax)\n axsL[4].set_ylim(bmin, bmax)\n for ax in axsL\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axsL[end].set_xlabel(L\"x [$R_E$]\"; fontsize)\n axsL[1].set_ylabel(\"Density [amu/cc]\"; fontsize)\n axsL[2].set_ylabel(\"Velocity [km/s]\"; fontsize)\n axsL[3].set_ylabel(\"Pressure [nPa]\"; fontsize)\n axsL[4].set_ylabel(\"Magnetic field [nT]\"; fontsize)\n\n fakeline = loc\n l1 = axsL[1].plot(loc, fakeline, label=\"Proton density\", color=\"#1f77b4\")\n l2 = axsL[2].plot(loc, fakeline, label=\"Vx\", color=\"#1f77b4\")\n l3 = axsL[3].plot(loc, fakeline, label=\"Ram\", color=\"#1f77b4\")\n l4 = axsL[3].plot(loc, fakeline, label=\"Thermal\", color=\"#ff7f0e\")\n l5 = axsL[4].plot(loc, fakeline, label=\"Bz\", color=\"#1f77b4\")\n\n ls = (l1, l2, l3, l4, l5)\n\n axsL[2].legend(;loc=\"upper right\", fontsize)\n axsL[3].legend(;loc=\"lower right\", fontsize)\n axsL[4].legend(;loc=\"upper right\", fontsize)\n\n vl1 = axsL[1].vlines(loc[imagnetopause_], ρmin, ρmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n vl2 = axsL[2].vlines(loc[imagnetopause_], vmin, vmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n vl3 = axsL[3].vlines(loc[imagnetopause_], pmin, pmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n vl4 = axsL[4].vlines(loc[imagnetopause_], bmin, bmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n hl4 = axsL[4].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n\n vlines = (vl1, vl2, vl3, vl4)\n\n for ax in axsR\n ax.set_aspect(\"equal\")\n\n # Set border line widths\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\n edge = get(ax.spines, loc, nothing)\n edge.set_linewidth(2.0)\n end\n ax.xaxis.set_tick_params(width=2.0, length=3)\n ax.yaxis.set_tick_params(width=2.0, length=3)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n\n ax.set_ylabel(L\"Y [$R_E$]\"; fontsize)\n end\n\n axsR[2].set_xlabel(L\"X [$R_E$]\"; fontsize)\n\n axsR[1].set_title(\"Alfven speed\", fontsize=\"x-large\")\n axsR[2].set_title(\"Sound speed\", fontsize=\"x-large\")\n\n x, y = Vlasiator.get_axis(pArgs1)\n\n fakedata = zeros(Float32, length(y), length(x))\n\n c1 = axsR[1].pcolormesh(x, y, fakedata, norm=cnorm1, cmap=cmap)\n c2 = axsR[2].pcolormesh(x, y, fakedata, norm=cnorm2, cmap=cmap)\n\n cb1 = colorbar(c1; ax=axsR[1], ticks=cticks1, fraction=0.046, pad=0.04)\n cb2 = colorbar(c2; ax=axsR[2], ticks=cticks2, fraction=0.046, pad=0.04)\n\n cs = (c1, c2)\n\n for cb in (cb1, cb2)\n cb.ax.set_ylabel(\"[km/s]\"; fontsize)\n cb.outline.set_linewidth(1.0)\n end\n\n fig.suptitle(\"Density Pulse Run\", fontsize=\"xx-large\")\n\n return fig, subfigs, ls, vlines, cs\nend\n\nfunction update_vline(h, x)\n seg_old = h.get_segments()\n ymin = seg_old[1][1, 2]\n ymax = seg_old[1][2, 2]\n\n seg_new = [[[x, ymin] [x, ymax]]]\n\n h.set_segments(seg_new)\nend\n\n@everywhere function process(subfigs, ls, vlines, cs, file, cellids)\n isfile(\"../out/\"*file[end-8:end-5]*\".png\") && return\n\n println(\"file = $(basename(file))\")\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1e9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1e9 # [nPa]\n\n bz = readvariable(meta, \"vg_b_vol\", cellids)[3,:] .* 1e9 #[nT]\n\n ls[1][1].set_ydata(rho_extract ./ 1e6)\n ls[2][1].set_ydata(v_extract[1,:] ./ 1e3)\n ls[3][1].set_ydata(pram_extract)\n ls[4][1].set_ydata(p_extract)\n ls[5][1].set_ydata(bz)\n\n imagnetopause_ = findfirst(<(0.0), bz)\n for vline in vlines\n update_vline(vline, loc[imagnetopause_])\n end\n\n str_title = @sprintf \"Sun-Earth line, t= %4.1fs\" meta.time\n subfigs[1].suptitle(str_title, fontsize=\"x-large\")\n\n data = prep2d(meta, \"VA\")'\n cs[1].set_array(data ./ 1e3)\n\n data = prep2d(meta, \"VS\")'\n cs[2].set_array(data ./ 1e3)\n\n savefig(\"../out/\"*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n return\nend\n\n## Parameters\n\nfiles = glob(\"bulk*.vlsv\", \"../run_rho2_bz-5_timevarying_startfrom300s\")\nnfiles = length(files)\n\nconst p = Progress(nfiles; showspeed=true)\nconst channel = RemoteChannel(()->Channel{Bool}(), 1)\n\n@passobj 1 workers() files\n\n@broadcast begin # on all workers\n const isinit = true\n # Set contour plots' axes and colorbars\n const cmap = matplotlib.cm.turbo\n colorscale = Linear\n axisunit = EARTH\n\n # Upper/lower limits for each variable\n const ρmin, ρmax = 0.0, 10.0 # [amu/cc]\n const vmin, vmax = -640.0, 0.0 # [km/s]\n const pmin, pmax = 0.0, 1.82 # [nPa]\n const bmin, bmax = -25.0, 60.0 # [nT]\n const vamin, vamax = 0.0, 250.0 # [km/s]\n const vsmin, vsmax = 30.0, 350.0 # [km/s]\n\n meta = load(files[1])\n\n const pArgs1 = set_args(meta, \"VA\", axisunit; normal=:none)\n const cnorm1, cticks1 = set_colorbar(colorscale, vamin, vamax)\n const cnorm2, cticks2 = set_colorbar(colorscale, vsmin, vsmax)\n\n const fontsize = 14\nend\n\nconst x1, x2 = 8.0, 29.0\nconst point1 = [x1, 0, 0] .* RE\nconst point2 = [x2, 0, 0] .* RE\n\nmeta = load(files[1])\ncellids, _, _ = getcellinline(meta, point1, point2)\npassobj(1, workers(), [:x1, :x2, :cellids])\n@broadcast const loc = range(x1, x2, length=length(cellids))\n\n## Execution\n\n@broadcast begin\n # initialize figure, axes, lines, and contours\n fig, subfigs, ls, vlines, cs = init_figure(x1, x2)\nend\n\n@sync begin # start two tasks which will be synced in the very end\n # the first task updates the progress bar\n @async while take!(channel)\n next!(p)\n end\n\n # the second task does the computation\n @async begin\n pmap(1:nfiles) do i\n process(subfigs, ls, vlines, cs, files[i], cellids)\n put!(channel, true) # trigger a progress bar update\n end\n put!(channel, false) # this tells the printing task to finish\n end\nend","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"","category":"page"},{"location":"examples/visualization/demo_mp_progressbar/","page":"Plot with multi-nodes","title":"Plot with multi-nodes","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/#demo_plot_mesh","page":"Plot mesh","title":"Plot mesh","text":"","category":"section"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"This demo shows how to plot mesh. The cell centers are represented by the markers.","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"using VlasiatorPyPlot\n\nconst file = \"test/data/bulk.amr.vlsv\"\nmeta = load(file)\n# 3D mesh\nfig = plt.figure()\nax = fig.add_subplot(projection=\"3d\")\n\nplotmesh(meta, marker=\"+\")\n\n# 2D mesh\nfig = plt.figure()\n\npcolormesh(meta, \"proton/vg_rho\"; axisunit=SI)\nplotmesh(meta, projection=\"y\"; color=\"w\")","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"","category":"page"},{"location":"examples/visualization/demo_mesh_pyplot/","page":"Plot mesh","title":"Plot mesh","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/#demo_poynting","page":"Poynting flux","title":"Poynting flux","text":"","category":"section"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"This demo shows how to extract the Poynting flux on a subdomain from 2D and plot.","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"Usage:","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"julia -t 4 demo_poynting_mt_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"or","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"JULIA_NUM_THREADS=4 julia demo_poynting_mt_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"using Statistics: mean, normalize\nusing LinearAlgebra: ×, ⋅\nusing Vlasiator\nusing Vlasiator: μ₀, prep2d, prep2dslice\nusing Glob, DSP, Polyester, Printf, PyPlot\n\n\"\"\"\n extract_EM(files, range1, range2, pArgs, ndim=2; normal=:y, verbose=true)\n\nExtract time-series of EM fields from `files` within `range1` in the 1st dim and `range1` in\nthe 2nd dim.\n\"\"\"\nfunction extract_EM(files, range1, range2, pArgs, ndim=2; normal=:y, verbose=true)\n @assert ndim ∈ (2,3) \"Only support extracting EM fields from 2D/3D runs.\"\n nfile = length(files)\n e = zeros(Float32, 3, length(range1), length(range2), nfile)\n b = zeros(Float32, 3, length(range1), length(range2), nfile)\n\n if ndim == 2\n @batch for i in eachindex(files)\n verbose && println(\"i = $i/$nfile, file = $(files[i])\")\n meta = load(files[i])\n\n e[1,:,:,i] = prep2d(meta, \"vg_e_vol\", 1)[range1, range2]\n e[2,:,:,i] = prep2d(meta, \"vg_e_vol\", 2)[range1, range2]\n e[3,:,:,i] = prep2d(meta, \"vg_e_vol\", 3)[range1, range2]\n b[1,:,:,i] = prep2d(meta, \"vg_b_vol\", 1)[range1, range2]\n b[2,:,:,i] = prep2d(meta, \"vg_b_vol\", 2)[range1, range2]\n b[3,:,:,i] = prep2d(meta, \"vg_b_vol\", 3)[range1, range2]\n end\n else\n @batch for i in eachindex(files)\n verbose && println(\"i = $i/$nfile, file = $(files[i])\")\n meta = load(files[i])\n\n e[1,:,:,i] = prep2dslice(meta, \"vg_e_vol\", normal, 1, pArgs)[range1, range2]\n e[2,:,:,i] = prep2dslice(meta, \"vg_e_vol\", normal, 2, pArgs)[range1, range2]\n e[3,:,:,i] = prep2dslice(meta, \"vg_e_vol\", normal, 3, pArgs)[range1, range2]\n b[1,:,:,i] = prep2dslice(meta, \"vg_b_vol\", normal, 1, pArgs)[range1, range2]\n b[2,:,:,i] = prep2dslice(meta, \"vg_b_vol\", normal, 2, pArgs)[range1, range2]\n b[3,:,:,i] = prep2dslice(meta, \"vg_b_vol\", normal, 3, pArgs)[range1, range2]\n end\n end\n e, b\nend\n\n\"Moving box average of vector `g` with box size `n`.\"\nfunction moving_average(g::AbstractVector{<:AbstractFloat}, n::Int)\n nbackward = div(n,2)\n nforward = isodd(n) ? div(n,2) : div(n,2) - 1\n len = length(g)\n g_avg = similar(g)\n @inbounds @batch for i = 1:len\n lo = max(1, i - nbackward)\n hi = min(len, i + nforward)\n g_avg[i] = mean(@view g[lo:hi])\n end\n g_avg\nend\n\n\"Extract the perturbation from vector `v` with moving box size `nbox`.\"\nfunction detrend(v::AbstractVector{<:AbstractFloat}; nbox=length(v)÷12)\n v̄ = moving_average(v, nbox)\n dv = v .- v̄\nend\n\n\"Extract the perturbation from 4D array `v` along the last dim with moving box size `nbox`.\"\nfunction detrend(v::AbstractArray{<:AbstractFloat}; nbox=size(v,4)÷12)\n v̄ = similar(v)\n for idim = 1:3\n for j in axes(v, 3), i in axes(v, 2)\n v̄[idim,i,j,:] = @views moving_average(v[idim,i,j,:], nbox)\n end\n end\n dv = v .- v̄\n dv, v̄\nend\n\n\"Band pass filter for vector field `var`.\"\nfunction band_pass_filter(var, responsetype, designmethod)\n\n filter = digitalfilter(responsetype, designmethod)\n\n var_filtered = zeros(eltype(var), size(var,4), 3, size(var,2), size(var,3))\n\n for idim = 1:3\n for j in axes(var, 3), i in axes(var, 2)\n var_filtered[:,idim,i,j] = filtfilt(filter, var[idim,i,j,:])\n end\n end\n var_filtered\nend\n\n\"\"\"\n calc_poynting(de, db, b̄, it)\n\nReturn full Poynting vector, also parallel and perpendicular Poynting vector components to\nthe magnetic field. The perpendicular components are in-plane.\n\"\"\"\nfunction calc_poynting(de, db, b̄, it)\n\n s = zeros(3, size(de,3), size(de,4))\n # parallel and perpendicular Poynting vector magnitudes\n s_par = zeros(size(de,3), size(de,4))\n s_perp = zeros(size(de,3), size(de,4))\n\n @views for j in axes(de,4), i in axes(de,3)\n # Poynting vector = dE × dB\n s[:,i,j] = de[it,:,i,j] × db[it,:,i,j] / μ₀\n\n # Transform into parallel and perpendicular direction w.r.t. B\n b̂ = normalize(b̄[:,i,j,it])\n s_par[i,j] = s[:,i,j] ⋅ b̂\n #s_perp[i,j] = norm(s[:,i,j] .- s_par[i,j] .* b̂)\n # in-plane perpendicular component only\n s_perp[i,j] = sqrt((s[1,i,j] - s_par[i,j]*b̂[1])^2 + (s[3,i,j] - s_par[i,j]*b̂[3])^2)\n end\n\n s, s_par, s_perp\nend\n\n\"Output figures of Poynting vectors for each snapshot.\"\nfunction plot_poynting(de_filtered, db_filtered, b̄, x1, x2, frequency_range)\n\n nt = size(de_filtered, 1)\n\n norm1 = let\n sparmax = frequency_range == \"high\" ? 5e-7 : 1e-5\n sparmin = -sparmax\n levels = matplotlib.ticker.MaxNLocator(nbins=255).tick_values(sparmin, sparmax)\n matplotlib.colors.BoundaryNorm(levels, ncolors=256, clip=true)\n end\n\n norm2 = let\n sperpmax = frequency_range == \"high\" ? 5e-7 : 1e-5\n sperpmin = 0.0\n levels = matplotlib.ticker.MaxNLocator(nbins=255).tick_values(sperpmin, sperpmax)\n matplotlib.colors.BoundaryNorm(levels, ncolors=256, clip=true)\n end\n\n stride = 10 # number of strides for quivers\n\n s, s_par, s_perp = calc_poynting(de_filtered, db_filtered, b̄, 1)\n\n\n fig, axs = plt.subplots(1, 2; figsize=(11,6), sharex=true, sharey=true,\n constrained_layout=true)\n\n axs[1].set_title(L\"S_\\parallel\"; fontsize=\"large\")\n axs[2].set_title(L\"S_\\perp\"; fontsize=\"large\")\n\n for ax in axs\n ax.set_aspect(\"equal\")\n ax.set_xlabel(L\"x1 [R_E]\"; fontsize=\"large\")\n ax.set_ylabel(L\"x2 [R_E]\"; fontsize=\"large\")\n end\n\n c1 = axs[1].pcolormesh(x1, x2, s_par';\n cmap=matplotlib.cm.RdBu_r,\n shading=\"nearest\",\n norm=norm1,\n )\n\n cb1 = colorbar(c1; ax=axs[1], extend=\"both\")\n cb1.ax.set_ylabel(L\"[W/m^2]\"; fontsize=\"large\")\n\n c2 = axs[2].pcolormesh(x1, x2, s_perp';\n cmap=matplotlib.cm.turbo,\n shading=\"nearest\",\n norm=norm2,\n )\n\n cb2 = colorbar(c2; ax=axs[2], extend=\"max\")\n cb2.ax.set_ylabel(L\"[W/m^2]\"; fontsize=\"large\")\n\n s1 = @views (s[1,:,:] ./ hypot.(s[1,:,:], s[3,:,:]))[1:stride:end, 1:stride:end]'\n s2 = @views (s[3,:,:] ./ hypot.(s[1,:,:], s[3,:,:]))[1:stride:end, 1:stride:end]'\n\n q = axs[1].quiver(x1[1:stride:end], x2[1:stride:end], s1, s2; color=\"k\")\n\n b1 = @views (b̄[1,:,:,1] ./ hypot.(b̄[1,:,:,1], b̄[3,:,:,1]))[1:stride:end, 1:stride:end]'\n b2 = @views (b̄[3,:,:,1] ./ hypot.(b̄[1,:,:,1], b̄[3,:,:,1]))[1:stride:end, 1:stride:end]'\n\n qb = axs[1].quiver(x1[1:stride:end], x2[1:stride:end], b1, b2; color=\"tab:purple\")\n\n if frequency_range == \"high\"\n fig.suptitle(\"t = $(t[1]) s, [0.1, 1.0] Hz\";\n fontsize=\"xx-large\")\n else\n fig.suptitle(\"t = $(t[1]) s, [$(responsetype.w1), $(responsetype.w2)] Hz\";\n fontsize=\"xx-large\")\n end\n\n for it = 1:nt\n @info \"it = $it\"\n local s, s_par, s_perp\n outname = \"poynting/poynting_$(lpad(it, 4, '0'))_band$frequency_range.png\"\n isfile(outname) && continue\n s, s_par, s_perp = calc_poynting(de_filtered, db_filtered, b̄, it)\n\n c1.set_array(s_par')\n c2.set_array(s_perp')\n\n ŝx = @views @. s[1,:,:] / hypot(s[1,:,:], s[3,:,:])\n ŝz = @views @. s[3,:,:] / hypot(s[1,:,:], s[3,:,:])\n\n q.set_UVC(ŝx[1:stride:end, 1:stride:end]', ŝz[1:stride:end, 1:stride:end]')\n\n b̂x = @views @. b̄[1,:,:,it] / hypot(b̄[1,:,:,it], b̄[3,:,:,it])\n b̂z = @views @. b̄[3,:,:,it] / hypot(b̄[1,:,:,it], b̄[3,:,:,it])\n\n qb.set_UVC(b̂x[1:stride:end, 1:stride:end]', b̂z[1:stride:end, 1:stride:end]')\n\n if frequency_range == \"high\"\n fig.suptitle(\"t = $(t[it]) s, [0.1, 1.0] Hz\";\n fontsize=\"xx-large\")\n else\n fig.suptitle(\"t = $(t[it]) s, [$(responsetype.w1), $(responsetype.w2)] Hz\";\n fontsize=\"xx-large\")\n end\n savefig(outname; dpi=300, bbox_inches=\"tight\")\n end\nend\n\n########## Main\n\nfiles = glob(\"bulk*.vlsv\", \".\")\nnfile = length(files)\n\nconst frequency_range = \"low\" # filtered frequency range ∈ (\"low\", \"high\")\nconst extent = [6., 16., -7., 7.] # [RE], default: [-Inf32, Inf32, -Inf32, Inf32]\nconst normal = :none # plane normal direction for 3D data, (:none, :x, :y, :z)\nconst fs = 2.0 # sampling frequency, [Hz]\n\n# WARNING: t may not be exact due to round-off errors in output time stamps!\nndim, pArgs, t, range1, range2 = let meta = load(files[1])\n pArgs = Vlasiator.set_args(meta, \"vg_e_vol\", EARTH; normal=:none)\n x1, x2 = Vlasiator.get_axis(pArgs)\n\n tstart = meta.time\n tend = load(files[end]).time\n\n ndims(meta), pArgs,\n range(round(tstart,digits=1), round(tend, digits=1), length=nfile),\n searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2]),\n searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\nend\n\n@assert ndim == 3 \"3D not working yet!\"\n\ne, b = extract_EM(files, range1, range2, pArgs, ndim; normal, verbose=true)\n\ndesignmethod = Butterworth(5)\nif frequency_range == \"high\"\n responsetype = Highpass(0.1; fs)\n nbox = 40\nelseif frequency_range == \"low\"\n responsetype = Bandpass(0.02, 0.067; fs)\n nbox = 200\nend\n\nde, _ = detrend(e; nbox)\ndb, b̄ = detrend(b; nbox)\n\nde_filtered = band_pass_filter(de, responsetype, designmethod)\ndb_filtered = band_pass_filter(db, responsetype, designmethod)\n\nx1 = range(extent[1], extent[2], length=length(range1))\nx2 = range(extent[3], extent[4], length=length(range2))\n\nplot_poynting(de_filtered, db_filtered, b̄, x1, x2, frequency_range)","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"","category":"page"},{"location":"examples/visualization/demo_poynting_mt_pyplot/","page":"Poynting flux","title":"Poynting flux","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/#demo_tensor","page":"Pressure tensor","title":"Pressure tensor","text":"","category":"section"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"This demo shows how to plot the pressure tensor from one snapshot.","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"using Vlasiator, VlasiatorPyPlot, LaTeXStrings, Printf\n\nfunction main()\n file = \"bulk.0001582.vlsv\"\n\n axisunit = EARTH\n colorscale = Linear\n cmap = matplotlib.cm.turbo\n\n vars = [\"proton/vg_ptensor_diagonal\", \"proton/vg_ptensor_offdiagonal\"]\n\n #####\n meta = load(file)\n\n pArgs1 = Vlasiator.set_args(meta, vars[1], axisunit; normal=:none)\n pArgs2 = Vlasiator.set_args(meta, vars[2], axisunit; normal=:none)\n\n x, y = Vlasiator.get_axis(pArgs1)\n # [nPa]\n pxx = Vlasiator.prep2d(meta, vars[1], :x)' .* 1e9\n pyy = Vlasiator.prep2d(meta, vars[1], :y)' .* 1e9\n pzz = Vlasiator.prep2d(meta, vars[1], :z)' .* 1e9\n pyz = Vlasiator.prep2d(meta, vars[2], :1)' .* 1e9\n pxz = Vlasiator.prep2d(meta, vars[2], :2)' .* 1e9\n pxy = Vlasiator.prep2d(meta, vars[2], :3)' .* 1e9\n\n P = (pxx, pyy, pzz, pyz, pxz, pxy)\n P_str = (\"Pxx\", \"Pyy\", \"Pzz\", \"Pyz\", \"Pxz\", \"Pxy\")\n\n vmin = minimum(minimum.(P))\n vmax = maximum(maximum.(P))\n\n cnorm1, cticks1 = set_colorbar(colorscale, vmin, vmax)\n\n fig, axs = subplots(3,2,\n figsize=(6, 12), sharex=true, sharey=true, constrained_layout=true)\n\n c1 = axs[1].pcolormesh(x, y, pxx; norm=cnorm1, cmap)\n\n for i in eachindex(axs)[2:end]\n axs[i].pcolormesh(x, y, P[i]; norm=cnorm1, cmap)\n end\n\n for (i, ax) in enumerate(axs)\n ax.set_aspect(\"equal\")\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.set_title(P_str[i])\n end\n\n for ax in axs[3,:]\n ax.set_xlabel(L\"x [$R_E$]\")\n end\n\n for ax in axs[:,1]\n ax.set_ylabel(L\"y [$R_E$]\")\n end\n\n # One colorbar for all subplots\n cb1 = colorbar(c1; ax=axs, ticks=cticks1, fraction=0.046, pad=0.04)\n cb1.ax.set_ylabel(\"[nPa]\")\n cb1.outline.set_linewidth(1.0)\n\n str_title = @sprintf \"Pressure Tensor at t = %4.1fs\" meta.time\n\n fig.suptitle(str_title, fontsize=\"xx-large\")\n\n savefig(\"ptensor.png\", bbox_inches=\"tight\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"","category":"page"},{"location":"examples/visualization/demo_tensor_pyplot/","page":"Pressure tensor","title":"Pressure tensor","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"python/#Interoperability-Between-Julia-and-Python","page":"Calling from Python","title":"Interoperability Between Julia and Python","text":"","category":"section"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"There are currently two ways to call Julia from Python and vice versa, which are described below. When converting from Julia to Python, there are two most important differences:","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"Julia is column-major, while Python is row-major.\nJulia adopts by default 1-based indexing, while Python adopts 0-based indexing.","category":"page"},{"location":"python/#JuliaCall","page":"Calling from Python","title":"JuliaCall","text":"","category":"section"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"Vlasiator.jl can be called from Python via JuliaCall. JuliaCall will link to the first Julia version in the system path. If Vlasiator.jl has been installed, we can use it directly; otherwise we need to state it in the juliacalldeps.json file.","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"from juliacall import Main as jl\njl.seval(\"using Vlasiator\")\nfile = \"bulk.1d.vlsv\"\nmeta = jl.load(file)","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"Matplotlib can then be used to visualize the data.","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"from matplotlib import pyplot as plt\nimport numpy as np\nrho = jl.readvariable(meta, \"proton/vg_rho\")\nx = np.arange(meta.coordmin[0], meta.coordmax[0], meta.dcoord[0])\nplt.plot(x, rho)\nplt.show()","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"warn: Warn\nThere is an issue that JuliaCall may decide to check pkg installation every time for a new session. We need to first make sure that PythonCall is installed in Julia; then make sure your PYTHONPATH is properly set. See this issue for more information.","category":"page"},{"location":"python/#PyJulia","page":"Calling from Python","title":"PyJulia","text":"","category":"section"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"Vlasiator.jl can also be called from Python with the aid of PyJulia. Following the installation steps described in the manual[1], and then inside Python REPL:","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"# Handling initialization issue for Conda\nfrom julia.api import Julia\njl = Julia(compiled_modules=False)\n\nfrom julia import Vlasiator\nfile = \"bulk1.0001000.vlsv\"\nmeta = Vlasiator.load(file)\nvar = \"proton/vg_rho\"\ndata = Vlasiator.readvariable(meta, var)","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"To run a Julia script in Python,","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"# Handling initialization issue for Conda\nfrom julia.api import Julia\njl = Julia(compiled_modules=False)\njl.eval('include(\"examples/demo_2dplot_pyplot.jl\")')\nimport matplotlib.pyplot as plt\nplt.show()","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"note: Note\nThis approach is for you to have a taste of the package with a Python frontend. The workaround shown above for handling the static python libraries makes it slow for regular use. An alternative solution would be creating system images, but as of Julia 1.6 the user experience is not smooth. For better integrated experience with its full power, it is recommended to use the package inside Julia.","category":"page"},{"location":"python/","page":"Calling from Python","title":"Calling from Python","text":"[1]: For Debian-based Linux distributions, it gets a little bit tricky. Please refer to Troubleshooting for details.","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/#demo_search_waves","page":"Search waves","title":"Search waves","text":"","category":"section"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"This demo shows how to search for wave-like structures and plot spatial-temporal distributions.","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"Procedures:","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"Extract variables in all cells from all snapshots.\nFor each cell and time interval, count time-series local peaks.\nPlot the peak occurrence frequencies across the whole domain as an indicator for waves.","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"note: Note\nWhen dealing with multiple variables, it is recommended to handle one variable at atime through the whole process due to memory considerations. With large number of frame counts, the current procedure is still memory-consuming.It assumes uniform sampling in time.\nPeak-finding is threaded, but plotting is still serial.","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"julia -t 4 demo_wave_search_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"or","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"JULIA_NUM_THREADS=4 julia demo_wave_search_mt.jl","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"using Glob, Vlasiator, PyPlot, LaTeXStrings\n\n\"Extract time series variable\"\nfunction extract_var(files, ncells, varname, component=0)\n nfiles = length(files)\n var = zeros(Float32, ncells[1], ncells[2], nfiles)\n\n # Extract data from each frame\n if component == 0 # scalar\n Threads.@threads for i = eachindex(files)\n meta = load(files[i])\n var[:,:,i] = meta[varname]\n end\n else # vector component\n Threads.@threads for i = eachindex(files)\n meta = load(files[i])\n var[:,:,i] = meta[varname][component,:]\n end\n end\n\n return var\nend\n\n\"Count local maxima of vector `y` with moving box length `n`.\"\nfunction countpeaks(y, n; interval=1)\n maxs = Int[]\n if interval == 1\n for i in 2:length(y)-1\n if y[i-1] < y[i] > y[i+1]\n push!(maxs, i)\n end\n end\n elseif interval == 2\n for i in 3:length(y)-2\n if y[i-2] ≤ y[i-1] < y[i] > y[i+1] ≥ y[i+2]\n push!(maxs, i)\n end\n end\n elseif interval == 3\n for i in 4:length(y)-3\n if y[i-3] ≤ y[i-2] ≤ y[i-1] < y[i] > y[i+1] ≥ y[i+2] > y[i+3]\n push!(maxs, i)\n end\n end\n else\n error(\"interval = $interval not implemented!\")\n end\n nCounts = zeros(Int, length(y)-n+1)\n nCounts[1] = count(i->(1 ≤ i ≤ n), maxs)\n for i in 1:length(y)-n\n nCounts[i+1] = nCounts[i]\n if i ∈ maxs\n nCounts[i+1] -= 1\n end\n if i+n-1 ∈ maxs\n nCounts[i+1] += 1\n end\n end\n nCounts\nend\n\n\"Check wave-like occurrence frequencies within box length `n` of output interval `dt`.\"\nfunction checkwaves_sma(var, dt=0.5, n::Int=size(var,3); interval=1)\n nPeaks = zeros(Int, size(var,3)-n+1, size(var,1), size(var,2))\n\n Threads.@threads for j in axes(var, 2)\n for i in axes(var, 1)\n var_series = @view var[i,j,:]\n nPeaks[:,i,j] = countpeaks(var_series, n; interval)\n end\n end\n nPeaks ./ (n*dt)\nend\n\nfunction plot_dist(files, varnames, varnames_print, components, Δt, nboxlength;\n interval=1, nplotstride=1)\n @assert nboxlength ≥ 3 && isodd(nboxlength) \"Expect odd box length ≥ 3!\"\n if (local nfiles = length(files)) < nboxlength\n @warn \"Set moving box length to the number of files...\"\n nboxlength = nfiles\n end\n local x, y, tStart, tEnd, ncells\n let RE = Vlasiator.RE\n meta = load(files[1])\n tStart = meta.time\n ncells = meta.ncells\n x = LinRange{Float32}(meta.coordmin[1]/RE, meta.coordmax[1]/RE, meta.ncells[1])\n y = LinRange{Float32}(meta.coordmin[2]/RE, meta.coordmax[2]/RE, meta.ncells[2])\n meta = load(files[end])\n tEnd = meta.time\n end\n\n fig, ax = plt.subplots(figsize=(16,9))\n fontsize = 14\n vmin, vmax = 0.0, 0.5\n levels = matplotlib.ticker.MaxNLocator(nbins=255).tick_values(vmin, vmax)\n norm = matplotlib.colors.BoundaryNorm(levels, ncolors=256, clip=true)\n ticks = range(vmin, vmax, length=11)\n\n fakedata = zeros(Float32, length(x), length(y))\n im = ax.pcolormesh(y, x, fakedata; norm)\n\n ax.set_aspect(\"equal\")\n ax.set_xlabel(L\"y [$R_E$]\"; fontsize, weight=\"black\")\n ax.set_ylabel(L\"x [$R_E$]\"; fontsize, weight=\"black\")\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true, color=\"grey\", linestyle=\"-\")\n\n cb = fig.colorbar(im; ax, ticks, pad=0.02)\n cb.ax.set_ylabel(\"Frequency of local maxima occurrence, [#/s]\"; fontsize)\n\n for i in eachindex(varnames)\n outdir = \"../out/$(lowercase(varnames_print[i]))\"\n !isdir(outdir) && mkdir(outdir)\n length(glob(\"spatial*.png\", outdir)) == length(files) - nboxlength + 1 && continue\n\n # Obtain time series data\n var = extract_var(files, ncells, varnames[i], components[i])\n # Count local peak occuring frequencies at each location\n fPeaks = checkwaves_sma(var, Δt, nboxlength; interval)\n\n for it in 1:nplotstride:size(fPeaks,1) # Iterate over time\n outname = joinpath(outdir,\n \"spatial_perturbation_distribution_$(lpad(it, 4, '0')).png\")\n isfile(outname) && continue\n # Update plot\n im.set_array(fPeaks[it,:,:])\n ax.set_title(\"$(varnames_print[i]) Perturbation Detection, \"*\n \"t = $(round(tStart+(it-1)*Δt, digits=1)) ~ \"*\n \"$(round(tStart+(it+nboxlength-1)*Δt, digits=1))s\";\n fontsize, fontweight=\"bold\")\n\n savefig(outname, bbox_inches=\"tight\")\n end\n end\nend\n\nfunction main()\n varnames = [\"proton/vg_rho\", \"vg_pressure\", \"proton/vg_v\", \"proton/vg_v\", \"vg_b_vol\",\n \"vg_e_vol\", \"vg_e_vol\"]\n varnames_print = [\"Density\", \"Thermal Pressure\", \"Vx\", \"Vy\", \"Bz\", \"Ex\", \"Ey\"]\n components = [0, 0, 1, 2, 3, 1, 2] # 0: scalar; 1: x, 2: y, 3: z\n Δt = 0.5 # output time interval [s]\n nboxlength = 101 # moving box average length\n interval = 2 # local peak gap minimal interval\n nplotstride = 50 # plot intervals in frames\n dir = \"./\" # data directory\n\n files = glob(\"bulk*.vlsv\", dir)\n\n println(\"Total number of snapshots: $(length(files))\")\n println(\"Running with $(Threads.nthreads()) threads...\")\n\n @time plot_dist(files, varnames, varnames_print, components, Δt, nboxlength;\n interval, nplotstride)\n\n println(\"Virtual satellite extraction done!\")\nend\n\nmain()","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"","category":"page"},{"location":"examples/postprocess/demo_wave_search_mt/","page":"Search waves","title":"Search waves","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"","page":"Home","title":"Home","text":"CurrentModule = Vlasiator","category":"page"},{"location":"#Vlasiator.jl","page":"Home","title":"Vlasiator.jl","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"Vlasiator.jl is a data processing and analyzing tool for the numerical model for collisionless ion-kinetic plasma physics Vlasiator. This lightweight package is built upon its sister in Python Analysator and carefully designed for performance, capability and ease of use. It can be easily integrated with external packages like FieldTracer.jl and TestParticle.jl to do all kinds of in-depth analysis.","category":"page"},{"location":"","page":"Home","title":"Home","text":"Vlasiator.jl contains the following features:","category":"page"},{"location":"","page":"Home","title":"Home","text":"Reading VLSV format data.\nCalculating derived quantities from raw VLSV outputs.\nExtracting quantities at a given point/line/plane/box.\nPlotting 1D curves/2D cuts of saved/derived variables and phase space distributions.\nAnalyzing velocity distribution functions.\nAppending DCCRG arrays to VLSV files.\nConverting selected domain and variables from VLSV into VTK format for data analysis and visualization in ParaView and VisIt.\nMonitoring Vlasiator run log files.","category":"page"},{"location":"","page":"Home","title":"Home","text":"warning: Warning\nThis package mostly aims at supporting Vlasiator 5.0+. Older versions of Vlasiator has different naming standards for outputs, and is not guaranteed to work. The full naming standards are described in the analysator wiki page.","category":"page"},{"location":"#What-is-Vlasiator","page":"Home","title":"What is Vlasiator","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"Vlasiator solves the Vlasov–Maxwell system of equations for ions while assuming massless electrons under quasi-neutrality. The fundamental description of charged particle motion in an electromagnetic field is given by the Vlasov equation","category":"page"},{"location":"","page":"Home","title":"Home","text":"fracpartial f_alphapartial t + mathbfvcdotfracpartial f_alphapartial mathbfr + fracq_alpham_alpha(mathbfE+mathbfvtimesmathbfB)cdot fracpartial f_alphapartial mathbfv = 0","category":"page"},{"location":"","page":"Home","title":"Home","text":"where alpha denotes the particle species, mathbfr and mathbfv are the spatial and velocity coordinates, f_alpha(mathbfrmathbfvt) is the six-dimensional phase-space density of a particle species with mass m_alpha and charge q_alpha, and acceleration mathbfa is given by the Lorentz force with mathbfE and mathbfB are the electric and magnetic field, respectively.","category":"page"},{"location":"","page":"Home","title":"Home","text":"The zeroth and first moments of plasma, ion density n_alpha and velocity mathbfu_alpha, are obtained as integrals of the ion velocity distribution function","category":"page"},{"location":"","page":"Home","title":"Home","text":"beginaligned\nn_alpha = int f_alpha(mathbfrmathbfvt)mathrmdmathbfv \nmathbfu_alpha = frac1n_alphaint mathbfvf_alpha(mathbfrmathbfvt)mathrmdmathbfv\nendaligned","category":"page"},{"location":"","page":"Home","title":"Home","text":"The magnetic field is updated using Faraday's law:","category":"page"},{"location":"","page":"Home","title":"Home","text":"nabla times mathbfE = -fracpartial mathbfBpartial t","category":"page"},{"location":"","page":"Home","title":"Home","text":"and the electric field is given by the generalized Ohm's law:","category":"page"},{"location":"","page":"Home","title":"Home","text":"mathbfE = -mathbfu_alpha timesmathbfB + frac1n_alpha q_alphamathbfjtimesmathbfB - frac1n_alpha q_alphanablacdotoverleftrightarrowP_e + eta mathbfj","category":"page"},{"location":"","page":"Home","title":"Home","text":"The four terms on the right-handed side are the convection term, the Hall term, the electron pressure gradient term, and the resistive term, respectively. The total current density mathbfj is obtained from Ampère's law where the displacement current has been neglected:","category":"page"},{"location":"","page":"Home","title":"Home","text":"nablatimesmathbfB = mu_0 mathbfj","category":"page"},{"location":"","page":"Home","title":"Home","text":"Finally, by determining the electron pressure tensor by using an appropriate equation of state, the evolution of the system can be followed in time. For example, let overleftrightarrowP_e = p_e overleftrightarrowI where p_e is the isotropic scalar electron pressure. In an isothermal process,","category":"page"},{"location":"","page":"Home","title":"Home","text":"p_e = n_e k_B T_e","category":"page"},{"location":"","page":"Home","title":"Home","text":"where n_e approx n_i and T_e is a constant. In an adiabatic process with index gamma,","category":"page"},{"location":"","page":"Home","title":"Home","text":"p_e n_e^gamma = textconst","category":"page"},{"location":"","page":"Home","title":"Home","text":"The different processes can be generalized into the polytropic process:","category":"page"},{"location":"","page":"Home","title":"Home","text":"p_e n_e^n = textconst","category":"page"},{"location":"","page":"Home","title":"Home","text":"When the ideal gas law applies, the polytropic index n=1 for an isothermal process, and n=gamma for an adiabatic process.","category":"page"},{"location":"","page":"Home","title":"Home","text":"For more details, please refer to Vlasov methods in space physics and astrophysics.","category":"page"},{"location":"#Getting-started","page":"Home","title":"Getting started","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"To install,","category":"page"},{"location":"","page":"Home","title":"Home","text":"julia> ]\npkg> add Vlasiator","category":"page"},{"location":"","page":"Home","title":"Home","text":"You can then use the package via","category":"page"},{"location":"","page":"Home","title":"Home","text":"julia> using Vlasiator","category":"page"},{"location":"#Visualization","page":"Home","title":"Visualization","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"PyPlot","category":"page"},{"location":"","page":"Home","title":"Home","text":"If you aim at using Matplotlib, besides adding PyPlot and the Vlasiator specific wrapper VlasiatorPyPlot, you should also link to a preinstalled Python version by setting the environment variable and building the PyCall package","category":"page"},{"location":"","page":"Home","title":"Home","text":"ENV[\"PYTHON\"]=\"your python executable\"\nPkg.build(\"PyCall\")","category":"page"},{"location":"","page":"Home","title":"Home","text":"If ENV[\"PYTHON\"] = \"\" before building, a private Python distribution will be installed via Miniconda. Details are described in automated matplotlib installation.","category":"page"},{"location":"","page":"Home","title":"Home","text":"Makie","category":"page"},{"location":"","page":"Home","title":"Home","text":"You can add Makie.jl and VlasiatorMakie.jl through the pkg manger. The sub-package VlasiatorMakie provides user recipes for Makie.","category":"page"},{"location":"","page":"Home","title":"Home","text":"Plots","category":"page"},{"location":"","page":"Home","title":"Home","text":"Add Plots.jl through the pkg manager. Built-in user recipes for Plots are provided.","category":"page"},{"location":"#Author","page":"Home","title":"Author","text":"","category":"section"},{"location":"","page":"Home","title":"Home","text":"This module is written by Hongyang Zhou. For citing Vlasiator.jl, please refer to (Image: DOI).","category":"page"},{"location":"contributing/#Contributing","page":"Contributing","title":"Contributing","text":"","category":"section"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"Try to explain your contribution with simple language.\nReferences are always welcome.\nFollow the coding standards in the source.","category":"page"},{"location":"contributing/#Reporting-issues","page":"Contributing","title":"Reporting issues","text":"","category":"section"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"If you are experiencing issues or have discovered a bug, please report it on GitHub. To make the resolution process easier, please include the version of Julia and Vlasiator.jl in your writeup. These can be found with two commands:","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"julia> versioninfo()\njulia> using Pkg; Pkg.status()","category":"page"},{"location":"contributing/#Feature-requests","page":"Contributing","title":"Feature requests","text":"","category":"section"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"If you have suggestions of improvement or algorithms that you would like to see implemented in Vlasiator.jl, please open an issue on GitHub. Suggestions as well as feature requests are very welcome.","category":"page"},{"location":"contributing/#Code-contribution","page":"Contributing","title":"Code contribution","text":"","category":"section"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"If you have code that you would like to contribute to Vlasiator.jl, that is awesome! Please open an issue before you create the pull request on GitHub so that we make sure your idea is aligned with our goals for the project.","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"After your idea is discussed and revised by maintainers, please get the development version of the project by typing the following in the package manager:","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"] activate @dev","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"This will create a fresh environment called @dev where you can play with the project components without compromising your normal user environment.","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"] dev Vlasiator","category":"page"},{"location":"contributing/","page":"Contributing","title":"Contributing","text":"This will clone all the project components in your ~/.julia folder so that you can modify it and submit a pull request on GitHub later. Don't hesitate to ask questions. We are looking forward to your contributions.","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/#demo_extract_magnetopause","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"","category":"section"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"This demo shows how to extract variables along the magnetopause defined by Bz == 0 from multiple frames.","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"julia -t 4 demo_magnetopause_2d_mt.jl","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"or","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"JULIA_NUM_THREADS=4 julia demo_magnetopause_2d_mt.jl","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"using Vlasiator, Glob\nusing Vlasiator: RE # Earth radius, [m]\nusing JLD2: jldsave\n\n\"\"\"\n extract_magnetopause_var(files; zmin=-4RE, zmax=4RE, verbose=true)\n\nExtract variables on the magnetopause defined by ``B_z = 0``.\n\"\"\"\nfunction extract_magnetopause_var(files; zmin=-4RE, zmax=4RE, verbose=true)\n nfiles = length(files)\n\n verbose && println(\"Number of files: $nfiles\")\n\n meta = load(files[1])\n\n x = LinRange{Float32}(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\n z = LinRange{Float32}(meta.coordmin[3], meta.coordmax[3], meta.ncells[3])\n\n z_range = let zmin_ = searchsortedfirst(z, zmin), zmax_ = searchsortedlast(z, zmax)\n zmin_:zmax_\n end\n\n x_crossing = zeros(Float32, length(z_range))\n z_crossing = z[z_range]\n\n cellids = Vector{Int}(undef, length(z_range))\n\n x_crossings = zeros(length(z_range), nfiles)\n v = zeros(3, length(z_range), nfiles)\n ey = zeros(length(z_range), nfiles)\n\n Threads.@threads for ifile in eachindex(files)\n verbose && println(\"$(files[ifile]) on thread $(Threads.threadid())\")\n meta = load(files[ifile])\n\n # Obtain thermal temperature\n b = meta[\"vg_b_vol\"]\n b = reshape(b, 3, meta.ncells[1], meta.ncells[3])\n\n # Extract the last point from right to left which fulfills Bz < 0\n for (i,k) in enumerate(z_range) # scan in z direction\n ind_ = findlast(>(0), @view b[3,:,k]) + 1 # count from upstream\n isnothing(ind_) && (ind_ = 1) # if not found then set to 1\n x_crossing[i] = x[ind_]\n end\n\n cellids = [ getcell(meta, [x_crossing[i], 0, z_crossing[i]])\n for i in eachindex(x_crossing, z_crossing) ]\n\n x_crossings[:,ifile] = x_crossing\n v[:,:,ifile] = readvariable(meta, \"proton/vg_v\", cellids)\n ey[:,ifile] = readvariable(meta, \"vg_e_vol\", cellids)[2,:]\n end\n\n z_crossing, x_crossings, v, ey\nend\n\n######\n\nfiles = glob(\"bulk*.vlsv\", \".\")\n\n@time z,x,v,ey = extract_magnetopause_var(files)\n\njldsave(\"magnetopause.jld2\"; z,x,v,ey)","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"","category":"page"},{"location":"examples/postprocess/demo_magnetopause_2d_mt/","page":"Extract variables along the magnetopause","title":"Extract variables along the magnetopause","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_log/#demo_log","page":"Log tracking","title":"Log tracking","text":"","category":"section"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"This is an example of extracting log file timing information and visualize them.","category":"page"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"using Vlasiator, Dates, Plots\n\n# plotly is nice for scanning through data interactively\nplotly()\n\nconst file = \"logfile.txt\"\n\ntimestamps, speed = readlog(file)\n\nscatter(timestamps, speed,\n markershape=:circle,\n #yaxis=:log10,\n xlabel=\"Time\", ylabel=\"Time per simulated second [s]\")","category":"page"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"","category":"page"},{"location":"examples/postprocess/demo_log/","page":"Log tracking","title":"Log tracking","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/#demo_plot_line2","page":"Plot variables along a line","title":"Plot variables along a line","text":"","category":"section"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"This demo shows how to plot variables along a line.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"using Vlasiator, PyPlot, Glob, Printf\nusing Vlasiator: RE # Earth radius [m]\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n nfiles = length(files)\n\n x1, x2 = 8.0, 29.0\n point1 = [x1, 0, 0] .* RE\n point2 = [x2, 0, 0] .* RE\n\n cellids, distances, coords =\n let meta = load(files[1])\n getcellinline(meta, point1, point2)\n end\n\n loc = range(x1, x2, length=length(cellids))\n\n ρmin, ρmax = 0.0, 10.0 # [amu/cc]\n vmin, vmax = -640.0, 0.0 # [km/s]\n pmin, pmax = 0.0, 1.82 # [nPa]\n bmin, bmax = -25.0, 60.0 # [nT]\n\n fontsize = 14\n\n fig, axs = plt.subplots(4, 1, figsize=(10, 15), sharex=true, constrained_layout=true)\n\n axs[end].set_xlim(x1, x2)\n\n axs[1].set_ylim(ρmin, ρmax)\n axs[2].set_ylim(vmin, vmax)\n axs[3].set_ylim(pmin, pmax)\n axs[4].set_ylim(bmin, bmax)\n for ax in axs\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axs[end].set_xlabel(\"x [Re]\"; fontsize)\n axs[1].set_ylabel(\"Density [amu/cc]\"; fontsize)\n axs[2].set_ylabel(\"Velocity [km/s]\"; fontsize)\n axs[3].set_ylabel(\"Pressure [nPa]\"; fontsize)\n axs[4].set_ylabel(\"Magnetic field [nT]\"; fontsize)\n\n # Loop over snapshots\n for (i, file) in enumerate(files)\n isfile(\"out/\"*file[end-8:end-5]*\".png\") && continue\n\n println(\"i = $i/$nfiles, file = $file\")\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1e9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1e9 # [nPa]\n\n bz = readvariable(meta, \"vg_b_vol\", cellids)[3,:] .* 1e9 #[nT]\n\n imagnetopause_ = findfirst(<(0.0), bz)\n\n axs[1].plot(loc, rho_extract ./ 1e6, label=\"Proton density\", color=\"#1f77b4\")\n vl1 = axs[1].vlines(loc[imagnetopause_], ρmin, ρmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[2].plot(loc, v_extract[1,:] ./ 1e3, label=\"Vx\", color=\"#1f77b4\")\n vl2 = axs[2].vlines(loc[imagnetopause_], vmin, vmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[3].plot(loc, pram_extract, label=\"Ram\", color=\"#1f77b4\")\n axs[3].plot(loc, p_extract, label=\"Thermal\", color=\"#ff7f0e\")\n vl3 = axs[3].vlines(loc[imagnetopause_], pmin, pmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n axs[4].plot(loc, bz, label=\"Bz\", color=\"#1f77b4\")\n hl4 = axs[4].hlines(0.0, loc[1], loc[end], colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n vl4 = axs[4].vlines(loc[imagnetopause_], bmin, bmax;\n colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n str_title = @sprintf \"t= %4.1fs\" meta.time\n axs[1].set_title(str_title; fontsize)\n\n axs[2].legend(;loc=\"upper right\", fontsize)\n axs[3].legend(;loc=\"upper left\", fontsize)\n axs[4].legend(;loc=\"upper right\", fontsize)\n\n savefig(\"out/\"*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n\n for ax in axs\n for line in ax.get_lines()\n line.remove()\n end\n end\n for line in (vl1, vl2, vl3, vl4, hl4)\n line.remove()\n end\n end\n\n close(fig)\n println(\"Finished!\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot/","page":"Plot variables along a line","title":"Plot variables along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/#demo_2d_bowshock_mt","page":"Extract bow shock location","title":"Extract bow shock location","text":"","category":"section"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"This demo shows how to extract the bow shock location from 2D equatorial run outputs and save into file. To run in multi-threading mode,","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"julia -t nthreads demo_bowshock_2d_mt.jl","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"or alternatively","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"JULIA_NUM_THREADS=$nthreads julia demo_bowshock_2d_mt.jl","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"using Vlasiator, Glob\nusing Vlasiator: RE # Earth radius, [m]\nusing JLD2: jldsave\n\n# Upstream solar wind temperature\nconst Tsw = 0.5e6 #[K]\n\nfunction extract_bowshock_position(files; verbose=true)\n nfiles = length(files)\n\n verbose && println(\"Number of files: $nfiles\")\n\n meta = load(files[1])\n\n x = LinRange{Float32}(meta.coordmin[1], meta.coordmax[1], meta.ncells[1])\n y = LinRange{Float32}(meta.coordmin[2], meta.coordmax[2], meta.ncells[2])\n\n close(meta.fid)\n\n # Only extract bow shock location near the front between y = ±20RE\n ymin_ = findlast(<(-20RE), y)\n ymax_ = findfirst(>(20RE), y)\n\n x_crossing = zeros(Float32, ymax_-ymin_+1, nfiles)\n y_crossing = y[ymin_:ymax_]\n\n Threads.@threads for ifile = 1:nfiles\n verbose && println(\"$(files[ifile]) on thread $(Threads.threadid())\")\n f = load(files[ifile])\n # Obtain thermal temperature\n T = f[\"T\"]\n close(f.fid)\n T = reshape(T, f.ncells[1], f.ncells[2])\n # Extract bow shock location from the 1st point which fulfills\n # the threshold: T > 4 * Tsw\n for (i,j) in enumerate(ymin_:ymax_) # scan in y direction\n ind_ = findlast(>(4*Tsw), @view T[:,j]) # count from upstream\n x_crossing[i,ifile] = x[ind_]\n end\n end\n\n return x_crossing, y_crossing\nend\n\n#####\nfiles = glob(\"bulk*.vlsv\", \".\")\n\n@time x_crossing, y_crossing = extract_bowshock_position(files)\n\njldsave(\"example.jld2\"; x_crossing, y_crossing)","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"","category":"page"},{"location":"examples/visualization/demo_bowshock_2d_mt/","page":"Extract bow shock location","title":"Extract bow shock location","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/#demo_vdf","page":"VDF","title":"VDF","text":"","category":"section"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"This demo shows how to plot the phase space density (i.e. velocity distribution function) near a given spatial location.","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"using VlasiatorPyPlot\nusing Vlasiator: RE # Earth radius [m]\n\nfunction main()\n file = \"bulk.0001347.vlsv\"\n meta = load(file)\n\n coordinates = [0.0, 0.0, 0.0]\n\n vdfslice(meta, coordinates; verbose=true)\n\n # Show the spatial distribution of cells with saved VDF\n cellswithVDF = getcellwithvdf(meta)\n locations = [getcellcoordinates(meta, cid) for cid in cellswithVDF]\n\n xcell = zeros(size(locations))\n ycell = similar(xcell)\n\n for i in eachindex(locations)\n xcell[i] = locations[i][1] / RE\n ycell[i] = locations[i][2] / RE\n end\n\n figure()\n pcolormesh(meta, \"vg_pressure\", colorscale=Linear)\n ax = plt.gca()\n ax.scatter(xcell, ycell, marker=\"+\", color=\"w\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"","category":"page"},{"location":"examples/visualization/demo_vdf_pyplot/","page":"VDF","title":"VDF","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_diff_extracting/#demo_3d_grid_diff","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"","category":"section"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"This demos shows how to extract differences between FsGrid and DCCRG variables from 3D data.","category":"page"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"using Vlasiator, PyPlot\nimport Vlasiator: RE\n\nfunction main()\n directory = \"./\"\n file = \"bulk1.0001284.vlsv\"\n # Box range for variation diff extraction\n extent = [0.0, 12.0, -7.0, 7.0] # default [-Inf, Inf, -Inf, Inf]\n\n normal = :y\n origin = 0.0\n axisunit = EARTH\n comp = 2\n\n meta = load(directory*file)\n\n pArgs = Vlasiator.set_args(meta, \"fg_e\", axisunit; normal, origin)\n e_fg = Vlasiator.prep2dslice(meta, \"fg_e\", normal, comp, pArgs)\n\n pArgs = Vlasiator.set_args(meta, \"vg_e_vol\", axisunit; normal, origin)\n e_vg = Vlasiator.prep2dslice(meta, \"vg_e_vol\", normal, comp, pArgs)\n\n x1, x2 = Vlasiator.get_axis(pArgs)\n\n range1, range2 =\n if axisunit == EARTH\n searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2]),\n searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\n else\n searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2]),\n searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\n end\n\n ## Visualization\n fig, ax = plt.subplots()\n\n diff = (e_fg[range1,range2] - e_vg[range1,range2])'\n\n c = ax.pcolormesh(x1[range1], x2[range2], diff,\n norm=matplotlib.colors.CenteredNorm(),\n cmap=matplotlib.cm.RdBu_r)\n\n if comp == 1\n fig.colorbar(c; ax, label=\"E_fg_x - E_vg_x [V/m]\")\n elseif comp == 2\n fig.colorbar(c; ax, label=\"E_fg_y - E_vg_y [V/m]\")\n elseif comp == 3\n fig.colorbar(c; ax, label=\"E_fg_z - E_vg_z [V/m]\")\n end\n\n ax.set_title(file)\n\n #savefig(\"test_diff.png\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"","category":"page"},{"location":"examples/visualization/demo_diff_extracting/","page":"Extract differences between FsGrid and DCCRG variables","title":"Extract differences between FsGrid and DCCRG variables","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"log/#FAQ","page":"FAQ","title":"FAQ","text":"","category":"section"},{"location":"log/#Test-Data","page":"FAQ","title":"Test Data","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"If you don't have VLSV data at hand, Vlasiator.jl provides some test data for you to begin with.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"using LazyArtifacts\n\nrootpath = artifact\"testdata\"\nfiles = joinpath.(rootpath, (\"bulk.1d.vlsv\", \"bulk.2d.vlsv\", \"bulk.amr.vlsv\"))","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"These are also used in the standard test. These will be automatically downloaded from vlsv_data if you run the package test locally.","category":"page"},{"location":"log/#Performance","page":"FAQ","title":"Performance","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"The VLSV loader inherits the basic structure from Analysator and is redesigned for performance.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"For general data reading, a dictionary is constructed for cell IDs and orderings for O(1) timings.\nIt is faster to read a bunch of cell IDs together, if possible, than to read each cell one-by-one.\nSpecific methods are provided for targeted tasks that are much faster than the generic approaches. For instance, extractsat for multi-frame static satellite extraction can be more than 10x faster than first reading the metadata and then extracting variables for each frame.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"For development, it is recommended to use PkgBenchmark.jl to run the test suite:","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"using PkgBenchmark, Vlasiator\nresults = benchmarkpkg(Vlasiator)","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"or if you want to compare the current status of the package against a different git version","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"judge(Vlasiator, \"97e3dca6b2474d7bdc5b62b5bf98ecf070516e5e\")","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"To export results to Markdown,","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"export_markdown(\"testresult\", results)","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"See more in the PkgBenchmark manual.","category":"page"},{"location":"log/#Precision","page":"FAQ","title":"Precision","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"For post-processing and data analysis purposes, it makes less sense to stick to double precisions, so we mostly use Float32 in Vlasiator.jl for numerical arrays. Several exceptions are:","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"physical constants are defined in Float64, since single precision only resolves up to ±3.4E+38, and it may go out of bound in the middle of calculation (e.g. plasma frequency).","category":"page"},{"location":"log/#Int-vs.-UInt","page":"FAQ","title":"Int vs. UInt","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"Integers but not unsigned integers shall be used for indexing, even though unsigned integers are tempting.","category":"page"},{"location":"log/#Memory","page":"FAQ","title":"Memory","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"Vlasiator output files can be large. If we have limited memory relative to the file size, Vlasiator.jl provide direct hard disk mapping through mmap in Julia. With this mechanism you never need to worry about unable to process data with small free memory. Besides, we found that proper usage of mmap can also speed up reading and reduce memory comsumption. However, without reinterpret we may encounter the alignment issue!","category":"page"},{"location":"log/#Parallelism","page":"FAQ","title":"Parallelism","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"The current design choice is to achieve optimal serial performance per file, and apply parallel processing across individual files. In most common cases, the time it takes for post-processing one snapshot is reasonably short, but the number of snapshots are large. Julia's built-in support for all kinds of parallelism paradigm (multithreading, multiprocessing, channel) and external support from packages (MPI.jl, Polyester.jl) can be relatively easily incorported to make the whole workflow parallel.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"multi-threading with @threads (recommended when working within one node)\nmulti-processing with pmap\nmulti-processing with RemoteChannel\nClusterManagers for multi-node jobs","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"See more in the examples.","category":"page"},{"location":"log/#VTK","page":"FAQ","title":"VTK","text":"","category":"section"},{"location":"log/","page":"FAQ","title":"FAQ","text":"VLSV is just an uncompressed binary format. If we convert VLSV to VTK through write_vtk, the generated VTK files, even the highest resolution one with every coarse cell mapping to the finest level, can be several times smaller than the original VLSV file.","category":"page"},{"location":"log/","page":"FAQ","title":"FAQ","text":"One drawback of this conversion is that it cannot deal with phase space outputs, i.e. VDFs.","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/#demo_1d2d_mp","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"","category":"section"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"This is an example for generating combined 1D/2D plots across multiple frames with multi-processing. To run on a single node,","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"julia -p $ncores demo_1d2d_mp_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"using Distributed, Glob\n@everywhere using Vlasiator, VlasiatorPyPlot, Printf, LaTeXStrings\n\n@assert matplotlib.__version__ ≥ \"3.4\" \"Require Matplotlib version 3.4+ to use subfigure!\"\n\n@everywhere struct Varminmax{T}\n \"Density, [amu/cc]\"\n ρmin::T\n ρmax::T\n \"Velocity, [km/s]\"\n vmin::T\n vmax::T\n \"Pressure, [nPa]\"\n pmin::T\n pmax::T\n \"Magnetic field, [nT]\"\n bmin::T\n bmax::T\n \"Electric field, [nT]\"\n emin::T\n emax::T\nend\n\n@everywhere function init_figure(loc, norms, ticks, pArgs1, varminmax)\n fig = plt.figure(myid(), constrained_layout=true, figsize=(12, 7.2))\n subfigs = fig.subfigures(1, 2, wspace=0.01, width_ratios=[2,1])\n\n axsL = subfigs[1].subplots(5, 1, sharex=true)\n axsR = subfigs[2].subplots(2, 1, sharex=true)\n\n # Set line plots' axes\n axsL[end].set_xlim(loc[1], loc[end])\n\n (;ρmin, ρmax, vmin, vmax, pmin, pmax, bmin, bmax, emin, emax) = varminmax\n\n axsL[1].set_ylim(ρmin, ρmax)\n axsL[2].set_ylim(vmin, vmax)\n axsL[3].set_ylim(pmin, pmax)\n axsL[4].set_ylim(bmin, bmax)\n axsL[5].set_ylim(emin, emax)\n for ax in axsL\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axsL[end].set_xlabel(L\"x [$R_E$]\"; fontsize=14)\n axsL[1].set_ylabel(\"n [amu/cc]\"; fontsize=14)\n axsL[2].set_ylabel(\"V [km/s]\"; fontsize=14)\n axsL[3].set_ylabel(\"P [nPa]\"; fontsize=14)\n axsL[4].set_ylabel(\"B [nT]\"; fontsize=14)\n axsL[5].set_ylabel(\"E [mV/m]\"; fontsize=14)\n\n fakeline = loc\n l1 = axsL[1].plot(loc, fakeline, label=\"Proton density\", color=\"#1f77b4\")\n l2 = axsL[2].plot(loc, fakeline, label=\"Vx\", color=\"#1f77b4\")\n l3 = axsL[2].plot(loc, fakeline, label=\"Vy\", color=\"#ff7f0e\")\n l4 = axsL[2].plot(loc, fakeline, label=\"Vz\", color=\"#2ca02c\")\n l5 = axsL[3].plot(loc, fakeline, label=\"Ram\", color=\"#1f77b4\")\n l6 = axsL[3].plot(loc, fakeline, label=\"Thermal\", color=\"#ff7f0e\")\n l7 = axsL[4].plot(loc, fakeline, label=\"Bx\", color=\"#1f77b4\")\n l8 = axsL[4].plot(loc, fakeline, label=\"By\", color=\"#ff7f0e\")\n l9 = axsL[4].plot(loc, fakeline, label=\"Bz\", color=\"#2ca02c\")\n l10= axsL[5].plot(loc, fakeline, label=\"Ex\", color=\"#1f77b4\")\n l11= axsL[5].plot(loc, fakeline, label=\"Ey\", color=\"#ff7f0e\")\n l12= axsL[5].plot(loc, fakeline, label=\"Ez\", color=\"#2ca02c\")\n\n ls = (l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12)\n\n axsL[2].legend(;loc=\"lower left\", ncol=3, frameon=false, fontsize=12)\n axsL[3].legend(;loc=\"upper right\", ncol=2, frameon=false, fontsize=12)\n axsL[4].legend(;loc=\"upper right\", ncol=3, frameon=false, fontsize=12)\n axsL[5].legend(;loc=\"lower right\", ncol=3, frameon=false, fontsize=12)\n\n vl1 = axsL[1].vlines(loc[1], ρmin, ρmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl2 = axsL[2].vlines(loc[1], vmin, vmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl3 = axsL[3].vlines(loc[1], pmin, pmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl4 = axsL[4].vlines(loc[1], bmin, bmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl5 = axsL[5].vlines(loc[1], emin, emax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n hl2 = axsL[2].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n hl4 = axsL[4].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n hl5 = axsL[5].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n\n vlines = (vl1, vl2, vl3, vl4, vl5)\n\n for ax in axsR\n ax.set_aspect(\"equal\")\n\n # Set border line widths\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\n edge = get(ax.spines, loc, nothing)\n edge.set_linewidth(2.0)\n end\n ax.xaxis.set_tick_params(width=2.0, length=3)\n ax.yaxis.set_tick_params(width=2.0, length=3)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n\n ax.set_ylabel(pArgs1.stry; fontsize=14)\n end\n\n axsR[2].set_xlabel(pArgs1.strx; fontsize=14)\n\n axsR[1].set_title(\"Alfvén speed\", fontsize=14)\n axsR[2].set_title(\"Sound speed\", fontsize=14)\n\n x, y = Vlasiator.get_axis(pArgs1)\n fakedata = fill(NaN32, length(y), length(x))\n\n c1 = axsR[1].pcolormesh(x, y, fakedata, norm=norms[1], cmap=matplotlib.cm.turbo)\n c2 = axsR[2].pcolormesh(x, y, fakedata, norm=norms[2], cmap=matplotlib.cm.turbo)\n\n rInner = 31.8e6 # [m]\n circle1 = plt.Circle((0, 0), rInner/Vlasiator.RE, facecolor=\"w\", edgecolor=\"tab:purple\")\n circle2 = plt.Circle((0, 0), rInner/Vlasiator.RE, facecolor=\"w\", edgecolor=\"tab:purple\")\n axsR[1].add_patch(circle1)\n axsR[2].add_patch(circle2)\n\n im_ratio = length(y)/length(x)\n fraction = 0.046 * im_ratio\n\n cb1 = colorbar(c1; ax=axsR[1], ticks=ticks[1], fraction, pad=0.02, extend=\"max\")\n cb1.ax.set_ylabel(\"[km/s]\"; fontsize=14)\n\n cb2 = colorbar(c2; ax=axsR[2], ticks=ticks[2], fraction, pad=0.02, extend=\"max\")\n cb2.ax.set_ylabel(\"[km/s]\"; fontsize=14)\n\n fig.suptitle(\"Density Pulse Run\", fontsize=\"x-large\")\n\n cs = (c1, c2)\n\n return fig, subfigs, ls, vlines, cs\nend\n\n@everywhere function update_vline(h, x)\n seg_old = h.get_segments()\n ymin = seg_old[1][1, 2]\n ymax = seg_old[1][2, 2]\n\n seg_new = [[x ymin; x ymax]]\n\n h.set_segments(seg_new)\nend\n\n@everywhere function update_plot!(subfigs, ls, vlines, cs, outdir, file, cellids, loc)\n isfile(outdir*file[end-8:end-5]*\".png\") && return\n\n println(\"file = $(basename(file))\")\n meta = load(file)\n\n rho = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v = readvariable(meta, \"proton/vg_v\", cellids)\n p = readvariable(meta, \"vg_pressure\", cellids) .* 1f9 |> vec # [nPa]\n\n vmag2 = sum(x -> x*x, v, dims=1) |> vec\n pram = rho .* Vlasiator.mᵢ .* vmag2 .* 1f9 # [nPa]\n\n b = readvariable(meta, \"vg_b_vol\", cellids) .* 1f9 #[nT]\n e = readvariable(meta, \"vg_e_vol\", cellids) .* 1f3 #[mV/m]\n\n ls[1][1].set_ydata(rho ./ 1f6)\n ls[2][1].set_ydata(@views v[1,:] ./ 1f3)\n ls[3][1].set_ydata(@views v[2,:] ./ 1f3)\n ls[4][1].set_ydata(@views v[3,:] ./ 1f3)\n ls[5][1].set_ydata(pram)\n ls[6][1].set_ydata(p)\n ls[7][1].set_ydata(@view b[1,:])\n ls[8][1].set_ydata(@view b[2,:])\n ls[9][1].set_ydata(@view b[3,:])\n ls[10][1].set_ydata(@view e[1,:])\n ls[11][1].set_ydata(@view e[2,:])\n ls[12][1].set_ydata(@view e[3,:])\n\n imagnetopause_ = findfirst(<(0.0), @views b[3,:])\n for vline in vlines\n update_vline(vline, loc[imagnetopause_])\n end\n\n str_title = @sprintf \"Sun-Earth line, t= %4.1fs\" meta.time\n subfigs[1].suptitle(str_title, fontsize=\"x-large\")\n\n data = Vlasiator.prep2d(meta, \"VA\", :z)'\n cs[1].set_array(data ./ 1f3)\n\n data = Vlasiator.prep2d(meta, \"VS\", :z)'\n cs[2].set_array(data ./ 1f3)\n\n savefig(outdir*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n return\nend\n\nfunction make_jobs(files)\n for f in files\n put!(jobs, f)\n end\nend\n\n@everywhere function do_work(jobs, status,\n outdir, loc, norms, ticks, pArgs1, cellids, varminmax)\n\n fig, subfigs, ls, vlines, cs = init_figure(loc, norms, ticks, pArgs1, varminmax)\n while true\n file = take!(jobs)\n update_plot!(subfigs, ls, vlines, cs, outdir, file, cellids, loc)\n put!(status, true)\n end\n close(fig)\nend\n\n################################################################################\nfiles = glob(\"bulk*.vlsv\", \".\")\n\nnfile = length(files)\n# Set output directory\nconst outdir = \"1d2d/\"\n\n# Set contour plots' axes\naxisunit = EARTH\n# Upper/lower limits for each variable\nρmin, ρmax = 0.0, 14.0 # [amu/cc]\nvmin, vmax = -620.0, 150.0 # [km/s]\npmin, pmax = 0.0, 2.8 # [nPa]\nbmin, bmax = -60.0, 60.0 # [nT]\nemin, emax = -8.0, 8.0 # [mV/m]\nvamin, vamax = 50.0, 600.0 # [km/s]\nvsmin, vsmax = 50.0, 600.0 # [km/s]\n\nvarminmax = Varminmax(ρmin, ρmax, vmin, vmax, pmin, pmax, bmin, bmax, emin, emax)\n\nmeta = load(files[1])\n\npArgs1 = Vlasiator.set_args(meta, \"VA\", axisunit; normal=:none)\nnorm1, ticks1 = set_colorbar(Linear, vamin, vamax)\nnorm2, ticks2 = set_colorbar(Linear, vsmin, vsmax)\n\nconst norms = (norm1, norm2)\nconst ticks = (ticks1, ticks2)\n\nconst jobs = RemoteChannel(()->Channel{String}(nfile))\nconst status = RemoteChannel(()->Channel{Bool}(nworkers()))\n\nxmin, xmax = 7.0, 17.0 # Earth radii\npoint1 = [xmin, 0, 0] .* Vlasiator.RE\npoint2 = [xmax, 0, 0] .* Vlasiator.RE\n\nmeta = load(files[1])\ncellids, _, _ = getcellinline(meta, point1, point2)\nloc = range(xmin, xmax, length=length(cellids))\n\nprintln(\"Total number of files: $nfile\")\nprintln(\"Running with $(nworkers()) workers...\")\n\n@async make_jobs(files) # Feed the jobs channel with all files to process.\n\n@sync for p in workers()\n @async remote_do(do_work, p, jobs, status,\n outdir, loc, norms, ticks, pArgs1, cellids, varminmax)\nend\n\nlet n = nfile\n t = @elapsed while n > 0 # wait for all jobs to complete\n take!(status)\n n -= 1\n end\n println(\"Finished in $(round(t, digits=2))s.\")\nend","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"","category":"page"},{"location":"examples/visualization/demo_1d2d_mp_pyplot/","page":"Combined plots with multi-processing","title":"Combined plots with multi-processing","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/#demo_virtual_sats","page":"Virtual satellites","title":"Virtual satellites","text":"","category":"section"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"This demo shows how to extract data for virtual satellites at multiple locations. Outputs are stored in binary format for sharing within Julia.","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"Usage:","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"julia -t nthreads demo_pointsextracting.jl","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"or","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"JULIA_NUM_THREADS=nthreads julia demo_pointsextracting.jl","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"using Glob, Vlasiator\nusing Vlasiator: RE # Earth radius, [m]\nusing JLD2: jldsave\n\nfunction extract_vars(files, locations)\n nfiles = length(files)\n nlocs = length(locations)\n # variables to be extracted\n t = zeros(Float32, nfiles)\n rho = zeros(Float32, nlocs, nfiles)\n v = zeros(Float32, 3, nlocs, nfiles)\n p = zeros(Float32, nlocs, nfiles)\n b = zeros(Float32, 3, nlocs, nfiles)\n e = zeros(Float32, 3, nlocs, nfiles)\n\n ids = Vector{Int}(undef, nlocs)\n load(files[1]) do meta\n for iloc in eachindex(locations)\n ids[iloc] = getcell(meta, locations[iloc])\n end\n end\n\n # Extract data from each frame\n Threads.@threads for i = eachindex(files)\n meta = load(files[i])\n t[i] = meta.time\n rho[:,i] = readvariable(meta, \"proton/vg_rho\", ids)\n v[:,:,i] = readvariable(meta, \"proton/vg_v\", ids)\n p[ :,i] = readvariable(meta, \"vg_pressure\", ids)\n b[:,:,i] = readvariable(meta, \"vg_b_vol\", ids)\n e[:,:,i] = readvariable(meta, \"vg_e_vol\", ids)\n end\n\n # Save into binary file\n jldsave(\"satellites.jld2\"; locations, t, rho, v, p, b, e)\nend\n\n#####\n\nfiles = glob(\"bulk*.vlsv\", \"./\")\n\n# virtual satellite locations\nconst locations = [[7RE, 0, 0], [9RE, 0, 0], [11RE, 0, 0], [12RE, 0, 0],\n [13RE, 0, 0], [14RE, 0, 0], [15RE, 0, 0], [16RE, 0, 0], [17RE, 0, 0],\n [29.3RE, 0, 0]]\n\nprintln(\"Number of files: $(length(files))\")\nprintln(\"Number of virtual satellites: $(length(locations))\")\nprintln(\"Running with $(Threads.nthreads()) threads...\")\n\n@time extract_vars(files, locations)\n\nprintln(\"Virtual satellite extraction done!\")","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"","category":"page"},{"location":"examples/postprocess/demo_pointsextracting/","page":"Virtual satellites","title":"Virtual satellites","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/postprocess/demo_convert2vti/#demo_convertvtk","page":"Converting to VTK","title":"Converting to VTK","text":"","category":"section"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"To convert VLSV time series files to VTK image files using multithreads,","category":"page"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"using Vlasiator, Glob\n\nfiles = glob(\"*.vlsv\")\n\nThreads.@threads for file in files\n @info file, Threads.threadid()\n write_vtk(file; vti=true)\nend","category":"page"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"","category":"page"},{"location":"examples/postprocess/demo_convert2vti/","page":"Converting to VTK","title":"Converting to VTK","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/#demo_2d_contour_mp","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"","category":"section"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"This demo shows how to generate 2D colored contours with multi-processing. To run on a single node,","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"julia -p $ncores demo_2d_mp_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"using Distributed, ParallelDataTransfer, Glob\r\n@everywhere using Vlasiator, VlasiatorPyPlot, Printf, LaTeXStrings\r\n\r\n@everywhere function init_figure(cmaps, norms, ticks, pArgs1, extent)\r\n fig, axs = plt.subplots(2, 3; num=myid(),\r\n figsize=(13.5, 9.5), sharex=true, sharey=true, constrained_layout=true)\r\n\r\n for ax in axs\r\n ax.set_aspect(\"equal\")\r\n # Set border line widths\r\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\r\n edge = get(ax.spines, loc, nothing)\r\n edge.set_linewidth(2.0)\r\n end\r\n ax.xaxis.set_tick_params(width=2.0, length=3)\r\n ax.yaxis.set_tick_params(width=2.0, length=3)\r\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\r\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\r\n end\r\n\r\n for ax in axs[end,:]\r\n ax.set_xlabel(pArgs1.strx; fontsize)\r\n end\r\n for ax in axs[:,1]\r\n ax.set_ylabel(pArgs1.stry; fontsize)\r\n end\r\n\r\n titles = (\"Density\", \"Pth\", \"Vx\", \"Bz\", \"Vz\", \"E\")\r\n\r\n for (ax, title) in zip(axs, titles)\r\n ax.set_title(title; fontsize)\r\n end\r\n\r\n x1, x2 = Vlasiator.get_axis(pArgs1)\r\n\r\n range1 = searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2])\r\n range2 = searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\r\n\r\n fakedata = zeros(Float32, length(range2), length(range1))\r\n\r\n c1 = axs[1,1].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[1], cmap=cmaps[1])\r\n c2 = axs[1,2].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[2], cmap=cmaps[2])\r\n c3 = axs[1,3].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[3], cmap=cmaps[2])\r\n c4 = axs[2,1].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[4], cmap=cmaps[1])\r\n c5 = axs[2,2].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[5], cmap=cmaps[2])\r\n c6 = axs[2,3].pcolormesh(x1[range1], x2[range2], fakedata;\r\n norm=norms[6], cmap=cmaps[1])\r\n\r\n cs = (c1, c2, c3, c4, c5, c6)\r\n\r\n format = matplotlib.ticker.FormatStrFormatter(\"%.1f\")\r\n\r\n cb1 = colorbar(c1; ax=axs[1,1], ticks=ticks[1], format)\r\n cb2 = colorbar(c2; ax=axs[1,2], ticks=ticks[2])\r\n cb3 = colorbar(c3; ax=axs[1,3], ticks=ticks[3])\r\n cb4 = colorbar(c4; ax=axs[2,1], ticks=ticks[4], format)\r\n cb5 = colorbar(c5; ax=axs[2,2], ticks=ticks[5], format, extend=\"both\")\r\n cb6 = colorbar(c6; ax=axs[2,3], ticks=ticks[6], extend=\"max\")\r\n\r\n ylabels = (\"[amu/cc]\", \"[km/s]\", \"[km/s]\", \"[nPa]\", \"[nT]\", \"[mV/m]\")\r\n\r\n for (i, cb) in enumerate((cb1, cb2, cb3, cb4, cb5, cb6))\r\n cb.ax.set_ylabel(ylabels[i]; fontsize)\r\n cb.outline.set_linewidth(1.0)\r\n end\r\n\r\n return fig, cs, range1, range2\r\nend\r\n\r\n@everywhere function update_plot!(fig, cs, range1, range2, outdir, file)\r\n isfile(outdir*file[end-8:end-5]*\".png\") && return\r\n\r\n println(\"file = $file\")\r\n meta = load(file)\r\n\r\n data = Vlasiator.prep2d(meta, \"proton/vg_rho\", :mag)'\r\n cs[1].set_array(data[range2,range1] ./ 1f6)\r\n\r\n data = Vlasiator.prep2d(meta, \"proton/vg_v\", :x)'\r\n cs[2].set_array(data[range2,range1] ./ 1f3)\r\n\r\n data = Vlasiator.prep2d(meta, \"proton/vg_v\", :z)'\r\n cs[3].set_array(data[range2,range1] ./ 1f3)\r\n\r\n data = Vlasiator.prep2d(meta, \"vg_pressure\", :mag)'\r\n cs[4].set_array(data[range2,range1] .* 1f9)\r\n\r\n data = Vlasiator.prep2d(meta, \"vg_b_vol\", :z)'\r\n cs[5].set_array(data[range2,range1] .* 1f9)\r\n\r\n data = Vlasiator.prep2d(meta, \"vg_e_vol\", :mag)'\r\n cs[6].set_array(data[range2,range1] .* 1f3)\r\n\r\n str_title = @sprintf \"Density pulse run, t= %4.1fs\" meta.time\r\n fig.suptitle(str_title; fontsize=\"xx-large\")\r\n\r\n savefig(outdir*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\r\nend\r\n\r\nfunction make_jobs(files)\r\n for f in files\r\n put!(jobs, f)\r\n end\r\nend\r\n\r\n@everywhere function do_work(jobs, status, outdir, cmaps, norms, ticks, pArgs1, extent)\r\n fig, cs, range1, range2 = init_figure(cmaps, norms, ticks, pArgs1, extent)\r\n while true\r\n file = take!(jobs)\r\n update_plot!(fig, cs, range1, range2, outdir, file)\r\n put!(status, true)\r\n end\r\n close(fig)\r\nend\r\n\r\n################################################################################\r\nfiles = glob(\"bulk*.vlsv\", \".\")\r\n\r\nnfile = length(files)\r\n# Set output directory\r\nconst outdir = \"contour/\"\r\n\r\n# Set colormaps for continuous and divergent data\r\nconst cmaps = (matplotlib.cm.turbo, matplotlib.cm.RdBu_r)\r\nconst axisunit = EARTH\r\nconst extent = [0., 20., -20., 20.] # [RE], default: [-Inf32, Inf32, -Inf32, Inf32]\r\n\r\n# Plotting range for each variable\r\nconst ρmin, ρmax = 0.1, 15.0 # [amu/cc]\r\nconst vxmin, vxmax = -650.0, 650.0 # [km/s]\r\nconst vzmin, vzmax = -500.0, 500.0 # [km/s]\r\nconst pmin, pmax = 0.0, 3.6 # [nPa]\r\nconst bmin, bmax = -60.0, 60. # [nT]\r\nconst emin, emax = 0.0, 20. # [mV/m]\r\n\r\nmeta = load(files[1])\r\n\r\npArgs1 = Vlasiator.set_args(meta, \"proton/vg_rho\", axisunit; normal=:none)\r\n\r\nnorm1, ticks1 = set_colorbar(Linear, ρmin, ρmax)\r\nnorm2, ticks2 = set_colorbar(Linear, vxmin, vxmax)\r\nnorm3, ticks3 = set_colorbar(Linear, vzmin, vzmax)\r\nnorm4, ticks4 = set_colorbar(Linear, pmin, pmax)\r\nnorm5, ticks5 = set_colorbar(Linear, bmin, bmax)\r\nnorm6, ticks6 = set_colorbar(Linear, emin, emax)\r\n\r\nconst norms = (norm1, norm2, norm3, norm4, norm5, norm6)\r\nconst ticks = (ticks1, ticks2, ticks3, ticks4, ticks5, ticks6)\r\n\r\nconst jobs = RemoteChannel(()->Channel{String}(nfile))\r\nconst status = RemoteChannel(()->Channel{Bool}(nworkers()))\r\n\r\n@broadcast begin\r\n const fontsize = \"x-large\"\r\nend\r\n\r\nprintln(\"Total number of files: $nfile\")\r\nprintln(\"Running with $(nworkers()) workers...\")\r\n\r\n@async make_jobs(files) # Feed the jobs channel with all files to process.\r\n\r\n@sync for p in workers()\r\n @async remote_do(do_work, p, jobs, status, outdir, cmaps, norms, ticks, pArgs1, extent)\r\nend\r\n\r\nlet n = nfile\r\n t = @elapsed while n > 0 # wait for all jobs to complete\r\n take!(status)\r\n n -= 1\r\n end\r\n println(\"Finished in $(round(t, digits=2))s.\")\r\nend","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"","category":"page"},{"location":"examples/visualization/demo_2d_mp_pyplot/","page":"2D contour plots with multi-processing","title":"2D contour plots with multi-processing","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/#demo_2d_contour_animation","page":"2D contour plot animation","title":"2D contour plot animation","text":"","category":"section"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"This example shows how to plot 2D colored contours with pcolormesh. ffmpeg is required to be installed for saving into mp4.","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"using Vlasiator, Glob, VlasiatorPyPlot, Printf\n\nfiles = glob(\"bulk*.vlsv\", \".\")\nconst var = \"proton/vg_rho\"\nconst comp = 0 # vector component for plotting (if applicable)\n\nfig = plt.figure(figsize=(6.4,5.1), constrained_layout=true)\n\nax = plt.axes()\n\nconst axisunit = EARTH\nconst colorscale = Log\nconst addcolorbar = true\n# Choose colormap\nconst cmap = matplotlib.cm.turbo\n# Set data plotting range\nconst vmin = 7.0e4\nconst vmax = 2.5e6\n\nmeta = load(files[1])\n\npArgs = Vlasiator.set_args(meta, var, axisunit; normal=:none)\n\nnorm, ticks = set_colorbar(colorscale, vmin, vmax)\n\nc = let\n x1, x2 = Vlasiator.get_axis(pArgs)\n fakedata = zeros(Float32, length(x2), length(x1))\n ax.pcolormesh(x1, x2, fakedata; norm, cmap)\nend\n\nVlasiator.set_plot(c, ax, pArgs, ticks, addcolorbar)\n\nfunction animate(i::Int, files::Vector{String}, var::String, comp::Int, c)\n meta = load(files[i+1])\n t = readparameter(meta, \"time\")\n data = Vlasiator.prep2d(meta, var, comp)'\n c.set_array(data)\n\n str_title = @sprintf \"t= %4.1fs\" t\n ax.set_title(str_title, fontweight=\"bold\")\n\n return (c,)\nend\n\n# https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html\nanim = matplotlib.animation.FuncAnimation(fig, animate, fargs=(files, var, comp, c),\n frames=length(files), blit=true,\n repeat_delay=1000, interval=50)\n# Make sure ffmpeg is available!\nanim.save(\"contour.mp4\", writer=\"ffmpeg\", fps=30)","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"","category":"page"},{"location":"examples/visualization/demo_2d_animation_pyplot/","page":"2D contour plot animation","title":"2D contour plot animation","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/#demo_1d2d","page":"Combined plots","title":"Combined plots","text":"","category":"section"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"To generate combined 1D/2D plots across multiple frames,","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"using Vlasiator, VlasiatorPyPlot, Glob, Printf, LaTeXStrings\nusing Vlasiator: set_args, prep2d\n\n@assert VERSION ≥ v\"1.7.0\" \"Compatible with Julia v1.7+!\"\n@assert matplotlib.__version__ >= \"3.4\" \"Require Matplotlib version 3.4+ to use subfigure!\"\n\n\nstruct Varminmax{T}\n \"Density, [amu/cc]\"\n ρmin::T\n ρmax::T\n \"Velocity, [km/s]\"\n vmin::T\n vmax::T\n \"Pressure, [nPa]\"\n pmin::T\n pmax::T\n \"Magnetic field, [nT]\"\n bmin::T\n bmax::T\n \"Electric field, [nT]\"\n emin::T\n emax::T\n \"Alfven speed, [km/s]\"\n vamin::T\n vamax::T\n \"Sonic speed, [km/s]\"\n vsmin::T\n vsmax::T\nend\n\nfunction init_figure(varminmax, loc, pArgs)\n (; ρmin, ρmax, vmin, vmax, pmin, pmax, bmin, bmax, emin, emax,\n vamin, vamax, vsmin, vsmax) = varminmax\n\n fig = plt.figure(constrained_layout=true, figsize=(12, 7.2))\n subfigs = fig.subfigures(1, 2, wspace=0.01, width_ratios=[2,1])\n\n axsL = subfigs[1].subplots(5, 1, sharex=true)\n axsR = subfigs[2].subplots(2, 1, sharex=true)\n\n # Set line plots' axes\n axsL[end].set_xlim(loc[1], loc[end])\n\n axsL[1].set_ylim(ρmin, ρmax)\n axsL[2].set_ylim(vmin, vmax)\n axsL[3].set_ylim(pmin, pmax)\n axsL[4].set_ylim(bmin, bmax)\n axsL[5].set_ylim(emin, emax)\n for ax in axsL\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.grid(true)\n end\n\n axsL[end].set_xlabel(L\"x [$R_E$]\"; fontsize=14)\n axsL[1].set_ylabel(\"n [amu/cc]\"; fontsize=14)\n axsL[2].set_ylabel(\"V [km/s]\"; fontsize=14)\n axsL[3].set_ylabel(\"P [nPa]\"; fontsize=14)\n axsL[4].set_ylabel(\"B [nT]\"; fontsize=14)\n axsL[5].set_ylabel(\"E [mV/m]\"; fontsize=14)\n\n fakeline = loc\n l1 = axsL[1].plot(loc, fakeline, label=\"Proton density\", color=\"#1f77b4\")\n l2 = axsL[2].plot(loc, fakeline, label=\"Vx\", color=\"#1f77b4\")\n l3 = axsL[2].plot(loc, fakeline, label=\"Vy\", color=\"#ff7f0e\")\n l4 = axsL[2].plot(loc, fakeline, label=\"Vz\", color=\"#2ca02c\")\n l5 = axsL[3].plot(loc, fakeline, label=\"Ram\", color=\"#1f77b4\")\n l6 = axsL[3].plot(loc, fakeline, label=\"Thermal\", color=\"#ff7f0e\")\n l7 = axsL[4].plot(loc, fakeline, label=\"Bx\", color=\"#1f77b4\")\n l8 = axsL[4].plot(loc, fakeline, label=\"By\", color=\"#ff7f0e\")\n l9 = axsL[4].plot(loc, fakeline, label=\"Bz\", color=\"#2ca02c\")\n l10= axsL[5].plot(loc, fakeline, label=\"Ex\", color=\"#1f77b4\")\n l11= axsL[5].plot(loc, fakeline, label=\"Ey\", color=\"#ff7f0e\")\n l12= axsL[5].plot(loc, fakeline, label=\"Ez\", color=\"#2ca02c\")\n\n ls = (l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12)\n\n axsL[2].legend(;loc=\"lower left\", ncol=3, frameon=false, fontsize=12)\n axsL[3].legend(;loc=\"upper left\", ncol=2, frameon=false, fontsize=12)\n axsL[4].legend(;loc=\"upper right\", ncol=3, frameon=false, fontsize=12)\n axsL[5].legend(;loc=\"lower right\", ncol=3, frameon=false, fontsize=12)\n\n vl1 = axsL[1].vlines(loc[1], ρmin, ρmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl2 = axsL[2].vlines(loc[1], vmin, vmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl3 = axsL[3].vlines(loc[1], pmin, pmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl4 = axsL[4].vlines(loc[1], bmin, bmax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n vl5 = axsL[5].vlines(loc[1], emin, emax; colors=\"r\", linestyle=\"dashed\", alpha=0.5)\n\n hl2 = axsL[2].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n hl4 = axsL[4].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n hl5 = axsL[5].hlines(0.0, loc[1], loc[end]; colors=\"k\", linestyle=\"dashed\", alpha=0.2)\n\n vlines = (vl1, vl2, vl3, vl4, vl5)\n\n for ax in axsR\n ax.set_aspect(\"equal\")\n\n # Set border line widths\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\n edge = get(ax.spines, loc, nothing)\n edge.set_linewidth(2.0)\n end\n ax.xaxis.set_tick_params(width=2.0, length=3)\n ax.yaxis.set_tick_params(width=2.0, length=3)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n\n ax.set_ylabel(L\"Y [$R_E$]\"; fontsize=14)\n end\n\n axsR[2].set_xlabel(L\"X [$R_E$]\"; fontsize=14)\n\n axsR[1].set_title(\"Alfven speed\", fontsize=14)\n axsR[2].set_title(\"Sound speed\", fontsize=14)\n\n x, y = Vlasiator.get_axis(pArgs)\n fakedata = fill(NaN32, length(y), length(x))\n\n cnorm1, cticks1 = set_colorbar(Linear, vamin, vamax)\n cnorm2, cticks2 = set_colorbar(Linear, vsmin, vsmax)\n cmap = matplotlib.cm.turbo\n\n c1 = axsR[1].pcolormesh(x, y, fakedata; norm=cnorm1, cmap)\n c2 = axsR[2].pcolormesh(x, y, fakedata; norm=cnorm2, cmap)\n\n rInner = 31.8e6 # [m]\n circle1 = plt.Circle((0, 0), rInner/Vlasiator.RE, color=\"w\")\n circle2 = plt.Circle((0, 0), rInner/Vlasiator.RE, color=\"w\")\n axsR[1].add_patch(circle1)\n axsR[2].add_patch(circle2)\n\n cb1 = colorbar(c1; ax=axsR[1], ticks=cticks1, fraction=0.046, pad=0.04, extend=\"max\")\n cb1.ax.set_ylabel(\"[km/s]\"; fontsize=14)\n\n cb2 = colorbar(c2; ax=axsR[2], ticks=cticks2, fraction=0.046, pad=0.04)\n cb2.ax.set_ylabel(\"[km/s]\"; fontsize=14)\n\n #fig.suptitle(\"Density Pulse Run\", fontsize=\"xx-large\")\n\n cs = (c1, c2)\n\n return fig, subfigs, ls, vlines, cs\nend\n\n\n\"Update frame.\"\nfunction update_plot!(plotargs, outdir, file)\n isfile(outdir*file[end-8:end-5]*\".png\") && return\n\n fig, subfigs, ls, vlines, cs = plotargs\n\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1f9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1f9 # [nPa]\n\n bz = readvariable(meta, \"vg_b_vol\", cellids)[3,:] .* 1f9 #[nT]\n\n ls[1][1].set_ydata(rho_extract ./ 1f6)\n ls[2][1].set_ydata(v_extract[1,:] ./ 1f3)\n ls[3][1].set_ydata(pram_extract)\n ls[4][1].set_ydata(p_extract)\n ls[5][1].set_ydata(bz)\n\n imagnetopause_ = findfirst(<(0.0), bz)\n for vline in vlines\n update_vline(vline, loc[imagnetopause_])\n end\n\n str_title = @sprintf \"Sun-Earth line, t= %4.1fs\" meta.time\n subfigs[1].suptitle(str_title, fontsize=14)\n\n data = prep2d(meta, \"VA\", :z)'\n cs[1].update(Dict(\"array\" => data ./ 1e3))\n\n data = prep2d(meta, \"VS\", :z)'\n cs[2].update(Dict(\"array\" => data ./ 1e3))\n\n savefig(outdir*file[end-8:end-5]*\".png\", bbox_inches=\"tight\", dpi=100)\n return\nend\n\nfunction update_vline(h, x)\n seg_old = h.get_segments()\n ymin = seg_old[1][1, 2]\n ymax = seg_old[1][2, 2]\n\n seg_new = [[x ymin; x ymax]]\n\n h.set_segments(seg_new)\nend\n\n####### Main\n\nfiles = glob(\"bulk*.vlsv\", \".\")\nnfile = length(files)\n# Set output directory\nconst outdir = \"out/\"\n\nmeta = load(files[1])\n\nconst x1, x2 = 7.0, 18.0 # Earth radii\nconst point1 = [x1, 0, 0] .* Vlasiator.RE\nconst point2 = [x2, 0, 0] .* Vlasiator.RE\n\ncellids, distances, coords = getcellinline(meta, point1, point2)\n\nloc = range(x1, x2, length=length(cellids))\n\npArgs = set_args(meta, \"fakename\", RE; normal=:none)\n\n# Upper/lower limits for each variable\nρmin, ρmax = 0.0, 10.0 # [amu/cc]\nvmin, vmax = -640.0, 100.0 # [km/s]\npmin, pmax = 0.0, 1.82 # [nPa]\nbmin, bmax = -25.0, 60.0 # [nT]\nemin, emax = -5.0, 5.0 # [mV/m]\nvamin, vamax = 0.0, 250.0 # [km/s]\nvsmin, vsmax = 0.0, 400.0 # [km/s]\n\nvarminmax =\n Varminmax(ρmin, ρmax, vmin, vmax, pmin, pmax, bmin, bmax, emin, emax,\n vamin, vamax, vsmin, vsmax)\n\n\nplotargs = init_figure(varminmax, loc, pArgs)\n\n# Loop over snapshots\nfor (i, file) in enumerate(files)\n println(\"i = $i/$nfile, file = $(basename(file))\")\n update_plot!(plotargs, outdir, file)\nend\n\nclose(plotargs[1])\nprintln(\"Finished!\")","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"","category":"page"},{"location":"examples/visualization/demo_1d2d_pyplot/","page":"Combined plots","title":"Combined plots","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"gallery/#Gallery","page":"Gallery","title":"Gallery","text":"","category":"section"},{"location":"gallery/#PyPlot","page":"Gallery","title":"PyPlot","text":"","category":"section"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density in a laminar flow with points denoting cell centers. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density of Earth's magnetosphere in the meridional cut from 2D simulation, with fieldlines through fixed seeding points. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density of Earth's magnetosphere in the meridional plane from 3D simulation.","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density of Earth's magnetosphere in the equatorial plane from 2D simulation, zoomed in to the magnetosheath and foreshock region, with streamlines and density contour at 10 amu/cc. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton density of Earth's magnetosphere in the normal cut planes from 3D simulation. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton phase space distribution projected onto the X-Z plane. demo","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/#Makie","page":"Gallery","title":"Makie","text":"","category":"section"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Demos can be found in the Usage section of VlasiatorMakie.","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Various colored contours from 2D equatorial run","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Interactive proton density slice from 3D AMR run","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Three orthogonal slices of proton density from 3D AMR run","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Isosurface of Bz = 0 from 3D AMR run","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton phase space distribution projected onto the X-Z plane","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Interactive proton phase space distribution in the three orthogonal planes","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"Proton phase space distribution","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/#ParaView","page":"Gallery","title":"ParaView","text":"","category":"section"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"VLSV files can be converted to the structured VTK format, and then visualized in ParaView.","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"2D slice contour of density in the meriodional plane with streamlines","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"2D slices of density viewing from upstream","category":"page"},{"location":"gallery/","page":"Gallery","title":"Gallery","text":"(Image: )","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/#demo_2d_fieldlines_mp","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"","category":"section"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"This demo shows how to plot field lines with handpicked seeds via multi-processing. To run on a single node,","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"julia -p $ncores demo_fieldline_mp_pyplot.jl","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"using Distributed, ParallelDataTransfer, Glob\n@everywhere using Vlasiator, VlasiatorPyPlot, PyCall, Printf, LaTeXStrings, FieldTracer\n@everywhere using Vlasiator: RE\n\nfunction generate_seeds(coordmin, coordmax, dim_, nseeds)\n seeds = Matrix{Float64}(undef, 2, nseeds)\n for i in 1:nseeds\n seeds[1,i] = coordmin[dim_[1]] +\n (coordmax[dim_[1]] - coordmin[dim_[1]]) / nseeds * (i - 1)\n seeds[2,i] = -20RE\n end\n seeds\nend\n\n@everywhere function init_figure(pArgs, norm, ticks, seeds, extent)\n fig, ax = plt.subplots(1, 1; num=myid(),\n figsize=(6, 8), constrained_layout=true)\n\n fontsize = \"x-large\"\n\n ax.set_aspect(\"equal\")\n # Set border line widths\n for loc in (\"left\", \"bottom\", \"right\", \"top\")\n edge = get(ax.spines, loc, nothing)\n edge.set_linewidth(2.0)\n end\n ax.xaxis.set_tick_params(width=2.0, length=3)\n ax.yaxis.set_tick_params(width=2.0, length=3)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n\n ax.set_xlabel(pArgs.strx; fontsize)\n ax.set_ylabel(pArgs.stry; fontsize)\n\n ax.set_title(\"Density\"; fontsize)\n\n x1, x2 = Vlasiator.get_axis(pArgs)\n\n range1 = searchsortedfirst(x1, extent[1]):searchsortedlast(x1, extent[2])\n range2 = searchsortedfirst(x2, extent[3]):searchsortedlast(x2, extent[4])\n\n fakedata = zeros(Float32, length(range2), length(range1))\n c = ax.pcolormesh(x1[range1], x2[range2], fakedata; norm, cmap=matplotlib.cm.turbo)\n\n format = matplotlib.ticker.FormatStrFormatter(\"%.1f\")\n cb1 = colorbar(c; ax, ticks, format)\n cb1.ax.set_ylabel(\"[amu/cc]\"; fontsize)\n cb1.outline.set_linewidth(1.0)\n\n fakeline = [0.0, 1.0]\n ls = [ax.plot(fakeline, fakeline, color=\"w\") for _ in 1:size(seeds,2)]\n\n return fig, ax, c, ls, range1, range2\nend\n\n@everywhere function update_plot!(ax, c, ls, range1, range2, dim_, seeds, grid1, grid2,\n outdir, file)\n isfile(outdir*file[end-8:end-5]*\".png\") && return\n\n println(\"file = $file\")\n meta = load(file)\n\n data = Vlasiator.prep2d(meta, \"proton/vg_rho\", :mag)'\n c.set_array(data[range2,range1] ./ 1f6)\n\n str_title = @sprintf \"Density pulse run, t= %4.1fs\" meta.time\n ax.set_title(str_title; fontsize=\"x-large\")\n\n b = meta[\"vg_b_vol\"]\n b1 = reshape(b[dim_[1],:], meta.ncells[dim_[1]], meta.ncells[dim_[2]])\n b2 = reshape(b[dim_[2],:], meta.ncells[dim_[1]], meta.ncells[dim_[2]])\n # Find existing arrow annotations\n annotations = [child for child in ax.get_children() if\n pybuiltin(:isinstance)(child, matplotlib.text.Annotation)]\n # Remove existing arrows\n for a in annotations\n a.remove()\n end\n # Add new arrows along field lines\n for i in axes(seeds,2)\n startx, starty = seeds[:,i]\n x1, y1 = trace(b1, b2, startx, starty, grid1, grid2;\n ds=0.5, maxstep=4000, gridtype=\"ndgrid\")\n x1 ./= RE\n y1 ./= RE\n if length(x1) < 5; continue; end\n ls[i][1].set_xdata(x1)\n ls[i][1].set_ydata(y1)\n add_arrow(ls[i][1])\n end\n\n savefig(outdir*file[end-8:end-5]*\".png\", bbox_inches=\"tight\")\nend\n\nfunction make_jobs(files)\n for f in files\n put!(jobs, f)\n end\nend\n\n@everywhere function do_work(jobs, status,\n outdir, pArgs, norm, ticks, grid1, grid2, dim_, seeds, extent)\n\n fig, ax, c, ls, range1, range2 = init_figure(pArgs, norm, ticks, seeds, extent)\n\n while true\n file = take!(jobs)\n update_plot!(ax, c, ls, range1, range2, dim_, seeds, grid1, grid2, outdir, file)\n put!(status, true)\n end\n close(fig)\nend\n\n################################################################################\nfiles = glob(\"bulk*.vlsv\", \".\")\n\nnfile = length(files)\n# Set output directory\nconst outdir = \"out/\"\n\nconst jobs = RemoteChannel(()->Channel{String}(nfile))\nconst status = RemoteChannel(()->Channel{Bool}(nworkers()))\n\nconst axisunit = EARTH # contour plot axes unit\nconst extent = [0., 20., -20., 20.] # [RE], default: [-Inf32, Inf32, -Inf32, Inf32]\n\n# Upper/lower limits for each variable\nconst ρmin, ρmax = 0.0, 11.0 # [amu/cc]\n\nmeta = load(files[1])\n# Construct pieces for plotting\npArgs = Vlasiator.set_args(meta, \"proton/vg_rho\", axisunit; normal=:none)\nnorm, ticks = set_colorbar(Linear, ρmin, ρmax)\n\n# Mark spatial dimensions\nconst dim_ = pArgs.stry[1] == 'Z' ? (1,3) : (1,2)\n\n(;coordmin, coordmax, ncells) = meta\n\n# Generate regular Cartesian range\ngrid1 = range(coordmin[dim_[1]], coordmax[dim_[1]], length=ncells[dim_[1]])\ngrid2 = range(coordmin[dim_[2]], coordmax[dim_[2]], length=ncells[dim_[2]])\n# Generate seeds for in-plane field line tracing\nconst nseeds = 10\nseeds = generate_seeds(coordmin, coordmax, dim_, nseeds)\n\n\nprintln(\"Total number of files: $nfile\")\nprintln(\"Running with $(nworkers()) workers...\")\n\n@async make_jobs(files) # Feed the jobs channel with all files to process.\n\n@sync for p in workers()\n @async remote_do(do_work, p, jobs, status,\n outdir, pArgs, norm, ticks, grid1, grid2, dim_, seeds, extent)\nend\n\nlet n = nfile\n t = @elapsed while n > 0 # wait for all jobs to complete\n take!(status)\n n -= 1\n end\n println(\"Finished in $(round(t, digits=2))s.\")\nend","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"","category":"page"},{"location":"examples/visualization/demo_B_fieldline_mp_pyplot/","page":"Field lines with customized seeds via multi-processing","title":"Field lines with customized seeds via multi-processing","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"benchmark/#Benchmarks","page":"Benchmarks","title":"Benchmarks","text":"","category":"section"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"The test file information are listed below:","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Index Filename Number of Cells Dimension AMR Public\n1 1d_single.vlsv 20 1 No Yes\n2 bulk.2d.vlsv 6,300 1 No Yes\n3 2d_double.vlsv 51,200 2 No Yes\n4 2d_AFC.vlsv 4,612,500 2 No Yes\n5 3d_EGI.vlsv 3,966,580 3 Yes No","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Access to the public data can be found from vlsv_data.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"note: Note\nThe numbers shown here are comparisons between Analysator v0.9 and Vlasiator.jl v0.9.32 running Python 3.6.9/3.9.7 and Julia 1.8.3 with the scripts perf.jl and perf.py. The timings are collected from a i5-10210U @ 1.6GHz CPU with 16 GB RAM if not specified.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Loading meta data[1]","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Julia [ms] Python [ms] Ratio\n1 0.18 1.19 6.6\n2 0.51 1.66 3.1\n3 2.33 3.11 1.3\n4 506 277 0.5\n5 549 283 0.5","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[1]: See the issue about sorting. The performance of EzXML is also not ideal: we may need to find a better XML parser in Julia.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Reading DCCRG grid variables","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Julia [ms] Python [ms] Ratio\n1 0.004 0.07 17\n2 0.02[2] 0.08 4\n3 0.17[2] 0.21 1.2\n4 20[2] 23 1.1\n5 11[2] 11 1.0","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[2]: Vlasiator.jl can be faster if there is no conversion from Float64 to Float32. See Precision.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Reading field solver grid variables[3]","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Size Julia [s] Julia, mmap [s] Python [s] Ratio\n5 6.2 GiB Float32 18 8 56 7","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[3]: The field solver grid is a regular Cartesian grid at the finest refinement level introduced after Vlasiator 5. Therefore fsgrid variables are quite large for 3D AMR runs: with limited memory (e.g. 16 GB RAM) you may encounter out-of-memory issues when reading fg_b more than once. In Vlasiator.jl, we provide the option usemmap=true for reading large arrays –- see Memory for more.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Plotting 2D density contours on a uniform mesh (no GUI)","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Julia [s] Python [s] Ratio\n4 0.5 5.4 11","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Plotting 2D density slices from a 3D AMR mesh (no GUI)","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"File Index Julia [s][4] Python [s] Ratio\n5 0.5 3.1 6.2","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[4]: The first time execution will be slower due to JIT compilation (which is excluded in the timing here). This is known as \"Time-To-First-X\" in the Julia community.","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Static virtual satellite tracking from 3D AMR data (26G per frame, 32 MB Cell IDs) on a cluster[5]","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"Frames Julia, 1 thread [s] Julia, 2 threads [s] Python [s]\n845 45 34 1220","category":"page"},{"location":"benchmark/","page":"Benchmarks","title":"Benchmarks","text":"[5]: University of Helsinki cluster Vorna with Intel Xeon E5-2697 @ 2.70GHz.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/#demo_plot_line","page":"Plot variable along a line","title":"Plot variable along a line","text":"","category":"section"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"This demo shows how to plot pressure along a line across multiple frames.","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"using Vlasiator, PyPlot, Glob, Printf\nusing Vlasiator: RE # Earth radius [m]\n\nfunction main()\n files = glob(\"bulk*.vlsv\", \".\")\n nfile = length(files)\n\n x1, x2 = 8.0, 29.0\n point1 = [x1, 0, 0] .* RE\n point2 = [x2, 0, 0] .* RE\n\n cellids, distances, coords =\n load(files[1]) do meta\n getcellinline(meta, point1, point2)\n end\n\n fig, ax = plt.subplots(figsize=(8, 4.8))\n\n for (i, file) in enumerate(files)\n println(\"i = $i/$nfile, file = $file\")\n meta = load(file)\n\n p_extract = readvariable(meta, \"vg_pressure\", cellids) .* 1e9 |> vec # [nPa]\n rho_extract = readvariable(meta, \"proton/vg_rho\", cellids) |> vec\n v_extract = readvariable(meta, \"proton/vg_v\", cellids)\n vmag2_extract = sum(x -> x*x, v_extract, dims=1) |> vec\n pram_extract = rho_extract .* Vlasiator.mᵢ .* vmag2_extract .* 1e9 # [nPa]\n loc = range(x1, x2, length=length(rho_extract))\n\n ax.plot(loc, pram_extract, label=\"ram\")\n ax.plot(loc, p_extract, label=\"thermal\")\n\n ax.set_xlim(x1, x2)\n ax.set_ylim(0.0, 1.8)\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n grid(true)\n\n xlabel(\"x [Re]\", fontsize=14)\n ylabel(\"Pressure [nPa]\", fontsize=14)\n str_title = @sprintf \"t= %4.1fs\" meta.time\n title(str_title, fontsize=14)\n legend(loc=\"upper left\", fontsize=14)\n savefig(\"out/\"*meta.name[end-8:end-5]*\".png\", bbox_inches=\"tight\")\n ax.cla()\n end\n\n close(fig)\n println(\"plot finished!\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"","category":"page"},{"location":"examples/visualization/demo_lineextracting_pyplot_basic2/","page":"Plot variable along a line","title":"Plot variable along a line","text":"This page was generated using DemoCards.jl.","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/#demo_vector_comps","page":"Vector components","title":"Vector components","text":"","category":"section"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"(Image: Author) (Image: Update time)","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"This demo shows how to plot the components of a vector from one snapshot.","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"using Vlasiator, VlasiatorPyPlot, LaTeXStrings, Printf\n\nfunction main()\n file = \"/wrk/group/spacephysics/vlasiator/2D/ABA/bulk/bulk.0001000.vlsv\"\n\n axisunit = EARTH\n colorscale = Linear\n cmap = matplotlib.cm.RdBu\n\n var = \"B_vol\"\n\n #####\n meta = load(file)\n\n pArgs = Vlasiator.set_args(meta, var, axisunit; normal=:none)\n\n x, y = Vlasiator.get_axis(pArgs)\n\n B = meta[\"B_vol\"] # [T]\n bx = @views B[1,:].*1e9\n bx = reshape(bx, meta.ncells[1], meta.ncells[2])\n by = @views B[2,:].*1e9\n by = reshape(by, meta.ncells[1], meta.ncells[2])\n bz = @views B[3,:].*1e9\n bz = reshape(bz, meta.ncells[1], meta.ncells[2])\n\n V = (bx, by, bz)\n V_str = (\"Bx\", \"By\", \"Bz\")\n\n # Symmetric range for diverging colormap\n vmin = minimum(minimum.(V))\n vmax = -vmin\n\n cnorm1, cticks1 = set_colorbar(colorscale, vmin, vmax)\n\n fig, axs = subplots(1,3,\n figsize=(10, 4), sharex=true, sharey=true, constrained_layout=true)\n\n c1 = axs[1].pcolormesh(x, y, V[1]'; norm=cnorm1, cmap)\n\n for i in eachindex(axs)[2:end]\n axs[i].pcolormesh(x, y, V[i]'; norm=cnorm1, cmap)\n end\n\n for (i, ax) in enumerate(axs)\n ax.set_aspect(\"equal\")\n ax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n ax.set_title(V_str[i])\n ax.set_xlabel(L\"x [$R_E$]\")\n end\n\n axs[1].set_ylabel(L\"y [$R_E$]\")\n\n # One colorbar for all subplots\n cb1 = colorbar(c1; ax=axs, ticks=cticks1, fraction=0.046, pad=0.04)\n cb1.ax.set_ylabel(\"[nT]\")\n cb1.outline.set_linewidth(1.0)\n\n str_title = @sprintf \"B at t = %4.1fs\" meta.time\n\n fig.suptitle(str_title, fontsize=\"xx-large\")\n\n savefig(\"Bvector.png\", bbox_inches=\"tight\")\nend\n\nmain()","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"","category":"page"},{"location":"examples/visualization/demo_vector_pyplot/","page":"Vector components","title":"Vector components","text":"This page was generated using DemoCards.jl.","category":"page"}] }