mbs_data.py 64.2 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
# -*- 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

25
26
27
28
# importing MbsysPy functions
from ..mbs_utilities import bytes_to_str
from ..mbs_utilities import str_to_bytes

29
30
# importing MbsysPy classes
from .mbs_sensor import MbsSensor
31
from .mbs_part import MbsPart
32
33
34
35
36
from .mbs_equil import MbsEquil
from .mbs_dirdyn import MbsDirdyn
from .mbs_modal import MbsModal
from .mbs_solvekin import MbsSolvekin
from .mbs_invdyn import MbsInvdyn
37
38

# importing libraries
39
40
from .._mbsysc_loader.loadlibs import libutilities
from .._mbsysc_loader.loadlibs import libloadXML
41

42
43
44
# importing utilities function
from ..mbs_utilities import callback_undefined

45
# importing wrapping function
46
47
48
49
50
51
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
52

53
54
55
56
57
58
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
59
60
61
62

#==============================================================================
# Global parameter of the current module
#==============================================================================
63
__DEBUG__ = False
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
__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]
84
85
86
    extforce_id : dict
        Dictionary containing the names of the extforces as keys and their ids 
        as values.
87
88
89
90
91
92
93
94
95
96
97
    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]
98
99
100
    joint_id : dict
        Dictionary containing the names of the joints as keys and their ids as 
        values.
101
102
103
104
105
106
    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.
107
108
109
    link_id : dict
        Dictionary containing the names of the links as keys and their ids as 
        values.
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
    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.
208
209
210
    sensor_id : dict
        Dictionary containing the names of the sensors as keys and their ids as 
        values.
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    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.
234
235
236
237
    user_model : dict
        Dictionary containing the names of the user models as keys and a second
        dictionary with their parameters as values. The second dictionary
        contains the names of the parameters as keys and their values as values
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    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.
Louis Beauloye's avatar
Louis Beauloye committed
254
255
256
257
258
        
    
    Example
    -------
        
259
    >>> mbs_data = MBsysPy.MbsData("../dataR/UExampleProject.mbs")
Louis Beauloye's avatar
Louis Beauloye committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    >>> mbs_data.user_model["MyUserModel"]["MyScalar"] = 3.0
    >>> print(mbs_data.user_model["MyUserModel"]["MyScalar"])
        3.0    
    >>> #get a copy of the scalar
    >>> a = mbs_data.user_model["MyUserModel"]["MyScalar"]
    >>> a = 2
    >>> print(mbs_data.user_model["MyUserModel"]["MyScalar"])
        3.0
    >>> print(mbs_data.user_model["MyUserModel"]["MyVector"])
        array([1.0, 3.0])
    >>> mbs_data.user_model["MyUserModel"]["MyVector"] = [1.0, 2.0]
    >>> print(mbs_data.user_model["MyUserModel"]["MyVector"])
        array([1.0, 2.0])
    >>> b = mbs_data.user_model["MyUserModel"]["MyVector"]
    >>> b[1] = 10.0
    >>> print(mbs_data.user_model["MyUserModel"]["MyVector"])
        array([1.0, 10.0])
    >>> b = np.array([2.0, 4.0])
    >>> print(mbs_data.user_model["MyUserModel"]["MyVector"])
        array([1.0, 10.0])
    
281
282
    """
    
283
    def __init__(self, name, user_path=None, symbolic_path=None, prj_functions_c=None, prj_lib_path = None):
284
285
286
287
288
289
290
291
292
293
294
295
296
        """
        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.
297
        prj_functions_c : None or str, optionnal
298
299
300
301
302
303
            Option to load some of the project functions from the project C 
            library. Accepted values are:
             - None : All project function are defined in python
             - "symbolic_only" or "S" : Symbolic function comes from C library
             - "symbolic_and_user" or "SU" : Symbolic and user functions come from C library
            default is None
304
        prj_lib_path : None or str, optionnal
305
            Required if 'prj_functions_c' is not None
306
307
308
309
310
311
312
313
314
315
316
             - In Linux, it gives the location of the folder containing the 
               "symbolicR/" and, or "userfctR/" folders. Each one of the subfolder
               have to contain the corresponding library (ie: libProject_symbolic.so).
             - In Windows, it gives the location of the folder containing the project
               libraries (Project_symbolic.dll and/or Project_userfct.dll).
             - In MacOs the expected behavior is the same as Linux. It must be tested.
            default is None
            
        Returns
        -------
            A loaded mbs file in a MbsData instance.
317
        """
318
319
320
321
322
323
        # Retrieve prj_functions_c value
        if prj_functions_c is None:
            self.opt_load_c = 0
            if not (prj_lib_path is None):
                print("Argument 'prj_lib_path' is ignored as option 'prj_functions_c' is 'None'.")
                prj_lib_path = None
324
325
326
        elif (type(prj_functions_c) is str) or (type(prj_functions_c) is bytes):
            if (type(prj_functions_c) is bytes):
                prj_functions_c = bytes_to_str(prj_functions_c)
327
328
329
330
331
332
333
334
335
336
            if prj_functions_c == "symbolic_only" or prj_functions_c == "S":
                self.opt_load_c = 1
            elif prj_functions_c == "symbolic_and_user" or prj_functions_c == "SU":
                self.opt_load_c = 2
            else:
                raise ValueError("prj_functions_c is not valid:'"+prj_functions_c+"'.")
                
            if (prj_lib_path is None):
                raise ValueError("prj_lib_path must be given if 'prj_functions_c' is set.")
            if not (type(prj_lib_path) is str):
337
                raise TypeError("prj_lib_path type must be str but it is '"+str(type(prj_lib_path))+"'.")
338
            else:
339
                prj_lib_path = str_to_bytes(os.path.abspath(prj_lib_path))
340
        else:
341
            raise TypeError("prj_functions_c type is not valid:'"+str(type(prj_functions_c))+"'.")            
342

343
        # Create a byte object from the string
344
        name_c = str_to_bytes(name)
345
        # Load the MbsInfos and keep a copy
346
        if __DEBUG__ : print( "DEBUG>>  Loading: '"+bytes_to_str(name)+"' from:'"+os.getcwd()+"'.")
347
        self.mbs_infos_ptr = libloadXML.mbs_info_reader(name_c)
348
        if __DEBUG__ : print( "DEBUG>>  mbs_infos structure loaded")
349
350
351
352
353
        
        # Preparing loader and its options for loading 
        loader = libloadXML.mbs_new_loader()
        if __DEBUG__ : print( "DEBUG>>  Loader structure created")
        
354
        loader.contents.opts.contents.no_project_fct = self.opt_load_c
355
356
        if __DEBUG__ : print( "DEBUG>>  flag ignoring project function set")
        
357
        loader.contents.mbs_infos = self.mbs_infos_ptr
358
        if __DEBUG__ : print( "DEBUG>>  mbs_infos assigned to loader")
359
360
        
        # Load and retrieve MbsData structure
361
        self.mbs_data_ptr = libloadXML.mbs_load_with_loader(name_c, prj_lib_path, loader)
362
        if __DEBUG__ : print( "DEBUG>>  MbsData loaded")
363
        libloadXML.mbs_delete_loader(loader)
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
        # 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
        
395
396
397
        # pointers dict to avoid garbage collecting
        self.ptrs_to_user_fcts = dict()
        self.ptrs_to_symb_fcts = dict()
398
399
400
401
        
        # Exposing some memory
        if __DEBUG__ : print( "DEBUG>>  Exposing MbsData fields")
        # Geometric and dynamic datas
402
403
404
        self.__dpt = None
        if(self.npt):
            self.__dpt = np.ctypeslib.as_array(self.mbs_data_ptr.contents.dpt[0], (3+1, self.npt+1))
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
        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,))
431
        self.__Qa = np.ctypeslib.as_array(self.mbs_data_ptr.contents.Qa, (self.njoint+1,))
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
        
        # Constraints datas
        self.nrod = 0
        self.__lrod = None
        if (self.mbs_data_ptr.contents.lrod):
            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,))
454
            self.__SWr = np.ctypeslib.as_array(self.mbs_data_ptr.contents.SWr[0], (self.Nxfrc+1, 9+1))
455
456
457
458
459
460
461
462
463
464
465
        
        # 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)]
        
466
        # ID
467
        self.body_id = {}
468
469
470
471
        self.joint_id = {}
        self.link_id = {}
        self.extforce_id = {}
        self.sensor_id = {}
472
        self.points_id = {}
473
474
        self.__generate_id__()
        
475
        #UserModel
Louis Beauloye's avatar
Louis Beauloye committed
476
        self.user_model = _UserModelDict()
477
478
        self.__load_user_model__()
        
479
        
480
        # Loading user function
481
482
483
        if self.opt_load_c < 2:
            if __DEBUG__ : print( "DEBUG>>  Loading user functions")
            self.__load_user_fct__(user_path)
484
        # Loading symbolic function
485
486
487
        if self.opt_load_c < 1:
            if __DEBUG__ : print( "DEBUG>>  Loading symbolic functions")
            self.__load_symbolic_fct__(symbolic_path)
488
489
490
491
492
493
494
495
        

    def __str__(self):
        if __DEBUG__ : print( "DEBUG>>  start of __str")
        
        libutilities.mbs_print_data(self.mbs_data_ptr)
        if __DEBUG__ : print( "DEBUG>>  MbsData printed")
        
496
        return ''
497
    
498
    def __load_user_fct__(self, user_path=None):
499
        """ 
Olivier Lantsoght's avatar
Olivier Lantsoght committed
500
501
502
503
504
505
506
507
508
509
        Load all user functions where arguments are in MbsData instance.
        
        Only load the user functions in which the arguments are not 
        dependent of another module instance (ie. MbsPart, MbsDirdyn...).
        The other user functions will be loaded when a module is created.
        The functions will be assigned to the MbsData instance when 
        the 'run' function in other modules is called and unassigned 
        at the end.
        
        The loader user functions are :
510
511
512
513
514
515
         - user_derivatives (from user_Derivative.py)
         - user_DrivenJoints (from user_DrivenJoints.py)
         - user_ExtForces (from user_ExtForces.py)
         - user_JointForces (from user_JointForces.py)
         - user_LinkForces (from user_LinkForces.py)
         - user_Link3DForces (from user_Link3DForces.py)
516
517
518
519
520
521
522

        Parameters
        ----------
        user_path : str or None, optionnal
            The path to the folder containing the user functions if the default
            project structure are not used.
            default is None
523
        """
524
        template_path = os.path.join(__MODULE_DIR__,'../templates/user')
525
526
527
528
529
530
531
532
533
534
535
536
537
538
        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

        # derivative
539
        user_file = "user_Derivative.py"
540
        path = os.path.abspath(os.path.join(user_path, user_file))
541
        if not os.path.isfile(path):
542
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
543
544
545
            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
546
547

        # drivenJoints
548
        user_file = "user_DrivenJoints.py"
549
        path = os.path.abspath(os.path.join(user_path, user_file))
550
        if not os.path.isfile(path):
551
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
552
553
554
            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
555
556

        # ext_forces
557
        user_file = "user_ExtForces.py"
558
        path = os.path.abspath(os.path.join(user_path, user_file))
559
        if not os.path.isfile(path):
560
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
561
562
563
            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
564
565

        # joint_forces
566
        user_file = "user_JointForces.py"
567
        path = os.path.abspath(os.path.join(user_path, user_file))
568
        if not os.path.isfile(path):
569
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
570
571
572
            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
573
574

        # link_forces
575
        user_file = "user_LinkForces.py"
576
        path = os.path.abspath(os.path.join(user_path, user_file))
577
        if not os.path.isfile(path):
578
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
579
580
581
            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
582
583

        # link3D_forces
584
        user_file = "user_Link3DForces.py"
585
        path = os.path.abspath(os.path.join(user_path, user_file))
586
        if not os.path.isfile(path):
587
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
588
589
590
            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
591
592
593
594
            
        return
        
    
595
    def __load_symbolic_fct__(self, symb_path=None):
596
        """ 
Olivier Lantsoght's avatar
Olivier Lantsoght committed
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
        Load all symbolic functions if all args are in MbsData instance.
        
        Only load the symbolic functions in which the arguments are not 
        dependent of another module instance (ie. MbsPart, MbsDirdyn...).
        The other symbolic functions will be loaded when a module is 
        instancied.
        The functions will be assigned to the MbsData instance when 
        the 'run' function in other modules is called and unassigned 
        at the end.
        
        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)
614
615
616
617
618
619
620

        Parameters
        ----------
        symbolic_path : str, optionnal
            The path to the folder containing the symbolic functions if the 
            default project structure are not used.
            defult is None
621
        """
622
        
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
        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))
641
        if not os.path.isfile(path):
642
643
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
            symb_file = "mbs_accelred_PRJ.py"
644
645
646
647
            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
            
648
649
650
651
        
        # mbs_extforces
        symb_file = "mbs_extforces_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
652
        if not os.path.isfile(path):
653
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
654
655
656
657
            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
658
659
660
661
        
        # mbs_gensensor
        symb_file = "mbs_gensensor_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
662
        if not os.path.isfile(path):
663
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
664
665
666
667
            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
668
669
670
671
        
        # mbs_link
        symb_file = "mbs_link_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
672
        if not os.path.isfile(path):
673
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
674
675
676
677
            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
678
679
680
681
        
        # mbs_link3D
        symb_file = "mbs_link3D_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
682
        if not os.path.isfile(path):
683
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
684
685
686
687
            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
688
        
689
        # mbs_sensor
690
691
        symb_file = "mbs_sensor_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symb_path, symb_file))
692
        if not os.path.isfile(path):
693
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
694
695
696
697
            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
698
699
700
701
        
        
    def __assign_user_fct__(self):
        """ 
Olivier Lantsoght's avatar
Olivier Lantsoght committed
702
703
704
705
706
707
708
709
        Assign all user functions if all args are in MbsData instance.
        
        Assign and wrap python user functions in which the arguments are 
        not dependent of another module instance (ie. MbsPart, MbsDirdyn...).
        Store the functions in the MbsData instance and assign the pointer 
        of functions in the C structure. 
        The other user functions will be assigned when a module is
        instancied.
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
        """
        data_c_ptr=self.mbs_data_ptr.contents

        # derivative
        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"]

        # 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"]

        # ext_forces
        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"]

        # joint_forces
        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"]

        # link_forces
        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"]

        # link3D_forces
        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"]
            
        return
        
    
    def __assign_symb_fct__(self):
        """ 
Olivier Lantsoght's avatar
Olivier Lantsoght committed
742
743
744
745
746
747
748
749
        Assign all symbolic functions if all args are in MbsData instance.
        
        Assign and wrap python symbolic functions in which the arguments are 
        not dependent of another module instance (ie. MbsPart, MbsDirdyn...).
        Store the functions in the MbsData instance and assign the pointer 
        of functions in the C structure. 
        The other user functions will be assigned when a module is
        instancied.
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
            
        """
        data_c_ptr=self.mbs_data_ptr.contents
            
        # 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"]
            
        
        # mbs_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"]
        
        # mbs_gensensor
        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"]
        
        # mbs_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"]
        
        # mbs_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"]
        
        # mbs_sensor
776
777
        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"]
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
    
    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]
798
    
799
    def __callback_mbs_sensor(self, fun, sens, isens):
Olivier Lantsoght's avatar
Olivier Lantsoght committed
800
        """ callback for gensensor, forcesensor and sensor """
801
802
803
804
805
806
        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)
807
        
808
809
    def __unassign_user_fct__(self):
        """
Olivier Lantsoght's avatar
Olivier Lantsoght committed
810
811
812
813
        Unassign all user function if all args are in MbsData instance.
        
        Only unassign the user functions in which the arguments are not 
        dependent of another module instance (ie. MbsPart, MbsDirdyn...).
814
815
816
817
818
819
820
821
822
823
824
825
826
827
        """
        #not necessary but if not present, dictionary must be filled in the load 
        #function and not the assign function
        self.ptrs_to_user_fcts = {}
        
        self.mbs_data_ptr.contents.user_Derivative = user_Derivative_wrap(lambda mbs : callback_undefined("user_Derivative"))
        self.mbs_data_ptr.contents.user_DrivenJoints = user_DrivenJoints_wrap(lambda mbs,t : callback_undefined("user_DrivenJoints"))
        self.mbs_data_ptr.contents.user_ExtForces = user_ExtForces_wrap(lambda PxF,RxF,VxF,OMxF,AxF,OMPxF,mbs,tsim,ixF : callback_undefined("user_ExtForces"))
        self.mbs_data_ptr.contents.user_JointForces  = user_JointForces_wrap(lambda mbs,t : callback_undefined("user_JointForces"))
        self.mbs_data_ptr.contents.user_LinkForces = user_LinkForces_wrap(lambda Z, Zd, mbs, tsim, ilnk : callback_undefined("user_LinkForces"))
        self.mbs_data_ptr.contents.user_Link3DForces = user_Link3DForces_wrap(lambda PxF,RxF,VxF,OMxF,AxF,OMPxF,mbs,tsim,ixF : callback_undefined("user_Link3DForces"))
        
    def __unassign_symb_fct__(self):
        """
Olivier Lantsoght's avatar
Olivier Lantsoght committed
828
829
830
831
        Unassign all symbolic function if all args are in MbsData instance.
        
        Only unassign the symbolic functions in which the arguments are not 
        dependent of another module instance (ie. MbsPart, MbsDirdyn...).
832
833
834
835
836
837
838
839
840
841
842
843
844
845
        """
        #not necessary but if not present, dictionary must be filled in the load
        #function and not the assign function
        self.ptrs_to_symb_fcts = {}
        
        self.mbs_data_ptr.contents.mbs_accelred = mbs_accelred_wrap(lambda mbs,tsim : callback_undefined("mbs_accelred"))
        self.mbs_data_ptr.contents.mbs_extforces= mbs_extforces_wrap(lambda frc,trq,mbs,tsim : callback_undefined("mbs_extforces"))
        self.mbs_data_ptr.contents.mbs_gensensor = mbs_gensensor_wrap(lambda sens,mbs,isens : callback_undefined("mbs_gensensor"))
        self.mbs_data_ptr.contents.mbs_link = mbs_link_wrap(lambda frc,trq,Flnk,Z,Zd,mbs,tsim : callback_undefined("mbs_link"))
        self.mbs_data_ptr.contents.mbs_link3D = mbs_link3D_wrap(lambda frc,trq,mbs,tsim  : callback_undefined("mbs_link3D"))
        self.mbs_data_ptr.contents.mbs_sensor = mbs_sensor_wrap(lambda sens,mbs,isens : callback_undefined("mbs_sensor"))
        
    def __generate_id__(self):
        """
Olivier Lantsoght's avatar
Olivier Lantsoght committed
846
847
       Read the id's of the joints, links, sensors and extforces from MbsInfos
       structure and store them into dictionaries in the MbsData instance.
848
849
850
        """
        
        for i in range(self.njoint):
851
            name = bytes_to_str(self.mbs_infos_ptr.contents.bodytree.contents.joint_list[i].contents.name)
852
            self.joint_id[name] = i+1
853
854
        
        for i in range(self.nbody):
855
            name = bytes_to_str(self.mbs_infos_ptr.contents.bodytree.contents.body_list[i].contents.name)
856
            local_id_parent_joint = self.mbs_infos_ptr.contents.bodytree.contents.body_list[i].contents.n_joint-1
857
            parent_joint_name =  bytes_to_str(self.mbs_infos_ptr.contents.bodytree.contents.body_list[i].contents.joint_list[local_id_parent_joint].contents.name)
858
            self.body_id[name] = self.joint_id[parent_joint_name]
859
            
860
861
862
863
864
865
866
867
        for i in range(self.npt):
            bodyname = bytes_to_str(self.mbs_infos_ptr.contents.point_list[i].contents.body_name)
            if not bodyname in self.points_id:
                self.points_id[bodyname]={}
            
            pointname = bytes_to_str(self.mbs_infos_ptr.contents.point_list[i].contents.name)
            self.points_id[bodyname][pointname]=i+1
            
868
869
        if self.Nlink:
            for i in range(self.Nlink):
870
                name = bytes_to_str(self.mbs_infos_ptr.contents.links.contents.link_list[i].contents.name)
871
872
873
874
875
                self.link_id[name] = i+1
                
        if self.Nsensor:
            for i in range(self.Nsensor):
                index = self.mbs_infos_ptr.contents.sensor_point_list[i]
876
                name = bytes_to_str(self.mbs_infos_ptr.contents.point_list[index].contents.sensor.contents.name)
877
878
879
880
881
                self.sensor_id[name] = i+1
        
        if self.Nxfrc:
            for i in range(self.Nxfrc):
                index = self.mbs_infos_ptr.contents.extforce_point_list[i]
882
                name = bytes_to_str(self.mbs_infos_ptr.contents.point_list[index].contents.extforce.contents.name)
883
                self.extforce_id[name] = i+1
884
885
886
                
                
    def __load_user_model__(self):
Louis Beauloye's avatar
Louis Beauloye committed
887
        """
Olivier Lantsoght's avatar
Olivier Lantsoght committed
888
889
890
891
892
893
894
        Load user models in 2 nested dictionaries
        
        
        The first one contains the names of the user models as keys and a
        second dictionary for the parameters as values.
        The second one contains the names of the parameters as keys and
        numpy arrays that point toward C memory as values
Louis Beauloye's avatar
Louis Beauloye committed
895
        """
896
897
898
899
        self.user_model._locked = False
        infos_c_ptr=self.mbs_infos_ptr.contents
        for i in range(infos_c_ptr.user_models.contents.n_user_model):
            user_model_list = infos_c_ptr.user_models.contents.user_model_list[i].contents
900
            name = bytes_to_str(user_model_list.name)
Louis Beauloye's avatar
Louis Beauloye committed
901
            self.user_model[name] = _UserModelDict()
902
903
904
905
906
            self.user_model[name]._parent_key = name
            self.user_model[name]._locked = False
            self.user_model[name]._type = dict()
            for j in range(user_model_list.n_parameter):
                parameter_list = user_model_list.parameter_list[j].contents
907
                name2 = bytes_to_str(parameter_list.name)
908
909
910
911
912
913
                val_ptr = parameter_list.val_ptr
                value_list = parameter_list.value_list
                self.user_model[name]._type[name2] = parameter_list.type
                size = parameter_list.n_value
                UmPy = (ctypes.cast(val_ptr, ctypes.c_void_p).value==ctypes.cast(value_list, ctypes.c_void_p).value)
                if UmPy :
Louis Beauloye's avatar
Louis Beauloye committed
914
915
916
917
918
                    if self.user_model[name]._type[name2] == 5:
                        self.user_model[name][name2] = np.array(np.ctypeslib.as_array(val_ptr, (1,size)), dtype = np.int)
                    else:
                        self.user_model[name][name2] = np.ctypeslib.as_array(val_ptr, (1,size))
                    #in full python project, the C memory is always a double
919
920
921
922
923
924
925
926
                else :
                    #not yet tested, it requires user and symbolic fonctions in C
                    if self.user_model[name]._type[name2] == 5 or self.user_model[name]._type[name2] == 7:
                        self.user_model[name][name2] = np.ctypeslib.as_array(ctypes.cast(val_ptr, ctypes.POINTER(ctypes.c_int)), (1,size))
                    else :
                        self.user_model[name][name2] = np.ctypeslib.as_array(val_ptr, (1,size))
            self.user_model[name]._locked = True
        self.user_model._locked = True
927
928
            
        
929
930
    
    def set_nb_userc(self, nb):
931
932
933
934
935
936
937
938
        """
        Set the number of user constraints.

        Parameters
        ----------
        nb : int
            The number of user constraints.
        """
939
940
941
        libutilities.mbs_set_nb_userc(self.mbs_data_ptr, nb)
    
    def set_qu(self, indices):
942
943
944
945
946
947
948
949
950
        """
        Set the specified joints as independent.

        Parameters
        ----------
        indices : int, list or numpy.ndarray
            The ids of the joints to set as independent.
        
        """
951
952
953
954
955
956
957
        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):
958
959
960
961
962
963
964
965
        """
        Set the specified joints as dependent.

        Parameters
        ----------
        indices : int, list or numpy.ndarray
            The ids of the joints to set as dependent.
        """
966
967
968
969
970
        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)
Olivier Lantsoght's avatar
Olivier Lantsoght committed
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
    
    def set_qdriven(self, indices):
        """
        Set the specified joints as driven.

        Parameters
        ----------
        indices : int, list or numpy.ndarray
            The ids of the joints to set as driven.
        """
        if isinstance(indices,(list,np.ndarray)):
            for index in indices:
                libutilities.mbs_set_qdriven(self.mbs_data_ptr, index)
        else:
            libutilities.mbs_set_qdriven(self.mbs_data_ptr, indices)
986
            
987
    def set_qa(self, indices):
988
989
990
991
992
993
994
995
996
997
998
999
        """
        Set the specified joints as actuated.
        
        Actuated joints are only used by equilibrium analysis (in some cases)
        and inverse dynamics. Actuated joint are also member of one of the other
        partition (independent or dependent).

        Parameters
        ----------
        indices : int, list or numpy.ndarray
            The ids of the joints to set as actuated.
        """
1000
1001
1002
1003
1004
1005
1006
        if isinstance(indices,(list,np.ndarray)):
            for index in indices:
                libutilities.mbs_set_qa(self.mbs_data_ptr, index)
        else:
            libutilities.mbs_set_qa(self.mbs_data_ptr, indices)
    
    def unset_qa(self, indices):
1007
1008
1009
1010
1011
1012
1013
1014
        """
        Remove the specified joints from the actuated joints.

        Parameters
        ----------
        indices : int, list or numpy.ndarray
            The ids of the joints to be removed from the actuated list.
        """
1015
1016
1017
1018
1019
1020
1021
        if isinstance(indices,(list,np.ndarray)):
            for index in indices:
                libutilities.mbs_unset_qa(self.mbs_data_ptr, index)
        else:
            libutilities.mbs_unset_qa(self.mbs_data_ptr, indices)
            
    def empty_qa(self):
Olivier Lantsoght's avatar
Olivier Lantsoght committed
1022
        """ Remove all joints from the actuated partition. """
1023
1024
        libutilities.mbs_empty_qa(self.mbs_data_ptr)
        
1025
1026
1027
1028
    def __del__(self):
        libloadXML.mbs_delete_infos(self.mbs_infos_ptr)
        libloadXML.mbs_delete_data(self.mbs_data_ptr)
        if __DEBUG__ : print("DEBUG>>  MbsData pointer deleted")
1029
        
Olivier Lantsoght's avatar
Olivier Lantsoght committed
1030
    def reset(self,verbose=False):
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
        """ 
        Reset mbs_data fields to its inital value.
        
        The following fields are resetted according to the values storied in the
        field in parentheses:
         - MbsData.q (MbsData.q0)
         - MbsData.qd (MbsData.qd0)
         - MbsData.qdd (MbsData.qdd0)
         - MbsData.ux (MbsData.ux0)
         - MbsData.Qq (filled with 0)
         - MbsData.Qa (filled with 0)
         - MbsData.Qc (filled with 0)
         - MbsData.tsim (MbsData.t0)

        Parameters
        ----------
        verbose : bool, optional
            Set to 'True' to print resetting validation.
            default is False
        """
1051
1052
1053
1054
        libutilities.mbs_reset_data(self.mbs_data_ptr)
        if verbose :
           print("mbs_data reseted to initial value")
    
1055
    def mbs_load_from_file(self, baseFileName="dirdyn", result_path="resultsR", time = -1):
1056
        """ Load a state to MbsData instance from files for specific time.
Olivier Lantsoght's avatar
Olivier Lantsoght committed
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
        
        If the time specified is not found in the file, the last time step 
        lower than the specification is taken.
        The fieds q, qd, qdd, ux, uxd, q0, qd0, qdd0, ux0 ant tsim are set.

        Parameters
        ----------
        baseFileName : str
            The path and resfilename containing the state to load. The suffix 
            _q, _qd, _ux.res will be added. 
            default is "dirdyn"
        result_path : str
            The relative path of the result folder from the project folder.
            default is "resultsR"
        time : float
            The time corresponding to the state to load.
            defaut is "-1" (last state of the files).
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
        """
        def find_index(temp, t):
            if (t == -1):
                index = -1
            else:
                # Look the specified time
                index = np.nonzero(temp[:,0]>=t)
                if (np.size(index)):
                    index=index[0][0]
                    if not temp[index,0]==t:
                        if __DEBUG__ : print ("Time specified not found, take the last occurence where t<time")
                        index = index-1
                else:
                    if __DEBUG__ : print ("Time specified greather than time in files, taking the last state.")
                    index = -1
            return(index)
        
        project_path = self.project_path
            
        
1094
        result_path = os.path.join(project_path, result_path)
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
        # Error handeling
        if not os.path.isdir(result_path):
            if __DEBUG__ : print ('DEBUG>> The result directory does not exist: "'+ result_path+'"')
            
        index = -2
        # Generalized coordinates
        CurFile = baseFileName+'_q.res'
        path = os.path.abspath(os.path.join(result_path, CurFile))
        if (os.path.isfile(path) ):
            temp = np.loadtxt(path)
            index = find_index(temp, time)
            self.q[1:] = temp[index, 1:]
            self.q0[1:] = self.q[1:]
            self.tsim = temp[index, 0]
        else:
            if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
        
        # Generalized velocities
        # Assumption: index is still valid
        CurFile = baseFileName+'_qd.res'
        path = os.path.abspath(os.path.join(result_path, CurFile))
        if (os.path.isfile(path)):
            temp = np.loadtxt(path)
            if index == -2:
                index = find_index(temp, time)
            self.qd[1:] = temp[index, 1:]
            self.qd0[1:] = self.qd[1:]
        else:
             if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
             
        # Generalized accelerations
        # Assumption: index is still valid    
        CurFile = baseFileName+'_qdd.res'
        path = os.path.abspath(os.path.join(result_path, CurFile))
        if (os.path.isfile(path)):
            temp = np.loadtxt(path)
            if index == -2:
                index = find_index(temp, time)
            self.qdd[1:] = temp[index, 1:]
            self.qdd0[1:] = self.qdd[1:]
        else:
             if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
        
        # Generalized user state
        # Assumption: index is still valid
        if self.Nux:
            CurFile = baseFileName+'_ux.res'
            path = os.path.abspath(os.path.join(result_path, CurFile))
            if (os.path.isfile(path) ):
                temp = np.loadtxt(path)
                if index == -2:
                    index = find_index(temp, time)              
                self.ux[1:] = temp[index, 1:]
                self.ux0[1:] = self.ux[1:]
            else:
                if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
            
            CurFile = baseFileName+'_uxd.res'
            path = os.path.abspath(os.path.join(result_path, CurFile))
            if (os.path.isfile(path)):
                temp = np.loadtxt(path)
                if index == -2:
                    index = find_index(temp, time)              
                self.uxd[1:] = temp[index, 1:]
            else:
                if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
    
    def exe_part(self, **kwargs):
        """ 
        Run a partitioning module with the specified set of options.

        Parameters
        ----------
        kwargs : 
            Options of the partitioning module (see 'set_options' in MbsPart).
            
        """
        mbs_part = MbsPart(self)
        mbs_part.set_options(**kwargs)
        mbs_part.run()
    
    def exe_equil(self, **kwargs):
        """ 
        Run a equil module with a specified set of options.
        
        Also run a partitioning module if needed. 
        Partioning options are setted to default values expect rowperm = 1

        Parameters
        ----------
        kwargs
            Options to user for the analysis (see 'set_options' in MbsEquil).
        
        Returns
        -------
        results : MbsResults instance
            This object contains the results of the dirdyn analysis.
        """
        if (not self.DonePart) and self.Ncons:
            mbs_part = MbsPart(self)
            mbs_part.set_options(verbose=False, rowperm = True)
            mbs_part.run()

        mbs_equil = MbsEquil(self)
        mbs_equil.set_options(**kwargs)
        results = mbs_equil.run()
            
        return results
    
1204
    def exe_dirdyn(self, **kwargs):
1205
1206
        """ 
        Run a dirdyn module with a specified set of options.
Olivier Lantsoght's avatar
Olivier Lantsoght committed
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
        
        Also run a partitioning module if needed. 
        Partioning options are setted to default values expect rowperm = 1

        Parameters
        ----------
        kwargs
            Options to user for the analysis (see 'set_options' in MbsDirdyn).
        
        Returns
        -------
        results : MbsResults instance
            This object contains the results of the dirdyn analysis.
1220
1221
1222
1223
1224
        """
        if (not self.DonePart) and self.Ncons:
            mbs_part = MbsPart(self)
            mbs_part.set_options(verbose=False, rowperm = True)
            mbs_part.run()
1225
1226
1227
1228

        mbs_dirdyn = MbsDirdyn(self)
        mbs_dirdyn.set_options(**kwargs)
        results = mbs_dirdyn.run()
Louis Beauloye's avatar
Louis Beauloye committed
1229
1230
            
        return results
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
    
    def exe_modal(self, **kwargs):
        """ 
        Run a modal module with a specified set of options.
        
        Also run a partitioning module if needed. 
        Partioning options are setted to default values expect rowperm = 1
        
        Note: A modal analysis should only be run on a equilibrium configuration.

        Parameters
        ----------
        kwargs
            Options to user for the analysis (see 'set_options' in MbsModal).
        
        Returns
        -------
        results : MbsResults instance
            This object contains the results of the dirdyn analysis.
        """
        if (not self.DonePart) and self.Ncons:
            mbs_part = MbsPart(self)
            mbs_part.set_options(verbose=False, rowperm = True)
            mbs_part.run()

        mbs_modal = MbsModal(self)
        mbs_modal.set_options(**kwargs)
        results = mbs_modal.run()
1259
            
1260
1261
1262
1263
1264
1265
1266
1267
        return results
    
    def exe_solvekin(self, **kwargs):
        """ 
        Run a solvekin module with a specified set of options.
        
        Also run a partitioning module if needed. 
        Partioning options are setted to default values expect rowperm = 1
Olivier Lantsoght's avatar
Olivier Lantsoght committed
1268
1269
1270

        Parameters
        ----------
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
        kwargs
            Options to user for the analysis (see 'set_options' in MbsSolvekin).
        
        Returns
        -------
        results : MbsResults instance
            This object contains the results of the solvekin analysis.
        """
        if (not self.DonePart) and self.Ncons:
            mbs_part = MbsPart(self)
            mbs_part.set_options(verbose=False, rowperm = True)
            mbs_part.run()

        mbs_solvekin = MbsSolvekin(self)
        mbs_solvekin.set_options(**kwargs)
        results = mbs_solvekin.run()
1287
            
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
        return results
    
    def exe_invdyn(self, **kwargs):
        """ 
        Run a invdyn module with a specified set of options.
        
        Also run a partitioning module if needed. 
        Partioning options are setted to default values expect rowperm = 1

        Parameters
        ----------
        kwargs
            Options to user for the analysis (see 'set_options' in MbsInvdyn).
        
        Returns
        -------
        results : MbsResults instance
            This object contains the results of the invdyn analysis.
1306
        """
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
        if (not self.DonePart) and self.Ncons:
            mbs_part = MbsPart(self)
            mbs_part.set_options(verbose=False, rowperm = True)
            mbs_part.run()

        mbs_invdyn = MbsInvdyn(self)
        mbs_invdyn.set_options(**kwargs)
        results = mbs_invdyn.run()
            
        return results
1317

1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
    #==========================================================================
    # 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
    
1421
1422
1423
1424
    @property
    def Qa(self):
        return self.__Qa
    
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
    @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):
1543
        return bytes_to_str(ctypes.string_at(self.mbs_data_ptr.contents.mbs_filename))
1544
1545
1546
    
    @property
    def project_path(self):
1547
        return bytes_to_str(ctypes.string_at(self.mbs_data_ptr.contents.project_path))
1548
1549
1550
    
    @property
    def mbs_name(self):
1551
        return bytes_to_str(ctypes.string_at(self.mbs_data_ptr.contents.mbs_name))
1552
1553
    
    
Louis Beauloye's avatar
Louis Beauloye committed
1554
1555
1556
1557
1558
1559
1560
class _UserModelDict(dict):
    """
        Class defined for user models, inherites from dict
        
        
        setitem and getitem function were updated
    """
1561
1562
1563
1564
        
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self._locked = True 
Louis Beauloye's avatar
Louis Beauloye committed
1565
        "flag that locks the addition of a new item"
1566
        self._parent_key = None
Louis Beauloye's avatar
Louis Beauloye committed
1567
1568
1569
        "key of the parent dict, None if not"
        self._type = None
        "type of the parameter, None if not"
1570
1571
1572
1573
        
    def __setitem__(self, key, value):
            
        if self._locked == True:
Louis Beauloye's avatar
Louis Beauloye committed
1574
            # if it is a parameter and not a parent 
1575
            if not (self._type is None):
Louis Beauloye's avatar
Louis Beauloye committed
1576
1577
1578
1579
1580
1581
1582
                if key in self.keys():
                    if self._type[key] == 1:
                        if type(value) is float:
                            tab = self.__getarray__(key)
                            tab[0][0] = value
                        elif type(value) is int:
                            tab = self.__getarray__(key)
1583
                            tab[0][0] = float(value)
Louis Beauloye's avatar
Louis Beauloye committed
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
                        else :
                            print("UserModel "+self._parent_key+"."+key+" is a float, "+str(type(value))+" was given")
                    elif self._type[key] == 7:
                        if type(value) is int:
                            tab = self.__getarray__(key)
                            tab[0][0] = value
                        else :
                            print("UserModel "+self._parent_key+"."+key+" is an int, "+str(type(value))+" was given")
                    elif self._type[key] == 2 or self._type[key] == 5:
                        if type(value) is np.ndarray or type(value) is list:
                            tab = self.__getarray__(key)
                            if np.size(value) == np.size(tab):
                                tab[:] = value[:]
                            else:
                                print("UserModel "+self._parent_key+"."+key+" is an array of size "+str(np.size(tab))+", array of size "+str(np.size(value))+" was given")
                        else :
                            print("UserModel "+self._parent_key+"."+key+" is an array, "+str(type(value))+" was given")