Skip to content

Commit f3da8f4

Browse files
committed
add to repo
1 parent 1334c8c commit f3da8f4

File tree

1 file changed

+354
-0
lines changed

1 file changed

+354
-0
lines changed

RVC3/bin/rvctool.py

Lines changed: 354 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,354 @@
1+
#!/usr/bin/env python3
2+
3+
# a simple Robotics & Vision Toolbox "shell", runs Python3 and loads
4+
# NumPy, SciPy, RTB-P, SMTB-P, MVTB-P.
5+
#
6+
# Run it from the shell
7+
# $ rvctool
8+
#
9+
# Default switches can be set using the environent variables RVCTOOL, eg.
10+
#
11+
# setenv RVCTOOL "-n"
12+
# export RVCTOOL="-n"
13+
14+
# import stuff
15+
import os
16+
from pathlib import Path
17+
import sys
18+
from importlib.metadata import version
19+
import argparse
20+
21+
from pygments.token import Token
22+
from IPython.terminal.prompts import Prompts
23+
from IPython.terminal.prompts import ClassicPrompts
24+
from traitlets.config import Config
25+
import IPython
26+
import matplotlib as mpl
27+
28+
try:
29+
from colored import fg, bg, attr
30+
31+
_colored = True
32+
# print('using colored output')
33+
except ImportError:
34+
# print('colored not found')
35+
_colored = False
36+
37+
# imports for use by IPython and user
38+
from math import pi # lgtm [py/unused-import]
39+
import numpy as np
40+
from scipy import linalg, optimize
41+
import matplotlib.pyplot as plt # lgtm [py/unused-import]
42+
from spatialmath import * # lgtm [py/polluting-import]
43+
from spatialmath.base import *
44+
from spatialmath.base import sym
45+
46+
47+
def parse_arguments():
48+
parser = argparse.ArgumentParser(
49+
prog="rvctool",
50+
epilog=(
51+
"To set defaults put the relevant command line switches as a string in the"
52+
" environment varible RVCTOOL."
53+
),
54+
description=(
55+
"Interactive python enviroment for exploring the Robotics & Machine Vision"
56+
" toolboxes for Python"
57+
),
58+
)
59+
parser.add_argument("script", default=None, nargs="?", help="specify script to run")
60+
61+
parser.add_argument(
62+
"-B", "--backend", default=None, help="specify graphics backend"
63+
)
64+
parser.add_argument(
65+
"-C",
66+
"--color",
67+
default="neutral",
68+
help=(
69+
"specify terminal color scheme (neutral, lightbg, nocolor, linux), linux is"
70+
" for dark mode"
71+
),
72+
)
73+
parser.add_argument("--confirmexit", "-x", default=False, help="confirm exit")
74+
parser.add_argument("--prompt", "-p", default=None, help="input prompt")
75+
parser.add_argument(
76+
"-r",
77+
"--resultprefix",
78+
default=None,
79+
help="execution result prefix, include {} for execution count number",
80+
)
81+
parser.add_argument(
82+
"-b",
83+
"--no-banner",
84+
dest="banner",
85+
default=True,
86+
action="store_false",
87+
help="suppress startup banner",
88+
)
89+
parser.add_argument(
90+
"-c",
91+
"--nocwd",
92+
dest="cwd",
93+
default=True,
94+
action="store_false",
95+
help="suppress cwd to RVC3 folder",
96+
)
97+
parser.add_argument(
98+
"-a",
99+
"--showassign",
100+
default=False,
101+
action="store_true",
102+
help="do not display the result of assignments",
103+
)
104+
parser.add_argument(
105+
"-n",
106+
"--normal",
107+
dest="book",
108+
default=True,
109+
action="store_false",
110+
help="use normal ipython settings for prompts and display on assignment",
111+
)
112+
parser.add_argument(
113+
"-R",
114+
"--no-robot",
115+
dest="robot",
116+
default=True,
117+
action="store_false",
118+
help="do not import robotics toolbox (RTB-P)",
119+
)
120+
parser.add_argument(
121+
"-V",
122+
"--no-vision",
123+
dest="vision",
124+
default=True,
125+
action="store_false",
126+
help="do not import vision toolbox (MVTB-P)",
127+
)
128+
parser.add_argument(
129+
"--ansi",
130+
default=False,
131+
action="store_true",
132+
help="use ANSImatrix to display matrices",
133+
)
134+
parser.add_argument(
135+
"-e",
136+
"--examples",
137+
default=False,
138+
action="store_true",
139+
help="change working directory to shipped examples",
140+
)
141+
parser.add_argument(
142+
"-s",
143+
"--swift",
144+
default=False,
145+
action="store_true",
146+
help="use Swift as default backend",
147+
)
148+
149+
# add options for light/dark mode
150+
151+
env = os.getenv("RVCTOOL")
152+
if env is not None:
153+
# if envariable is set, parse it just like command line options
154+
args = parser.parse_args(env.split())
155+
# then use it to set the defaults for the actual command line parsing
156+
parser.set_defaults(**args.__dict__)
157+
158+
args, rest = parser.parse_known_args()
159+
160+
# remove the arguments we've just parsed from sys.argv so that IPython can have a
161+
# go at them later
162+
sys.argv = [sys.argv[0]] + rest
163+
164+
if args.script is not None:
165+
args.banner = False
166+
167+
return args
168+
169+
170+
def make_banner(args):
171+
# http://patorjk.com/software/taag/#p=display&f=Standard&t=RVC%203
172+
# print the banner: standard
173+
# https://patorjk.com/software/taag/#p=display&f=Standard&t=Robotics%2C%20Vision%20%26%20Control%203
174+
175+
banner = fg("yellow")
176+
banner += r""" ____ _ _ _ __ ___ _ ___ ____ _ _ _____
177+
| _ \ ___ | |__ ___ | |_(_) ___ ___ \ \ / (_)___(_) ___ _ __ ( _ ) / ___|___ _ __ | |_ _ __ ___ | | |___ /
178+
| |_) / _ \| '_ \ / _ \| __| |/ __/ __| \ \ / /| / __| |/ _ \| '_ \ / _ \/\ | | / _ \| '_ \| __| '__/ _ \| | |_ \
179+
| _ < (_) | |_) | (_) | |_| | (__\__ \_ \ V / | \__ \ | (_) | | | | | (_> < | |__| (_) | | | | |_| | | (_) | | ___) |
180+
|_| \_\___/|_.__/ \___/ \__|_|\___|___( ) \_/ |_|___/_|\___/|_| |_| \___/\/ \____\___/|_| |_|\__|_| \___/|_| |____/
181+
|/
182+
for Python"""
183+
184+
versions = []
185+
if args.robot:
186+
versions.append(f"RTB=={version('roboticstoolbox-python')}")
187+
if args.vision:
188+
versions.append(f"MVTB=={version('machinevision-toolbox-python')}")
189+
try:
190+
versions.append(f"SG=={version('spatialmath-python')}")
191+
except:
192+
pass
193+
versions.append(f"SMTB=={version('spatialmath-python')}")
194+
versions.append(f"NumPy=={version('numpy')}")
195+
versions.append(f"SciPy=={version('scipy')}")
196+
versions.append(f"Matplotlib=={version('matplotlib')}")
197+
198+
# create banner
199+
banner += " (" + ", ".join(versions) + ")"
200+
banner += r"""
201+
202+
import math
203+
import numpy as np
204+
from scipy import linalg, optimize
205+
import matplotlib.pyplot as plt
206+
from spatialmath import *
207+
from spatialmath.base import *
208+
from spatialmath.base import sym
209+
from spatialgeometry import *
210+
"""
211+
if args.robot:
212+
banner += "from roboticstoolbox import *\n"
213+
if args.vision:
214+
banner += """ from machinevisiontoolbox import *
215+
import machinevisiontoolbox.base as mvb
216+
"""
217+
218+
banner += r"""
219+
# useful variables
220+
from math import pi
221+
puma = models.DH.Puma560()
222+
panda = models.DH.Panda()
223+
224+
func/object? - show brief help
225+
help(func/object) - show detailed help
226+
func/object?? - show source code
227+
"""
228+
banner += attr(0)
229+
230+
return banner
231+
232+
233+
def startup():
234+
plt.ion()
235+
236+
237+
def main():
238+
args = parse_arguments()
239+
# print(args)
240+
241+
if args.book:
242+
# set book options
243+
args.resultprefix = ""
244+
args.prompt = ">>> "
245+
args.showassign = True
246+
args.ansi = False
247+
args.examples = True
248+
249+
# setup defaults
250+
np.set_printoptions(
251+
linewidth=120,
252+
formatter={"float": lambda x: f"{x:8.4g}" if abs(x) > 1e-10 else f"{0:8.4g}"},
253+
)
254+
255+
globs = globals()
256+
if args.robot:
257+
exec("from spatialgeometry import *", globs)
258+
exec("from roboticstoolbox import *", globs)
259+
from roboticstoolbox import __path__
260+
261+
sys.path.append(str(Path(__path__[0]) / "examples"))
262+
263+
# load some robot models
264+
globs["puma"] = models.DH.Puma560()
265+
globs["panda"] = models.DH.Panda()
266+
267+
# set default backend for Robot.plot
268+
if args.swift:
269+
Robot.default_backend = "swift"
270+
271+
if args.vision:
272+
exec("from machinevisiontoolbox import *", globs)
273+
exec("import machinevisiontoolbox.base as mvbase", globs)
274+
275+
# set matrix printing mode for spatialmath
276+
SE3._ansimatrix = args.ansi
277+
278+
# set default matplotlib backend
279+
if args.backend is not None:
280+
print(f"Using matplotlib backend {args.backend}")
281+
mpl.use(args.backend)
282+
283+
if args.banner:
284+
banner = make_banner(args)
285+
print(banner)
286+
287+
if args.showassign and args.banner:
288+
print(
289+
fg("red")
290+
+ "Results of assignments will be displayed, use trailing ; to suppress"
291+
+ attr(0)
292+
+ "\n"
293+
)
294+
295+
# append to the module path
296+
# - RVC3 models and examples
297+
# - RTB examples
298+
root = Path(__file__).absolute().parent.parent
299+
sys.path.append(str(root / "models"))
300+
sys.path.append(str(root / "examples"))
301+
302+
if args.cwd:
303+
os.chdir(root)
304+
305+
class MyPrompt(Prompts):
306+
def in_prompt_tokens(self, cli=None):
307+
if args.prompt is None:
308+
return super().in_prompt_tokens()
309+
else:
310+
return [(Token.Prompt, args.prompt)]
311+
312+
def out_prompt_tokens(self, cli=None):
313+
if args.resultprefix is None:
314+
# traditional behaviour
315+
return super().out_prompt_tokens()
316+
else:
317+
return [
318+
(Token.Prompt, args.resultprefix.format(self.shell.execution_count))
319+
]
320+
321+
# set configuration options, there are lots, see
322+
# https://ipython.readthedocs.io/en/stable/config/options/terminal.html
323+
c = Config()
324+
c.InteractiveShellEmbed.colors = args.color
325+
c.InteractiveShell.confirm_exit = args.confirmexit
326+
# c.InteractiveShell.prompts_class = ClassicPrompts
327+
c.InteractiveShell.prompts_class = MyPrompt
328+
if args.showassign:
329+
c.InteractiveShell.ast_node_interactivity = "last_expr_or_assign"
330+
c.TerminalIPythonApp.display_banner = args.banner
331+
332+
# set precision, same as %precision
333+
c.PlainTextFormatter.float_precision = "%.3f"
334+
335+
# set up a script to be executed by IPython when we get there
336+
code = None
337+
if args.script is not None:
338+
path = Path(args.script)
339+
if not path.exists():
340+
raise ValueError(f"script does not exist: {args.script}")
341+
code = path.open("r").readlines()
342+
343+
if code is None:
344+
code = [
345+
"startup()",
346+
"%precision %.3g;",
347+
]
348+
349+
c.InteractiveShellApp.exec_lines = code
350+
IPython.start_ipython(config=c, user_ns=globals())
351+
352+
353+
if __name__ == "__main__":
354+
main()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy