Skip to content

Commit 6f522df

Browse files
authored
Merge pull request #181 from ammarhakim/gk_nodes_script_mode
gk-nodes script mode
2 parents 862318b + 726aed8 commit 6f522df

File tree

10 files changed

+125
-61
lines changed

10 files changed

+125
-61
lines changed

src/postgkyl/commands/collect.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def collect(ctx, **kwargs):
9292
time[i] = np.array(time[i])
9393
values[i] = np.array(values[i])
9494

95-
if "period" in kwargs.keys():
95+
if kwargs.get("period"):
9696
time[i] = (time[i] - kwargs["offset"]) % kwargs["period"]
9797
# end
9898

src/postgkyl/commands/differentiate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def differentiate(ctx, **kwargs):
2424

2525
basis_type = None
2626
is_modal = None
27-
if "basis_type" in kwargs.keys():
27+
if kwargs.get("basis_type"):
2828
if kwargs["basis_type"] == "ms":
2929
basis_type = "serendipity"
3030
is_modal = True

src/postgkyl/commands/gk_nodes.py

Lines changed: 76 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,14 @@ def nodes_to_RZ(nodes, is_mapc2p):
6161

6262
return majorR, vertZ
6363

64+
def str_append_multib_suffix_mb(str_in, suffix, bidx):
65+
# Append the suffix to the input string str_in and format it with the block
66+
# index bidx.
67+
return str_in + suffix % bidx
68+
69+
def str_append_multib_suffix_sb(str_in, suffix, bidx):
70+
# Just return the input string.
71+
return str_in
6472

6573
@click.command()
6674
@click.option("--name", "-n", required=True, type=click.STRING, default=None,
@@ -77,17 +85,17 @@ def nodes_to_RZ(nodes, is_mapc2p):
7785
help="Vacuum vessel wall (.csv format).")
7886
@click.option("--contour", "-c", is_flag=True, help="Plot contours of psi.")
7987
@click.option("--clevels", type=click.STRING,
80-
help="Specify levels for contours: comma-separated level values or start:end:nlevels.")
88+
help="Specify levels for contours: comma-separated level values or start:end:nlevels.")
8189
@click.option("--cnlevels", type=click.INT, default=11, help="Specify the number of levels for contours.")
82-
@click.option("--fix-aspect", "-a", "fixaspect", is_flag=True,
83-
help="Enforce the same scaling on both axes.")
90+
@click.option("--fix_aspect", "-a", "fixaspect", is_flag=True,
91+
help="Enforce the same scaling on both axes.")
8492
@click.option("--xlim", default=None, type=click.STRING,
85-
help="Set limits for the x-coordinate (lower,upper)")
93+
help="Set limits for the x-coordinate (lower,upper)")
8694
@click.option("--ylim", default=None, type=click.STRING,
87-
help="Set limits for the y-coordinate (lower,upper).")
95+
help="Set limits for the y-coordinate (lower,upper).")
8896
@click.option("--xlabel", type=click.STRING, default="R (m)",
8997
help="Label for the x axis.")
90-
@click.option("--ylabel", type=click.STRING, default="R (z)",
98+
@click.option("--ylabel", type=click.STRING, default="Z (m)",
9199
help="Label for the y axis.")
92100
@click.option("--zlabel", type=click.STRING, default=r"$\psi$",
93101
help="Label for the color bar.")
@@ -100,6 +108,8 @@ def nodes_to_RZ(nodes, is_mapc2p):
100108
@click.option("--multib_unicolor", is_flag=True, default=False, help="Use one color for all blocks.")
101109
@click.option("--saveas", type=click.STRING, default=None,
102110
help="Name of figure file.")
111+
@click.option("--no_show", is_flag=True, default=False,
112+
help="Suppreses showing the figure.")
103113
@click.pass_context
104114
def gk_nodes(ctx, **kwargs):
105115
"""
@@ -120,6 +130,8 @@ def gk_nodes(ctx, **kwargs):
120130
"""
121131

122132
data = ctx.obj["data"] # Data stack.
133+
ctx.obj["plot_handles"] = {} # Handles to objects in plot.
134+
handles = ctx.obj["plot_handles"]
123135

124136
verb_print(ctx, "Plotting nodes for " + kwargs["name"])
125137

@@ -147,6 +159,12 @@ def gk_nodes(ctx, **kwargs):
147159
# Determine number of blocks.
148160
blocks = gku.get_block_indices(kwargs["multib"], nodes_file)
149161
num_blocks = len(blocks)
162+
# Tag for dataset.
163+
tag_multib_suffix = ""
164+
str_append_multib_suffix = str_append_multib_suffix_sb
165+
if num_blocks > 1:
166+
tag_multib_suffix = "_b%d"
167+
str_append_multib_suffix = str_append_multib_suffix_mb
150168

151169
block_path_prefix = file_path_prefix
152170

@@ -172,12 +190,16 @@ def gk_nodes(ctx, **kwargs):
172190
lengthR, lengthZ = Rmax-Rmin, Zmax-Zmin
173191
aspect_ratio = lengthR/lengthZ
174192

175-
ax1aPos = [0.82-(8.36*aspect_ratio)/(8.36*aspect_ratio+2.5)+kwargs["indent_left"], 0.08,
176-
(8.36*aspect_ratio)/(8.36*aspect_ratio+2.5)+kwargs["add_width"], 0.88]
177-
cax1aPos = [ax1aPos[0]+ax1aPos[2]+0.01, ax1aPos[1], 0.02, ax1aPos[3]];
178-
figProp1a = (8.36*aspect_ratio+2.5, 8.36+1.14)
179-
fig1a = plt.figure(figsize=figProp1a)
180-
ax1a = fig1a.add_axes(ax1aPos)
193+
ax_pos = [0.82-(8.36*aspect_ratio)/(8.36*aspect_ratio+2.5)+kwargs["indent_left"], 0.08,
194+
(8.36*aspect_ratio)/(8.36*aspect_ratio+2.5)+kwargs["add_width"], 0.88]
195+
cax_pos = [ax_pos[0]+ax_pos[2]+0.01, ax_pos[1], 0.02, ax_pos[3]];
196+
fig_prop = (8.36*aspect_ratio+2.5, 8.36+1.14)
197+
fig_h = plt.figure(figsize=fig_prop)
198+
ax_h = fig_h.add_axes(ax_pos)
199+
200+
# Store figure handles in case script mode wishes to modify them.
201+
handles["figure"] = fig_h
202+
handles["axis"] = ax_h
181203

182204
# Color cycler for plotting each block in a different color.
183205
color_list = plt.rcParams['axes.prop_cycle'].by_key()['color']
@@ -187,8 +209,8 @@ def gk_nodes(ctx, **kwargs):
187209
# end
188210

189211
# Loop through blocks to plot.
190-
hpl1a = list()
191-
hcb1a = list()
212+
pl_nodes_h = list()
213+
pl_edges_h = list()
192214
for bI in blocks:
193215

194216
block_path_prefix = file_path_prefix.replace("*",str(bI))
@@ -199,26 +221,34 @@ def gk_nodes(ctx, **kwargs):
199221
majorR, vertZ = nodes_to_RZ(nodes, is_mapc2p) # Major radius and vertical location.
200222

201223
# Plot each node.
202-
hpl1a.append(ax1a.plot(majorR,vertZ,marker=".", color="k", linestyle="none"))
224+
pl_nodes_h.append(ax_h.plot(majorR,vertZ,marker=".", color="k", linestyle="none"))
203225

204226
cdim = np.size(np.shape(nodes))-1
205227
# Connect nodes with line segments.
206228
cell_color = next(block_colors)
207229
if (cdim == 1):
208-
hpl1a.append(ax1a.plot(majorR,vertZ,color=cell_color, linestyle="-"))
230+
pl_edges_h.append(ax_h.plot(majorR,vertZ,color=cell_color, linestyle="-"))
209231
else:
210-
segs1 = np.stack((majorR,vertZ), axis=2)
211-
segs2 = segs1.transpose(1,0,2)
212-
hpl1a.append(ax1a.add_collection(LineCollection(segs1, color=cell_color)))
213-
hpl1a.append(ax1a.add_collection(LineCollection(segs2, color=cell_color)))
232+
segs_constx = np.stack((majorR,vertZ), axis=2)
233+
segs_consty = segs_constx.transpose(1,0,2)
234+
pl_edges_h.append(ax_h.add_collection(LineCollection(segs_constx, color=cell_color)))
235+
pl_edges_h.append(ax_h.add_collection(LineCollection(segs_consty, color=cell_color)))
236+
237+
# Add datasets plotted to stack.
238+
gdat_edges = GData(tag=str_append_multib_suffix("edges",tag_multib_suffix,bI), ctx=gdat.ctx)
239+
gdat_edges.push(segs_constx, segs_consty)
240+
data.add(gdat_edges)
214241
# end
215242

216243
# Add datasets plotted to stack.
217-
gdat_nodes = GData(tag="nodes", label="nodes", ctx=gdat.ctx)
244+
gdat_nodes = GData(tag=str_append_multib_suffix("nodes",tag_multib_suffix,bI), ctx=gdat.ctx)
218245
gdat_nodes.push(majorR, vertZ)
219246
data.add(gdat_nodes)
220247
# end
221248

249+
handles["nodes"] = pl_nodes_h
250+
handles["edges"] = pl_edges_h
251+
222252
if kwargs["psi_file"]:
223253
if kwargs["psi_file"][0] == "/":
224254
# Absolute path included in node file. Don't append path.
@@ -255,7 +285,7 @@ def gk_nodes(ctx, **kwargs):
255285
colorbar = False
256286
# end
257287

258-
hpl1a.append(ax1a.contour(psi_grid_cc[0], psi_grid_cc[1], psi_values.transpose(), psi_clevels))
288+
pl_psi_h = ax_h.contour(psi_grid_cc[0], psi_grid_cc[1], psi_values.transpose(), psi_clevels)
259289

260290
# Add colorbar.
261291
if isinstance(psi_clevels, np.ndarray):
@@ -266,25 +296,29 @@ def gk_nodes(ctx, **kwargs):
266296

267297
else:
268298
# Color plot.
269-
hpl1a.append(ax1a.pcolormesh(psi_grid[0], psi_grid[1], psi_values.transpose(), cmap='inferno'))
299+
pl_psi_h = ax_h.pcolormesh(psi_grid[0], psi_grid[1], psi_values.transpose(), cmap='inferno')
270300
# end
271301

302+
handles["psi"] = pl_psi_h
303+
272304
if colorbar:
273-
cbar_ax1a = fig1a.add_axes(cax1aPos)
274-
hcb1a.append(plt.colorbar(hpl1a[-1], ax=ax1a, cax=cbar_ax1a))
275-
hcb1a[0].ax.tick_params(labelsize=gku.tick_font_size)
276-
hcb1a[0].set_label(kwargs["zlabel"], rotation=90, labelpad=0, fontsize=gku.colorbar_label_font_size)
305+
psi_cbar_ax_h = fig_h.add_axes(cax_pos)
306+
psi_cbar_h = plt.colorbar(pl_psi_h, ax=ax_h, cax=psi_cbar_ax_h)
307+
psi_cbar_h.ax.tick_params(labelsize=gku.tick_font_size)
308+
psi_cbar_h.set_label(kwargs["zlabel"], rotation=90, labelpad=0, fontsize=gku.colorbar_label_font_size)
309+
handles["psi_colorbar_axis"] = psi_cbar_ax_h
310+
handles["psi_colorbar"] = psi_cbar_h
277311
# end
278312

279313
# Add datasets plotted to stack.
280-
gdat_psi = GData(tag="psi", label="psi", ctx=gdat.ctx)
314+
gdat_psi = GData(tag="psi", ctx=gdat.ctx)
281315
if kwargs["contour"]:
282316
gdat_psi.push(psi_grid_cc, psi_values.transpose())
283317
else:
284318
gdat_psi.push(psi_grid, psi_values.transpose())
285319
# end
286-
287320
data.add(gdat_psi)
321+
288322
# end
289323

290324
if kwargs["wall_file"]:
@@ -297,29 +331,32 @@ def gk_nodes(ctx, **kwargs):
297331
#end
298332

299333
wall_data = np.loadtxt(open(wall_file),delimiter=',')
300-
ax1a.plot(wall_data[:,0],wall_data[:,1],color="grey")
334+
wall_h = ax_h.plot(wall_data[:,0],wall_data[:,1],color="grey")
335+
handles["wall"] = wall_h
301336
# end
302337

303-
ax1a.set_xlabel(kwargs["xlabel"],fontsize=gku.xy_label_font_size)
304-
ax1a.set_ylabel(kwargs["ylabel"],fontsize=gku.xy_label_font_size)
305-
ax1a.set_title(kwargs["title"],fontsize=gku.title_font_size)
338+
ax_h.set_xlabel(kwargs["xlabel"],fontsize=gku.xy_label_font_size)
339+
ax_h.set_ylabel(kwargs["ylabel"],fontsize=gku.xy_label_font_size)
340+
ax_h.set_title(kwargs["title"],fontsize=gku.title_font_size)
306341
if kwargs["xlim"]:
307-
ax1a.set_xlim( float(kwargs["xlim"].split(",")[0]), float(kwargs["xlim"].split(",")[1]) )
342+
ax_h.set_xlim( float(kwargs["xlim"].split(",")[0]), float(kwargs["xlim"].split(",")[1]) )
308343
# else:
309-
# ax1a.set_xlim( Rmin-0.05*lengthR, Rmax+0.05*lengthR )
344+
# ax_h.set_xlim( Rmin-0.05*lengthR, Rmax+0.05*lengthR )
310345
# end
311346

312347
if kwargs["ylim"]:
313-
ax1a.set_ylim( float(kwargs["ylim"].split(",")[0]), float(kwargs["ylim"].split(",")[1]) )
348+
ax_h.set_ylim( float(kwargs["ylim"].split(",")[0]), float(kwargs["ylim"].split(",")[1]) )
314349
# else:
315-
# ax1a.set_ylim( Zmin-0.05*lengthZ, Zmax+0.05*lengthZ )
350+
# ax_h.set_ylim( Zmin-0.05*lengthZ, Zmax+0.05*lengthZ )
316351
# end
317352

318-
gku.set_tick_font_size(ax1a,gku.tick_font_size)
353+
gku.set_tick_font_size(ax_h,gku.tick_font_size)
319354

320355
if kwargs["saveas"]:
321356
plt.savefig(kwargs["saveas"])
322-
else:
357+
# end
358+
359+
if not kwargs["no_show"]:
323360
plt.show()
324361
# end
325362

src/postgkyl/commands/interpolate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def interpolate(ctx, **kwargs):
2424

2525
basis_type = None
2626
is_modal = None
27-
if "basis_type" in kwargs.keys():
27+
if kwargs.get("basis_type"):
2828
if kwargs["basis_type"] == "ms":
2929
basis_type = "serendipity"
3030
is_modal = True

src/postgkyl/commands/mask.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,11 @@ def mask(ctx, **kwargs):
2828
if kwargs["filename"]:
2929
mask_fld_rep = np.repeat(mask_fld, dat.get_num_comps(), axis=-1)
3030
data.set_values(np.ma.masked_where(mask_fld_rep < 0.0, values))
31-
elif "lower" in kwargs.keys() and "upper" in kwargs.keys():
31+
elif kwargs.get("lower") and kwargs.get("upper"):
3232
dat.set_values(np.ma.masked_outside(values, kwargs["lower"], kwargs["upper"]))
33-
elif "lower" in kwargs.keys():
33+
elif kwargs.get("lower"):
3434
dat.set_values(np.ma.masked_less(values, kwargs["lower"]))
35-
elif "upper" in kwargs.keys():
35+
elif kwargs.get("upper"):
3636
dat.set_values(np.ma.masked_greater(values, kwargs["upper"]))
3737
else:
3838
data.set_values(values)

src/postgkyl/commands/plot.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -209,14 +209,13 @@ def plot(ctx, **kwargs):
209209

210210
# Parse legend labels if provided
211211
legend_labels = None
212-
if "legend" in kwargs.keys():
213-
if kwargs["legend"] is not None:
214-
legend_labels = [label.strip() for label in kwargs["legend"].split(",")]
212+
if kwargs.get("legend"):
213+
legend_labels = [label.strip() for label in kwargs["legend"].split(",")]
215214
# end
216215

217216
# Overwrite show_legend if no_legend is set
218217
show_legend = True
219-
if "no_legend" in kwargs.keys():
218+
if kwargs.get("no_legend"):
220219
if kwargs["no_legend"]:
221220
show_legend = False
222221

@@ -287,7 +286,7 @@ def plot(ctx, **kwargs):
287286

288287

289288
# end
290-
if (kwargs["save"] or kwargs["saveas"]) and "figure" in kwargs.keys():
289+
if (kwargs["save"] or kwargs["saveas"]):
291290
file_name = str(file_name)
292291
plt.savefig(file_name, dpi=kwargs["dpi"])
293292
# end

src/postgkyl/commands/select.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,14 @@ def select(ctx, **kwargs):
6060
botlef_point.append(min([dat.get_bounds()[0][dim] for dat in frame]))
6161
# end
6262
#find starting block for lineout coordinate
63-
if "z0" in kwargs.keys():
63+
if kwargs.get("z0"):
6464
for dat in frame:
6565
if dat.get_bounds()[0][0] <= float(kwargs["z0"]) <= dat.get_bounds()[1][0] and dat.get_bounds()[0][1] == botlef_point[1]:
6666
block = dat
6767
# end
6868
# end
6969
# end
70-
if "z1" in kwargs.keys():
70+
if kwargs.get("z1"):
7171
for dat in frame:
7272
if dat.get_bounds()[0][1] <= float(kwargs["z1"]) <= dat.get_bounds()[1][1] and dat.get_bounds()[0][0] == botlef_point[0]:
7373
block = dat
@@ -80,7 +80,7 @@ def select(ctx, **kwargs):
8080
value_list = []
8181

8282
#creates new grid and value list containing data from blocks which contain specified z0 coordinate
83-
if "z0" in kwargs.keys():
83+
if kwargs.get("z0"):
8484
grid, values = postgkyl.data.select(block,
8585
z0=kwargs["z0"],
8686
comp=kwargs["comp"])
@@ -105,7 +105,7 @@ def select(ctx, **kwargs):
105105

106106

107107
#same but for z1 coordinate
108-
if "z1" in kwargs.keys():
108+
if kwargs.get("z1"):
109109
grid, values = postgkyl.data.select(block,
110110
z1=kwargs["z1"],
111111
comp=kwargs["comp"])

src/postgkyl/commands/trajectory.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def trajectory(ctx, **kwargs):
108108
num_pos = dat.get_num_cells()[0]
109109

110110
jump = 1
111-
if "numframes" in kwargs.keys():
111+
if kwargs.get("numframes"):
112112
jump = int(math.floor(num_pos / kwargs["numframes"]))
113113
num_pos = int(kwargs["numframes"])
114114
# end

src/postgkyl/data/dg.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ def __init__(self, data, poly_order=None, basis_type=None, num_interp=None,
392392
self.num_dims = data.get_num_dims()
393393
if poly_order is not None:
394394
self.poly_order = poly_order
395-
elif "poly_order" in data.ctx.keys():
395+
elif data.ctx.get("poly_order"):
396396
self.poly_order = data.ctx["poly_order"]
397397
else:
398398
raise ValueError(
@@ -410,7 +410,7 @@ def __init__(self, data, poly_order=None, basis_type=None, num_interp=None,
410410
elif basis_type == "pkpmhyb":
411411
self.basis_type = "hybrid"
412412
# end
413-
elif "basis_type" in data.ctx.keys():
413+
elif data.ctx.get("basis_type"):
414414
self.basis_type = data.ctx["basis_type"]
415415
else:
416416
raise ValueError(
@@ -477,6 +477,7 @@ def interpolate(self, comp=0, overwrite=False, stack=False):
477477
grid = []
478478
for d in range(self.num_dims):
479479
grid.append(_interpOnMesh(cMat, q[d], self.num_interp + 1, basis, True))
480+
# end
480481
else:
481482
if self.basis_type == "gkhybrid":
482483
# 1x1v, 1x2v, 2x2v, 3x2v cases, with p=2 in the first velocity dim.
@@ -489,6 +490,7 @@ def interpolate(self, comp=0, overwrite=False, stack=False):
489490
num_interp[-1] = self.num_interp + 1
490491
else:
491492
num_interp = [int(round(cMat.shape[0] ** (1.0 / self.num_dims)))] * self.num_dims
493+
# end
492494

493495
grid = _make1Dgrids(num_interp, self.Xc, self.num_dims, None)
494496
if self.data.ctx["grid_type"] == "c2p_vel":
@@ -502,11 +504,15 @@ def interpolate(self, comp=0, overwrite=False, stack=False):
502504
self.read, True, True)
503505
grid[num_cdim + d] = _interpOnMesh(cMat, q[num_cdim + d],
504506
num_interp[num_cdim + d] + 1, basis, True)
507+
# end
508+
# end
509+
# end
505510

506511
if overwrite:
507512
self.data.push(grid, values)
508513
else:
509514
return grid, values
515+
# end
510516

511517
def interpolateGrid(self, overwrite=False):
512518
if self.data.ctx["grid_type"] == "c2p":

0 commit comments

Comments
 (0)