pion-reader 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,972 @@
1
+ import sys
2
+ import os
3
+ import matplotlib.pyplot as plt
4
+ import astropy.units as u
5
+ import numpy as np
6
+ from .pion2yt import pion2yt
7
+ import yt
8
+ from yt.visualization.volume_rendering.api import PointSource
9
+
10
+ yt.set_log_level("ERROR")
11
+ #print(plt.style.available)
12
+ #plt.style.use('classic')
13
+
14
+ from matplotlib import ticker
15
+ from matplotlib import cm
16
+ from mpl_toolkits.axes_grid1 import ImageGrid
17
+ from matplotlib.colorbar import Colorbar
18
+ import sys
19
+ import pathlib
20
+
21
+ home = str(pathlib.Path.home())
22
+ #from misc.make_movies import make_movies
23
+ from datetime import datetime
24
+
25
+
26
+ class yt_example_plots(pion2yt):
27
+
28
+ # Constructor
29
+ def __init__(self,
30
+ data_path,
31
+ file_base,
32
+ img_dir,
33
+ sim_name,
34
+ quantities=["density"]):
35
+
36
+ #self.p2y = pion2yt
37
+
38
+ self.evolution = self.make_snapshots(
39
+ data_path, file_base) # list of all snapshots
40
+ self.data_path = data_path # path to data
41
+ self.file_base = file_base # base of filename
42
+ self.img_dir = img_dir # path to save images
43
+ self.sim_name = sim_name
44
+ if not os.path.exists(self.img_dir):
45
+ os.makedirs(self.img_dir)
46
+ print("Created images directory:{} ".format(self.img_dir))
47
+ else:
48
+ print("Images directory already exists")
49
+ self.quantities = quantities # list of quantities to include in dataset
50
+
51
+ def get_nframes(self):
52
+ return self.evolution.shape[0]
53
+
54
+ ###########################################################################
55
+ def plot_projected_quantity(self, i, plot_quantity, ds_quantities,
56
+ north_vec, norm, **kwargs):
57
+ print(f"Loading dataset: Sim Snapshot {i}")
58
+ ds = self.get_ds(self.evolution[i], ds_quantities)
59
+ time = (ds.current_time.to("Myr"))
60
+ print(time)
61
+ print(f"Successfully Loaded dataset: {str(ds)}")
62
+ print(f"Plotting {plot_quantity} for snapshot {i}...")
63
+ prj = yt.OffAxisProjectionPlot(ds,
64
+ normal=norm,
65
+ north_vector=north_vec,
66
+ fields=("gas", plot_quantity))
67
+ prj.set_cmap(("gas", plot_quantity), kwargs.get("cmap", "viridis"))
68
+ prj.set_figure_size(kwargs.get("figsize", 5))
69
+ # prj.set_zlim(("gas", plot_quantity), kwargs.get("zlim", None))
70
+
71
+ fig = prj.export_to_mpl_figure(
72
+ (1, 1), cbar_mode="single") # export to matplotlib figure
73
+ ax = fig.axes[0]
74
+ #ax.set_xlabel("x (AU)")
75
+ #ax.set_ylabel("y (AU)")
76
+ st = r"$t=$ = " + f"{time:.5f}"
77
+ ax.text(0.1,
78
+ 0.9,
79
+ st,
80
+ color="black",
81
+ fontsize=8,
82
+ transform=ax.transAxes,
83
+ bbox=dict(facecolor='white',
84
+ edgecolor='black',
85
+ boxstyle='round,pad=1',
86
+ alpha=0.5))
87
+ num = str(i).zfill(5)
88
+ print(f"Saving image {self.sim_name}_{plot_quantity}_{num}.png...")
89
+ fig.savefig(os.path.join(self.img_dir,
90
+ f"{self.sim_name}_{plot_quantity}_{num}.png"),
91
+ dpi=300,
92
+ bbox_inches="tight")
93
+ #return fig
94
+
95
+ ###########################################################################
96
+ def temp_quantity_plotter(self, plot_quantity, ds_quantities, north_vec,
97
+ norm, **kwargs):
98
+ self.plot_indices = self.three_slice_indices(
99
+ ) # list of indices for pre-periastron, periastron, and post-periastron snapshots
100
+ num = 0
101
+ for index in self.plot_indices:
102
+ fig = self.plot_projected_quantity(index, plot_quantity,
103
+ ds_quantities, north_vec, norm,
104
+ **kwargs)
105
+ fig.savefig(os.path.join(
106
+ self.img_dir, f"{self.sim_name}_{plot_quantity}_{index}.png"),
107
+ dpi=300,
108
+ bbox_inches="tight")
109
+ num += 1
110
+
111
+ ###########################################################################
112
+ def plot_grid_plot(self, i):
113
+ print(f"Loading dataset: Sim Snapshot {i}")
114
+ ds = self.get_ds(self.evolution[i], quantities=["density"])
115
+ time = (ds.current_time.to("Myr"))
116
+ print(time)
117
+ print(f"Successfully Loaded dataset: {str(ds)}")
118
+ print(f"Plotting SMR grid for snapshot {i}...")
119
+ slc = yt.SlicePlot(ds, "z", "density")
120
+
121
+ slc.set_cmap("density", "GnBu")
122
+ slc.set_figure_size(5)
123
+ slc.zoom(1)
124
+ slc.set_log("density", True)
125
+ #slc.set_zlim("density", )
126
+ slc.annotate_grids(linewidth=1, edgecolors="black")
127
+ slc.annotate_cell_edges(line_width=0.00001, alpha=0.6, color="black")
128
+ # slc.set_font({"family": "times new roman"})
129
+ slc.set_font({"family": "Sans", "size": 14, "weight": "normal"})
130
+ fig = slc.export_to_mpl_figure(
131
+ (1, 1), cbar_mode="single") # export to matplotlib figure
132
+ ax = fig.axes[0]
133
+ t = ax.get_xlabel()
134
+ ax.set_xlabel(t, weight='bold') # not working because it is mathmode
135
+
136
+ #ax.legend(loc="upper right", frameon=True, framealpha=1, facecolor="white", fontsize=14)
137
+ num = str(i).zfill(5)
138
+ fig.savefig(os.path.join(self.img_dir,
139
+ f"{self.sim_name}_grid_{num}.png"),
140
+ dpi=300,
141
+ bbox_inches="tight")
142
+ fig.savefig(os.path.join(self.img_dir,
143
+ f"{self.sim_name}_grid_{num}.pdf"),
144
+ dpi=300,
145
+ bbox_inches="tight")
146
+
147
+ ###########################################################################
148
+ def plot_Bfield_XY(self, i, dmin, dmax):
149
+ print(f"Loading dataset: Sim Snapshot {i}")
150
+ ds = self.get_ds(self.evolution[i],
151
+ quantities=["density", "magnetic_field"])
152
+ time = (ds.current_time.to("Myr"))
153
+ print(time)
154
+ print(f"Successfully Loaded dataset: {str(ds)}")
155
+ print(f"Plotting rho+B for snapshot {i}...")
156
+ # Coordinates are in (z,y,x) ordering.
157
+ #slc = yt.SlicePlot(ds, "z", "density", width=(4.5, "pc"),origin="native")
158
+ slc = yt.SlicePlot(ds, "z", "density", origin="native")
159
+ slc.set_cmap("density", "viridis")
160
+ slc.set_figure_size(5)
161
+ slc.set_log("density", True)
162
+ slc.set_zlim(("gas", "density"),
163
+ zmin=(dmin, "g/cm**3"),
164
+ zmax=(dmax, "g/cm**3"))
165
+ slc.annotate_streamlines(("gas", "magnetic_field_x"),
166
+ ("gas", "magnetic_field_y"),
167
+ color="white",
168
+ factor=1,
169
+ density=1.5)
170
+ #slc.annotate_grids()
171
+ #slc.annotate_line_integral_convolution(("gas", "magnetic_field_x"), ("gas", "magnetic_field_y"),lim=(0.5,0.65))
172
+
173
+ fig = slc.export_to_mpl_figure(
174
+ (1, 1), cbar_mode="single") # export to matplotlib figure
175
+ ax = fig.axes[0]
176
+ #ax.set_xlabel("x (pc)")
177
+ #ax.set_ylabel("y (pc)")
178
+ #num = "{:05.4f}".format(time.value) + " Myr"
179
+ num = "{:05.4f}".format(time)
180
+ ax.text(0.725, 0.95, num, transform=ax.transAxes, fontsize=16)
181
+
182
+ num = str(i).zfill(5)
183
+
184
+ fig.savefig(os.path.join(
185
+ self.img_dir, f"{self.sim_name}_Bfield_contours_XY_{num}.png"),
186
+ dpi=300,
187
+ bbox_inches="tight")
188
+ plt.close(fig)
189
+
190
+ ###########################################################################
191
+ def plot_Bfield_ZX(self, i, dmin, dmax):
192
+ print(f"Loading dataset: Sim Snapshot {i}")
193
+ ds = get_ds(self.evolution[i],
194
+ quantities=["density", "magnetic_field"])
195
+ time = (ds.current_time.to("Myr"))
196
+ print(time)
197
+ print(f"Successfully Loaded dataset: {str(ds)}")
198
+ print(f"Plotting rho+B for snapshot {i}...")
199
+ # Coordinates are in (z,y,x) ordering.
200
+ # plot density
201
+ #slc = yt.SlicePlot(ds, "y", "density", width=(4.5, "pc"),origin="native")
202
+ slc = yt.SlicePlot(ds, "y", "density", origin="native")
203
+ slc.swap_axes()
204
+ slc.set_cmap("density", "viridis")
205
+ slc.set_figure_size(5)
206
+ slc.set_log("density", True)
207
+ slc.set_zlim(("gas", "density"),
208
+ zmin=(dmin, "g/cm**3"),
209
+ zmax=(dmax, "g/cm**3"))
210
+ # add streamlines
211
+ slc.annotate_streamlines(("gas", "magnetic_field_z"),
212
+ ("gas", "magnetic_field_x"),
213
+ color="white",
214
+ factor=1,
215
+ density=1.5)
216
+ #slc.hide_colorbar("density")
217
+ #slc.annotate_grids()
218
+ #slc.annotate_line_integral_convolution(("gas", "magnetic_field_x"), ("gas", "magnetic_field_y"),lim=(0.5,0.65))
219
+
220
+ fig = slc.export_to_mpl_figure(
221
+ (1, 1), cbar_mode="single") # export to matplotlib figure
222
+ ax = fig.axes[0]
223
+ #ax.set_xlabel("x (pc)")
224
+ #ax.set_ylabel("z (pc)")
225
+ num = "{:05.4f}".format(time.value) + " Myr"
226
+ ax.text(0.725, 0.95, num, transform=ax.transAxes, fontsize=16)
227
+
228
+ num = str(i).zfill(5)
229
+ fig.savefig(os.path.join(
230
+ self.img_dir, f"{self.sim_name}_Bfield_contours_ZX_{num}.png"),
231
+ dpi=300,
232
+ bbox_inches="tight")
233
+ plt.close(fig)
234
+
235
+ ###########################################################################
236
+ def plot_Bfield_Bmag(self, i, bmin, bmax, zoom):
237
+ print(f"Loading dataset: Sim Snapshot {i}")
238
+ ds = self.get_ds(self.evolution[i], quantities=["magnetic_field"])
239
+ time = (ds.current_time.to("Myr"))
240
+ print(time)
241
+ print(f"Successfully Loaded dataset: {str(ds)}")
242
+ print(f"Plotting rho+B for snapshot {i}...")
243
+
244
+ fig = plt.figure()
245
+ grid = ImageGrid(fig, (0.075, 0.075, 0.85, 0.85),
246
+ nrows_ncols=(1, 2),
247
+ axes_pad=0.075,
248
+ label_mode="all",
249
+ share_all=True,
250
+ cbar_mode="single",
251
+ cbar_location="right",
252
+ cbar_size="7%",
253
+ cbar_pad="28%")
254
+
255
+ # first plot: XZ plane, on the left
256
+ #slc1 = yt.SlicePlot(ds, "y", "magnetic_field_magnitude", width=(4.5, "pc"),origin="native")
257
+ slc1 = yt.SlicePlot(ds,
258
+ "z",
259
+ "magnetic_field_magnitude",
260
+ origin="native")
261
+ #slc1.set_font({'family': 'serif', 'style': 'normal', 'weight': 'normal', 'size': 12})
262
+ slc1.swap_axes()
263
+ slc1.set_cmap("magnetic_field_magnitude", "magma")
264
+ slc1.set_zlim(("gas", "magnetic_field_magnitude"),
265
+ zmin=(bmin, "G"),
266
+ zmax=(bmax, "G"))
267
+ slc1.set_log("magnetic_field_magnitude", True)
268
+ slc1.zoom(zoom)
269
+ slc1.set_figure_size(7)
270
+ #slc1.hide_colorbar()
271
+ st = r"$t=$ " + f"{time:.3f}"
272
+ slc1.annotate_text([0.325, 0.25],
273
+ st,
274
+ coord_system="figure",
275
+ text_args={
276
+ "color": "black",
277
+ "fontsize": 12
278
+ },
279
+ inset_box_args={
280
+ 'boxstyle': 'square',
281
+ 'pad': 0.3,
282
+ 'facecolor': 'white',
283
+ 'linewidth': 1,
284
+ 'edgecolor': 'black',
285
+ 'alpha': 0.5
286
+ }) # , fontsize=14
287
+ # add streamlines
288
+ slc1.annotate_streamlines(("gas", "magnetic_field_z"),
289
+ ("gas", "magnetic_field_x"),
290
+ color="white",
291
+ factor=zoom,
292
+ density=1.3)
293
+ #slc1.annotate_line_integral_convolution(("gas", "magnetic_field_x"), ("gas", "magnetic_field_y"),lim=(0.5,0.65))
294
+
295
+ plot1 = slc1.plots['magnetic_field_magnitude']
296
+ plot1.figure = fig
297
+ plot1.axes = grid[0].axes
298
+ plot1.cax = grid.cbar_axes[0]
299
+
300
+ slc1._setup_plots()
301
+ plot1.axes.tick_params(which="major",
302
+ direction="inout",
303
+ width=1,
304
+ length=8)
305
+ plot1.axes.tick_params(which="minor",
306
+ direction="in",
307
+ width=1,
308
+ length=2)
309
+ #plot1.axes.yaxis.set_label_coords(-0.1,0.5)
310
+ #plot1.axes.xaxis.set_label_coords(0.5,-0.1)
311
+
312
+ # second plot: XY plane, on the right
313
+ #slc2 = yt.SlicePlot(ds, "z", "magnetic_field_magnitude", width=(4.5, "pc"),origin="native")
314
+ slc2 = yt.SlicePlot(ds,
315
+ "z",
316
+ "magnetic_field_magnitude",
317
+ origin="native")
318
+ #slc2.set_font({'family': 'serif', 'style': 'normal', 'weight': 'normal', 'size': 12})
319
+ slc2.set_cmap("magnetic_field_magnitude", "magma")
320
+ slc2.set_figure_size(7)
321
+ slc2.set_log("magnetic_field_magnitude", True)
322
+ slc2.zoom(zoom)
323
+ slc2.set_zlim(("gas", "magnetic_field_magnitude"),
324
+ zmin=(bmin, "G"),
325
+ zmax=(bmax, "G"))
326
+ slc2.annotate_streamlines(("gas", "magnetic_field_x"),
327
+ ("gas", "magnetic_field_y"),
328
+ color="white",
329
+ factor=zoom,
330
+ density=1.3)
331
+
332
+ #slc2.hide_colorbar()
333
+ plot2 = slc2.plots['magnetic_field_magnitude']
334
+ plot2.figure = fig
335
+ plot2.axes = grid[1].axes
336
+ plot2.cax = grid.cbar_axes[1]
337
+ plot2.axes.yaxis.tick_right()
338
+ slc2._setup_plots()
339
+ plot2.axes.yaxis.set_label_position("right")
340
+ #plot2.axes.yaxis.set_label_coords(1.1,0.5)
341
+ #plot2.axes.xaxis.set_label_coords(0.5,-0.1)
342
+ plot2.axes.tick_params(which="major",
343
+ direction="inout",
344
+ width=1,
345
+ length=8)
346
+ plot2.axes.tick_params(which="minor",
347
+ direction="in",
348
+ width=1,
349
+ length=2)
350
+
351
+ num = str(i).zfill(5)
352
+ fig.savefig(os.path.join(self.img_dir,
353
+ f"{self.sim_name}_Bmag_contours_{num}.png"),
354
+ dpi=300,
355
+ bbox_inches="tight")
356
+ plt.close(fig)
357
+
358
+ ###########################################################################
359
+ def plot_Bfield_both(self, i, dmin, dmax):
360
+ print(f"Loading dataset: Sim Snapshot {i}")
361
+ ds = self.get_ds(self.evolution[i],
362
+ quantities=["density", "magnetic_field"])
363
+ time = (ds.current_time.to("Myr"))
364
+ print(time)
365
+ print(f"Successfully Loaded dataset: {str(ds)}")
366
+ print(f"Plotting rho+B for snapshot {i}...")
367
+
368
+ fig = plt.figure()
369
+ grid = ImageGrid(fig, (0.075, 0.075, 0.85, 0.85),
370
+ nrows_ncols=(1, 2),
371
+ axes_pad=0.075,
372
+ label_mode="all",
373
+ share_all=True,
374
+ cbar_mode="single",
375
+ cbar_location="right",
376
+ cbar_size="7%",
377
+ cbar_pad="28%")
378
+
379
+ # first plot: XZ plane, on the left
380
+ #slc1 = yt.SlicePlot(ds, "y", "density", width=(4.5, "pc"),origin="native")
381
+ slc1 = yt.SlicePlot(ds, "y", "density", origin="native")
382
+ #slc1.set_font({'family': 'serif', 'style': 'normal', 'weight': 'normal', 'size': 12})
383
+ slc1.swap_axes()
384
+ slc1.set_cmap("density", "viridis")
385
+ slc1.set_zlim(("gas", "density"),
386
+ zmin=(dmin, "g/cm**3"),
387
+ zmax=(dmax, "g/cm**3"))
388
+ slc1.set_log("density", True)
389
+ slc1.set_figure_size(7)
390
+ #slc1.hide_colorbar()
391
+ st = r"$t=$ " + f"{time:.3f}"
392
+ slc1.annotate_text([0.325, 0.25],
393
+ st,
394
+ coord_system="figure",
395
+ text_args={
396
+ "color": "black",
397
+ "fontsize": 12
398
+ },
399
+ inset_box_args={
400
+ 'boxstyle': 'square',
401
+ 'pad': 0.3,
402
+ 'facecolor': 'white',
403
+ 'linewidth': 1,
404
+ 'edgecolor': 'black',
405
+ 'alpha': 0.5
406
+ }) # , fontsize=14
407
+ # add streamlines
408
+ slc1.annotate_streamlines(("gas", "magnetic_field_z"),
409
+ ("gas", "magnetic_field_x"),
410
+ color="white",
411
+ factor=1,
412
+ density=1.3)
413
+ #slc1.annotate_line_integral_convolution(("gas", "magnetic_field_x"), ("gas", "magnetic_field_y"),lim=(0.5,0.65))
414
+
415
+ plot1 = slc1.plots['density']
416
+ plot1.figure = fig
417
+ plot1.axes = grid[0].axes
418
+ plot1.cax = grid.cbar_axes[0]
419
+
420
+ #cb1.set_label("$\\rho$ (g cm$^{-3}$)", loc='right', fontsize=14)
421
+ slc1._setup_plots()
422
+ plot1.axes.tick_params(which="major",
423
+ direction="inout",
424
+ width=1,
425
+ length=8)
426
+ plot1.axes.tick_params(which="minor",
427
+ direction="in",
428
+ width=1,
429
+ length=2)
430
+ #plot1.axes.yaxis.set_label_coords(-0.1,0.5)
431
+ #plot1.axes.xaxis.set_label_coords(0.5,-0.1)
432
+
433
+ # second plot: XY plane, on the right
434
+ #slc2 = yt.SlicePlot(ds, "z", "density", width=(4.5, "pc"),origin="native")
435
+ slc2 = yt.SlicePlot(ds, "z", "density", origin="native")
436
+ #slc2.set_font({'family': 'serif', 'style': 'normal', 'weight': 'normal', 'size': 12})
437
+ slc2.set_cmap("density", "viridis")
438
+ slc2.set_figure_size(7)
439
+ slc2.set_log("density", True)
440
+ #slc2.zoom(16)
441
+ slc2.set_zlim(("gas", "density"),
442
+ zmin=(dmin, "g/cm**3"),
443
+ zmax=(dmax, "g/cm**3"))
444
+ slc2.annotate_streamlines(("gas", "magnetic_field_x"),
445
+ ("gas", "magnetic_field_y"),
446
+ color="white",
447
+ factor=1,
448
+ density=1.3)
449
+
450
+ #slc2.annotate_grids()
451
+ #slc2.annotate_line_integral_convolution(("gas", "magnetic_field_x"), ("gas", "magnetic_field_y"),lim=(0.5,0.65))
452
+
453
+ #slc2.hide_colorbar()
454
+ plot2 = slc2.plots['density']
455
+ plot2.figure = fig
456
+ plot2.axes = grid[1].axes
457
+ plot2.cax = grid.cbar_axes[1]
458
+ plot2.axes.yaxis.tick_right()
459
+ #plot2.axes.yaxis.set_label_position("right")
460
+ #new_ax = plot2.figure.add_axes((0.025,0.94,0.75,0.025))
461
+ #cb2 = plot2.figure.colorbar(plot2.image, new_ax, extend='both', orientation='horizontal', format='%.0E')
462
+ slc2._setup_plots()
463
+ plot2.axes.yaxis.set_label_position("right")
464
+ #plot2.axes.yaxis.set_label("right")
465
+ #plot2.axes.yaxis.set_label_coords(1.1,0.5)
466
+ #plot2.axes.xaxis.set_label_coords(0.5,-0.1)
467
+ plot2.axes.tick_params(which="major",
468
+ direction="inout",
469
+ width=1,
470
+ length=8)
471
+ plot2.axes.tick_params(which="minor",
472
+ direction="in",
473
+ width=1,
474
+ length=2)
475
+
476
+ num = str(i).zfill(5)
477
+ fig.savefig(os.path.join(self.img_dir,
478
+ f"{self.sim_name}_Bfield_contours_{num}.png"),
479
+ dpi=300,
480
+ bbox_inches="tight")
481
+ plt.close(fig)
482
+
483
+ ###########################################################################
484
+ def plot_density_2d(self, i, dmin, dmax, Tmin, Tmax):
485
+ # Plots density and temperature on a log scale, with T reflected onto
486
+ # the lower half-plane.
487
+ print(f"Loading dataset: Sim Snapshot {i}")
488
+ ds = self.get_ds(self.evolution[i],
489
+ quantities=["density", "temperature"])
490
+ time = (ds.current_time.to("Myr"))
491
+ print(time)
492
+ print(f"Successfully Loaded dataset: {str(ds)}")
493
+ print(f"Plotting rho-2d for snapshot {i}...")
494
+
495
+ fig = plt.figure()
496
+ grid = ImageGrid(fig, (0.075, 0.075, 0.85, 0.85),
497
+ nrows_ncols=(2, 1),
498
+ axes_pad=0.0,
499
+ label_mode="all",
500
+ share_all=False,
501
+ cbar_mode="each",
502
+ cbar_location="right",
503
+ cbar_size="5%",
504
+ cbar_pad="1%")
505
+
506
+ # first plot: upper half-plane, density
507
+ slc1 = yt.SlicePlot(ds, "theta", "density")
508
+ slc1.swap_axes()
509
+ slc1.set_cmap("density", "viridis")
510
+ slc1.set_zlim(("gas", "density"),
511
+ zmin=(dmin, "g/cm**3"),
512
+ zmax=(dmax, "g/cm**3"))
513
+ slc1.set_log("density", True)
514
+ slc1.set_figure_size(7)
515
+ st = r"$t=$ " + f"{time:.3f}"
516
+ slc1.annotate_text([0.85, 0.525],
517
+ st,
518
+ coord_system="figure",
519
+ text_args={
520
+ "color": "black",
521
+ "fontsize": 12
522
+ },
523
+ inset_box_args={
524
+ 'boxstyle': 'square',
525
+ 'pad': 0.3,
526
+ 'facecolor': 'white',
527
+ 'linewidth': 1,
528
+ 'edgecolor': 'black',
529
+ 'alpha': 0.5
530
+ }) # , fontsize=14
531
+
532
+ plot1 = slc1.plots['density']
533
+ plot1.figure = fig
534
+ plot1.axes = grid[0].axes
535
+ plot1.cax = grid.cbar_axes[0]
536
+
537
+ slc1._setup_plots()
538
+ plot1.axes.tick_params(which="major",
539
+ direction="inout",
540
+ width=1,
541
+ length=8)
542
+ plot1.axes.tick_params(which="minor",
543
+ direction="inout",
544
+ width=1,
545
+ length=3)
546
+ #plot1.axes.set_yticks([0,1,2])
547
+
548
+ # second plot: lower half-plane, temperature
549
+ slc2 = yt.SlicePlot(ds, "theta", "temperature")
550
+ slc2.swap_axes()
551
+ slc2.flip_vertical() # reflect the domain
552
+ slc2.set_cmap("temperature", "plasma")
553
+ slc2.set_figure_size(7)
554
+ slc2.set_log("temperature", True)
555
+ slc2.set_zlim(("gas", "temperature"),
556
+ zmin=(Tmin, "K"),
557
+ zmax=(Tmax, "K"))
558
+ plot2 = slc2.plots['temperature']
559
+ plot2.figure = fig
560
+ plot2.axes = grid[1].axes
561
+ plot2.cax = grid.cbar_axes[1]
562
+ slc2._setup_plots()
563
+ plot2.axes.tick_params(which="major",
564
+ direction="inout",
565
+ width=1,
566
+ length=8)
567
+ plot2.axes.tick_params(which="minor",
568
+ direction="inout",
569
+ width=1,
570
+ length=3)
571
+ #plot2.axes.set_yticks([1,2])
572
+
573
+ num = str(i).zfill(5)
574
+ fig.savefig(os.path.join(self.img_dir,
575
+ f"{self.sim_name}_rho2d_{num}.png"),
576
+ dpi=300,
577
+ bbox_inches="tight")
578
+ plt.close(fig)
579
+
580
+ ###########################################################################
581
+ ###########################################################################
582
+ def plot_Vfield_Bfield_2d(self, i, Vmin, Vmax, Bmin, Bmax):
583
+ '''
584
+ Plots a 2D slice of the velocity and magnetic field magnitudes from a simulation snapshot.
585
+
586
+ The upper panel shows the velocity magnitude with velocity vectors overlaid.
587
+ The lower panel shows the magnetic field magnitude with magnetic field vectors overlaid.
588
+
589
+ Parameters:
590
+ -----------
591
+ i : int
592
+ Index of the simulation snapshot to load and plot.
593
+ Vmin : float
594
+ Minimum value for the velocity magnitude color scale.
595
+ Vmax : float
596
+ Maximum value for the velocity magnitude color scale.
597
+ Bmin : float
598
+ Minimum value for the magnetic field magnitude color scale.
599
+ Bmax : float
600
+ Maximum value for the magnetic field magnitude color scale.
601
+
602
+ Returns:
603
+ --------
604
+ None
605
+ '''
606
+
607
+ # Define a derived field: magnitude of velocity vector
608
+ def _V_magnitude(field, data):
609
+ Vx = data[("gas", "velocity_x")]
610
+ Vy = data[("gas", "velocity_y")]
611
+ return np.sqrt(Vx**2 + Vy**2)
612
+
613
+ # Define a derived field: magnitude of magnetic field vector
614
+ def _B_magnitude(field, data):
615
+ Bx = data[("gas", "magnetic_field_x")]
616
+ By = data[("gas", "magnetic_field_y")]
617
+ return np.sqrt(Bx**2 + By**2)
618
+
619
+ print(f"Loading dataset: Sim Snapshot {i}")
620
+ ds = self.get_ds(self.evolution[i],
621
+ quantities=["velocity", "magnetic_field"])
622
+
623
+ # Register derived fields in yt dataset
624
+ ds.add_field(("gas", "velocity_field_magnitude"),
625
+ function=_V_magnitude,
626
+ units="km/s",
627
+ sampling_type="cell")
628
+
629
+ ds.add_field(("gas", "magnetic_field_magnitude"),
630
+ function=_B_magnitude,
631
+ units="gauss",
632
+ sampling_type="cell")
633
+
634
+ # Current simulation time
635
+ time = ds.current_time.to("kyr")
636
+ print(f"Time: {time}")
637
+ print(f"Successfully Loaded dataset: {str(ds)}")
638
+ print(f"Plotting velocity and magnetic field for snapshot {i}...")
639
+
640
+ # Set up a figure with two rows for the two panels
641
+ fig = plt.figure(figsize=(10, 14))
642
+ grid = ImageGrid(fig, (0.075, 0.075, 0.85, 0.85),
643
+ nrows_ncols=(2, 1),
644
+ axes_pad=0.0,
645
+ label_mode="all",
646
+ share_all=False,
647
+ cbar_mode="each",
648
+ cbar_size="5%",
649
+ cbar_pad="1%")
650
+
651
+ # ================= Upper Panel: Velocity =================
652
+ slc1 = yt.SlicePlot(ds, "theta", ("gas", "velocity_field_magnitude"))
653
+ slc1.swap_axes()
654
+ slc1.set_cmap(("gas", "velocity_field_magnitude"), "magma")
655
+ slc1.set_zlim(("gas", "velocity_field_magnitude"), Vmin, Vmax)
656
+ slc1.set_figure_size(7)
657
+
658
+ # Add velocity vectors (quiver plot)
659
+ slc1.annotate_quiver(("gas", "velocity_y"), ("gas", "velocity_x"),
660
+ color="white",
661
+ factor=25,
662
+ scale=45,
663
+ normalize=True)
664
+
665
+ # Annotate time and label
666
+ st = r"$t=$ " + f"{time:.3f}"
667
+ slc1.annotate_text([0.85, 0.325],
668
+ st,
669
+ coord_system="figure",
670
+ text_args={
671
+ "color": "black",
672
+ "fontsize": 2
673
+ },
674
+ inset_box_args={
675
+ 'boxstyle': 'square',
676
+ 'pad': 0.3,
677
+ 'facecolor': 'white',
678
+ 'linewidth': 1,
679
+ 'edgecolor': 'black',
680
+ 'alpha': 0.5
681
+ })
682
+ slc1.annotate_text([0.85, 0.55],
683
+ r"$|\vec{v}|$ km/s",
684
+ coord_system="figure",
685
+ text_args={
686
+ "color": "black",
687
+ "fontsize": 2
688
+ },
689
+ inset_box_args={
690
+ 'boxstyle': 'square',
691
+ 'pad': 0.3,
692
+ 'facecolor': 'white',
693
+ 'linewidth': 1,
694
+ 'edgecolor': 'black',
695
+ 'alpha': 0.5
696
+ })
697
+
698
+ # Set plot to corresponding grid location
699
+ plot1 = slc1.plots[("gas", "velocity_field_magnitude")]
700
+ plot1.figure = fig
701
+ plot1.axes = grid[0].axes
702
+ plot1.cax = grid.cbar_axes[0]
703
+ slc1._setup_plots()
704
+ grid.cbar_axes[0].set_ylabel("")
705
+
706
+ # ================= Lower Panel: Magnetic Field =================
707
+ slc2 = yt.SlicePlot(ds, "theta", ("gas", "magnetic_field_magnitude"))
708
+ slc2.swap_axes()
709
+ slc2.flip_vertical() # Flip to match expected orientation
710
+ slc2.set_cmap(("gas", "magnetic_field_magnitude"), "magma")
711
+ slc2.set_zlim(("gas", "magnetic_field_magnitude"), Bmin, Bmax)
712
+ slc2.set_log(("gas", "magnetic_field_magnitude"), True)
713
+ slc2.set_figure_size(7)
714
+
715
+ # Add magnetic field vectors
716
+ slc2.annotate_quiver(("gas", "magnetic_field_y"),
717
+ ("gas", "magnetic_field_x"),
718
+ color="white",
719
+ factor=25,
720
+ scale=45,
721
+ normalize=True)
722
+
723
+ # Annotate label
724
+ slc2.annotate_text([0.15, 0.55],
725
+ r"$|\vec{B}|$ G",
726
+ coord_system="figure",
727
+ text_args={
728
+ "color": "black",
729
+ "fontsize": 2
730
+ },
731
+ inset_box_args={
732
+ 'boxstyle': 'square',
733
+ 'pad': 0.3,
734
+ 'facecolor': 'black',
735
+ 'linewidth': 1,
736
+ 'edgecolor': 'black',
737
+ 'alpha': 0.1
738
+ })
739
+
740
+ # Set plot to corresponding grid location
741
+ plot2 = slc2.plots[("gas", "magnetic_field_magnitude")]
742
+ plot2.figure = fig
743
+ plot2.axes = grid[1].axes
744
+ plot2.cax = grid.cbar_axes[1]
745
+ slc2._setup_plots()
746
+ grid.cbar_axes[1].set_ylabel("")
747
+
748
+ # Save the resulting figure to file
749
+ num = str(i).zfill(5)
750
+ fig.savefig(os.path.join(self.img_dir,
751
+ f"{self.sim_name}_VBfield2d_{num}.png"),
752
+ dpi=300,
753
+ bbox_inches="tight")
754
+ plt.close(fig)
755
+
756
+ ###########################################################################
757
+ def get_1ddata_from_2ddata(self, i, length, theta, resolution=64):
758
+ import numpy as np
759
+ from scipy.interpolate import griddata
760
+
761
+ # Convert angle to radians
762
+ theta_rad = np.radians(theta)
763
+
764
+ # Define the number of points along the line and generate indices
765
+ # For simplicity, we will assume you want to map the length to the grid resolution
766
+ indices = np.linspace(0, resolution - 1, resolution)
767
+ r_indices = indices * np.cos(theta_rad)
768
+ z_indices = indices * np.sin(theta_rad)
769
+
770
+ print(r_indices, z_indices)
771
+
772
+ line_points = np.vstack(
773
+ (r_indices, z_indices)).T # shape: (resolution, 2)
774
+
775
+ # Load dataset
776
+ print(f"Loading dataset: Sim Snapshot {i}")
777
+ ds = self.get_ds(self.evolution[i],
778
+ quantities=["velocity", "magnetic_field", "density"])
779
+ ad = ds.all_data()
780
+
781
+ # Get grid cell positions in r and z (indices, not physical coordinates)
782
+ r_index = ad[('index', 'r')].v # Get r indices
783
+ z_index = ad[('index', 'z')].v # Get z indices
784
+
785
+ # Get the density field directly from the grid data
786
+ density = ad['density'].v
787
+
788
+ # Flatten the grid data for easier processing
789
+ pos_indices = np.vstack([r_index.ravel(),
790
+ z_index.ravel()]).T # shape: (n_cells, 2)
791
+
792
+ print(pos_indices)
793
+ exit(1)
794
+
795
+ # Interpolate density along the line using the grid indices
796
+ interpolated_density = griddata(pos_indices,
797
+ density.ravel(),
798
+ line_points,
799
+ method='linear')
800
+
801
+ # Calculate distance along the line (Euclidean distance) based on grid indices
802
+ line_distances = np.sqrt(np.diff(r_indices)**2 + np.diff(z_indices)**2)
803
+
804
+ # Compute cumulative distance along the line from origin
805
+ distance = np.cumsum(line_distances)
806
+
807
+ # Remove NaNs if interpolation falls outside domain
808
+ mask = ~np.isnan(interpolated_density)
809
+ distance = distance[mask]
810
+ interpolated_density = interpolated_density[mask]
811
+
812
+ # Output the distance and interpolated density
813
+ print("Distance along the line (in grid units):", distance)
814
+ print("Interpolated density values:", interpolated_density)
815
+
816
+ ###########################################################################
817
+ def plot_Xray_intensity(self, i, jmin, jmax):
818
+ print(f"Loading dataset: Sim Snapshot {i}")
819
+ ds = self.get_ds(self.evolution[i], quantities=["xray_emission"])
820
+ time = (ds.current_time.to("Myr"))
821
+ print(time)
822
+ print(f"Successfully Loaded dataset: {str(ds)}")
823
+ print(f"Plotting x-ray intensity for snapshot {i}...")
824
+
825
+ fig = plt.figure()
826
+ grid = ImageGrid(fig, (0.075, 0.075, 0.85, 0.85),
827
+ nrows_ncols=(1, 2),
828
+ axes_pad=0.075,
829
+ label_mode="all",
830
+ share_all=True,
831
+ cbar_mode="single",
832
+ cbar_location="right",
833
+ cbar_size="7%",
834
+ cbar_pad="28%")
835
+
836
+ # first plot: XZ plane, on the left
837
+ #prj1 = yt.ProjectionPlot( ds, "y", ("gas", "xray_0.3"), width=(4.5, "pc"),origin="native", method="integrate", buff_size=(1024, 1024))
838
+ prj1 = yt.ProjectionPlot(ds,
839
+ "y", ("gas", "xray_0.3"),
840
+ origin="native",
841
+ method="integrate",
842
+ buff_size=(1024, 1024))
843
+ prj1.swap_axes()
844
+ prj1.set_cmap("xray_0.3", "magma")
845
+ prj1.set_zlim(("gas", "xray_0.3"),
846
+ zmin=(jmin, "erg/cm**2/s/arcmin**2"),
847
+ zmax=(jmax, "erg/cm**2/s/arcmin**2"))
848
+ prj1.set_log("xray_0.3", True)
849
+ prj1.set_figure_size(7)
850
+ st = r"$t=$ " + f"{time:.3f}"
851
+ prj1.annotate_text([0.675, 0.265],
852
+ st,
853
+ coord_system="figure",
854
+ text_args={
855
+ "color": "black",
856
+ "fontsize": 12
857
+ },
858
+ inset_box_args={
859
+ 'boxstyle': 'square',
860
+ 'pad': 0.3,
861
+ 'facecolor': 'white',
862
+ 'linewidth': 1,
863
+ 'edgecolor': 'black',
864
+ 'alpha': 0.5
865
+ })
866
+ # add streamlines
867
+ #prj1.annotate_streamlines(("gas", "magnetic_field_z"), ("gas", "magnetic_field_x"), color="white", factor=1, density=1.3)
868
+ #slc1.annotate_line_integral_convolution(("gas", "magnetic_field_x"), ("gas", "magnetic_field_y"),lim=(0.5,0.65))
869
+
870
+ plot1 = prj1.plots['xray_0.3']
871
+ plot1.figure = fig
872
+ plot1.axes = grid[0].axes
873
+ plot1.cax = grid.cbar_axes[0]
874
+
875
+ prj1._setup_plots()
876
+ plot1.axes.tick_params(which="major",
877
+ direction="inout",
878
+ width=1,
879
+ length=8)
880
+ plot1.axes.tick_params(which="minor",
881
+ direction="in",
882
+ width=1,
883
+ length=2)
884
+ plot1.axes.yaxis.set_label_coords(-0.1, 0.5)
885
+ plot1.axes.xaxis.set_label_coords(0.5, -0.1)
886
+
887
+ # second plot: XY plane, on the right
888
+ #prj2 = yt.ProjectionPlot( ds, "z", ("gas", "xray_0.3"), width=(4.5, "pc"),origin="native", method="integrate", buff_size=(1024, 1024))
889
+ prj2 = yt.ProjectionPlot(ds,
890
+ "z", ("gas", "xray_0.3"),
891
+ origin="native",
892
+ method="integrate",
893
+ buff_size=(1024, 1024))
894
+ prj2.set_cmap("xray_0.3", "magma")
895
+ prj2.set_zlim(("gas", "xray_0.3"),
896
+ zmin=(jmin, "erg/cm**2/s/arcmin**2"),
897
+ zmax=(jmax, "erg/cm**2/s/arcmin**2"))
898
+ prj2.set_log("xray_0.3", True)
899
+ prj2.set_figure_size(7)
900
+
901
+ plot2 = prj2.plots['xray_0.3']
902
+ plot2.figure = fig
903
+ plot2.axes = grid[1].axes
904
+ plot2.cax = grid.cbar_axes[1]
905
+ plot2.axes.yaxis.tick_right()
906
+ prj2._setup_plots()
907
+ plot2.axes.yaxis.set_label_position("right")
908
+ plot2.axes.yaxis.set_label_coords(1.1, 0.5)
909
+ plot2.axes.xaxis.set_label_coords(0.5, -0.1)
910
+ plot2.axes.tick_params(which="major",
911
+ direction="inout",
912
+ width=1,
913
+ length=8)
914
+ plot2.axes.tick_params(which="minor",
915
+ direction="in",
916
+ width=1,
917
+ length=2)
918
+
919
+ num = str(i).zfill(5)
920
+ fig.savefig(os.path.join(self.img_dir,
921
+ f"{self.sim_name}_Proj_Xray003_{num}.png"),
922
+ dpi=300,
923
+ bbox_inches="tight")
924
+ plt.close(fig)
925
+
926
+ ###########################################################################
927
+ # i - index in dataset
928
+ # jmin - min of intensity colour scale
929
+ # jmax - max of intensity colour scale
930
+ # z - zoom level (integer 2^n) >=1
931
+
932
+ def plot_Xray_intensity_XY(self, i, jmin, jmax, z):
933
+ print(f"Loading dataset: Sim Snapshot {i}")
934
+ ds = self.get_ds(self.evolution[i], quantities=["xray_emission"])
935
+ time = (ds.current_time.to("yr"))
936
+ print(time)
937
+ print(f"Successfully Loaded dataset: {str(ds)}")
938
+ print(
939
+ f"Plotting x-ray intensity for snapshot {i}... for $\hat{z}$ projection"
940
+ )
941
+ # XY plane
942
+ #prj2 = yt.ProjectionPlot( ds, "z", ("gas", "xray_0.3"), width=(4.5, "pc"),origin="native", method="integrate", buff_size=(1024, 1024))
943
+ prj2 = yt.ProjectionPlot(ds,
944
+ "z", ("gas", "xray_0.3"),
945
+ origin="native",
946
+ method="integrate",
947
+ buff_size=(1024, 1024))
948
+ prj2.set_cmap("xray_0.3", "magma")
949
+ prj2.set_zlim(("gas", "xray_0.3"),
950
+ zmin=(jmin, "erg/cm**2/s/arcmin**2"),
951
+ zmax=(jmax, "erg/cm**2/s/arcmin**2"))
952
+ prj2.set_log("xray_0.3", True)
953
+ prj2.zoom(z)
954
+ prj2.set_figure_size(7)
955
+
956
+ fig = prj2.export_to_mpl_figure((1, 1), cbar_mode="single")
957
+ ax = fig.axes[0]
958
+ num = "{:05.4f}".format(time)
959
+ ax.text(0.725, 0.95, num, transform=ax.transAxes, fontsize=16)
960
+ ax.tick_params(which="major", direction="inout", width=1, length=8)
961
+ ax.tick_params(which="minor", direction="in", width=1, length=2)
962
+
963
+ num = str(i).zfill(5)
964
+ fig.savefig(os.path.join(self.img_dir,
965
+ f"{self.sim_name}_Proj_Xray003_XY_{num}.png"),
966
+ dpi=300,
967
+ bbox_inches="tight")
968
+ plt.close(fig)
969
+
970
+
971
+ ###########################################################################
972
+ ###########################################################################