Skip to content

Commit c9e72f4

Browse files
authored
Merge pull request #2483 from willend/main
Silence mcdisplay-matplotlib noise when pressing 'q'
2 parents 719d18e + d85c4de commit c9e72f4

2 files changed

Lines changed: 61 additions & 11 deletions

File tree

tools/Python/mcdisplay/matplotlib/mcdisplay.in

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,13 @@ canrun() {
2727
}
2828

2929
if ( canrun ); then
30-
arguments=""
3130
ncountmax="1e2"
3231
ncount=""
3332
trace=""
3433
next=0
3534
found_ncount=0
35+
backend=""
36+
args=()
3637
for arg in "${@}"; do
3738
if [ "${next}" == "1" ]; # We found -n or --ncount in last pass, this is NUMBER
3839
then
@@ -56,6 +57,10 @@ if ( canrun ); then
5657
elif [[ ${arg} =~ ^--trace= ]]; # Case: --trace=NUMBER
5758
then
5859
trace=`echo $arg | cut -f2 -d=`
60+
args+=("$arg")
61+
elif [[ ${arg} =~ ^--backend= ]]; # Case: --backend=Something
62+
then
63+
backend=`echo $arg | cut -f2 -d=`
5964
elif [[ ${arg} =~ ^--help ]]; # Case: --help
6065
then
6166
script=`basename $0`
@@ -67,10 +72,12 @@ if ( canrun ); then
6772
echo " --ncount=N - set number of particles to trace, max/default N=1e2"
6873
echo " -n N "
6974
echo " -nN "
75+
echo " --backend=B - use matplotlib backend 'B' (e.g. WebAgg, pdf etc.)"
76+
echo " Backends 'pdf', 'pgf', 'ps', 'svg' saves a hardcopy."
7077
echo ""
7178
exit
7279
else
73-
arguments="$arguments $arg"
80+
args+=("$arg")
7481
fi
7582
done
7683
if [ "${trace}" == "" ];
@@ -89,7 +96,7 @@ if ( canrun ); then
8996
else
9097
ncount=$ncountmax
9198
fi
92-
@P@run $* --trace=$trace --no-output-files -n $ncount | python3 ${UTILDIR}/${TOOL}.py
99+
@P@run ${args[@]} --trace=${trace} --no-output-files -n ${ncount} | python3 ${UTILDIR}/${TOOL}.py ${backend}
93100
else
94101
@FLAVOR@_errmsg Failed to run Python ${TOOL} - permissions or missing dependencies\?
95102
fi

tools/Python/mcdisplay/matplotlib/mcdisplay.py

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@
55
import matplotlib as mpl
66
from mpl_toolkits.mplot3d import art3d
77
from matplotlib import pyplot as plt
8+
from matplotlib import use
89
import numpy as np
910
import json
11+
import sys
12+
import os
1013

1114
from util import (parse_multiline, rotate, rotate_points, draw_circle, get_line,
1215
draw_box, draw_sphere, draw_cylinder, draw_disc, rotate_xyz, draw_cone, draw_hollow_box, draw_annulus, draw_new_circle)
@@ -47,19 +50,50 @@
4750
x_max_polygon = y_max_polygon = z_max_polygon = float('-inf')
4851
x_min_polygon = y_min_polygon = z_min_polygon = float('inf')
4952

53+
def dumpfile(frmat, filename = None):
54+
""" save current fig to softcopy """
55+
from pylab import savefig
5056

51-
def parse_trace():
57+
if filename is None:
58+
filename = "display_matplotlib"
59+
60+
# get directory, basename and extension
61+
if isinstance(filename, list):
62+
filename = filename[0]
63+
basename = os.path.splitext(filename)[0] # contains full path and base filename
64+
if frmat is None:
65+
ext = os.path.splitext(filename)[1] # extension with the dot
66+
else:
67+
ext = frmat
68+
if ext[0] != '.':
69+
ext = '.'+ext
70+
# assemble target name
71+
saveto = basename + ext
72+
73+
# Check for existance of earlier exports
74+
if os.path.isfile(saveto):
75+
index=1
76+
saveto = f"{basename}_{index}{frmat}"
77+
while os.path.isfile(saveto):
78+
index += 1
79+
saveto = f"{basename}_{index}{frmat}"
80+
81+
savefig(saveto)
82+
print("Saved " + saveto)
83+
84+
def parse_trace(backend):
5285
''' Parse McStas trace output from stdin and write results
5386
to file objects csv_comps and csv_lines '''
5487

88+
if backend is not None:
89+
use(backend)
90+
if backend in ('pdf', 'pgf', 'ps', 'svg'):
91+
use('template')
92+
5593
mpl.rcParams['legend.fontsize'] = 10
5694

5795
ax = plt.figure(figsize=plt.figaspect(0.5) * 1.5).add_subplot(projection='3d')
58-
ax.set(xlabel='z', ylabel='x', zlabel='y')
59-
try:
60-
ax.set_aspect('equal')
61-
except:
62-
print("manual aspect not supported")
96+
ax.set(xlabel='z / [m]', ylabel='x / [m]', zlabel='y / [m]')
6397

6498
color = 0
6599

@@ -174,9 +208,15 @@ def parse_trace():
174208
else:
175209
print(line)
176210

211+
ax.set_box_aspect(None)
177212
set_axis_limits(ax)
178213

179-
plt.show()
214+
try:
215+
plt.show()
216+
if backend in ('pdf', 'pgf', 'ps', 'svg'):
217+
dumpfile(backend)
218+
except KeyboardInterrupt:
219+
pass
180220

181221

182222
def process_circle(ax, line, color, comp, transparency):
@@ -427,4 +467,7 @@ def set_axis_limits(ax):
427467

428468

429469
if __name__ == '__main__':
430-
parse_trace()
470+
backend=None
471+
if len(sys.argv) > 1:
472+
backend = sys.argv[1]
473+
parse_trace(backend)

0 commit comments

Comments
 (0)