mbs_dirdyn.py 42 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- 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 MbsDirdyn based on the MbsDirdyn structure of MBsysC.
This class has the functions required to manipulate the direct dynamic module.
This include setting the options, running an (or multiple) analysis and freeing
the memory.
"""

import os
import imp
22
import ctypes
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

import numpy as np

# importing MbsysPy classes

# importing libraries
from ..mbsysc_loader.loadlibs import libmodules

# importing wrapping function
from ..mbsysc_loader.callback import user_cons_hJ_wrap
from ..mbsysc_loader.callback import user_cons_jdqd_wrap
from ..mbsysc_loader.callback import user_dirdyn_init_wrap
from ..mbsysc_loader.callback import user_dirdyn_loop_wrap
from ..mbsysc_loader.callback import user_dirdyn_finish_wrap

from ..mbsysc_loader.callback import mbs_cons_hJ_wrap
from ..mbsysc_loader.callback import mbs_cons_jdqd_wrap
from ..mbsysc_loader.callback import mbs_invdyna_wrap
from ..mbsysc_loader.callback import mbs_dirdyna_wrap


#==============================================================================
# Global parameter of the current module
#==============================================================================
47
__DEBUG__ = False
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
__MODULE_DIR__ = os.path.dirname(os.path.abspath(__file__))


#==============================================================================
# Defining Python MbsDirdyn class
#==============================================================================

class MbsDirdyn(object):
        
    def __init__(self, mbs, user_path=None, symbolic_path=None):
        if __DEBUG__ : print( "DEBUG>>  Creating MbsDirdyn struct for "+mbs.mbs_name+"' MBS.")
        self.mbs_dirdyn_ptr = libmodules.mbs_new_dirdyn(mbs.mbs_data_ptr)
        if __DEBUG__ : print( "DEBUG>>  MbsDirdyn structure loaded")
        self.mbs = mbs

        #Test
        if __DEBUG__ :
            print( "DEBUG>>  MbsDirdyn created.")
            print( "     >>  options->tf (5.0): ", self.mbs_dirdyn_ptr.contents.options.contents.tf)
            print( "     >>  options->dt_max (1e-3): ", self.mbs_dirdyn_ptr.contents.options.contents.dt_max)
            print( "     >>  mbs_aux->NRerr (-): ", self.mbs_dirdyn_ptr.contents.mbs_aux.contents.NRerr)
            print( "     >>  mbs_aux->nquc (-): ", self.mbs_dirdyn_ptr.contents.mbs_aux.contents.nquc)
            print( "     >>  mbs_aux->M[1:3][1:3]: ", 
                  self.mbs_dirdyn_ptr.contents.mbs_aux.contents.M[1][1], 
                  self.mbs_dirdyn_ptr.contents.mbs_aux.contents.M[1][2], 
                  self.mbs_dirdyn_ptr.contents.mbs_aux.contents.M[2][1], 
                  self.mbs_dirdyn_ptr.contents.mbs_aux.contents.M[2][2])
75
        # Path to user function used by partitionning module
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
        self.user_path = self.mbs.user_path
        if not (user_path==None):
            project_path  = (self.mbs.project_path).decode("utf-8")
            user_path = os.path.join(project_path, user_path)
            # Error handeling
            if not os.path.isdir(user_path):
                print ('The user function directory for direct dynamic module does not exist: "'+ user_path+'"')
                print ('The current root folder is: "'+os.getcwd()+'"')
                print ('The following directory is used instead: "'+self.user_path+'".')
            else:
                self.user_path = user_path
        # Path to user function used by partitionning modue
        self.symbolic_path = self.mbs.symbolic_path
        if not (user_path==None):
            project_path  = (self.mbs.project_path).decode("utf-8")
            symbolic_path = os.path.join(project_path, symbolic_path)
            # Error handeling
            if not os.path.isdir(symbolic_path):
                print ('Thesymbolic function directory for direct dynamic module does not exist: "'+ symbolic_path+'"')
                print ('The current root folder is: "'+os.getcwd()+'"')
                print ('The following directory is used instead: "'+self.symbolic_path+'".')
            else:
                self.symbolic_path = symbolic_path
        
        # pointers list to avoid garbage collecting
101
102
        self.ptrs_to_user_fcts = dict()
        self.ptrs_to_symb_fcts = dict()
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
        # [0]: user_cons_hJ
        # [1]: user_cons_jdqd
        # [2]: user_dirdyn_init
        # [3]: user_dirdyn_loop
        # [4]: user_dirdyn_finish
        # [5]: mbs_cons_hJ
        # [6]: mbs_cons_jdqd
        # [6]: mbs_invdyna
        # [6]: mbs_dirdyna
        
        # Storing project function pointer
        self.user_cons_hJ = None
        self.user_cons_jdqd = None
        self.user_dirdyn_init = None
        self.user_dirdyn_loop = None
        self.user_dirdyn_finish = None
        self.mbs_cons_hJ = None
        self.mbs_cons_jdqd = None
        self.mbs_invdyna = None
        self.mbs_dirdyna = None
        
124
125
126
127
        # Storing Results
        self.results = MbsResult(self.mbs)
        self.mbs_get_results = False
        
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
        # Exposing some memory
        if __DEBUG__ : print( "DEBUG>>  Exposing MbsDirdyn fields")
        # Constraints
        self._h = self._Jac = self._jdqd = None
        if self.mbs.Ncons>0:
            self._h = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.mbs_aux.contents.h, (self.mbs.Ncons+1,))
            self._Jac = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.mbs_aux.contents.Jac[0], (self.mbs.Ncons+1,self.mbs.njoint+1))
            self._jdqd = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.mbs_aux.contents.jdqd, (self.mbs.Ncons+1,))
        self._huserc = self._Juserc = self._jdqduserc = None
        if self.mbs.Nuserc>0:
            self._huserc = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.mbs_aux.contents.huserc, (self.mbs.Nuserc+1,))
            self._Juserc = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.mbs_aux.contents.Juserc[0], (self.mbs.Nuserc+1,self.mbs.njoint+1))
            self._jdqduserc = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.mbs_aux.contents.jdqduserc, (self.mbs.Nuserc+1,))
        # Fields from equation of motion
        self._M = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.mbs_aux.contents.M[0], (self.mbs.njoint+1,self.mbs.njoint+1))
        self._c = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.mbs_aux.contents.c, (self.mbs.njoint+1,))
        self._F = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.mbs_aux.contents.F, (self.mbs.njoint+1,))
        
        # Loading user function
        if __DEBUG__ : print( "DEBUG>>  Loading user functions")
        self.__load_user_fct__(self.user_path)
        # Loading symbolic function
        if __DEBUG__ : print( "DEBUG>>  Loading symbolic functions")
        self.__load_symbolic_fct__(self.symbolic_path)
        

    def __str__(self):
        if __DEBUG__ : print( "DEBUG>>  start of __str")
        
        return "MbsDirdyn instance has nothing to be printed from C library!"
    
    def __load_user_fct__(self, user_path):
        """ 
            Load user function where some args depend on MbsDirdyn module.
            
            Load the user functions in which some of the arguments are  
            dependent of MbsDirdyn module instance. The functions will be 
            assigned to the MbsData instance when the 'run' functions is called 
            and unassigned at the end.
            
            The loader user functions are :
             - user_cons_hJ (from cons_hJ.py)
             - user_cons_jdqd (from cons_hJ.py)
             - user_dirdyn_init (from user_dirdyn.py)
             - user_dirdyn_loop (from user_dirdyn.py)
             - user_dirdyn_finish (from user_dirdyn.py)
        """
175
176
177
178
        
        template_path = os.path.join(__MODULE_DIR__,'../templates/user')
        
        
179
180
181
        # cons_hJ
        user_file = "cons_hJ.py"
        path = os.path.abspath(os.path.join(user_path, user_file))
182
        if not os.path.isfile(path):
183
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
184
185
186
187
            path = os.path.abspath(os.path.join(template_path, user_file))
        module = imp.load_source(user_file[:-3], path)
        self.user_cons_hJ = module.user_cons_hJ
        self.ptrs_to_user_fcts["user_cons_hJ"] = user_cons_hJ_wrap(lambda h,Jac,mbs,tsim : self.user_cons_hJ(self._huserc, self._Juserc, self.mbs, tsim))
188
189
190
191
        
        # cons_jdqd
        user_file = "cons_jdqd.py"
        path = os.path.abspath(os.path.join(user_path, user_file))
192
        if not os.path.isfile(path):
193
            if __DEBUG__ : print( "DEBUG>>  file '"+user_file+"' not found in folder '"+os.path.dirname(path))
194
195
196
            path = os.path.abspath(os.path.join(template_path, user_file))
        module = imp.load_source(user_file[:-3], path)
        self.user_cons_jdqd = module.user_cons_jdqd
197
        self.ptrs_to_user_fcts["user_cons_jdqd"] = user_cons_jdqd_wrap(lambda jdqd,mbs,tsim : self.user_cons_jdqd(self._jdqduserc, self.mbs))
198
199
200
201

        # user_dirdyn
        user_file = "user_dirdyn.py"
        path      = os.path.abspath(os.path.join(user_path, user_file))
202
        if not os.path.isfile(path):
203
            print ("file '"+user_file+"' not found in folder '"+os.path.dirname(path))
204
205
206
207
208
209
210
211
212
213
            path = os.path.abspath(os.path.join(template_path, user_file))
        else:
            if __DEBUG__ : print( "DEBUG>>  loading file '"+user_file+"' in folder '"+os.path.dirname(path))
        module = imp.load_source(user_file[:-3], path)
        self.user_dirdyn_init   = module.user_dirdyn_init
        self.user_dirdyn_loop   = module.user_dirdyn_loop
        self.user_dirdyn_finish = module.user_dirdyn_finish
        self.ptrs_to_user_fcts["user_dirdyn_init"] = user_dirdyn_init_wrap(lambda mbs, dd : self.mbs.user_dirdyn_init(self.mbs, self))
        self.ptrs_to_user_fcts["user_dirdyn_loop"] = user_dirdyn_loop_wrap(lambda mbs, dd : self.mbs.user_dirdyn_loop(self.mbs, self))
        self.ptrs_to_user_fcts["user_dirdyn_finish"] = user_dirdyn_finish_wrap(lambda mbs, dd : self.mbs.user_dirdyn_finish(self.mbs, self))
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        return
        
    def __load_symbolic_fct__(self, symbolic_path):
        """ 
            Load symbolic function where some args depend on MbsDirdyn module.
            
            Load the symb functions in which some of the arguments are  
            dependent of MbsDirdyn module instance. The functions will be 
            assigned to the MbsData instance when the 'run' functions is called 
            and unassigned at the end.
            
            The loader user functions are :
             - cons_hJ (from mbs_cons_hJ_MBSNAME.py)
             - cons_jdqd (from mbs_cons_jdqd_MBSNAME.py)
             - dirdyna (from mbs_dirdyna_MBSNAME.py)
             - invdyna (from mbs_invdyna_MBSNAME.py)
        """
        mbs_name = self.mbs.mbs_name
232
        template_path = os.path.join(__MODULE_DIR__,'../templates/symbolic')
233
234
235
        # mbs_cons_hJ
        symb_file = "mbs_cons_hJ_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symbolic_path, symb_file))
236
        if not os.path.isfile(path):
237
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
238
239
240
241
            symb_file = "mbs_cons_hJ_PRJ.py"
            path = os.path.abspath(os.path.join(template_path, symb_file))
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_cons_hJ = module.cons_hJ
242
        self.ptrs_to_symb_fcts["mbs_cons_hJ"] = mbs_cons_hJ_wrap(lambda h,Jac,mbs,tsim : self.mbs_cons_hJ(self._h,self._Jac, self.mbs))
243
        
244
245
246
247
        
        # mbs_cons_jdqd
        symb_file = "mbs_cons_jdqd_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symbolic_path, symb_file))
248
        if not os.path.isfile(path):
249
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
250
251
252
253
254
            symb_file = "mbs_cons_jdqd_PRJ.py"
            path = os.path.abspath(os.path.join(template_path, symb_file))
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_cons_jdqd = module.cons_jdqd
        self.ptrs_to_symb_fcts["mbs_cons_jdqd"] = mbs_cons_jdqd_wrap(lambda jdqd,mbs,tsim : self.mbs_cons_jdqd(self._jdqd, self.mbs))
255
256
257
258
        
        # invdyna
        symb_file = "mbs_invdyna_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symbolic_path, symb_file))
259
        if not os.path.isfile(path):
260
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
261
262
263
264
265
            symb_file = "mbs_invdyna_PRJ.py"
            path = os.path.abspath(os.path.join(template_path, symb_file))
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_invdyna = module.invdyna
        self.ptrs_to_symb_fcts["mbs_invdyna"] = mbs_invdyna_wrap(lambda Q,mbs,tsim : self.mbs_invdyna(self.mbs, tsim, None))
266
267
268
269
        
        # dirdyna
        symb_file = "mbs_dirdyna_"+mbs_name+".py"
        path = os.path.abspath(os.path.join(symbolic_path, symb_file))
270
        if not os.path.isfile(path):
271
            if __DEBUG__ : print( "DEBUG>>  file '"+symb_file+"' not found in folder '"+os.path.dirname(path))
272
273
274
275
276
277
            symb_file = "mbs_dirdyna_PRJ.py"
            path = os.path.abspath(os.path.join(template_path, symb_file))
        module = imp.load_source(symb_file[:-3], path)
        self.mbs_dirdyna = module.dirdyna
        self.ptrs_to_symb_fcts["mbs_dirdyna"] = mbs_dirdyna_wrap(lambda M,c,mbs,tsim : self.mbs_dirdyna(self._M, self._c, self.mbs, tsim))
         
278
279
        return
    
280
281
282
283
284
285
286
     # Callback function for function with advanced arguments
    def __callback_mbs_cons_hJ(self, fun, h, Jac):
        if __DEBUG__ : print( "DEBUG>>  callback_mbs_cons_hJ")
        __h = np.ctypeslib.as_array(h, (self.mbs.Ncons+1,))
        __Jac = np.ctypeslib.as_array(Jac[0], (self.mbs.Ncons+1,self.mbs.njoint+1))
        fun(__h,__Jac,self.mbs)
    
287
288
289
290
291
292
293
294
295
296
297
298
    def run(self):
        # [0]: user_cons_hJ
        # [1]: user_cons_jdqd
        # [2]: user_dirdyn_init
        # [3]: user_dirdyn_loop
        # [4]: user_dirdyn_finish
        # [5]: mbs_cons_hJ
        # [6]: mbs_cons_jdqd
        # [6]: mbs_invdyna
        # [6]: mbs_dirdyna
        # Assing required user functions
        self.mbs.user_cons_hJ = self.user_cons_hJ
299
        self.mbs.mbs_data_ptr.contents.user_cons_hJ = self.ptrs_to_user_fcts["user_cons_hJ"]
300
        self.mbs.user_cons_jdqd = self.user_cons_jdqd
301
        self.mbs.mbs_data_ptr.contents.user_cons_jdqd = self.ptrs_to_user_fcts["user_cons_jdqd"]
302
        self.mbs.user_dirdyn_init = self.user_dirdyn_init
303
        self.mbs.mbs_data_ptr.contents.user_dirdyn_init = self.ptrs_to_user_fcts["user_dirdyn_init"]
304
        self.mbs.user_dirdyn_loop = self.user_dirdyn_loop
305
        self.mbs.mbs_data_ptr.contents.user_dirdyn_loop = self.ptrs_to_user_fcts["user_dirdyn_loop"]
306
        self.mbs.user_dirdyn_finish = self.user_dirdyn_finish
307
        self.mbs.mbs_data_ptr.contents.user_dirdyn_finish = self.ptrs_to_user_fcts["user_dirdyn_finish"]
308
309
        # Assing required symbolic functions
        self.mbs.mbs_cons_hJ = self.mbs_cons_hJ
310
        self.mbs.mbs_data_ptr.contents.mbs_cons_hJ = self.ptrs_to_symb_fcts["mbs_cons_hJ"]
311
        self.mbs.mbs_cons_jdqd = self.mbs_cons_jdqd
312
        self.mbs.mbs_data_ptr.contents.mbs_cons_jdqd = self.ptrs_to_symb_fcts["mbs_cons_jdqd"]
313
        self.mbs.mbs_invdyna = self.mbs_invdyna
314
        self.mbs.mbs_data_ptr.contents.mbs_invdyna = self.ptrs_to_symb_fcts["mbs_invdyna"]
315
        self.mbs.mbs_dirdyna = self.mbs_dirdyna
316
        self.mbs.mbs_data_ptr.contents.mbs_dirdyna = self.ptrs_to_symb_fcts["mbs_dirdyna"]
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
        
        if not self.mbs_get_results:   
            libmodules.mbs_run_dirdyn(self.mbs_dirdyn_ptr, self.mbs.mbs_data_ptr)
        else:
            #save2file forced to 1 because if buffers don't have the complete results, results are loaded from files
            self.set_options(save2file = 1)
            libmodules.mbs_dirdyn_init(self.mbs_dirdyn_ptr, self.mbs.mbs_data_ptr)
            libmodules.mbs_dirdyn_loop(self.mbs_dirdyn_ptr, self.mbs.mbs_data_ptr)
       
            # Results (buffer) memory is kept BUT FILES WILL BE WRITTEN LATER
            if self.get_options("save2file"):
                #c_mbs_dirdyn_write_buffers(self.mbs_dirdyn_ptr)
                size1 = self.mbs_dirdyn_ptr.contents.buffers[0].contents.index
                size2 = self.mbs_dirdyn_ptr.contents.buffers[0].contents.nx+1
                
                # array are initialized to the time pointer so as to start index of joints at 1 (we have to ensure contiguity between t and x in buffers ! ! !)    
                self.results.q = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[0].contents.tx ,(size1, size2)))
                # get time array from the q buffer
                self.results.t = self.results.q[:,0]
                if not self.results.t[0] == self.get_options("t0"):
                    print("The beginning of the integration is not available in the buffer.\n The complete results have to be loaded from files.")
                    self.results.load_results_from_file()
                # get qd and qdd buffer
                self.results.qd = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[1].contents.tx ,(size1, size2)))
                self.results.qdd = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[2].contents.tx ,(size1, size2)))
                size2 = self.mbs_dirdyn_ptr.contents.buffers[3].contents.nx+1
                self.results.Qq = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[3].contents.tx ,(size1, size2)))
                
                if self.mbs.mbs_data_ptr.contents.Nux:
                    size2 = self.mbs_dirdyn_ptr.contents.buffers[4].contents.nx+1
                    self.results.ux = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[4].contents.tx ,(size1, size2)))
                    self.results.uxd = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[5].contents.tx ,(size1, size2)))
                    if self.mbs.mbs_data_ptr.contents.Nlink:
                        size2 = self.mbs_dirdyn_ptr.contents.buffers[6].contents.nx+1
                        self.results.Z = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[6].contents.tx ,(size1, size2)))
                        self.results.Zd = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[7].contents.tx ,(size1, size2)))
                        self.results.Fl = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[8].contents.tx ,(size1, size2)))
                else :
                     if self.mbs.mbs_data_ptr.contents.Nlink:
                        size2 = self.mbs_dirdyn_ptr.contents.buffers[4].contents.nx+1
                        self.results.Z = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[4].contents.tx ,(size1, size2)))
                        self.results.Zd = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[5].contents.tx ,(size1, size2)))
                        self.results.Fl = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.buffers[6].contents.tx ,(size1, size2)))
                    
                if self.mbs_dirdyn_ptr.contents.user_buffer.contents.nx:
                    size = self.mbs_dirdyn_ptr.contents.user_buffer.contents.index
                    nbOutput = self.mbs_dirdyn_ptr.contents.user_buffer.contents.nx
                    user_out = np.copy(np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.user_buffer.contents.X[0],(nbOutput, size)))
                    for i in np.arange(nbOutput):
                        name = self.mbs_dirdyn_ptr.contents.user_buffer.contents.names[i]
                        name = name.decode('utf-8')
                        self.results.outputs[name] = user_out[i,:]
            
            libmodules.mbs_dirdyn_finish(self.mbs_dirdyn_ptr, self.mbs.mbs_data_ptr)
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
        
        # Anassign user functions
        self.mbs.user_cons_hJ = None
        self.mbs.mbs_data_ptr.contents.user_cons_hJ = user_cons_hJ_wrap(lambda h,Jac,mbs,tsim : self.mbs.callback_undefined("user_cons_hJ"))
        self.mbs.user_cons_jdqd = None
        self.mbs.mbs_data_ptr.contents.user_cons_jdqd = user_cons_jdqd_wrap(lambda h,Jac,mbs,tsim : self.mbs.callback_undefined("user_cons_jdqd"))
        self.mbs.user_dirdyn_init = None
        self.mbs.mbs_data_ptr.contents.user_dirdyn_init = user_dirdyn_init_wrap(lambda mbs, dd : self.mbs.callback_undefined("user_dirdyn_init"))
        self.mbs.user_dirdyn_loop = None
        self.mbs.mbs_data_ptr.contents.user_dirdyn_loop = user_dirdyn_loop_wrap(lambda mbs, dd : self.mbs.callback_undefined("user_dirdyn_loop"))
        self.mbs.user_dirdyn_finish = None
        self.mbs.mbs_data_ptr.contents.user_dirdyn_finish = user_dirdyn_finish_wrap(lambda mbs, dd : self.mbs.callback_undefined("user_dirdyn_finish"))
        
        # Anassing required symbolic functions
        self.mbs.mbs_cons_hJ = None
        self.mbs.mbs_data_ptr.contents.mbs_cons_hJ = mbs_cons_hJ_wrap(lambda h,Jac,mbs,tsim : self.mbs.callback_undefined("mbs_cons_hJ"))
        self.mbs.mbs_cons_jdqd = None
        self.mbs.mbs_data_ptr.contents.mbs_cons_jdqd = mbs_cons_jdqd_wrap(lambda jdqd,mbs,tsim : self.mbs.callback_undefined("mbs_cons_jdqd"))
        self.mbs.mbs_invdyna = None
        self.mbs.mbs_data_ptr.contents.mbs_invdyna = mbs_invdyna_wrap(lambda Q,mbs,tsim : self.mbs.callback_undefined("mbs_invdyna"))
        self.mbs.mbs_dirdyna = None
        self.mbs.mbs_data_ptr.contents.mbs_dirdyna = mbs_dirdyna_wrap(lambda M,c,mbs,tsim : self.mbs.callback_undefined("mbs_dirdyna"))
    
395
    
396
397
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
    
    def set_options(self, **kwargs):
        """
        Set the specified options for Dirdyn module
        
        Parameters
        ----------
        
        t0 : float
            initial time of the simulation, default = 0.0
        tf : float
            final time of the simulation, default = 5.0
        dt0 : float
            initial value of the integration step size, default = 0.001
        save2file : int
            Determine whether results are written to files on disk (in resultsR folder):  
            1: results are saved
            0: results are not saved 
            default = 1
        resfilename : str
            The keyword used for determining the name of result files
        respath : str
            Path in which result file are saved.
            Default: the resultsR folder of the project
        animpath : str
            Path in which anim file is saved.
            Default: the animationR folder of the project
        save_anim : int
            1 to save the anim file
            0 otherwise (only valid if 'save2file' is set to 1)
            default = 1
        save_visu : int 
            1 to save the visualizazion file (as it appears in 'user_realtime_visu.c')
            0 otherwise (only valid if 'save2file' is set to 1)
            default = 0
        framerate : int
            number of frame per second for the .anim file
            default = 1000
        saveperiod : int
            The number of time steps between two buffer records
            default: 1 (every time step are recorded)
        max_save_user : int
            The maximal number of user variables saved
            default: 12
        buffersize : int 
            The number of time step that can be recorded in the buffer.
            Results are written to disk when the buffer is full.
            default: -1
            compute the buffer size for saving results only once at the end according to dt0, t0 and tf.
        realtime : int
            1 to activate to real-time features
            0 to deactivate them
            default = 0
        accelred : int
            1 to use accelred
            0 otherwise
            default = 0
        flag_compute_Qc : int
            choose to compute (or not) the Qc for driven variables
            For dirdyn only
            ==1 by default
            this allows to go faster
        compute_Qc : numpy.ndarray
            If options->flag_compute_Qc is set to 0, the vector allows to compute only the needed Qc
            For dirdyn only.
			Empty vector by default
            If compute_Qc = [njoint 1 0 0 1 0], we will compute Qc(1) and Qc(4) only.
			length by default to njoint+1, compute_Qc[0] = njoint
        integrator : str
            Set integrator to use, available value: "RK4", "Dopri5", "Rosenbrock","EulerEx", "Eulaire","EulerIm","Bader", "WMethods", "Custom"
            default = "RK4".
        verbose : int 
            1 to get print indications related to time adaptive integrator
            0 otherwise
            default = 1
        flag_stop_stiff : int 
            1 to stop integration if it become stiff
            0 (default value) otherwise
            default = 0
        flag_precise_dynamics : int
            = 1 to call the direct dynamics at the beginning of each time step of integration
            default = 1 
            Not calling it (flag = 0) will be faster to compute but will create small errors in the results
            Options related to waypoints: force integrator to stop at fixed time
        flag_waypoint : int
            1 to use waypoints
            0 otherwise
            default =0
        flag_solout_wp : int
            1 to call solout only at required waypoints (only if flag_waypoint activated)
            default = 0
        delta_t_wp : float
            time interval between two waypoints [s]
            default = 1.0e-3
        nmax : int
            maximal number of steps [-]
            default = 1e9
        toler : float 
            mixed error tolerances [-]
            default = 1.0e-3
        rtoler : float
            relative error tolerances [-]
            default = 1.0e-3
        atoler : float
            absolute error tolerances [-]
            default = 1.0e-6
        dt_max : float
            maximal time step [s]
            default = 1.0e-3
        n_freeze : int 
            number of time step when the jacobian is freezed (computed once at the start of the n_freeze time steps)
            default = 0
508
509
510
        mbs_get_results : int
            1 to save a copy of the results from the buffers
            default = 0
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
            
        """
        
        for key, value in kwargs.items():
            if key == "t0":
                self.mbs_dirdyn_ptr.contents.options.contents.t0 = value
            elif key == "tf":
                self.mbs_dirdyn_ptr.contents.options.contents.tf = value
            elif key == "dt0":
                self.mbs_dirdyn_ptr.contents.options.contents.dt0 = value
            elif key == "save2file":
                self.mbs_dirdyn_ptr.contents.options.contents.save2file = value
            elif key == "resfilename":
                self.mbs_dirdyn_ptr.contents.options.contents.resfilename = value.encode('utf-8')
            elif key == "respath":
                self.mbs_dirdyn_ptr.contents.options.contents.respath = value.encode('utf-8')
            elif key == "animpath":
                self.mbs_dirdyn_ptr.contents.options.contents.animpath = value.encode('utf-8')
            elif key == "save_anim":
                self.mbs_dirdyn_ptr.contents.options.contents.save_anim = value
            elif key == "save_visu":
                self.mbs_dirdyn_ptr.contents.options.contents.save_visu = value
            elif key == "framerate":
                self.mbs_dirdyn_ptr.contents.options.contents.framerate = value
            elif key == "saveperiod":
                self.mbs_dirdyn_ptr.contents.options.contents.saveperiod= value
            elif key == "max_save_user":
                self.mbs_dirdyn_ptr.contents.options.contents.max_save_user = value
            elif key == "buffersize":
                self.mbs_dirdyn_ptr.contents.options.contents.buffersize = value
            elif key == "realtime":
                self.mbs_dirdyn_ptr.contents.options.contents.realtime = value
            elif key == "accelred":
                self.mbs_dirdyn_ptr.contents.options.contents.accelred = value
            elif key == "flag_compute_Qc":
                self.mbs_dirdyn_ptr.contents.options.contents.flag_compute_Qc = value
            elif key == "compute_Qc":
                if (type(value) is np.ndarray) or (type(value) is list):
                    if  np.size(value) == self.mbs.mbs_data_ptr.contents.njoint + 1:
                        for i, val in enumerate(value[1:]):
                            self.mbs_dirdyn_ptr.contents.options.contents.compute_Qc[i+1] = val
                    else:
                        print(">>DIRDYN>> The size of compute_Qc is not consistent with njoint")
                else:
                    print(">>DIRDYN>> The specified value for compute_Qc is not a list or a np.array")
            elif key == "integrator":
                if (type(value) is int) and (value>=0 and value<=8):
                    self.mbs_dirdyn_ptr.contents.options.contents.integrator = value
                elif type(value) is str:
                    if value == "RK4":
                        self.mbs_dirdyn_ptr.contents.options.contents.integrator = 0
                    elif value == "Dopri5":
                        self.mbs_dirdyn_ptr.contents.options.contents.integrator = 1
                    elif value == "Rosenbrock":
                        self.mbs_dirdyn_ptr.contents.options.contents.integrator = 2
                    elif value == "EulerEx":
                        self.mbs_dirdyn_ptr.contents.options.contents.integrator = 3
                    elif value == "Eulaire":
                        self.mbs_dirdyn_ptr.contents.options.contents.integrator = 4
                    elif value == "EulerIm":
                        self.mbs_dirdyn_ptr.contents.options.contents.integrator = 5
                    elif value == "Bader":
                        self.mbs_dirdyn_ptr.contents.options.contents.integrator = 6
                    elif value == "WMethods":
                        self.mbs_dirdyn_ptr.contents.options.contents.integrator = 7
                    elif value == "Custom":
                        self.mbs_dirdyn_ptr.contents.options.contents.integrator = 8
                    else:
                        print(">>DIRDYN>>  " + value + " is not an integrator")
                else:
                    print(">>DIRDYN>>  " + value + " is not an integrator")
            elif key == "verbose":
                self.mbs_dirdyn_ptr.contents.options.contents.verbose = value
            elif key == "flag_stop_stiff":
                self.mbs_dirdyn_ptr.contents.options.contents.flag_stop_stiff = value
            elif key == "flag_precise_dynamics":
                self.mbs_dirdyn_ptr.contents.options.contents.flag_precise_dynamics = value
            elif key == "flag_waypoint":
                self.mbs_dirdyn_ptr.contents.options.contents.flag_waypoint = value
            elif key == "flag_solout_wp":
                self.mbs_dirdyn_ptr.contents.options.contents.flag_solout_wp= value
            elif key == "delta_t_wp":
                self.mbs_dirdyn_ptr.contents.options.contents.delta_t_wp = value
            elif key == "nmax":
                self.mbs_dirdyn_ptr.contents.options.contents.nmax = value
            elif key == "toler":
                self.mbs_dirdyn_ptr.contents.options.contents.toler = value
            elif key == "rtoler":
                self.mbs_dirdyn_ptr.contents.options.contents.rtoler = value
            elif key == "atoler":
                self.mbs_dirdyn_ptr.contents.options.contents.atoler = value
            elif key == "dt_max":
                self.mbs_dirdyn_ptr.contents.options.contents.dt_max = value
            elif key == "n_freeze":
                self.mbs_dirdyn_ptr.contents.options.contents.n_freeze = value
606
607
            elif key == "mbs_get_results":
                self.mbs_get_results = value
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
            else:
                print(">>DIRDYN>> The option "+key+ " is not defined in this module")
                
        
    def get_options(self, *args):
        """
        Get the specified options for Dirdyn module
        
        Parameters
        ----------
        
        The different options specifed in the documentation of set_options
        
        Returns
        -------
    
        The value of the different options specifed in the documentation of set_options
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
676
677
678
679
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
        
        """
        options = []
        for key in args:
            if key == "t0":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.t0)
            elif key == "tf":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.tf)
            elif key == "dt0":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.dt0)
            elif key == "save2file":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.save2file)
            elif key == "resfilename":
                options.append(ctypes.string_at(self.mbs_dirdyn_ptr.contents.options.contents.resfilename).decode("utf-8"))
            elif key == "respath":
                options.append(ctypes.string_at(self.mbs_dirdyn_ptr.contents.options.contents.respath).decode("utf-8"))
            elif key == "animpath":
                options.append(ctypes.string_at(self.mbs_dirdyn_ptr.contents.options.contents.animpath).decode("utf-8"))
            elif key == "save_anim":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.save_anim)
            elif key == "save_visu":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.save_visu)
            elif key == "framerate":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.framerate)
            elif key == "saveperiod":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.saveperiod)
            elif key == "max_save_user":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.max_save_user)
            elif key == "buffersize":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.buffersize)
            elif key == "realtime":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.realtime)
            elif key == "accelred":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.accelred)
            elif key == "flag_compute_Qc":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.flag_compute_Qc)
            elif key == "compute_Qc":
                compute_Qc_py = np.ctypeslib.as_array(self.mbs_dirdyn_ptr.contents.options.contents.compute_Qc, (self.mbs.mbs_data_ptr.contents.njoint+1,))
                options.append(compute_Qc_py)
            elif key == "integrator":
                if self.mbs_dirdyn_ptr.contents.options.contents.integrator == 0:
                    options.append("RK4")
                elif self.mbs_dirdyn_ptr.contents.options.contents.integrator == 1:
                    options.append("Dopri5")
                elif self.mbs_dirdyn_ptr.contents.options.contents.integrator == 2:
                    options.append("Rosenbrock")
                elif self.mbs_dirdyn_ptr.contents.options.contents.integrator == 3:
                    options.append("EulerEx")    
                elif self.mbs_dirdyn_ptr.contents.options.contents.integrator == 4:
                    options.append("Eulaire") 
                elif self.mbs_dirdyn_ptr.contents.options.contents.integrator == 5:
                    options.append("EulerIm")  
                elif self.mbs_dirdyn_ptr.contents.options.contents.integrator == 6:
                    options.append("Bader")
                elif self.mbs_dirdyn_ptr.contents.options.contents.integrator == 7:
                    options.append("WMethods")   
                elif self.mbs_dirdyn_ptr.contents.options.contents.integrator == 8:
                    options.append("Custom")   
            elif key == "verbose":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.verbose)
            elif key == "flag_stop_stiff":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.flag_stop_stiff)
            elif key == "flag_precise_dynamics":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.flag_precise_dynamics)
            elif key == "flag_waypoint":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.flag_waypoint)
            elif key == "flag_solout_wp":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.flag_solout_wp)
            elif key == "delta_t_wp":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.delta_t_wp)
            elif key == "nmax":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.nmax)
            elif key == "toler":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.toler)
            elif key == "rtoler":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.rtoler)
            elif key == "atoler":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.atoler)
            elif key == "dt_max":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.dt_max)
            elif key == "n_freeze":
                options.append(self.mbs_dirdyn_ptr.contents.options.contents.n_freeze)
708
709
            elif key == "mbs_get_results":
                options.append(self.mbs_get_results)
710
711
            else:
                print(">>DIRDYN>> The option "+key+ " is not defined in this module")
712
713
714
715
716
                
        if len(options) == 0:
            return
        if len(options) == 1:
            return options[0]
717
718
            
        return tuple(options)
719
    
720
                
721
722
723
724
725
726
727
728
729
730
731
732
733
    #==========================================================================
    # Defining properties
    #==========================================================================
    @property
    def mbs_filename(self):
        return self.mbs.mbs_filename
    
    @property
    def project_path(self):
        return self.mbs.project_path
    
    @property
    def mbs_name(self):
734
        return self.mbs.mbs_name
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
    
    
class MbsResult(object):
        
    def __init__(self,mbs):
        self.q=[]
        self.qd=[]
        self.qdd=[]
        self.Fl=[]
        self.Z=[]
        self.Zd=[]
        self.Qq=[]
        self.t=[]
        self.ux=[]
        self.uxd=[]
        self.outputs={}
        self.mbs=mbs
    
    def load_results_from_file(self, baseFileName=None, result_path=None):
        
        project_path = self.mbs.project_path
        if baseFileName == None:
            baseFileName = "dirdyn"
            
        
        if result_path == None:
            result_path = os.path.join(project_path, "ResultR")
        else : 
            result_path = os.path.join(project_path, result_path)
        # Error handeling
        if not os.path.isdir(result_path):
            if __DEBUG__ : print ('DEBUG>> The result directory does not exist: "'+ result_path+'"')
            
        # Generalized coordinates
        CurFile = baseFileName+'_q.res'
        path = os.path.abspath(os.path.join(result_path, CurFile))
        if (os.path.isfile(path) ):
            self.results.q = np.loadtxt(path)
            self.results.t = self.results.q[:,0]
        else:
            if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
        
        # Generalized velocities
        CurFile = baseFileName+'_qd.res'
        path = os.path.abspath(os.path.join(result_path, CurFile))
        if (os.path.isfile(path)):
            self.results.qd = np.loadtxt(path)
        else:
             if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
             
        # Generalized accelerations   
        CurFile = baseFileName+'_qdd.res'
        path = os.path.abspath(os.path.join(result_path, CurFile))
        if (os.path.isfile(path)):
            self.results.qdd = np.loadtxt(path)
        else:
             if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
             
          
        CurFile = baseFileName+'_Qq.res'
        path = os.path.abspath(os.path.join(result_path, CurFile))
        if (os.path.isfile(path)):
            self.results.Qq = np.loadtxt(path)
        else:
             if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
        
        # Generalized user state
        if self.mbs.mbs_data_ptr.contents.Nux:
            CurFile = baseFileName+'_ux.res'
            path = os.path.abspath(os.path.join(result_path, CurFile))
            if (os.path.isfile(path) ):
                self.results.ux = np.loadtxt(path)
            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)):
                self.results.uxd = np.loadtxt(path)
            else:
                if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
                
                
        if self.mbs.mbs_data_ptr.contents.Nlink: 
            CurFile = baseFileName+'_linkF.res'
            path = os.path.abspath(os.path.join(result_path, CurFile))
            if (os.path.isfile(path) ):
                self.results.Fl = np.loadtxt(path)
            else:
                if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
            
            CurFile = baseFileName+'_linkZ.res'
            path = os.path.abspath(os.path.join(result_path, CurFile))
            if (os.path.isfile(path)):
                self.results.Z = np.loadtxt(path)
            else:
                if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))
            
            CurFile = baseFileName+'_linkZd.res'
            path = os.path.abspath(os.path.join(result_path, CurFile))
            if (os.path.isfile(path)):
                self.results.Zd = np.loadtxt(path)
            else:
                if __DEBUG__ : print( "DEBUG>>  file '"+CurFile+"' not found in folder '"+os.path.dirname(path))