summaryrefslogtreecommitdiff
path: root/modules/xcos/macros/xcos_simulate.sci
blob: d29b1940fa18392f82d00d0d5ef7587aa47610f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
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
//
// Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
// Copyright (C) Scilab Enterprises - 2013 - Bruno JOFRET
// Copyright (C) 2009-2009 - DIGITEO - Bruno JOFRET
//
// This file must be used under the terms of the CeCILL.
// This source file is licensed as described in the file COPYING, which
// you should have received as part of this distribution.  The terms
// are also available at
// http://www.cecill.info/licences/Licence_CeCILL_V2.1-en.txt
//
//

function %cpr = xcos_simulate(scs_m, needcompile)

    // Load the block libs if not defined
    prot = funcprot();
    funcprot(0);
    if ~exists("scicos_diagram") then
        loadXcosLibs();
    end
    funcprot(prot);
    [modelica_libs, scicos_pal_libs, %scicos_with_grid, %scs_wgrid] = initial_scicos_tables();

    // Hook according to SEP066
    function [ok]=invoke_pre_simulate(fun, scs_m, needcompile)
        ok=%f;
        ierr=execstr("[continueSimulation]="+fun+"(scs_m, needcompile);", "errcatch");
        if ierr<>0 then
            disp(_("Error occurred in pre_xcos_simulate: Cancelling simulation."));
            [str,n,line,func]=lasterror();
            mprintf(" at line %d of function %s\n", line, func);
            return
        end
        if ~continueSimulation then
            return
        end
        ok=%t;

        // Force update on the parent in case of scoped modification
        scs_m=resume(scs_m);
    endfunction

    if isdef("pre_xcos_simulate") then
        if type(pre_xcos_simulate) == 15 then
            // If has a multiple implementation (on a list)
            for f=pre_xcos_simulate;
                ok=invoke_pre_simulate(f, scs_m, needcompile);
                if ~ok then
                    %cpr=[];
                    return;
                end
            end
        else
            // If has a unique implementation
            ok=invoke_pre_simulate("pre_xcos_simulate", scs_m, needcompile);
            if ~ok then
                %cpr=[];
                return;
            end
        end
    end

    //**---- prepare from and to workspace stuff ( "From workspace" block )
    scicos_workspace_init()


    //** extract tolerances from scs_m.props.tol
    tolerances = scs_m.props.tol ;
    //** extract solver type from tolerances
    solver = tolerances(6) ;
    //** initialize a "scicos_debug_gr" variable
    %scicos_debug_gr = %f;

    ////////////////////////////////////////////////////////////////
    // Add global environment variable so that scicos is not lost //
    ////////////////////////////////////////////////////////////////
    if needcompile == 4 then
        %state0     = list();
        needcompile = 4;
        curwin      = 1000;
        %cpr        = struct();
        %tcur       = 0;
        %cpr.state  = %state0;
        alreadyran = %f;
    else
        %state0 = %cpr.state;
        alreadyran = %f;
    end

    tf          = scs_m.props.tf;
    %zoom       = 1.4;
    Select      = [];

    //** extract tolerances from scs_m.props.tol
    tolerances = scs_m.props.tol ;
    //** extract solver type from tolerances
    solver = tolerances(6) ;

    // Propagate context through all blocks
    %scicos_context = struct();
    context = scs_m.props.context;
    //** context eval here
    [%scicos_context, ierr] = script2var(context, %scicos_context);

    // For backward compatibility for scifunc
    if ierr==0 then
        %mm = getfield(1,%scicos_context)
        for %mi=%mm(3:$)
            ierr = execstr(%mi+"=%scicos_context(%mi)","errcatch")
            if ierr<>0 then
                break; //** in case of error exit
            end
        end
    end
    // End of for backward compatibility for scifuncpagate context values

    [scs_m,%cpr,needcompile,ok] = do_eval(scs_m, %cpr, %scicos_context);
    if ~ok then
        msg = msprintf(gettext("%s: Error during block parameters evaluation.\n"), "Xcos");
        messagebox(msg, "Xcos", "error");
        error(msprintf(gettext("%s: Error during block parameters evaluation.\n"), "xcos_simulate"));
    end

    //** update parameters or compilation results
    [%cpr,%state0_n,needcompile,alreadyran,ok] = do_update(%cpr,%state0,needcompile)
    if ~ok then
        error(msprintf(gettext("%s: Error during block parameters update.\n"), "xcos_simulate"));
    end

    //** if alreadyran then set the var choice
    if alreadyran then
        choix = ["Continue";"Restart";"End"]
    else
        choix = [] ;
    end

    issequal = %t;
    //** initial state has been changed
    if ~isequal(%state0_n,%state0) then
        issequal = %f
    else
        //** test typeof outtb element
        for i=1:lstsize(%state0_n.outtb)
            if typeof(%state0_n.outtb(i))<>typeof(%state0.outtb(i))
                issequal = %f
                break
            end
        end
        //** test typeof oz element
        for i=1:lstsize(%state0_n.oz)
            if typeof(%state0_n.oz(i))<>typeof(%state0.oz(i))
                issequal = %f
                break
            end
        end
    end

    //** if state have changed
    //** finish the simulation via do_terminate()
    if ~issequal then
        %state0 = %state0_n
        [alreadyran,%cpr] = do_terminate()
        choix = []
    end

    //** switch to appropriate solver
    if %cpr.sim.xptr($)-1<size(%cpr.state.x,"*") & solver<100 then
        warning(["Diagram has been compiled for implicit solver"
        "switching to implicit Solver"])
        solver = 100 ; //** Magic number
        tolerances(6) = solver ; //** save Magic number solver type
    elseif (%cpr.sim.xptr($)-1==size(%cpr.state.x,"*")) & ((or (solver == [100 101 102])) & size(%cpr.state.x,"*")<>0) then
        message(["Diagram has been compiled for explicit solver"
        "switching to explicit Solver"])
        solver = 0 ; //** Magic number
        tolerances(6) = solver ; //** save Magic number solver type
    end

    //** ask user what to do
    if choix<>[] then
        //** open dialog box
        to_do = choose(choix,"What do you want to do")

        //** if cancel then exit
        if to_do==0 then
            ok = %f
            return
        end

        select choix(to_do)

        case "Continue" then
            needstart = %f ;
            state     = %cpr.state ;

        case "Restart" then
            needstart = %t ;
            state     = %state0 ;

        case "End" then
            state     = %cpr.state ;
            needstart = %t ;
            tf        = scs_m.props.tf;

            //Alan: Cannot call do_terminate() here ?
            //Answer: No, because do_terminate() doesn't
            //          return control to the user

            //** run scicosim via 'finish' flag
            ierr = execstr("[state,t]=scicosim(%cpr.state,%tcur,tf,%cpr.sim,"+..
            "''finish'',tolerances)","errcatch")

            %cpr.state = state
            alreadyran = %f

            //** error case
            if ierr<>0 then
                str_err = split_lasterror(lasterror());
                kfun    = curblock()
                corinv  = %cpr.corinv

                if kfun<>0 & length(corinv) > kfun then //** block error
                    path = corinv(kfun)
                    //** get error cmd for the block
                    get_errorcmd(path,"End problem.",str_err);

                else //** simulator error
                    message(["End problem:";str_err])
                    //scf(curwin);
                end
                ok = %f
            end

            return
        end

    else //** Normal first start simulation

        needstart = %t
        state     = %state0

    end

    //gh_win = gcf();

    //** scicos initialization
    if needstart then
        //** if the simulation has already run
        //** and is not finished then call do_terminate
        if alreadyran then
            [alreadyran,%cpr] = do_terminate()
            alreadyran = %f ;
        end
        //** set initial values for a new simulation
        %tcur      = 0
        %cpr.state = %state0
        tf         = scs_m.props.tf;
        if tf*tolerances==[] then
            message(["Simulation parameters not set";"use setup button"]);
            return;
        end

        //** Run the normal first start simulation here

        //** run scicosim via 'start' flag
        ierr = execstr("[state,t]=scicosim(%cpr.state,%tcur,tf,%cpr.sim,"+..
        "''start'',tolerances)","errcatch")

        %cpr.state = state ; //** save the state
        //** error case
        if ierr<>0 then
            str_err=split_lasterror(lasterror());
            kfun=curblock()
            corinv=%cpr.corinv

            if kfun<>0 & length(corinv) > kfun then  //** block error
                path=corinv(kfun)
                //** get error cmd for the block
                disp(str_err);
                get_errorcmd(path,gettext("Initialisation problem"),str_err);


            else //** simulator error
                message(["Initialisation problem:";str_err])
                //scf(curwin);
            end

            ok = %f;
            //xset('window',curwin)
            return
        end
        //scf(gh_win);
        //xset('window',win);
    end

    //** scicos simulation
    tf = scs_m.props.tf

    // Inform Xcos the simulator is going to run
    xcosSimulationStarted();

    //** run scicosim via 'start' flag
    ierr = execstr("[state,t]=scicosim(%cpr.state,%tcur,tf,%cpr.sim,"+..
    "''run'',tolerances)","errcatch")

    %cpr.state = state

    //** no error
    if ierr==0 then
        alreadyran = %t;
        //** we are at the end of the simulation
        //** finish the simulation via do_terminate()
        if tf-t<tolerances(3) then
            //disp('fin');
            //Alan : removing do_terminate() here because it
            //       doesn't return control
            //[alreadyran,%cpr]=do_terminate()
            needstart  = %t;
            alreadyran = %f;
            //** run scicosim via 'finish' flag
            ierr = execstr("[state,t]=scicosim(%cpr.state,tf,tf,%cpr.sim,"+..
            "''finish'',tolerances)","errcatch")

            %cpr.state = state;

            //** error case
            if ierr<>0 then
                str_err = split_lasterror(lasterror());
                kfun   = curblock()
                corinv = %cpr.corinv

                if kfun<>0 & length(corinv) > kfun then //** block error
                    path = corinv(kfun)
                    //** get error cmd for the block
                    get_errorcmd(path,gettext("End problem"),str_err);
                else //** simulator error
                    message(["End problem:";str_err])
                    //scf(curwin);
                end
            end
        else
            %tcur = t;
        end
        //** error case
    else
        str_err = split_lasterror(lasterror());

        alreadyran = %f;
        kfun       = curblock();
        corinv     = %cpr.corinv;
        if kfun<>0 & length(corinv) > kfun then //** block error
            path = corinv(kfun);
            //** get error cmd for the block
            execstr(get_errorcmd(path,gettext("Simulation problem"),str_err));
        else //** simulator error
            message(["Simulation problem:";str_err])
            //scf(curwin);
        end
        ok = %f;
    end

    // Restore saved variables in Scilab environment ("To workspace" block)

    // First step: Search the %cpr tree for TOWS_c blocks, and extract the variable names.
    path = %cpr.sim;
    Names = [];
    buff_sizes = [];
    increment = 1;
    for i=1:size(path.funs)
        increment2 = path.ipptr(i+1);
        if (increment2 - increment <> 0) then   // ipar has at least a few elements
            space = increment2 - increment;     // The number of elements that the current block pushed into ipar
            if (path.funs(i) == "tows_c") then  // Found a Tow_workspace block
                varNameLen = space - 2;         // Space minus 'buffer_size' and 'var length' ipar elements
                varNameCode = path.ipar(increment+2:increment+2+varNameLen-1);  // varName is stored in Scilab code
                varName = ascii(varNameCode);
                Names = [Names varName];        // Append varName in Names
                buff_size  = path.ipar(increment);  // Retrieve buffer size
                buff_sizes = [buff_sizes buff_size];
            end
            increment = increment2;
        end
    end
    // At the end, Names contains the string names of the variables and buff_sizes the respective buffer sizes

    // Second step: Link the variable names to their values vectors,
    //and call '[names(1), names(2), ...] = resume(names(1), names(2), ...)' to save the variable into Scilab
    if ~isempty(Names) then
        for i=1:size(Names, "c")
            execstr("NamesIval  = "+Names(i)+"_val;");
            execstr("NamesIvalt = "+Names(i)+"_valt;");
            // If input is a matrix, use function matrix() to reshape the saved values
            // Check condition using time vector, if we have more values than time stamps, split it
            if (size(NamesIval, "r") > size(NamesIvalt, "r")) then
                nRows  = size(NamesIvalt, "r");
                nCols  = size(NamesIval, "c");
                nCols2 = size(NamesIval, "r") / nRows;
                NamesIval = matrix(NamesIval, nCols, nCols2, nRows);
            end
            ierr = execstr(Names(i)+" = struct(''values'', NamesIval, ''time'', NamesIvalt)", "errcatch");
            if ierr <> 0 then
                str_err = split_lasterror(lasterror());
                message(["Simulation problem" ; "Unable to resume To Workspace Variable {"+Names(i)+"}:" ; str_err]);
                break;
            end
            if i == 1 then
                Resume_line_args = Names(1);
            else
                Resume_line_args = Resume_line_args + ", " + Names(i);  // Concatenate the variable names up to the last one
            end
        end
        Resume_line = "[" + Resume_line_args + "] = resume(" + Resume_line_args + ");";  // Build the message
        // Will execute Resume_line at the end of the function, to run the following Hook instructions
    end

    // Hook according to SEP066
    function ok=invoke_post_simulate(fun, %cpr, scs_m, needcompile)
        ok=%f;
        ierr=execstr(fun+"(%cpr, scs_m, needcompile);", "errcatch");
        if ierr<>0 then
            disp(_("Error in post_xcos_simulate: ending simulation."))
            return
        end
        ok=%t
        // Force update on the parent in case of scoped modification
        scs_m=resume(scs_m);
    endfunction

    if isdef("post_xcos_simulate") then
        if type(post_xcos_simulate) == 15 then
            // If has a multiple implementation (on a list)
            for f=post_xcos_simulate;
                ok=invoke_post_simulate(f, %cpr, scs_m, needcompile);
                if ~ok then
                    %cpr=[];
                    return;
                end
            end
        else
            // If has a unique implementation
            ok=invoke_post_simulate("post_xcos_simulate", %cpr, scs_m, needcompile);
            if ~ok then
                %cpr=[];
                return;
            end
        end
    end

    // Executing the resume() function at the end, because it does not return control
    if ~isempty(Names) then
        execstr(Resume_line);
    end

endfunction