mbs_data.py 37 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# -*- coding: utf-8 -*-
"""
-------------------------------
(c) Universite catholique de Louvain, 2019

Creation : 2019 by O. Lantsoght
Last update : 2019

version MBsysC v1.11.2

-------------------------------
Portable Python interface to MBsysC using Ctypes.

Define the class MbsData based on the MbsData structure of MBsysC.
This class has the functions required to manipulate the Data (set the number of
user constraints, set the independant or dependant variables...).
"""

import os
import imp
import ctypes

import numpy as np

# importing MbsysPy classes
from .mbs_sensor import MbsSensor

# importing libraries
from ..mbsysc_loader.loadlibs import libutilities
from ..mbsysc_loader.loadlibs import libloadXML

# importing wrapping function
from ..mbsysc_loader.callback import user_Derivative_wrap
from ..mbsysc_loader.callback import user_DrivenJoints_wrap
from ..mbsysc_loader.callback import user_ExtForces_wrap
from ..mbsysc_loader.callback import user_JointForces_wrap
from ..mbsysc_loader.callback import user_LinkForces_wrap
from ..mbsysc_loader.callback import user_Link3DForces_wrap

from ..mbsysc_loader.callback import mbs_accelred_wrap
from ..mbsysc_loader.callback import mbs_extforces_wrap
from ..mbsysc_loader.callback import mbs_gensensor_wrap
from ..mbsysc_loader.callback import mbs_link_wrap
from ..mbsysc_loader.callback import mbs_link3D_wrap
from ..mbsysc_loader.callback import mbs_sensor_wrap

#==============================================================================
# Global parameter of the current module
#==============================================================================
__DEBUG__ = False
__MODULE_DIR__ = os.path.dirname(os.path.abspath(__file__))


#==============================================================================
# Defining Python MbsData class
#==============================================================================

class MbsData(object):
    
    """
    Class containing geometrical and dynamical information of robotran Mbs.
    
    Attributes
    ----------
    DonePart : int
        Flag that indicates if the coordinate partitioning module has been 
        executed (default: 0=not done; 1=done).
    dpt : ndarray
        Numpy array containing the coordinates of all anchor points in body 
        fixed frame: [X_i,Y_i,Z_i] = dpt[1:4,i]
    Fl : ndarray
        Numpy array containing the current values of the forces on each link.
    frc: ndarray
        Numpy array containing the components of the resultant external forces 
        (in the body fixed frame) applied to the center of mass of each body.
    g : ndarray
        The 3 gravity components in the inertial frame: g[1:4]=[g_x, g_y, g_z]
    In : ndarray
        Numpy array containing the inertia tensor component of each body (in 
        the body fixed frame, relative to the center of mass). For body k:
        In[1:10, k]=[I_11,I_12,I_13,I_21,I_22,I_23,I_31,I_32,I_33]
    l : ndarray
        Numpy array containing the center of mass coordinates in the body fixed
        frame. For body k: l[1:4, k]=[gc_x, gc_y, gc_z]
    lambda_ : ndarray
        Numpy array containing the values of the Lagrange Multipliers related 
        to the constraints.
    lrod : ndarray
        Numpy array containing the length of each rod.
    m : ndarray
        Numpy array containing the mass of each body.
    mbs_filename : str
        Path to mbs file including the file with the extension (.mbs).
    mbs_name : str
        Filename of the mbs file (excluding path and ".mbs" extension).
    nbody : int
        Number of bodies in the system. The fictious bodies are not taken into 
        account.
    Ncons : int
        Number of algebraic constraints.
    nhu : int
        Number of independent constraints.
    njoint : int
        Number of joints in the system.
    Nlink : int
        Number of forces acting between two points of the system.
    Nloopc : int
        Number of loop constraints.
    npt : int
        Number of anchor points.
    nqa : int
        Number of actuated articulations.
    nqc : int
        Number of driven articulations, it includes qlocked and qdriven..
    nqdriven : int
        Number of driven articulations.
    nqlocked : int
        Number of locked articulations.
    nqu : int
        Number of independent articulations.
    nqv : int
        Number of dependent articulations.
    NRerr : float
        Maximal error on constraint allowed in Newton-Raphson algorithm, 
        default 1.0e-9.
    nrod : int
        Number of rod constraints defined on the system.
    Nsensor : int
        Number of kinematic sensors.
    Nuserc : int
        Number of user constraints.
    Nux : int
        Number of user variable.
    Nxfrc : int
        Number of points where an external force is applied into a body.
    process : int
        Flag that indicate which module is currently running: 
        1=partitioning; 2=equilibrium; 3=direct dynamic; 4=modal
    project_path : str
        Path to the mbs project folder.
    q : ndarray
        Numpy array containing the current values of the generalized 
        coordinates.
    q0 : ndarray
        Numpy array containing the initial values of the generalized 
        coordinates.
    qa : ndarray of int
        Numpy array of integers containing the indices of actuated 
        articulations (only for inverse dynamic). Those articulations are 
        controlled by an actuator.
    qc : ndarray of int
        Numpy array of integers containing the indices of driven (locked and 
        driven) articulations.
    Qc : ndarray
        Numpy array containing the value of joint force introduced in driven 
        joints to respect the user function. The driven forces/torques are 
        saved in the entries given by index vector 'qc'.
    qd : ndarray
        Numpy array containing the current values of the generalized 
        velocities.
    qd0 : ndarray
        Numpy array containing the initial values of the generalized 
        velocities.
    qdd : ndarray
        Numpy array containing the current values of the generalized 
        accelerations.
    qdd0 : ndarray
        Numpy array containing the initial values of the generalized 
        accelerations.
    qdriven : ndarray of int
        Numpy array of integers containing the indices of driven articulations.
        Those articulations are controlled by a user function: 
        q[qdriven]=f(tsim)
    qlocked : ndarray of int
        Numpy array of integers containing the indices of locked articulations.
        Those articulations have a constant position defined by the user:
        q[qlocked]=cte
    Qq : ndarray
        Numpy array containing the values of the joint forces.
    qu : ndarray of int
        Numpy array of integers containing the indices of the independent 
        articulations.
    qv : ndarray of int
        Numpy array of integers containing the indices of the dependent 
        articulations.
    sensors : list of MbsSensor
        List containing one instance of MbsSensor (without defined id). User 
        can append as many as needed sensor in the list. Sensors defined in 
        this list can be used by the user for various computation.
    SWr : ndarray
        Numpy array containing the Swr vector for each external forces.
        for force k, Swr[k,1:10] = [Fx, Fy, Fz, Mx, My, Mz, dxF] with
          - Force components (expressed in the inertial frame) : Fx,Fy,Fz
          - Pure torque components (expressed in the inertial frame) : Mx,My,Mz
          - Application point local coordinates vector (expressed in the body 
            fixed frame): dxF[1:4]
    t0 : scalar
        Initial time of the simulation [s]. For dirdyn and invdyn only. This 
        parameter is set from dirdyn/invyn option at start of time simulation.
    tf : scalar
        Final time of the simulation [s]. For dirdyn and invdyn only. This 
        parameter is set from dirdyn/invyn option at start of time simulation.
    trq : ndarray
        Numpy array containing the components of the resultant external torques
        (pure torque and couple produced by forces displacement in the body 
        fixed frame) applied to each body.
    tsim : scalar
        The time value.
    ux : ndarray
        Numpy array containing the values of the user variables.
    ux0 : ndarray
        Numpy array containing the initial values of the user variables.
    uxd : ndarray
        Numpy array containing the values of the time derivative of the user 
        variables.
    xfidpt : ndarray of int
        Numpy array of integers containing the indices of the points defined as
        force application points.
    Z : ndarray
        Numpy array containing the current values of the distances between of 
        the points of a link.
    Zd : ndarray
        Numpy array containing the current values of the speed (spreading) 
        between of the points of a link.
    """
    
    def __init__(self, name, user_path=None, symbolic_path=None):
        """
        Load a specific *.mbs file into a MbsData class instance.

        Parameters
        ----------
        name : str
            The path to the .mbs file to load, including the file extension.
        user_path : str, optionnal
            The path to the folder containing the user functions if the default
            project structure are not used.
        symbolic_path : str, optionnal
            The path to the folder containing the symbolic functions if the 
            default project structure are not used.
        """
        # Create a byte object from the string
        name_c = name.encode('utf-8')
244
        # Load the MbsInfos and keep a copy
245
        if __DEBUG__ : print( "DEBUG>>  Loading: '"+name+"' from:'"+os.getcwd()+"'.")
246
247
        self.MbsInfos_ptr = libloadXML.mbs_info_reader(name_c)
        if __DEBUG__ : print( "DEBUG>>  mbs_infos structure loaded")
248
249
250
251
252
253
254
255
        
        # Preparing loader and its options for loading 
        loader = libloadXML.mbs_new_loader()
        if __DEBUG__ : print( "DEBUG>>  Loader structure created")
        
        loader.contents.opts.contents.no_project_fct = 1
        if __DEBUG__ : print( "DEBUG>>  flag ignoring project function set")
        
256
257
        loader.contents.mbs_infos = self.MbsInfos_ptr
        if __DEBUG__ : print( "DEBUG>>  mbs_infos assigned to loader")
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
        
        # Load and retrieve MbsData structure
        self.mbs_data_ptr = libloadXML.mbs_load_with_loader(name_c, None, loader)
        if __DEBUG__ : print( "DEBUG>>  MbsData loaded")
            
        # symbolic and user function folder
        self.user_path = None
        self.symbolic_path = None
        
        # Storing project function pointer
        # User function that only relies on MbsData structure
        self.user_cons_hJ = None
        self.user_cons_jdqd = None
        self.user_derivative = None
        self.user_DrivenJoints = None
        self.user_ExtForces = None
        self.user_JointForces = None
        self.user_LinkForces = None
        self.user_Link3DForces = None
        # User function also related to dirdyn, equil...
        self.user_dirdyn_init = None
        self.user_dirdyn_loop = None
        self.user_dirdyn_finish = None
        
        # Symbolic functions
        self.mbs_accelred = None
        self.mbs_cons_hJ = None
        self.mbs_cons_jdqd = None
        self.mbs_dirdyna = None
        self.mbs_extforces = None
        self.mbs_gensensor = None
        self.mbs_invdyna = None
        self.mbs_link = None
        self.mbs_link3D = None
        self.mbs_sensor = None
        
294
295
296
        # pointers dict to avoid garbage collecting
        self.ptrs_to_user_fcts = dict()
        self.ptrs_to_symb_fcts = dict()
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
        
        # Exposing some memory
        if __DEBUG__ : print( "DEBUG>>  Exposing MbsData fields")
        # Geometric and dynamic datas
        self.__dpt = np.ctypeslib.as_array(self.mbs_data_ptr.contents.dpt[0], (3+1, self.npt+1))
        self.__l = np.ctypeslib.as_array(self.mbs_data_ptr.contents.l[0], (3+1, self.njoint+1))
        self.__m = np.ctypeslib.as_array(self.mbs_data_ptr.contents.m, (self.njoint+1,))
        self.__In = np.ctypeslib.as_array(self.mbs_data_ptr.contents.In[0], (9+1, self.njoint+1))
        self.__g = np.ctypeslib.as_array(self.mbs_data_ptr.contents.g, (4,))
        
        # Partitioning informations
        self.__qu = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qu, (self.njoint+1,))
        self.__qc = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qc, (self.njoint+1,))
        self.__qlocked = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qlocked, (self.njoint+1,))
        self.__qdriven = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qdriven, (self.njoint+1,))
        self.__qa = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qa, (self.njoint+1,))
        self.__qv = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qv, (self.njoint+1,))
        
        # Generalized coordinates velocities and acceleration
        self.__q = np.ctypeslib.as_array(self.mbs_data_ptr.contents.q, (self.njoint+1,))
        self.__qd = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qd, (self.njoint+1,))
        self.__qdd = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qdd, (self.njoint+1,))
        
        self.__q0 = np.ctypeslib.as_array(self.mbs_data_ptr.contents.q0, (self.njoint+1,))
        self.__qd0 = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qd0, (self.njoint+1,))
        self.__qdd0 = np.ctypeslib.as_array(self.mbs_data_ptr.contents.qdd0, (self.njoint+1,))
        
        # Forces array
        self.__frc = np.ctypeslib.as_array(self.mbs_data_ptr.contents.frc[0], (3+1, self.njoint+1))
        self.__trq = np.ctypeslib.as_array(self.mbs_data_ptr.contents.trq[0], (3+1, self.njoint+1))
        self.__Qq = np.ctypeslib.as_array(self.mbs_data_ptr.contents.Qq, (self.njoint+1,))
        
        # Constraints datas
        self.nrod = 0
        self.__lrod = None
        if (self.mbs_data_ptr.contents.lrod):
            print(self.mbs_data_ptr.contents.lrod)
            print(self.mbs_data_ptr.contents.lrod is None)
            self.nrod = int(round(self.mbs_data_ptr.contents.lrod[0]))
            self.__lrod = np.ctypeslib.as_array(self.mbs_data_ptr.contents.lrod,(self.nrod+1,))
        
        self.__lambda_ = np.ctypeslib.as_array(self.mbs_data_ptr.contents.lambda_,(self.njoint+1,))
        self.__Qc = np.ctypeslib.as_array(self.mbs_data_ptr.contents.Qc,(self.njoint+1,))
        
        # LinksForces
        self.__Z = self.__Zd = self.__Fl = None
        if self.Nlink:
            self.__Z = np.ctypeslib.as_array(self.mbs_data_ptr.contents.Z, (self.Nlink+1,))
            self.__Zd = np.ctypeslib.as_array(self.mbs_data_ptr.contents.Zd, (self.Nlink+1,))
            self.__Fl = np.ctypeslib.as_array(self.mbs_data_ptr.contents.Fl, (self.Nlink+1,))
            
        # ExtForces
        self.__xfidpt = self.__SWr = None
        if self.Nxfrc:
            self.__xfidpt = np.ctypeslib.as_array(self.mbs_data_ptr.contents.xfidpt, (self.Nxfrc+1,))
352
            self.__SWr = np.ctypeslib.as_array(self.mbs_data_ptr.contents.SWr[0], (self.Nxfrc+1, 9+1))
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
        
        # User State
        self.__ux = self.__ux0 = self.__uxd = None
        if self.Nux:
            self.__ux = np.ctypeslib.as_array(self.mbs_data_ptr.contents.ux, (self.Nux+1,))
            self.__ux0 = np.ctypeslib.as_array(self.mbs_data_ptr.contents.ux0, (self.Nux+1,))
            self.__uxd = np.ctypeslib.as_array(self.mbs_data_ptr.contents.uxd, (self.Nux+1,))
        
        # Adding internal sensor
        self.sensors = [MbsSensor(self,None)]
        
        # Loading user function
        if __DEBUG__ : print( "DEBUG>>  Loading user functions")
        self.__assign_user_fct__(user_path)
        # Loading symbolic function
        if __DEBUG__ : print( "DEBUG>>  Loading symbolic functions")
        self.__assign_symb_fct__(symbolic_path)
        

    def __str__(self):
        if __DEBUG__ : print( "DEBUG>>  start of __str")
        
        libutilities.mbs_print_data(self.mbs_data_ptr)
        if __DEBUG__ : print( "DEBUG>>  MbsData printed")
        
        return "MbsData instance printed from C library!"
    
    def __assign_user_fct__(self, user_path=None):
        """ 
            Assign all user function where arguments are in MbsData instance.
            
            Only assign the user functions in which the arguments are not 
            dependent of another module instance (ie. MbsPart, MbsDirdyn...).
            The other user function will be assigned when a module is created.
            
            The loader user functions are :
             - user_derivatives (from derivatives.py)
             - user_DrivenJoints (from driven_joints.py)
             - user_ExtForces (from ext_forces.py)
             - user_JointForces (from joint_forces.py)
             - user_LinkForces (from link_forces.py)
             - user_Link3DForces (from link3D_forces.py)
        """
        data_c_ptr=self.mbs_data_ptr.contents
397
        template_path = os.path.join(__MODULE_DIR__,'../templates/user')
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
        project_path = self.project_path
        
        # Creating user path
        if user_path == None:
            user_path = os.path.join(project_path, "userfctR")
        else:
            user_path = os.path.join(project_path, user_path)
        # Error handeling
        if not os.path.isdir(user_path):
            print ('The user function directory does not exist: "'+ user_path+'"')
            print ('The current root folder is: "'+os.getcwd()+'"')
        self.user_path = user_path

#        # cons_hJ
#        user_file = "cons_hJ.py"
#        path = os.path.abspath(os.path.join(user_path, user_file))
#        if os.path.isfile(path):
#            module = imp.load_source(user_file[:-3], path)
#            self.user_cons_hJ = module.user_cons_hJ
#            self.ptrs_to_fcts.append(user_cons_hJ_wrap(lambda h,Jac,mbs,tsim : self.__callback_user_cons_hJ(self.user_cons_hJ,h,Jac,tsim)))
#            data_c_ptr.user_cons_hJ = self.ptrs_to_fcts[-1]
#        else:
#            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
#            self.user_cons_hJ = None

#        # cons_jdqd
#        user_file = "cons_jdqd.py"
#        path = os.path.abspath(os.path.join(user_path, user_file))
#        if os.path.isfile(path):
#            module = imp.load_source(user_file[:-3], path)
#            self.user_cons_jdqd = module.user_cons_jdqd
#            self.ptrs_to_fcts.append(user_cons_jdqd_wrap(lambda jdqd,mbs,tsim : self.__callback_user_cons_jdqd(self.user_cons_jdqd,jdqd,tsim)))
#            data_c_ptr.user_cons_jdqd = self.ptrs_to_fcts[-1]
#        else:
#            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
#            self.user_cons_jdqd = None

        # derivative
        user_file = "derivatives.py"
        path = os.path.abspath(os.path.join(user_path, user_file))
438
        if not os.path.isfile(path):
439
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
440
441
442
443
444
            path = os.path.abspath(os.path.join(template_path, user_file))
        module = imp.load_source(user_file[:-3], path)
        self.user_derivative = module.user_derivatives
        self.ptrs_to_user_fcts["user_Derivative"] = user_Derivative_wrap(lambda mbs : self.user_derivative(self))
        data_c_ptr.user_Derivative = self.ptrs_to_user_fcts["user_Derivative"]
445
446
447
448

        # drivenJoints
        user_file = "driven_joints.py"
        path = os.path.abspath(os.path.join(user_path, user_file))
449
        if not os.path.isfile(path):
450
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
451
452
453
454
455
            path = os.path.abspath(os.path.join(template_path, user_file))
        module = imp.load_source(user_file[:-3], path)
        self.user_DrivenJoints = module.user_DrivenJoints
        self.ptrs_to_user_fcts["user_DrivenJoints"] = user_DrivenJoints_wrap(lambda mbs,t : self.user_DrivenJoints(self, t))
        data_c_ptr.user_DrivenJoints = self.ptrs_to_user_fcts["user_DrivenJoints"]
456
457
458
459

        # ext_forces
        user_file = "ext_forces.py"
        path = os.path.abspath(os.path.join(user_path, user_file))
460
        if not os.path.isfile(path):
461
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
462
463
464
465
466
            path = os.path.abspath(os.path.join(template_path, user_file))
        module = imp.load_source(user_file[:-3], path)
        self.user_ExtForces = module.user_ExtForces
        self.ptrs_to_user_fcts["user_ExtForces"] = user_ExtForces_wrap(lambda PxF,RxF,VxF,OMxF,AxF,OMPxF,mbs,tsim,ixF : self.__callback_user_ExtForces(self.user_ExtForces,PxF,RxF,VxF,OMxF,AxF,OMPxF,tsim,ixF))
        data_c_ptr.user_ExtForces = self.ptrs_to_user_fcts["user_ExtForces"]
467
468
469
470

        # joint_forces
        user_file = "joint_forces.py"
        path = os.path.abspath(os.path.join(user_path, user_file))
471
        if not os.path.isfile(path):
472
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
473
474
475
476
477
            path = os.path.abspath(os.path.join(template_path, user_file))
        module = imp.load_source(user_file[:-3], path)
        self.user_JointForces = module.user_JointForces
        self.ptrs_to_user_fcts["user_JointForces"] = user_JointForces_wrap(lambda mbs,t : self.user_JointForces(self, t))
        data_c_ptr.user_JointForces = self.ptrs_to_user_fcts["user_JointForces"]
478
479
480
481

        # link_forces
        user_file = "link_forces.py"
        path = os.path.abspath(os.path.join(user_path, user_file))
482
        if not os.path.isfile(path):
483
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
484
485
486
487
488
            path = os.path.abspath(os.path.join(template_path, user_file))
        module = imp.load_source(user_file[:-3], path)
        self.user_LinkForces = module.user_LinkForces
        self.ptrs_to_user_fcts["user_LinkForces"] = user_LinkForces_wrap(lambda Z, Zd, mbs, tsim, ilnk : self.user_LinkForces(Z, Zd, self, tsim, ilnk))
        data_c_ptr.user_LinkForces = self.ptrs_to_user_fcts["user_LinkForces"]
489
490
491
492

        # link3D_forces
        user_file = "link3D_forces.py"
        path = os.path.abspath(os.path.join(user_path, user_file))
493
        if not os.path.isfile(path):
494
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
495
496
497
498
499
            path = os.path.abspath(os.path.join(template_path, user_file))
        module = imp.load_source(user_file[:-3], path)
        self.user_Link3DForces = module.user_Link3DForces
        self.ptrs_to_user_fcts["user_Link3DForces"] = user_Link3DForces_wrap(lambda PxF,RxF,VxF,OMxF,AxF,OMPxF,mbs,tsim,ixF : self.__callback_user_Link3DForces(self.user_Link3DForces,PxF,RxF,VxF,OMxF,AxF,OMPxF,tsim,ixF))
        data_c_ptr.user_Link3DForces = self.ptrs_to_user_fcts["user_Link3DForces"]
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
            
        return
        
    
    def __assign_symb_fct__(self, symb_path=None, ):
        """ 
            Assign all symbolic function if all args are in MbsData instance.
            
            Only assign the symbolic functions in which the arguments are not 
            dependent of another module instance (ie. MbsPart, MbsDirdyn...).
            The other symbolic function will be assigned when a module is 
            instancied.
            
            The loader symbolic functions are :
             - mbs_accelred (from mbs_accelred_MBSNAME.py)
             - extforces (from mbs_extforces_MBSNAME.py)
             - sensor (from mbs_gensensor_MBSNAME.py)
             - sensor (from mbs_sensor_MBSNAME.py)
             - link (from mbs_link_MBSNAME.py)
             - link3D (from mbs_link3D_MBSNAME.py)
        """
        data_c_ptr=self.mbs_data_ptr.contents
        mbs_name = self.mbs_name
        template_path = os.path.join(__MODULE_DIR__,'../templates/symbolic')
        project_path = self.project_path
        
        # Creating user path
        if symb_path == None:
            symb_path = os.path.join(project_path, "symbolicR")
        else:
            symb_path = os.path.join(project_path, symb_path)
        # Error handeling
        if not os.path.isdir(symb_path):
            print ('The symbolic function directory does not exist: "'+ symb_path+'"')
            print ('The current root folder is: "'+os.getcwd()+'"')
        self.symbolic_path = symb_path
            
        # mbs_accelred
        symb_file = "mbs_accelred_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
540
        if not os.path.isfile(path):
541
542
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
            symb_file = "mbs_accelred_PRJ.py"
543
544
545
546
547
548
            path = os.path.abspath(os.path.join(template_path, symb_file))  
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_accelred = module.mbs_accelred
        self.ptrs_to_symb_fcts["mbs_accelred"] = mbs_accelred_wrap(lambda mbs,tsim : self.mbs_accelred(self, tsim))
        data_c_ptr.mbs_accelred = self.ptrs_to_symb_fcts["mbs_accelred"]
            
549
550
551
552
        
        # mbs_extforces
        symb_file = "mbs_extforces_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
553
        if not os.path.isfile(path):
554
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
555
556
557
558
559
560
            symb_file = "mbs_extforces_PRJ.py"
            path = os.path.abspath(os.path.join(template_path, symb_file))
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_extforces = module.extforces
        self.ptrs_to_symb_fcts["mbs_extforces"] = mbs_extforces_wrap(lambda frc,trq,mbs,tsim : self.mbs_extforces(self.frc,self.trq, self, tsim))
        data_c_ptr.mbs_extforces = self.ptrs_to_symb_fcts["mbs_extforces"]
561
562
563
564
        
        # mbs_gensensor
        symb_file = "mbs_gensensor_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
565
        if not os.path.isfile(path):
566
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
567
568
569
570
571
572
            symb_file = "mbs_gensensor_PRJ.py"
            path = os.path.abspath(os.path.join(template_path, symb_file))
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_gensensor = module.sensor
        self.ptrs_to_symb_fcts["mbs_gensensor"] = mbs_gensensor_wrap(lambda sens,mbs,isens : self.__callback_mbs_sensor(self.mbs_gensensor, sens, isens))
        data_c_ptr.mbs_gensensor = self.ptrs_to_symb_fcts["mbs_gensensor"]
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
        
#        # mbs_invdyna
#        symb_file = "mbs_invdyna_"+mbs_name+".py"
#        path = os.path.abspath(os.path.join(symb_path, symb_file))
#        if os.path.isfile(path):
#            module = imp.load_source(symb_file[:-3], path)
#            self.mbs_invdyna = module.invdyna
#            self.ptrs_to_fcts.append(mbs_invdyna_wrap(lambda Q,mbs,tsim : self.__callback_mbs_invdyna(self.mbs_invdyna,Q,tsim)))
#            data_c_ptr.mbs_invdyna = self.ptrs_to_fcts[-1]
#        else:
#            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
#            self.mbs_invdyna = None
        
        # mbs_link
        symb_file = "mbs_link_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
589
        if not os.path.isfile(path):
590
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
591
592
593
594
595
596
            symb_file = "mbs_link_PRJ.py"
            path = os.path.abspath(os.path.join(template_path, symb_file))
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_link = module.link
        self.ptrs_to_symb_fcts["mbs_link"] = mbs_link_wrap(lambda frc,trq,Flnk,Z,Zd,mbs,tsim : self.mbs_link(self.frc,self.trq,self.Fl,self.Z,self.Zd, self, tsim))
        data_c_ptr.mbs_link = self.ptrs_to_symb_fcts["mbs_link"]
597
598
599
600
        
        # mbs_link3D
        symb_file = "mbs_link3D_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
601
        if not os.path.isfile(path):
602
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
603
604
605
606
607
608
            symb_file = "mbs_link3D_PRJ.py"
            path = os.path.abspath(os.path.join(template_path, symb_file))
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_link3D = module.link3D
        self.ptrs_to_symb_fcts["mbs_link3D"] = mbs_link3D_wrap(lambda frc,trq,mbs,tsim : self.mbs_link3D(self.frc,self.trq,self, tsim))
        data_c_ptr.mbs_link3D = self.ptrs_to_symb_fcts["mbs_link3D"]
609
        
610
        # mbs_sensor
611
612
        symb_file = "mbs_sensor_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
613
        if not os.path.isfile(path):
614
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
615
616
617
618
619
620
            symb_file = "mbs_sensor_PRJ.py"
            path = os.path.abspath(os.path.join(template_path, symb_file))
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_sensor = module.sensor
        self.ptrs_to_symb_fcts["mbs_sensor"] = mbs_sensor_wrap(lambda sens,mbs,isens : self.__callback_mbs_sensor(self.mbs_sensor, sens, isens))
        data_c_ptr.mbs_sensor = self.ptrs_to_symb_fcts["mbs_sensor"]
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
    
    
    # Callback function for function with advanced arguments
#    def __callback_user_cons_hJ(self, fun, h, Jac, tsim):
#        __h = np.ctypeslib.as_array(h, (self.Nuserc+1,))
#        __Jac = np.ctypeslib.as_array(Jac[0], (self.Nuserc+1,self.njoint+1))
#        fun(__h,__Jac,self,tsim)
#        
#    def __callback_user_cons_jdqd(self, fun, jdqd, tsim):
#        __jdqd = np.ctypeslib.as_array(jdqd, (self.Nuserc+1,))
#        fun(__jdqd,self,tsim)
#        
    def __callback_user_ExtForces(self, fun, PxF,RxF,VxF,OMxF,AxF,OMPxF,tsim,ixF):
        __PxF = np.ctypeslib.as_array(PxF, (4,))
        __RxF = np.ctypeslib.as_array(RxF, (4,4))
        __VxF = np.ctypeslib.as_array(VxF, (4,))
        __OMxF = np.ctypeslib.as_array(OMxF, (4,))
        __AxF = np.ctypeslib.as_array(AxF, (4,))
        __OMPxF = np.ctypeslib.as_array(OMPxF, (4,))
        SWr = fun(__PxF, __RxF, __VxF, __OMxF, __AxF, __OMPxF, self, tsim, ixF)
        self.SWr[ixF,:] = SWr[:]
        
    def __callback_user_Link3DForces(self, fun, PxF,RxF,VxF,OMxF,AxF,OMPxF,tsim,ixF):
        __PxF = np.ctypeslib.as_array(PxF, (4,))
        __RxF = np.ctypeslib.as_array(RxF, (4,4))
        __VxF = np.ctypeslib.as_array(VxF, (4,))
        __OMxF = np.ctypeslib.as_array(OMxF, (4,))
        __AxF = np.ctypeslib.as_array(AxF, (4,))
        __OMPxF = np.ctypeslib.as_array(OMPxF, (4,))
        SWr = fun(__PxF, __RxF, __VxF, __OMxF, __AxF, __OMPxF, self, tsim, ixF)
        self.SWr[ixF,1:7] = SWr[1:7]
#        
#    def __callback_mbs_cons_hJ(self, fun, h, Jac):
#        __h = np.ctypeslib.as_array(h, (self.Ncons+1,))
#        __Jac = np.ctypeslib.as_array(Jac[0], (self.Ncons+1,self.njoint+1))
#        fun(__h,__Jac,self)
#        
#    def __callback_mbs_cons_jdqd(self, fun, jdqd, tsim):
#        __jdqd = np.ctypeslib.as_array(jdqd, (self.Ncons+1,))
#        fun(__jdqd,self)
#        
#    def __callback_mbs_dirdyna(self, fun, M, c, tsim):
#        __M = np.ctypeslib.as_array(M[0], (self.njoint+1,self.njoint+1))
#        __c = np.ctypeslib.as_array(c, (self.njoint+1,))
#        fun(__M,__c,self, tsim)
#        
    def __callback_mbs_sensor(self, fun, sens, isens):
        """ callback for gensensor, forcesensor and sensor
        """
        self.__sens.__reassign_memory__(sens)
        fun(self.__sens,self, isens)
    
    def __callback_mbs_invdyna(self, fun,Q, tsim):
        __Q = np.ctypeslib.as_array(Q, (self.njoint+1,))
        fun(self, tsim, __Q)
676
677
678
679
        
    def callback_undefined(self,function_name=None):
        print("undefined functions: "+function_name)
        return
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
    
    def set_nb_userc(self, nb):
        """ Set the number of user constraints.
        """
        libutilities.mbs_set_nb_userc(self.mbs_data_ptr, nb)
    
    def set_qu(self, indices):
        """ Set the specified joints as independent.
        """
        if isinstance(indices,(list,np.ndarray)):
            for index in indices:
                libutilities.mbs_set_qu(self.mbs_data_ptr, index)
        else:
            libutilities.mbs_set_qu(self.mbs_data_ptr, indices)
    
    def set_qv(self, indices):
        """ Set the specified joints as dependent.
        """
        if isinstance(indices,(list,np.ndarray)):
            for index in indices:
                libutilities.mbs_set_qv(self.mbs_data_ptr, index)
        else:
            libutilities.mbs_set_qv(self.mbs_data_ptr, indices)
        
        
    
    #==========================================================================
    # Defining properties
    #==========================================================================
    @property
    def npt(self):
        return self.mbs_data_ptr.contents.npt
    
    @property
    def dpt(self):
        return self.__dpt
    
    @property
    def l(self):
        return self.__l
    
    @property
    def m(self):
        return self.__m
    
    @property
    def In(self):
        return self.__In
    
    @property
    def g(self):
        return self.__g
    
    @property
    def nbody(self):
        return self.mbs_data_ptr.contents.nbody
    
    @property
    def njoint(self):
        return self.mbs_data_ptr.contents.njoint
    
    @property
    def nqu(self):
        return self.mbs_data_ptr.contents.nqu
    
    @property
    def nqc(self):
        return self.mbs_data_ptr.contents.nqc
    
    @property
    def nqlocked(self):
        return self.mbs_data_ptr.contents.nqlocked
    
    @property
    def nqdriven(self):
        return self.mbs_data_ptr.contents.nqdriven
    
    @property
    def nqa(self):
        return self.mbs_data_ptr.contents.nqa
    
    @property
    def nqv(self):
        return self.mbs_data_ptr.contents.nqv
    
    @property
    def nhu(self):
        return self.mbs_data_ptr.contents.nhu
    
    @property
    def qc(self):
        return self.__qc
    
    @property
    def qa(self):
        return self.__qa
    
    @property
    def q(self):
        return self.__q
    
    @property
    def qd(self):
        return self.__qd
        
    @property
    def qdd(self):
        return self.__qdd
    
    @property
    def q0(self):
        return self.__q0
    
    @property
    def qd0(self):
        return self.__qd0
        
    @property
    def qdd0(self):
        return self.__qdd0
        
    @property
    def frc(self):
        return self.__frc
        
    @property
    def trq(self):
        return self.__trq
    
    @property
    def Qq(self):
        return self.__Qq
    
    @property
    def tsim(self):
        return self.mbs_data_ptr.contents.tsim
        
    @tsim.setter
    def tsim(self, value):
        self.mbs_data_ptr.contents.tsim = value
    
    @property
    def t0(self):
        return self.mbs_data_ptr.contents.t0
        
    @t0.setter
    def t0(self, value):
        self.mbs_data_ptr.contents.t0 = value
    
    @property
    def tf(self):
        return self.mbs_data_ptr.contents.tf
        
    @tf.setter
    def tf(self, value):
        self.mbs_data_ptr.contents.tf = value
    
    @property
    def lrod(self):
        return self.__lrod
    
    @property
    def Nloopc(self):
        return self.mbs_data_ptr.contents.Nloopc
    
    @property
    def Ncons(self):
        return self.mbs_data_ptr.contents.Ncons
    
    @property
    def Nuserc(self):
        return self.mbs_data_ptr.contents.Nuserc
    
    @property
    def lambda_(self):
        return self.__lambda_
    
    @property
    def Qc(self):
        return self.__Qc
        
    @property
    def Nlink(self):
        return self.mbs_data_ptr.contents.Nlink
        
    @property
    def Z(self):
        return self.__Z
        
    @property
    def Zd(self):
        return self.__Zd
    
    @property
    def Fl(self):
        return self.__Fl
        
#    @property
#    def Nlink3D(self):
#        return self.mbs_data_ptr.contents.Nlink3D
    
    @property
    def Nsensor(self):
        return self.mbs_data_ptr.contents.Nsensor
        
    @property
    def Nxfrc(self):
        return self.mbs_data_ptr.contents.Nxfrc
    
    @property
    def xfidpt(self):
        return self.__xfidpt
    
    @property
    def SWr(self):
        return self.__SWr
    
    @property
    def ux(self):
        return self.__ux
    
    @property
    def uxd(self):
        return self.__uxd
    
    @property
    def ux0(self):
        return self.__ux0
    
    @property
    def Nux(self):
        return self.mbs_data_ptr.contents.Nux
    
    @property
    def DonePart(self):
        return self.mbs_data_ptr.contents.DonePart
    
    @property
    def process(self):
        return self.mbs_data_ptr.contents.process
        
    @process.setter
    def process(self, value):
        self.mbs_data_ptr.contents.process = value
    
    @property
    def mbs_filename(self):
        return ctypes.string_at(self.mbs_data_ptr.contents.mbs_filename).decode("utf-8")
    
    @property
    def project_path(self):
        return ctypes.string_at(self.mbs_data_ptr.contents.project_path).decode("utf-8")
    
    @property
    def mbs_name(self):
935
        return ctypes.string_at(self.mbs_data_ptr.contents.mbs_name).decode("utf-8")