Esempio n. 1
0
def compare_csv(filename, kind):
    """Assert analogs's to_csv method."""
    idx = [0, 1, 2, 3]
    out = Path(".") / "temp.csv"

    if kind == "markers":
        header = 2
        arr_ref, arr = Markers3d(), Markers3d()
    else:
        header = 3
        arr_ref, arr = Analogs3d(), Analogs3d()
    # read a csv
    arr_ref = arr_ref.from_csv(filename,
                               first_row=5,
                               first_column=2,
                               header=header,
                               prefix=":",
                               idx=idx)
    # write a csv
    arr_ref.to_csv(out, header=False)
    # read the generated csv
    arr = arr.from_csv(out,
                       first_row=0,
                       first_column=0,
                       header=0,
                       prefix=":",
                       idx=idx)

    out.unlink()

    a = arr_ref[:, :, 1:100]
    b = arr[:, :, 1:100]

    np.testing.assert_equal(a.shape, b.shape)
    np.testing.assert_almost_equal(a, b, decimal=1)
Esempio n. 2
0
    def transpose(self):
        """

        Returns
        -------
        Rt_t : RotoTrans
            Transposed RotoTrans matrix ([R.T -R.T*t],[0 0 0 1])
        """
        # Create a matrix with the transposed rotation part
        rt_t = RotoTrans(rt=np.ndarray((4, 4, self.get_num_frames())))
        rt_t[0:3, 0:3, :] = np.transpose(self[0:3, 0:3, :], (1, 0, 2))

        # Fill the last column and row with 0 and bottom corner with 1
        rt_t[3, 0:3, :] = 0
        rt_t[0:3, 3, :] = 0
        rt_t[3, 3, :] = 1

        # Transpose the translation part
        t = Markers3d(
            data=np.reshape(self[0:3, 3, :], (3, 1, self.get_num_frames())))
        rt_t[0:3, 3, :] = t.rotate(-rt_t)[0:3, :].reshape(
            (3, self.get_num_frames()))

        # Return transposed matrix
        return rt_t
Esempio n. 3
0
    def __init__(self, parent,
                 markers_size=5, markers_color=(1, 1, 1), markers_opacity=1.0,
                 rt_size=25):
        """
        Creates a model that will holds things to plot
        Parameters
        ----------
        parent
            Parent of the Model window
        markers_size : float
            Size the markers should be drawn
        markers_color : Tuple(int)
            Color the markers should be drawn (1 is max brightness)
        markers_opacity : float
            Opacity of the markers (0.0 is completely transparent, 1.0 completely opaque)
        rt_size : int
            Length of the axes of the system of axes
        """
        QtWidgets.QWidget.__init__(self, parent)
        self.parent_window = parent

        palette = QPalette()
        palette.setColor(self.backgroundRole(), QColor(255, 255, 255))
        self.setAutoFillBackground(True)
        self.setPalette(palette)

        self.markers = Markers3d()
        self.markers_size = markers_size
        self.markers_color = markers_color
        self.markers_opacity = markers_opacity
        self.markers_actors = list()

        self.all_rt = RotoTransCollection()
        self.n_rt = 0
        self.rt_size = rt_size
        self.rt_actors = list()
        self.parent_window.should_reset_camera = True

        self.all_meshes = MeshCollection()
        self.mesh_actors = list()
Esempio n. 4
0
    def __init__(self,
                 parent,
                 markers_size=0.010,
                 markers_color=(1, 1, 1),
                 markers_opacity=1.0,
                 global_ref_frame_length=0.15,
                 global_ref_frame_width=5,
                 global_center_of_mass_size=0.0075,
                 global_center_of_mass_color=(0, 0, 0),
                 global_center_of_mass_opacity=1.0,
                 segments_center_of_mass_size=0.005,
                 segments_center_of_mass_color=(0, 0, 0),
                 segments_center_of_mass_opacity=1.0,
                 mesh_color=(0, 0, 0),
                 mesh_opacity=1.0,
                 muscle_color=(150 / 255, 15 / 255, 15 / 255),
                 muscle_opacity=1.0,
                 rt_length=0.1,
                 rt_width=2):
        """
        Creates a model that will holds things to plot
        Parameters
        ----------
        parent
            Parent of the Model window
        markers_size : float
            Size the markers should be drawn
        markers_color : Tuple(int)
            Color the markers should be drawn (1 is max brightness)
        markers_opacity : float
            Opacity of the markers (0.0 is completely transparent, 1.0 completely opaque)
        rt_length : int
            Length of the axes of the system of axes
        """
        QtWidgets.QWidget.__init__(self, parent)
        self.parent_window = parent

        palette = QPalette()
        palette.setColor(self.backgroundRole(), QColor(255, 255, 255))
        self.setAutoFillBackground(True)
        self.setPalette(palette)

        self.markers = Markers3d()
        self.markers_size = markers_size
        self.markers_color = markers_color
        self.markers_opacity = markers_opacity
        self.markers_actors = list()

        self.has_global_ref_frame = False
        self.global_ref_frame_length = global_ref_frame_length
        self.global_ref_frame_width = global_ref_frame_width

        self.global_center_of_mass = Markers3d()
        self.global_center_of_mass_size = global_center_of_mass_size
        self.global_center_of_mass_color = global_center_of_mass_color
        self.global_center_of_mass_opacity = global_center_of_mass_opacity
        self.global_center_of_mass_actors = list()

        self.segments_center_of_mass = Markers3d()
        self.segments_center_of_mass_size = segments_center_of_mass_size
        self.segments_center_of_mass_color = segments_center_of_mass_color
        self.segments_center_of_mass_opacity = segments_center_of_mass_opacity
        self.segments_center_of_mass_actors = list()

        self.all_rt = RotoTransCollection()
        self.n_rt = 0
        self.rt_length = rt_length
        self.rt_width = rt_width
        self.rt_actors = list()
        self.parent_window.should_reset_camera = True

        self.all_meshes = MeshCollection()
        self.mesh_color = mesh_color
        self.mesh_opacity = mesh_opacity
        self.mesh_actors = list()

        self.all_muscles = MeshCollection()
        self.muscle_color = muscle_color
        self.muscle_opacity = muscle_opacity
        self.muscle_actors = list()
Esempio n. 5
0
    def __init__(self,
                 model_path=None,
                 loaded_model=None,
                 show_meshes=True,
                 show_global_center_of_mass=True,
                 show_segments_center_of_mass=True,
                 show_global_ref_frame=True,
                 show_local_ref_frame=True,
                 show_markers=True,
                 markers_size=0.010,
                 show_muscles=True,
                 show_analyses_panel=True,
                 **kwargs):
        """
        Class that easily shows a biorbd model
        Args:
            loaded_model: reference to a biorbd loaded model (if both loaded_model and model_path, load_model is selected
            model_path: path of the model to load
        """

        # Load and store the model
        if loaded_model is not None:
            if not isinstance(loaded_model, biorbd.Model):
                raise TypeError(
                    "loaded_model should be of a biorbd.Model type")
            self.model = loaded_model
        elif model_path is not None:
            self.model = biorbd.Model(model_path)
        else:
            raise ValueError("loaded_model or model_path must be provided")

        # Create the plot
        self.vtk_window = VtkWindow(background_color=(.5, .5, .5))
        self.vtk_model = VtkModel(self.vtk_window,
                                  markers_color=(0, 0, 1),
                                  markers_size=markers_size)
        self.is_executing = False
        self.animation_warning_already_shown = False

        # Set Z vertical
        cam = self.vtk_window.ren.GetActiveCamera()
        cam.SetFocalPoint(0, 0, 0)
        cam.SetPosition(5, 0, 0)
        cam.SetRoll(-90)

        # Get the options
        self.show_markers = show_markers
        self.show_global_ref_frame = show_global_ref_frame
        self.show_global_center_of_mass = show_global_center_of_mass
        self.show_segments_center_of_mass = show_segments_center_of_mass
        self.show_local_ref_frame = show_local_ref_frame
        if self.model.nbMuscles() > 0:
            self.show_muscles = show_muscles
        else:
            self.show_muscles = False
        if sum([
                len(i)
                for i in self.model.meshPoints(np.zeros(self.model.nbQ()))
        ]) > 0:
            self.show_meshes = show_meshes
        else:
            self.show_meshes = 0

        # Create all the reference to the things to plot
        self.nQ = self.model.nbQ()
        self.Q = np.zeros(self.nQ)
        self.markers = Markers3d(np.ndarray((3, self.model.nbMarkers(), 1)))
        if self.show_markers:
            self.Markers = InterfacesCollections.Markers(self.model)
            self.global_center_of_mass = Markers3d(np.ndarray((3, 1, 1)))
        if self.show_global_center_of_mass:
            self.CoM = InterfacesCollections.CoM(self.model)
            self.segments_center_of_mass = Markers3d(
                np.ndarray((3, self.model.nbSegment(), 1)))
        if self.show_segments_center_of_mass:
            self.CoMbySegment = InterfacesCollections.CoMbySegment(self.model)
        if self.show_meshes:
            self.mesh = MeshCollection()
            self.meshPointsInMatrix = InterfacesCollections.MeshPointsInMatrix(
                self.model)
            for i, vertices in enumerate(
                    self.meshPointsInMatrix.get_data(Q=self.Q,
                                                     compute_kin=False)):
                triangles = np.ndarray((len(self.model.meshFaces()[i]), 3),
                                       dtype="int32")
                for k, patch in enumerate(self.model.meshFaces()[i]):
                    triangles[k, :] = patch.face()
                self.mesh.append(Mesh(vertex=vertices, triangles=triangles.T))
        self.model.updateMuscles(self.Q, True)
        self.muscles = MeshCollection()
        for group_idx in range(self.model.nbMuscleGroups()):
            for muscle_idx in range(
                    self.model.muscleGroup(group_idx).nbMuscles()):
                musc = self.model.muscleGroup(group_idx).muscle(muscle_idx)
                tp = np.zeros(
                    (3, len(musc.position().musclesPointsInGlobal()), 1))
                self.muscles.append(Mesh(vertex=tp))
        self.musclesPointsInGlobal = InterfacesCollections.MusclesPointsInGlobal(
            self.model)
        self.rt = RotoTransCollection()
        self.allGlobalJCS = InterfacesCollections.AllGlobalJCS(self.model)
        for rt in self.allGlobalJCS.get_data(Q=self.Q, compute_kin=False):
            self.rt.append(RotoTrans(rt))

        if self.show_global_ref_frame:
            self.vtk_model.create_global_ref_frame()

        self.show_analyses_panel = show_analyses_panel
        if self.show_analyses_panel:
            self.muscle_analyses = []
            self.palette_active = QPalette()
            self.palette_inactive = QPalette()
            self.set_viz_palette()
            self.animated_Q = []

            self.play_stop_push_button = []
            self.is_animating = False
            self.is_recording = False
            self.start_icon = QIcon(
                QPixmap(f"{os.path.dirname(__file__)}/ressources/start.png"))
            self.pause_icon = QIcon(
                QPixmap(f"{os.path.dirname(__file__)}/ressources/pause.png"))
            self.record_icon = QIcon(
                QPixmap(f"{os.path.dirname(__file__)}/ressources/record.png"))
            self.add_icon = QIcon(
                QPixmap(f"{os.path.dirname(__file__)}/ressources/add.png"))
            self.stop_icon = QIcon(
                QPixmap(f"{os.path.dirname(__file__)}/ressources/stop.png"))

            self.double_factor = 10000
            self.sliders = list()
            self.movement_slider = []

            self.active_analyses_widget = None
            self.analyses_layout = QHBoxLayout()
            self.analyses_muscle_widget = QWidget()
            self.add_options_panel()

        # Update everything at the position Q=0
        self.set_q(self.Q)
Esempio n. 6
0
    def __init__(self,
                 model_path=None,
                 loaded_model=None,
                 show_global_ref_frame=True,
                 show_markers=True,
                 show_global_center_of_mass=True,
                 show_segments_center_of_mass=True,
                 show_rt=True,
                 show_muscles=True,
                 show_meshes=True,
                 show_options=True):
        """
        Class that easily shows a biorbd model
        Args:
            loaded_model: reference to a biorbd loaded model (if both loaded_model and model_path, load_model is selected
            model_path: path of the model to load
        """

        # Load and store the model
        if loaded_model is not None:
            if not isinstance(loaded_model, biorbd.Model):
                raise TypeError(
                    "loaded_model should be of a biorbd.Model type")
            self.model = loaded_model
        elif model_path is not None:
            self.model = biorbd.Model(model_path)
        else:
            raise ValueError("loaded_model or model_path must be provided")

        # Create the plot
        self.vtk_window = VtkWindow(background_color=(.5, .5, .5))
        self.vtk_model = VtkModel(self.vtk_window, markers_color=(0, 0, 1))
        self.is_executing = False
        self.animation_warning_already_shown = False

        # Set Z vertical
        cam = self.vtk_window.ren.GetActiveCamera()
        cam.SetFocalPoint(0, 0, 0)
        cam.SetPosition(5, 0, 0)
        cam.SetRoll(-90)

        # Get the options
        self.show_markers = show_markers
        self.show_global_ref_frame = show_global_ref_frame
        self.show_global_center_of_mass = show_global_center_of_mass
        self.show_segments_center_of_mass = show_segments_center_of_mass
        self.show_rt = show_rt
        if self.model.nbMuscleTotal() > 0:
            self.show_muscles = show_muscles
        else:
            self.show_muscles = False
        if sum([
                len(i)
                for i in self.model.meshPoints(np.zeros(self.model.nbQ()))
        ]) > 0:
            self.show_meshes = show_meshes
        else:
            self.show_meshes = 0

        # Create all the reference to the things to plot
        self.nQ = self.model.nbQ()
        self.Q = np.zeros(self.nQ)
        self.markers = Markers3d(np.ndarray((3, self.model.nTags(), 1)))
        self.global_center_of_mass = Markers3d(np.ndarray((3, 1, 1)))
        self.segments_center_of_mass = Markers3d(
            np.ndarray((3, self.model.nbBone(), 1)))
        self.mesh = MeshCollection()
        for l, meshes in enumerate(self.model.meshPoints(self.Q)):
            tp = np.ndarray((3, len(meshes), 1))
            for k, mesh in enumerate(meshes):
                tp[:, k, 0] = mesh.get_array()
            self.mesh.append(Mesh(vertex=tp))
        self.model.updateMuscles(self.model, self.Q, True)
        self.muscles = MeshCollection()
        for group_idx in range(self.model.nbMuscleGroups()):
            for muscle_idx in range(
                    self.model.muscleGroup(group_idx).nbMuscles()):
                musc_tp = self.model.muscleGroup(group_idx).muscle(muscle_idx)
                muscle_type = biorbd.Model.getMuscleType(musc_tp).getString()
                if muscle_type == "Hill":
                    musc = biorbd.HillType(musc_tp)
                elif muscle_type == "HillThelen":
                    musc = biorbd.HillTypeThelen(musc_tp)
                elif muscle_type == "HillSimple":
                    musc = biorbd.HillTypeSimple(musc_tp)
                tp = np.ndarray(
                    (3, len(musc.position().musclesPointsInGlobal()), 1))
                for k, pts in enumerate(
                        musc.position().musclesPointsInGlobal()):
                    tp[:, k, 0] = pts.get_array()
                self.muscles.append(Mesh(vertex=tp))
        self.rt = RotoTransCollection()
        for rt in self.model.globalJCS(self.Q):
            self.rt.append(RotoTrans(rt.get_array()))

        if self.show_global_ref_frame:
            self.vtk_model.create_global_ref_frame()

        self.show_options = show_options
        if self.show_options:
            self.muscle_analyses = []
            self.palette_active = QPalette()
            self.palette_inactive = QPalette()
            self.set_viz_palette()
            self.animated_Q = []

            self.play_stop_push_button = []
            self.is_animating = False
            self.start_icon = QIcon(
                QPixmap(f"{os.path.dirname(__file__)}/ressources/start.png"))
            self.stop_icon = QIcon(
                QPixmap(f"{os.path.dirname(__file__)}/ressources/pause.png"))

            self.double_factor = 10000
            self.sliders = list()
            self.movement_slider = []

            self.active_analyses_widget = None
            self.analyses_layout = QHBoxLayout()
            self.analyses_muscle_widget = QWidget()
            self.add_options_panel()

        # Update everything at the position Q=0
        self.set_q(self.Q)
Esempio n. 7
0
                           [0, 2 * 3 + 1, 5 * 3])
dataSetTripod = dataSetTripod.rotate(rt.transpose())
dataSetAll = dataSetAll.rotate(rt.transpose())
# rt = matrix.define_axes(dataSetTripod, [rtm[2], rtm[0]], [[rtm[0], rtm[1]], [rtm[2], rtm[1]]], "xz", "z", rtm)

# split into input (X) and output (Y) variables
X_data = dataSetTripod[:, 0:nTriPod * 3, :].to_2d()
y_data = dataSetAll.to_2d()
t = time.time()
y_recons = model.predict(X_data)
print(f"Prediction done in {time.time() - t} seconds")

# View it.
# Convert back points matrix to Vectors3d
TReal = dataSetAll  # Markers3d(X_data)
TPred = Markers3d(y_recons)
TPred.to_csv(saveReconstructionFileName)
TPred.rotate(rt).to_csv(
    f"{saveReconstructionFileName[:-4]}_inGlobal{saveReconstructionFileName[-4:]}"
)

# Put back the markers in global frame
if show_in_global:
    TReal = TReal.rotate(rt)
    TPred = TPred.rotate(rt)

# Calculate total error [For the paper]
if calculate_error:
    error = (TReal[0:3, nTriPod * 3:nTriPod * 3 + nMarkOnInsole, :] -
             TPred[0:3, :, :]).norm()
    mean_rmse = np.mean(error)