rational-linkages 2.1.0__cp313-cp313-win_amd64.whl → 2.2.1__cp313-cp313-win_amd64.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.
@@ -1,9 +1,7 @@
1
1
  import sys
2
-
3
2
  import numpy as np
4
- import pyqtgraph.opengl as gl
5
- from PyQt6 import QtCore, QtGui, QtWidgets
6
- from PyQt6.QtWidgets import QApplication
3
+
4
+ from warnings import warn
7
5
 
8
6
  from .DualQuaternion import DualQuaternion
9
7
  from .Linkage import LineSegment
@@ -17,6 +15,21 @@ from .RationalCurve import RationalCurve
17
15
  from .RationalMechanism import RationalMechanism
18
16
  from .TransfMatrix import TransfMatrix
19
17
 
18
+ # Try importing GUI components
19
+ try:
20
+ import pyqtgraph.opengl as gl
21
+ from PyQt6 import QtCore, QtGui, QtWidgets
22
+ from PyQt6.QtWidgets import QApplication
23
+ except (ImportError, OSError):
24
+ warn("Failed to import OpenGL or PyQt6. If you expect interactive GUI to work, "
25
+ "please check the package installation.")
26
+
27
+ gl = None
28
+ QtCore = None
29
+ QtGui = None
30
+ QtWidgets = None
31
+ QApplication = None
32
+
20
33
 
21
34
  class PlotterPyqtgraph:
22
35
  """
@@ -598,99 +611,102 @@ class PlotterPyqtgraph:
598
611
  event.accept()
599
612
 
600
613
 
601
- class CustomGLViewWidget(gl.GLViewWidget):
602
- def __init__(self, white_background=False, *args, **kwargs):
603
- super().__init__(*args, **kwargs)
604
- self.labels = []
605
- self.white_background = white_background
606
- # Create an overlay widget for displaying text
607
- self.text_overlay = QtWidgets.QWidget(self)
608
- self.text_overlay.setAttribute(
609
- QtCore.Qt.WidgetAttribute.WA_TransparentForMouseEvents)
610
- self.text_overlay.setStyleSheet("background:transparent;")
611
- self.text_overlay.resize(self.size())
612
- self.text_overlay.show()
613
-
614
- def resizeEvent(self, event):
615
- super().resizeEvent(event)
616
- if hasattr(self, 'text_overlay'):
614
+ if gl is not None:
615
+ class CustomGLViewWidget(gl.GLViewWidget):
616
+ def __init__(self, white_background=False, *args, **kwargs):
617
+ super().__init__(*args, **kwargs)
618
+ self.labels = []
619
+ self.white_background = white_background
620
+ # Create an overlay widget for displaying text
621
+ self.text_overlay = QtWidgets.QWidget(self)
622
+ self.text_overlay.setAttribute(
623
+ QtCore.Qt.WidgetAttribute.WA_TransparentForMouseEvents)
624
+ self.text_overlay.setStyleSheet("background:transparent;")
617
625
  self.text_overlay.resize(self.size())
618
-
619
- def add_label(self, point, text):
620
- """Adds a label for a 3D point."""
621
- self.labels.append({'point': point, 'text': text})
622
- self.update()
623
-
624
- def paintEvent(self, event):
625
- # Only handle standard OpenGL rendering here - no mixing with QPainter
626
- super().paintEvent(event)
627
-
628
- # Schedule label painting as a separate operation
629
- QtCore.QTimer.singleShot(0, self.update_text_overlay)
630
-
631
- def update_text_overlay(self):
632
- """Update the text overlay with current labels"""
633
- # Create a new painter for the overlay widget
634
- self.text_overlay.update()
635
-
636
- def _obtain_label_vec(self, pt):
637
- """Obtain the label vector."""
638
- # Convert the 3D point to homogeneous coordinates
639
- if isinstance(pt, np.ndarray):
640
- point_vec = pt
641
- elif isinstance(pt, PointHomogeneous):
642
- point_vec = [pt.coordinates_normalized[1],
643
- pt.coordinates_normalized[2],
644
- pt.coordinates_normalized[3]]
645
- elif isinstance(pt, TransfMatrix):
646
- point_vec = [pt.t[0], pt.t[1], pt.t[2]]
647
- elif isinstance(pt, FramePlotHelper):
648
- point_vec = [pt.tr.t[0], pt.tr.t[1], pt.tr.t[2]]
649
- else: # is pyqtgraph marker (scatter)
650
- point_vec = [pt.pos[0][0], pt.pos[0][1], pt.pos[0][2]]
651
-
652
- return QtGui.QVector4D(point_vec[0], point_vec[1], point_vec[2], 1.0)
653
-
654
- # This method renders text on the overlay
655
- def paintOverlay(self, event):
656
- painter = QtGui.QPainter(self.text_overlay)
657
- painter.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing)
658
- if self.white_background:
659
- painter.setPen(QtGui.QColor(QtCore.Qt.GlobalColor.black))
660
- else:
661
- painter.setPen(QtGui.QColor(QtCore.Qt.GlobalColor.white))
662
-
663
- # Get the Model-View-Projection matrix
664
- projection_matrix = self.projectionMatrix()
665
- view_matrix = self.viewMatrix()
666
- mvp = projection_matrix * view_matrix
667
-
668
- # Draw all labels
669
- for entry in self.labels:
670
- point = entry['point']
671
- text = entry['text']
672
-
673
- projected = mvp.map(self._obtain_label_vec(point))
674
- if projected.w() != 0:
675
- ndc_x = projected.x() / projected.w()
676
- ndc_y = projected.y() / projected.w()
677
- # Check if the point is in front of the camera
678
- if projected.z() / projected.w() < 1.0:
679
- x = int((ndc_x * 0.5 + 0.5) * self.width())
680
- y = int((1 - (ndc_y * 0.5 + 0.5)) * self.height())
681
- painter.drawText(x, y, text)
682
-
683
- painter.end()
684
-
685
- def showEvent(self, event):
686
- super().showEvent(event)
687
- self.text_overlay.installEventFilter(self)
688
-
689
- def eventFilter(self, obj, event):
690
- if obj is self.text_overlay and event.type() == QtCore.QEvent.Type.Paint:
691
- self.paintOverlay(event)
692
- return True
693
- return super().eventFilter(obj, event)
626
+ self.text_overlay.show()
627
+
628
+ def resizeEvent(self, event):
629
+ super().resizeEvent(event)
630
+ if hasattr(self, 'text_overlay'):
631
+ self.text_overlay.resize(self.size())
632
+
633
+ def add_label(self, point, text):
634
+ """Adds a label for a 3D point."""
635
+ self.labels.append({'point': point, 'text': text})
636
+ self.update()
637
+
638
+ def paintEvent(self, event):
639
+ # Only handle standard OpenGL rendering here - no mixing with QPainter
640
+ super().paintEvent(event)
641
+
642
+ # Schedule label painting as a separate operation
643
+ QtCore.QTimer.singleShot(0, self.update_text_overlay)
644
+
645
+ def update_text_overlay(self):
646
+ """Update the text overlay with current labels"""
647
+ # Create a new painter for the overlay widget
648
+ self.text_overlay.update()
649
+
650
+ def _obtain_label_vec(self, pt):
651
+ """Obtain the label vector."""
652
+ # Convert the 3D point to homogeneous coordinates
653
+ if isinstance(pt, np.ndarray):
654
+ point_vec = pt
655
+ elif isinstance(pt, PointHomogeneous):
656
+ point_vec = [pt.coordinates_normalized[1],
657
+ pt.coordinates_normalized[2],
658
+ pt.coordinates_normalized[3]]
659
+ elif isinstance(pt, TransfMatrix):
660
+ point_vec = [pt.t[0], pt.t[1], pt.t[2]]
661
+ elif isinstance(pt, FramePlotHelper):
662
+ point_vec = [pt.tr.t[0], pt.tr.t[1], pt.tr.t[2]]
663
+ else: # is pyqtgraph marker (scatter)
664
+ point_vec = [pt.pos[0][0], pt.pos[0][1], pt.pos[0][2]]
665
+
666
+ return QtGui.QVector4D(point_vec[0], point_vec[1], point_vec[2], 1.0)
667
+
668
+ # This method renders text on the overlay
669
+ def paintOverlay(self, event):
670
+ painter = QtGui.QPainter(self.text_overlay)
671
+ painter.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing)
672
+ if self.white_background:
673
+ painter.setPen(QtGui.QColor(QtCore.Qt.GlobalColor.black))
674
+ else:
675
+ painter.setPen(QtGui.QColor(QtCore.Qt.GlobalColor.white))
676
+
677
+ # Get the Model-View-Projection matrix
678
+ projection_matrix = self.projectionMatrix()
679
+ view_matrix = self.viewMatrix()
680
+ mvp = projection_matrix * view_matrix
681
+
682
+ # Draw all labels
683
+ for entry in self.labels:
684
+ point = entry['point']
685
+ text = entry['text']
686
+
687
+ projected = mvp.map(self._obtain_label_vec(point))
688
+ if projected.w() != 0:
689
+ ndc_x = projected.x() / projected.w()
690
+ ndc_y = projected.y() / projected.w()
691
+ # Check if the point is in front of the camera
692
+ if projected.z() / projected.w() < 1.0:
693
+ x = int((ndc_x * 0.5 + 0.5) * self.width())
694
+ y = int((1 - (ndc_y * 0.5 + 0.5)) * self.height())
695
+ painter.drawText(x, y, text)
696
+
697
+ painter.end()
698
+
699
+ def showEvent(self, event):
700
+ super().showEvent(event)
701
+ self.text_overlay.installEventFilter(self)
702
+
703
+ def eventFilter(self, obj, event):
704
+ if obj is self.text_overlay and event.type() == QtCore.QEvent.Type.Paint:
705
+ self.paintOverlay(event)
706
+ return True
707
+ return super().eventFilter(obj, event)
708
+ else:
709
+ CustomGLViewWidget = None
694
710
 
695
711
 
696
712
  class FramePlotHelper:
@@ -753,388 +769,389 @@ class FramePlotHelper:
753
769
  view.addItem(self.y_axis)
754
770
  view.addItem(self.z_axis)
755
771
 
756
-
757
- class InteractivePlotterWidget(QtWidgets.QWidget):
758
- """
759
- A QWidget that contains a PlotterPyqtgraph 3D view and interactive controls.
760
-
761
- Containts (sliders and text boxes) for plotting and manipulating a mechanism.
762
- """
763
- def __init__(self,
764
- mechanism: RationalMechanism,
765
- base=None,
766
- show_tool: bool = True,
767
- steps: int = 1000,
768
- joint_sliders_lim: float = 1.0,
769
- arrows_length: float = 1.0,
770
- white_background: bool = False,
771
- parent=None,
772
- parent_app=None):
773
- super().__init__(parent)
774
- self.setMinimumSize(800, 600)
775
-
776
- self.mechanism = mechanism
777
- self.show_tool = show_tool
778
- self.steps = steps
779
- self.joint_sliders_lim = joint_sliders_lim
780
- self.arrows_length = arrows_length
781
-
782
- if base is not None:
783
- if isinstance(base, TransfMatrix):
784
- if not base.is_rotation():
785
- raise ValueError("Given matrix is not proper rotation.")
786
- self.base = base
787
- self.base_arr = self.base.array()
788
- elif isinstance(base, DualQuaternion):
789
- self.base = TransfMatrix(base.dq2matrix())
790
- self.base_arr = self.base.array()
772
+ if QtWidgets is not None:
773
+ class InteractivePlotterWidget(QtWidgets.QWidget):
774
+ """
775
+ A QWidget that contains a PlotterPyqtgraph 3D view and interactive controls.
776
+
777
+ Containts (sliders and text boxes) for plotting and manipulating a mechanism.
778
+ """
779
+ def __init__(self,
780
+ mechanism: RationalMechanism,
781
+ base=None,
782
+ show_tool: bool = True,
783
+ steps: int = 1000,
784
+ joint_sliders_lim: float = 1.0,
785
+ arrows_length: float = 1.0,
786
+ white_background: bool = False,
787
+ parent=None,
788
+ parent_app=None):
789
+ super().__init__(parent)
790
+ self.setMinimumSize(800, 600)
791
+
792
+ self.mechanism = mechanism
793
+ self.show_tool = show_tool
794
+ self.steps = steps
795
+ self.joint_sliders_lim = joint_sliders_lim
796
+ self.arrows_length = arrows_length
797
+
798
+ if base is not None:
799
+ if isinstance(base, TransfMatrix):
800
+ if not base.is_rotation():
801
+ raise ValueError("Given matrix is not proper rotation.")
802
+ self.base = base
803
+ self.base_arr = self.base.array()
804
+ elif isinstance(base, DualQuaternion):
805
+ self.base = TransfMatrix(base.dq2matrix())
806
+ self.base_arr = self.base.array()
807
+ else:
808
+ raise TypeError("Base must be a TransfMatrix or DualQuaternion instance.")
791
809
  else:
792
- raise TypeError("Base must be a TransfMatrix or DualQuaternion instance.")
793
- else:
794
- self.base = None
795
- self.base_arr = None
810
+ self.base = None
811
+ self.base_arr = None
796
812
 
797
- self.white_background = white_background
798
- if self.white_background:
799
- self.render_mode = 'translucent'
800
- else:
801
- self.render_mode = 'additive'
802
-
803
- # Create the PlotterPyqtgraph instance.
804
- self.plotter = PlotterPyqtgraph(base=None,
805
- steps=self.steps,
806
- arrows_length=self.arrows_length,
807
- white_background=self.white_background,
808
- parent_app=parent_app)
809
- # Optionally adjust the camera.
810
- self.plotter.widget.setCameraPosition(distance=10, azimuth=30, elevation=30)
811
-
812
- # Main layout: split between the 3D view and a control panel.
813
- main_layout = QtWidgets.QHBoxLayout(self)
814
-
815
- # Add the 3D view (PlotterPyqtgraph’s widget) to the layout.
816
- main_layout.addWidget(self.plotter.widget, stretch=5)
817
-
818
- # Create the control panel (on the right).
819
- control_panel = QtWidgets.QWidget()
820
- control_layout = QtWidgets.QVBoxLayout(control_panel)
821
-
822
- # --- Driving joint angle slider ---
823
- control_layout.addWidget(QtWidgets.QLabel("Joint angle [rad]:"))
824
- self.move_slider = self.create_float_slider(0.0, 2 * np.pi, 0.0,
825
- orientation=QtCore.Qt.Orientation.Horizontal)
826
- control_layout.addWidget(self.move_slider)
827
-
828
- # --- Text boxes ---
829
- self.text_box_angle = QtWidgets.QLineEdit()
830
- self.text_box_angle.setPlaceholderText("Set angle [rad]:")
831
- control_layout.addWidget(self.text_box_angle)
832
-
833
- self.text_box_param = QtWidgets.QLineEdit()
834
- self.text_box_param.setPlaceholderText("Set parameter t [-]:")
835
- control_layout.addWidget(self.text_box_param)
836
-
837
- self.save_mech_pkl = QtWidgets.QLineEdit()
838
- self.save_mech_pkl.setPlaceholderText("Save mechanism PKL, filename:")
839
- control_layout.addWidget(self.save_mech_pkl)
840
-
841
- self.save_figure_box = QtWidgets.QLineEdit()
842
- self.save_figure_box.setPlaceholderText("Save figure PNG, filename:")
843
- control_layout.addWidget(self.save_figure_box)
844
-
845
- # --- Joint connection sliders ---
846
- joint_sliders_layout = QtWidgets.QHBoxLayout()
847
- self.joint_sliders = []
848
-
849
- # Initialize sliders for each joint
850
- for i in range(self.mechanism.num_joints):
851
- slider0, slider1 = self._init_joint_sliders(i, self.joint_sliders_lim)
852
- self.joint_sliders.append(slider0)
853
- self.joint_sliders.append(slider1)
854
-
855
- # Arrange sliders vertically for each joint
856
- joint_layout = QtWidgets.QVBoxLayout()
857
-
858
- joint_layout.addWidget(QtWidgets.QLabel(f"j{i}cp0"))
859
- joint_layout.addWidget(slider0)
860
- joint_layout.addWidget(QtWidgets.QLabel(f"j{i}cp1"))
861
- joint_layout.addWidget(slider1)
862
-
863
- joint_sliders_layout.addLayout(joint_layout)
864
-
865
- control_layout.addLayout(joint_sliders_layout)
866
-
867
- # Set default values for the first factorization
868
- for i in range(self.mechanism.factorizations[0].number_of_factors):
869
- default_val0 = self.mechanism.factorizations[0].linkage[i].points_params[0]
870
- default_val1 = self.mechanism.factorizations[0].linkage[i].points_params[1]
871
- self.joint_sliders[2 * i].setValue(int(default_val0 * 100))
872
- self.joint_sliders[2 * i + 1].setValue(int(default_val1 * 100))
873
-
874
- # Set default values for the second factorization
875
- offset = 2 * self.mechanism.factorizations[0].number_of_factors
876
- for i in range(self.mechanism.factorizations[1].number_of_factors):
877
- default_val0 = self.mechanism.factorizations[1].linkage[i].points_params[0]
878
- default_val1 = self.mechanism.factorizations[1].linkage[i].points_params[1]
879
- self.joint_sliders[offset + 2 * i].setValue(int(default_val0 * 100))
880
- self.joint_sliders[offset + 2 * i + 1].setValue(int(default_val1 * 100))
881
-
882
- main_layout.addWidget(control_panel, stretch=1)
883
-
884
- # --- Initialize plot items for the mechanism links ---
885
- self.lines = []
886
- num_lines = self.mechanism.num_joints * 2
887
- for i in range(num_lines):
888
- # if i is even, make the link color green, and joints red
889
- if i % 2 == 0:
890
- line_item = gl.GLLinePlotItem(pos=np.zeros((2, 3)),
891
- color=(0, 1, 0, 1),
892
- glOptions=self.render_mode,
893
- width=5,
894
- antialias=True)
813
+ self.white_background = white_background
814
+ if self.white_background:
815
+ self.render_mode = 'translucent'
895
816
  else:
896
- line_item = gl.GLLinePlotItem(pos=np.zeros((2, 3)),
897
- color=(1, 0, 0, 1),
898
- glOptions=self.render_mode,
899
- width=5,
900
- antialias=True)
901
- self.lines.append(line_item)
902
- self.plotter.widget.addItem(line_item)
903
-
904
- # --- If desired, initialize tool plot and tool frame ---
905
- if self.show_tool:
906
- self.tool_link = gl.GLLinePlotItem(pos=np.zeros((3, 3)),
907
- color=(0, 1, 0, 0.5),
908
- glOptions=self.render_mode,
909
- width=5,
910
- antialias=True)
911
- self.plotter.widget.addItem(self.tool_link)
912
- self.tool_frame = FramePlotHelper(
913
- transform=TransfMatrix(self.mechanism.tool_frame.dq2matrix()),
914
- length=self.arrows_length)
915
- self.tool_frame.addToView(self.plotter.widget)
916
-
917
- # --- Plot the tool path ---
918
- self._plot_tool_path()
919
-
920
- # --- Connect signals to slots ---
921
- self.move_slider.valueChanged.connect(self.on_move_slider_changed)
922
- self.text_box_angle.returnPressed.connect(self.on_angle_text_entered)
923
- self.text_box_param.returnPressed.connect(self.on_param_text_entered)
924
- self.save_mech_pkl.returnPressed.connect(self.on_save_save_mech_pkl)
925
- self.save_figure_box.returnPressed.connect(self.on_save_figure_box)
926
- for slider in self.joint_sliders:
927
- slider.valueChanged.connect(self.on_joint_slider_changed)
928
-
929
- # Set initial configuration (home position)
930
- self.move_slider.setValue(self.move_slider.minimum())
931
- self.plot_slider_update(self.move_slider.value() / 100.0)
932
-
933
- self.setWindowTitle('Rational Linkages')
934
-
935
- # --- Helper to create a “float slider” (using integer scaling) ---
936
- def create_float_slider(self, min_val, max_val, init_val,
937
- orientation=QtCore.Qt.Orientation.Horizontal):
938
- slider = QtWidgets.QSlider(orientation)
939
- slider.setMinimum(int(min_val * 100))
940
- slider.setMaximum(int(max_val * 100))
941
- slider.setValue(int(init_val * 100))
942
- slider.setTickPosition(QtWidgets.QSlider.TickPosition.TicksBelow)
943
- slider.setTickInterval(10)
944
- return slider
945
-
946
- def _init_joint_sliders(self, idx, slider_limit):
947
- """
948
- Create a pair of vertical sliders for joint connection parameters.
949
- (The slider values are scaled by 100.)
950
- """
951
- slider0 = self.create_float_slider(-slider_limit,
952
- slider_limit,
953
- 0.0,
954
- orientation=QtCore.Qt.Orientation.Vertical)
955
- slider1 = self.create_float_slider(-slider_limit,
956
- slider_limit,
957
- 0.0,
958
- orientation=QtCore.Qt.Orientation.Vertical)
959
- return slider0, slider1
960
-
961
- def _plot_tool_path(self):
962
- """
963
- Plot the tool path (as a continuous line) using a set of computed points.
964
- """
965
- t_lin = np.linspace(0, 2 * np.pi, self.steps)
966
- t_vals = [self.mechanism.factorizations[0].joint_angle_to_t_param(t)
967
- for t in t_lin]
968
- ee_points = [self.mechanism.factorizations[0].direct_kinematics_of_tool(
969
- t, self.mechanism.tool_frame.dq2point_via_matrix())
970
- for t in t_vals]
971
-
972
- if self.base_arr is not None:
973
- # transform the end-effector points by the base transformation
974
- ee_points = [self.base_arr @ np.insert(p, 0, 1) for p in ee_points]
975
- # normalize
976
- ee_points = [p[1:4]/p[0] for p in ee_points]
977
-
978
- pts = np.array(ee_points)
979
- tool_path = gl.GLLinePlotItem(pos=pts,
980
- color=(0.5, 0.5, 0.5, 1),
981
- glOptions=self.render_mode,
982
- width=2,
983
- antialias=True)
984
- self.plotter.widget.addItem(tool_path)
985
-
986
- # --- Slots for interactive control events ---
987
- def on_move_slider_changed(self, value):
988
- """
989
- Called when the driving joint angle slider is moved.
990
- """
991
- angle = value / 100.0 # Convert back to a float value.
992
- self.plot_slider_update(angle)
993
-
994
- def on_angle_text_entered(self):
995
- """
996
- Called when the angle text box is submitted.
997
- """
998
- try:
999
- val = float(self.text_box_angle.text())
1000
- # Normalize angle to [0, 2*pi]
1001
- if val >= 0:
1002
- val = val % (2 * np.pi)
817
+ self.render_mode = 'additive'
818
+
819
+ # Create the PlotterPyqtgraph instance.
820
+ self.plotter = PlotterPyqtgraph(base=None,
821
+ steps=self.steps,
822
+ arrows_length=self.arrows_length,
823
+ white_background=self.white_background,
824
+ parent_app=parent_app)
825
+ # Optionally adjust the camera.
826
+ self.plotter.widget.setCameraPosition(distance=10, azimuth=30, elevation=30)
827
+
828
+ # Main layout: split between the 3D view and a control panel.
829
+ main_layout = QtWidgets.QHBoxLayout(self)
830
+
831
+ # Add the 3D view (PlotterPyqtgraph’s widget) to the layout.
832
+ main_layout.addWidget(self.plotter.widget, stretch=5)
833
+
834
+ # Create the control panel (on the right).
835
+ control_panel = QtWidgets.QWidget()
836
+ control_layout = QtWidgets.QVBoxLayout(control_panel)
837
+
838
+ # --- Driving joint angle slider ---
839
+ control_layout.addWidget(QtWidgets.QLabel("Joint angle [rad]:"))
840
+ self.move_slider = self.create_float_slider(0.0, 2 * np.pi, 0.0,
841
+ orientation=QtCore.Qt.Orientation.Horizontal)
842
+ control_layout.addWidget(self.move_slider)
843
+
844
+ # --- Text boxes ---
845
+ self.text_box_angle = QtWidgets.QLineEdit()
846
+ self.text_box_angle.setPlaceholderText("Set angle [rad]:")
847
+ control_layout.addWidget(self.text_box_angle)
848
+
849
+ self.text_box_param = QtWidgets.QLineEdit()
850
+ self.text_box_param.setPlaceholderText("Set parameter t [-]:")
851
+ control_layout.addWidget(self.text_box_param)
852
+
853
+ self.save_mech_pkl = QtWidgets.QLineEdit()
854
+ self.save_mech_pkl.setPlaceholderText("Save mechanism PKL, filename:")
855
+ control_layout.addWidget(self.save_mech_pkl)
856
+
857
+ self.save_figure_box = QtWidgets.QLineEdit()
858
+ self.save_figure_box.setPlaceholderText("Save figure PNG, filename:")
859
+ control_layout.addWidget(self.save_figure_box)
860
+
861
+ # --- Joint connection sliders ---
862
+ joint_sliders_layout = QtWidgets.QHBoxLayout()
863
+ self.joint_sliders = []
864
+
865
+ # Initialize sliders for each joint
866
+ for i in range(self.mechanism.num_joints):
867
+ slider0, slider1 = self._init_joint_sliders(i, self.joint_sliders_lim)
868
+ self.joint_sliders.append(slider0)
869
+ self.joint_sliders.append(slider1)
870
+
871
+ # Arrange sliders vertically for each joint
872
+ joint_layout = QtWidgets.QVBoxLayout()
873
+
874
+ joint_layout.addWidget(QtWidgets.QLabel(f"j{i}cp0"))
875
+ joint_layout.addWidget(slider0)
876
+ joint_layout.addWidget(QtWidgets.QLabel(f"j{i}cp1"))
877
+ joint_layout.addWidget(slider1)
878
+
879
+ joint_sliders_layout.addLayout(joint_layout)
880
+
881
+ control_layout.addLayout(joint_sliders_layout)
882
+
883
+ # Set default values for the first factorization
884
+ for i in range(self.mechanism.factorizations[0].number_of_factors):
885
+ default_val0 = self.mechanism.factorizations[0].linkage[i].points_params[0]
886
+ default_val1 = self.mechanism.factorizations[0].linkage[i].points_params[1]
887
+ self.joint_sliders[2 * i].setValue(int(default_val0 * 100))
888
+ self.joint_sliders[2 * i + 1].setValue(int(default_val1 * 100))
889
+
890
+ # Set default values for the second factorization
891
+ offset = 2 * self.mechanism.factorizations[0].number_of_factors
892
+ for i in range(self.mechanism.factorizations[1].number_of_factors):
893
+ default_val0 = self.mechanism.factorizations[1].linkage[i].points_params[0]
894
+ default_val1 = self.mechanism.factorizations[1].linkage[i].points_params[1]
895
+ self.joint_sliders[offset + 2 * i].setValue(int(default_val0 * 100))
896
+ self.joint_sliders[offset + 2 * i + 1].setValue(int(default_val1 * 100))
897
+
898
+ main_layout.addWidget(control_panel, stretch=1)
899
+
900
+ # --- Initialize plot items for the mechanism links ---
901
+ self.lines = []
902
+ num_lines = self.mechanism.num_joints * 2
903
+ for i in range(num_lines):
904
+ # if i is even, make the link color green, and joints red
905
+ if i % 2 == 0:
906
+ line_item = gl.GLLinePlotItem(pos=np.zeros((2, 3)),
907
+ color=(0, 1, 0, 1),
908
+ glOptions=self.render_mode,
909
+ width=5,
910
+ antialias=True)
911
+ else:
912
+ line_item = gl.GLLinePlotItem(pos=np.zeros((2, 3)),
913
+ color=(1, 0, 0, 1),
914
+ glOptions=self.render_mode,
915
+ width=5,
916
+ antialias=True)
917
+ self.lines.append(line_item)
918
+ self.plotter.widget.addItem(line_item)
919
+
920
+ # --- If desired, initialize tool plot and tool frame ---
921
+ if self.show_tool:
922
+ self.tool_link = gl.GLLinePlotItem(pos=np.zeros((3, 3)),
923
+ color=(0, 1, 0, 0.5),
924
+ glOptions=self.render_mode,
925
+ width=5,
926
+ antialias=True)
927
+ self.plotter.widget.addItem(self.tool_link)
928
+ self.tool_frame = FramePlotHelper(
929
+ transform=TransfMatrix(self.mechanism.tool_frame.dq2matrix()),
930
+ length=self.arrows_length)
931
+ self.tool_frame.addToView(self.plotter.widget)
932
+
933
+ # --- Plot the tool path ---
934
+ self._plot_tool_path()
935
+
936
+ # --- Connect signals to slots ---
937
+ self.move_slider.valueChanged.connect(self.on_move_slider_changed)
938
+ self.text_box_angle.returnPressed.connect(self.on_angle_text_entered)
939
+ self.text_box_param.returnPressed.connect(self.on_param_text_entered)
940
+ self.save_mech_pkl.returnPressed.connect(self.on_save_save_mech_pkl)
941
+ self.save_figure_box.returnPressed.connect(self.on_save_figure_box)
942
+ for slider in self.joint_sliders:
943
+ slider.valueChanged.connect(self.on_joint_slider_changed)
944
+
945
+ # Set initial configuration (home position)
946
+ self.move_slider.setValue(self.move_slider.minimum())
947
+ self.plot_slider_update(self.move_slider.value() / 100.0)
948
+
949
+ self.setWindowTitle('Rational Linkages')
950
+
951
+ # --- Helper to create a “float slider” (using integer scaling) ---
952
+ def create_float_slider(self, min_val, max_val, init_val,
953
+ orientation=QtCore.Qt.Orientation.Horizontal):
954
+ slider = QtWidgets.QSlider(orientation)
955
+ slider.setMinimum(int(min_val * 100))
956
+ slider.setMaximum(int(max_val * 100))
957
+ slider.setValue(int(init_val * 100))
958
+ slider.setTickPosition(QtWidgets.QSlider.TickPosition.TicksBelow)
959
+ slider.setTickInterval(10)
960
+ return slider
961
+
962
+ def _init_joint_sliders(self, idx, slider_limit):
963
+ """
964
+ Create a pair of vertical sliders for joint connection parameters.
965
+ (The slider values are scaled by 100.)
966
+ """
967
+ slider0 = self.create_float_slider(-slider_limit,
968
+ slider_limit,
969
+ 0.0,
970
+ orientation=QtCore.Qt.Orientation.Vertical)
971
+ slider1 = self.create_float_slider(-slider_limit,
972
+ slider_limit,
973
+ 0.0,
974
+ orientation=QtCore.Qt.Orientation.Vertical)
975
+ return slider0, slider1
976
+
977
+ def _plot_tool_path(self):
978
+ """
979
+ Plot the tool path (as a continuous line) using a set of computed points.
980
+ """
981
+ t_lin = np.linspace(0, 2 * np.pi, self.steps)
982
+ t_vals = [self.mechanism.factorizations[0].joint_angle_to_t_param(t)
983
+ for t in t_lin]
984
+ ee_points = [self.mechanism.factorizations[0].direct_kinematics_of_tool(
985
+ t, self.mechanism.tool_frame.dq2point_via_matrix())
986
+ for t in t_vals]
987
+
988
+ if self.base_arr is not None:
989
+ # transform the end-effector points by the base transformation
990
+ ee_points = [self.base_arr @ np.insert(p, 0, 1) for p in ee_points]
991
+ # normalize
992
+ ee_points = [p[1:4]/p[0] for p in ee_points]
993
+
994
+ pts = np.array(ee_points)
995
+ tool_path = gl.GLLinePlotItem(pos=pts,
996
+ color=(0.5, 0.5, 0.5, 1),
997
+ glOptions=self.render_mode,
998
+ width=2,
999
+ antialias=True)
1000
+ self.plotter.widget.addItem(tool_path)
1001
+
1002
+ # --- Slots for interactive control events ---
1003
+ def on_move_slider_changed(self, value):
1004
+ """
1005
+ Called when the driving joint angle slider is moved.
1006
+ """
1007
+ angle = value / 100.0 # Convert back to a float value.
1008
+ self.plot_slider_update(angle)
1009
+
1010
+ def on_angle_text_entered(self):
1011
+ """
1012
+ Called when the angle text box is submitted.
1013
+ """
1014
+ try:
1015
+ val = float(self.text_box_angle.text())
1016
+ # Normalize angle to [0, 2*pi]
1017
+ if val >= 0:
1018
+ val = val % (2 * np.pi)
1019
+ else:
1020
+ val = (val % (2 * np.pi)) - np.pi
1021
+ self.move_slider.setValue(int(val * 100))
1022
+ except ValueError:
1023
+ pass
1024
+
1025
+ def on_param_text_entered(self):
1026
+ """
1027
+ Called when the t-parameter text box is submitted.
1028
+ """
1029
+ try:
1030
+ val = float(self.text_box_param.text())
1031
+ self.plot_slider_update(val, t_param=val)
1032
+ joint_angle = self.mechanism.factorizations[0].t_param_to_joint_angle(val)
1033
+ self.move_slider.setValue(int(joint_angle * 100))
1034
+ except ValueError:
1035
+ pass
1036
+
1037
+ def on_save_save_mech_pkl(self):
1038
+ """
1039
+ Called when the save text box is submitted.
1040
+ """
1041
+ filename = self.save_mech_pkl.text()
1042
+ self.mechanism.save(filename=filename)
1043
+
1044
+ QtWidgets.QMessageBox.information(self,
1045
+ "Success",
1046
+ f"Mechanism saved as {filename}.pkl")
1047
+
1048
+ def on_save_figure_box(self):
1049
+ """
1050
+ Called when the filesave text box is submitted.
1051
+
1052
+ Saves the current figure in the specified format.
1053
+ """
1054
+ filename = self.save_figure_box.text()
1055
+
1056
+ # better quality but does not save the text overlay
1057
+ #self.plotter.widget.readQImage().save(filename + "_old.png")
1058
+ #self.plotter.widget.readQImage().save(filename + "_old.png", quality=100)
1059
+
1060
+ image = QtGui.QImage(self.plotter.widget.size(),
1061
+ QtGui.QImage.Format.Format_ARGB32_Premultiplied)
1062
+ image.fill(QtCore.Qt.GlobalColor.transparent)
1063
+
1064
+ # Create a painter and render the widget into the image
1065
+ painter = QtGui.QPainter(image)
1066
+ self.plotter.widget.render(painter)
1067
+ painter.end()
1068
+
1069
+ # Save the image
1070
+ image.save(filename + ".png", "PNG", 80)
1071
+
1072
+ QtWidgets.QMessageBox.information(self,
1073
+ "Success",
1074
+ f"Figure saved as {filename}.png")
1075
+
1076
+ def on_joint_slider_changed(self, value):
1077
+ """
1078
+ Called when any joint slider is changed.
1079
+ Updates the joint connection parameters and refreshes the plot.
1080
+ """
1081
+ num_of_factors = self.mechanism.factorizations[0].number_of_factors
1082
+ # Update first factorization's linkage parameters.
1083
+ for i in range(num_of_factors):
1084
+ self.mechanism.factorizations[0].linkage[i].set_point_by_param(
1085
+ 0, self.joint_sliders[2 * i].value() / 100.0)
1086
+ self.mechanism.factorizations[0].linkage[i].set_point_by_param(
1087
+ 1, self.joint_sliders[2 * i + 1].value() / 100.0)
1088
+ # Update second factorization's linkage parameters.
1089
+ for i in range(num_of_factors):
1090
+ self.mechanism.factorizations[1].linkage[i].set_point_by_param(
1091
+ 0, self.joint_sliders[2 * num_of_factors + 2 * i].value() / 100.0)
1092
+ self.mechanism.factorizations[1].linkage[i].set_point_by_param(
1093
+ 1, self.joint_sliders[2 * num_of_factors + 1 + 2 * i].value() / 100.0)
1094
+ self.plot_slider_update(self.move_slider.value() / 100.0)
1095
+
1096
+ def plot_slider_update(self, angle, t_param=None):
1097
+ """
1098
+ Update the mechanism plot based on the current joint angle or t parameter.
1099
+ """
1100
+ if t_param is not None:
1101
+ t = t_param
1003
1102
  else:
1004
- val = (val % (2 * np.pi)) - np.pi
1005
- self.move_slider.setValue(int(val * 100))
1006
- except ValueError:
1007
- pass
1008
-
1009
- def on_param_text_entered(self):
1010
- """
1011
- Called when the t-parameter text box is submitted.
1012
- """
1013
- try:
1014
- val = float(self.text_box_param.text())
1015
- self.plot_slider_update(val, t_param=val)
1016
- joint_angle = self.mechanism.factorizations[0].t_param_to_joint_angle(val)
1017
- self.move_slider.setValue(int(joint_angle * 100))
1018
- except ValueError:
1019
- pass
1020
-
1021
- def on_save_save_mech_pkl(self):
1022
- """
1023
- Called when the save text box is submitted.
1024
- """
1025
- filename = self.save_mech_pkl.text()
1026
- self.mechanism.save(filename=filename)
1027
-
1028
- QtWidgets.QMessageBox.information(self,
1029
- "Success",
1030
- f"Mechanism saved as {filename}.pkl")
1103
+ t = self.mechanism.factorizations[0].joint_angle_to_t_param(angle)
1031
1104
 
1032
- def on_save_figure_box(self):
1033
- """
1034
- Called when the filesave text box is submitted.
1035
-
1036
- Saves the current figure in the specified format.
1037
- """
1038
- filename = self.save_figure_box.text()
1039
-
1040
- # better quality but does not save the text overlay
1041
- #self.plotter.widget.readQImage().save(filename + "_old.png")
1042
- #self.plotter.widget.readQImage().save(filename + "_old.png", quality=100)
1043
-
1044
- image = QtGui.QImage(self.plotter.widget.size(),
1045
- QtGui.QImage.Format.Format_ARGB32_Premultiplied)
1046
- image.fill(QtCore.Qt.GlobalColor.transparent)
1047
-
1048
- # Create a painter and render the widget into the image
1049
- painter = QtGui.QPainter(image)
1050
- self.plotter.widget.render(painter)
1051
- painter.end()
1052
-
1053
- # Save the image
1054
- image.save(filename + ".png", "PNG", 80)
1055
-
1056
- QtWidgets.QMessageBox.information(self,
1057
- "Success",
1058
- f"Figure saved as {filename}.png")
1059
-
1060
- def on_joint_slider_changed(self, value):
1061
- """
1062
- Called when any joint slider is changed.
1063
- Updates the joint connection parameters and refreshes the plot.
1064
- """
1065
- num_of_factors = self.mechanism.factorizations[0].number_of_factors
1066
- # Update first factorization's linkage parameters.
1067
- for i in range(num_of_factors):
1068
- self.mechanism.factorizations[0].linkage[i].set_point_by_param(
1069
- 0, self.joint_sliders[2 * i].value() / 100.0)
1070
- self.mechanism.factorizations[0].linkage[i].set_point_by_param(
1071
- 1, self.joint_sliders[2 * i + 1].value() / 100.0)
1072
- # Update second factorization's linkage parameters.
1073
- for i in range(num_of_factors):
1074
- self.mechanism.factorizations[1].linkage[i].set_point_by_param(
1075
- 0, self.joint_sliders[2 * num_of_factors + 2 * i].value() / 100.0)
1076
- self.mechanism.factorizations[1].linkage[i].set_point_by_param(
1077
- 1, self.joint_sliders[2 * num_of_factors + 1 + 2 * i].value() / 100.0)
1078
- self.plot_slider_update(self.move_slider.value() / 100.0)
1079
-
1080
- def plot_slider_update(self, angle, t_param=None):
1081
- """
1082
- Update the mechanism plot based on the current joint angle or t parameter.
1083
- """
1084
- if t_param is not None:
1085
- t = t_param
1086
- else:
1087
- t = self.mechanism.factorizations[0].joint_angle_to_t_param(angle)
1088
-
1089
- # Compute link positions.
1090
- links = (self.mechanism.factorizations[0].direct_kinematics(t) +
1091
- self.mechanism.factorizations[1].direct_kinematics(t)[::-1])
1092
- links.insert(0, links[-1])
1093
-
1094
- if self.base is not None:
1095
- # Transform the links by the base transformation.
1096
- links = [self.base_arr @ np.insert(p, 0, 1) for p in links]
1097
- # Normalize the homogeneous coordinates.
1098
- links = [p[1:4] / p[0] for p in links]
1099
-
1100
- # Update each line segment.
1101
- for i, line in enumerate(self.lines):
1102
- pt1 = links[i]
1103
- pt2 = links[i+1]
1104
- pts = np.array([pt1, pt2])
1105
- line.setData(pos=pts)
1106
-
1107
- if self.show_tool:
1108
- pts0 = self.mechanism.factorizations[0].direct_kinematics(t)[-1]
1109
- pts1 = self.mechanism.factorizations[0].direct_kinematics_of_tool(
1110
- t, self.mechanism.tool_frame.dq2point_via_matrix())
1111
- pts2 = self.mechanism.factorizations[1].direct_kinematics(t)[-1]
1112
-
1113
- tool_triangle = [pts0, pts1, pts2]
1105
+ # Compute link positions.
1106
+ links = (self.mechanism.factorizations[0].direct_kinematics(t) +
1107
+ self.mechanism.factorizations[1].direct_kinematics(t)[::-1])
1108
+ links.insert(0, links[-1])
1114
1109
 
1115
1110
  if self.base is not None:
1116
- # Transform the tool triangle by the base transformation.
1117
- tool_triangle = [self.base_arr @ np.insert(p, 0, 1)
1118
- for p in tool_triangle]
1111
+ # Transform the links by the base transformation.
1112
+ links = [self.base_arr @ np.insert(p, 0, 1) for p in links]
1119
1113
  # Normalize the homogeneous coordinates.
1120
- tool_triangle = [p[1:4] / p[0] for p in tool_triangle]
1121
-
1122
- self.tool_link.setData(pos=np.array(tool_triangle))
1123
-
1124
- # Update tool frame (pose) arrows.
1125
- pose_dq = DualQuaternion(self.mechanism.evaluate(t))
1126
- # Compute the pose matrix by composing the mechanism’s pose and tool frame.
1127
- pose_matrix = TransfMatrix(pose_dq.dq2matrix()) * TransfMatrix(
1128
- self.mechanism.tool_frame.dq2matrix())
1129
-
1130
- if self.base is not None:
1131
- # Transform the pose matrix by the base transformation.
1132
- pose_matrix = self.base * pose_matrix
1133
-
1134
- self.tool_frame.setData(pose_matrix)
1135
-
1136
- self.plotter.widget.update()
1137
-
1114
+ links = [p[1:4] / p[0] for p in links]
1115
+
1116
+ # Update each line segment.
1117
+ for i, line in enumerate(self.lines):
1118
+ pt1 = links[i]
1119
+ pt2 = links[i+1]
1120
+ pts = np.array([pt1, pt2])
1121
+ line.setData(pos=pts)
1122
+
1123
+ if self.show_tool:
1124
+ pts0 = self.mechanism.factorizations[0].direct_kinematics(t)[-1]
1125
+ pts1 = self.mechanism.factorizations[0].direct_kinematics_of_tool(
1126
+ t, self.mechanism.tool_frame.dq2point_via_matrix())
1127
+ pts2 = self.mechanism.factorizations[1].direct_kinematics(t)[-1]
1128
+
1129
+ tool_triangle = [pts0, pts1, pts2]
1130
+
1131
+ if self.base is not None:
1132
+ # Transform the tool triangle by the base transformation.
1133
+ tool_triangle = [self.base_arr @ np.insert(p, 0, 1)
1134
+ for p in tool_triangle]
1135
+ # Normalize the homogeneous coordinates.
1136
+ tool_triangle = [p[1:4] / p[0] for p in tool_triangle]
1137
+
1138
+ self.tool_link.setData(pos=np.array(tool_triangle))
1139
+
1140
+ # Update tool frame (pose) arrows.
1141
+ pose_dq = DualQuaternion(self.mechanism.evaluate(t))
1142
+ # Compute the pose matrix by composing the mechanism’s pose and tool frame.
1143
+ pose_matrix = TransfMatrix(pose_dq.dq2matrix()) * TransfMatrix(
1144
+ self.mechanism.tool_frame.dq2matrix())
1145
+
1146
+ if self.base is not None:
1147
+ # Transform the pose matrix by the base transformation.
1148
+ pose_matrix = self.base * pose_matrix
1149
+
1150
+ self.tool_frame.setData(pose_matrix)
1151
+
1152
+ self.plotter.widget.update()
1153
+ else:
1154
+ InteractivePlotterWidget = None
1138
1155
 
1139
1156
  class InteractivePlotter:
1140
1157
  """