-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsympy_solver.cpp
2125 lines (2037 loc) · 75.8 KB
/
sympy_solver.cpp
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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*************************************************************************
* Copyright (C) 2018-2022 Blue Brain Project
*
* This file is part of NMODL distributed under the terms of the GNU
* Lesser General Public License. See top-level LICENSE file for details.
*************************************************************************/
#include <catch2/catch.hpp>
#include "ast/program.hpp"
#include "parser/nmodl_driver.hpp"
#include "test/unit/utils/test_utils.hpp"
#include "visitors/checkparent_visitor.hpp"
#include "visitors/constant_folder_visitor.hpp"
#include "visitors/loop_unroll_visitor.hpp"
#include "visitors/nmodl_visitor.hpp"
#include "visitors/sympy_solver_visitor.hpp"
#include "visitors/symtab_visitor.hpp"
using namespace nmodl;
using namespace visitor;
using namespace test;
using namespace test_utils;
using ast::AstNodeType;
using nmodl::parser::NmodlDriver;
//=============================================================================
// SympySolver visitor tests
//=============================================================================
std::vector<std::string> run_sympy_solver_visitor(
const std::string& text,
bool pade = false,
bool cse = false,
AstNodeType ret_nodetype = AstNodeType::DIFF_EQ_EXPRESSION) {
std::vector<std::string> results;
// construct AST from text
NmodlDriver driver;
const auto& ast = driver.parse_string(text);
// construct symbol table from AST
SymtabVisitor().visit_program(*ast);
// unroll loops and fold constants
ConstantFolderVisitor().visit_program(*ast);
LoopUnrollVisitor().visit_program(*ast);
ConstantFolderVisitor().visit_program(*ast);
SymtabVisitor().visit_program(*ast);
// run SympySolver on AST
SympySolverVisitor(pade, cse).visit_program(*ast);
// check that, after visitor rearrangement, parents are still up-to-date
CheckParentVisitor().check_ast(*ast);
// run lookup visitor to extract results from AST
for (const auto& eq: collect_nodes(*ast, {ret_nodetype})) {
results.push_back(to_nmodl(eq));
}
return results;
}
// check if in a list of vars (like LOCAL) there are duplicates
bool is_unique_vars(std::string result) {
result.erase(std::remove(result.begin(), result.end(), ','), result.end());
std::stringstream ss(result);
std::string token;
std::unordered_set<std::string> old_vars;
while (getline(ss, token, ' ')) {
if (!old_vars.insert(token).second) {
return false;
}
}
return true;
}
/**
* \brief Compare nmodl blocks that contain systems of equations (i.e. derivative, linear, etc.)
*
* This is basically and advanced string == string comparison where we detect the (various) systems
* of equations and check if they are equivalent. Implemented mostly in python since we need a call
* to sympy to simplify the equations.
*
* - compare_systems_of_eq The core of the code. \p result_dict and \p expected_dict are
* dictionaries that represent the systems of equations in this way:
*
* a = b*x + c -> result_dict['a'] = 'b*x + c'
*
* where the variable \p a become a key \p k of the dictionary.
*
* In there we go over all the equations in \p result_dict and \p expected_dict and check that
* result_dict[k] - expected_dict[k] simplifies to 0.
*
* - sanitize is to transform the equations in something treatable by sympy (i.e. pow(dt, 3) ->
* dt**3
* - reduce back-substitution of the temporary variables
*
* \p require_fail requires that the equations are different. Used only for unit-test this function
*
* \warning do not use this method when there are tmp variables not in the form: tmp_<number>
*/
void compare_blocks(const std::string& result,
const std::string& expected,
const bool require_fail = false) {
using namespace pybind11::literals;
auto locals =
pybind11::dict("result"_a = result, "expected"_a = expected, "is_equal"_a = false);
pybind11::exec(R"(
# Comments are in the doxygen for better highlighting
def compare_blocks(result, expected):
def sanitize(s):
import re
d = {'\[(\d+)\]':'_\\1', 'pow\((\w+), ?(\d+)\)':'\\1**\\2', 'beta': 'beta_var', 'gamma': 'gamma_var'}
out = s
for key, val in d.items():
out = re.sub(key, val, out)
return out
def compare_systems_of_eq(result_dict, expected_dict):
from sympy.parsing.sympy_parser import parse_expr
try:
for k, v in result_dict.items():
if parse_expr(f'simplify(({v})-({expected_dict[k]}))'):
return False
except KeyError:
return False
result_dict.clear()
expected_dict.clear()
return True
def reduce(s):
max_tmp = -1
d = {}
sout = ""
# split of sout and a dict with the tmp variables
for line in s.split('\n'):
line_split = line.lstrip().split('=')
if len(line_split) == 2 and line_split[0].startswith('tmp_'):
# back-substitution of tmp variables in tmp variables
tmp_var = line_split[0].strip()
if tmp_var in d:
continue
max_tmp = max(max_tmp, int(tmp_var[4:]))
for k, v in d.items():
line_split[1] = line_split[1].replace(k, f'({v})')
d[tmp_var] = line_split[1]
elif 'LOCAL' in line:
sout += line.split('tmp_0')[0] + '\n'
else:
sout += line + '\n'
# Back-substitution of the tmps
# so that we do not replace tmp_11 with (tmp_1)1
for j in range(max_tmp, -1, -1):
k = f'tmp_{j}'
sout = sout.replace(k, f'({d[k]})')
return sout
result = reduce(sanitize(result)).split('\n')
expected = reduce(sanitize(expected)).split('\n')
if len(result) != len(expected):
return False
result_dict = {}
expected_dict = {}
for token1, token2 in zip(result, expected):
if token1 == token2:
if not compare_systems_of_eq(result_dict, expected_dict):
return False
continue
eq1 = token1.split('=')
eq2 = token2.split('=')
if len(eq1) == 2 and len(eq2) == 2:
result_dict[eq1[0]] = eq1[1]
expected_dict[eq2[0]] = eq2[1]
continue
return False
return compare_systems_of_eq(result_dict, expected_dict)
is_equal = compare_blocks(result, expected))",
pybind11::globals(),
locals);
// Error log
if (require_fail == locals["is_equal"].cast<bool>()) {
if (require_fail) {
REQUIRE(result != expected);
} else {
REQUIRE(result == expected);
}
} else { // so that we signal to ctest that an assert was performed
REQUIRE(true);
}
}
void run_sympy_visitor_passes(ast::Program& node) {
// construct symbol table from AST
SymtabVisitor v_symtab;
v_symtab.visit_program(node);
// run SympySolver on AST several times
SympySolverVisitor v_sympy1;
v_sympy1.visit_program(node);
v_sympy1.visit_program(node);
// also use a second instance of SympySolver
SympySolverVisitor v_sympy2;
v_sympy2.visit_program(node);
v_sympy1.visit_program(node);
v_sympy2.visit_program(node);
}
std::string ast_to_string(ast::Program& node) {
std::stringstream stream;
NmodlPrintVisitor(stream).visit_program(node);
return stream.str();
}
SCENARIO("Check compare_blocks in sympy unit tests", "[visitor][sympy]") {
GIVEN("Empty strings") {
THEN("Strings are equal") {
compare_blocks("", "");
}
}
GIVEN("Equivalent equation") {
THEN("Strings are equal") {
compare_blocks("a = 3*b + c", "a = 2*b + b + c");
}
}
GIVEN("Equivalent systems of equations") {
std::string result = R"(
x = 3*b + c
y = 2*a + b)";
std::string expected = R"(
x = b+2*b + c
y = 2*a + 2*b-b)";
THEN("Systems of equations are equal") {
compare_blocks(result, expected);
}
}
GIVEN("Equivalent systems of equations with brackets") {
std::string result = R"(
DERIVATIVE {
A[0] = 3*b + c
y = pow(a, 3) + b
})";
std::string expected = R"(
DERIVATIVE {
tmp_0 = a + c
tmp_1 = tmp_0 - a
A[0] = b+2*b + tmp_1
y = pow(a, 2)*a + 2*b-b
})";
THEN("Blocks are equal") {
compare_blocks(result, expected);
}
}
GIVEN("Different systems of equations (additional space)") {
std::string result = R"(
DERIVATIVE {
x = 3*b + c
y = 2*a + b
})";
std::string expected = R"(
DERIVATIVE {
x = b+2*b + c
y = 2*a + 2*b-b
})";
THEN("Blocks are different") {
compare_blocks(result, expected, true);
}
}
GIVEN("Different systems of equations") {
std::string result = R"(
DERIVATIVE {
tmp_0 = a - c
tmp_1 = tmp_0 - a
x = 3*b + tmp_1
y = 2*a + b
})";
std::string expected = R"(
DERIVATIVE {
x = b+2*b + c
y = 2*a + 2*b-b
})";
THEN("Blocks are different") {
compare_blocks(result, expected, true);
}
}
}
SCENARIO("Check local vars name-clash prevention", "[visitor][sympy]") {
GIVEN("LOCAL tmp") {
std::string nmodl_text = R"(
STATE {
x y
}
BREAKPOINT {
SOLVE states METHOD sparse
}
DERIVATIVE states {
LOCAL tmp, b
x' = tmp + b
y' = tmp + b
})";
THEN("There are no duplicate vars in LOCAL") {
auto result =
run_sympy_solver_visitor(nmodl_text, true, true, AstNodeType::LOCAL_LIST_STATEMENT);
REQUIRE(!result.empty());
REQUIRE(is_unique_vars(result[0]));
}
}
GIVEN("LOCAL tmp_0") {
std::string nmodl_text = R"(
STATE {
x y
}
BREAKPOINT {
SOLVE states METHOD sparse
}
DERIVATIVE states {
LOCAL tmp_0, b
x' = tmp_0 + b
y' = tmp_0 + b
})";
THEN("There are no duplicate vars in LOCAL") {
auto result =
run_sympy_solver_visitor(nmodl_text, true, true, AstNodeType::LOCAL_LIST_STATEMENT);
REQUIRE(!result.empty());
REQUIRE(is_unique_vars(result[0]));
}
}
}
SCENARIO("Solve ODEs with cnexp or euler method using SympySolverVisitor",
"[visitor][sympy][cnexp][euler]") {
GIVEN("Derivative block without ODE, solver method cnexp") {
std::string nmodl_text = R"(
BREAKPOINT {
SOLVE states METHOD cnexp
}
DERIVATIVE states {
m = m + h
}
)";
THEN("No ODEs found - do nothing") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.empty());
}
}
GIVEN("Derivative block with ODES, solver method is euler") {
std::string nmodl_text = R"(
BREAKPOINT {
SOLVE states METHOD euler
}
DERIVATIVE states {
m' = (mInf-m)/mTau
h' = (hInf-h)/hTau
z = a*b + c
}
)";
THEN("Construct forwards Euler solutions") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 2);
REQUIRE(result[0] == "m = (-dt*(m-mInf)+m*mTau)/mTau");
REQUIRE(result[1] == "h = (-dt*(h-hInf)+h*hTau)/hTau");
}
}
GIVEN("Derivative block with calling external functions passes sympy") {
std::string nmodl_text = R"(
BREAKPOINT {
SOLVE states METHOD euler
}
DERIVATIVE states {
m' = sawtooth(m)
n' = sin(n)
p' = my_user_func(p)
}
)";
THEN("Construct forward Euler interpreting external functions as symbols") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 3);
REQUIRE(result[0] == "m = dt*sawtooth(m)+m");
REQUIRE(result[1] == "n = dt*sin(n)+n");
REQUIRE(result[2] == "p = dt*my_user_func(p)+p");
}
}
GIVEN("Derivative block with ODE, 1 state var in array, solver method euler") {
std::string nmodl_text = R"(
STATE {
m[1]
}
BREAKPOINT {
SOLVE states METHOD euler
}
DERIVATIVE states {
m'[0] = (mInf-m[0])/mTau
}
)";
THEN("Construct forwards Euler solutions") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 1);
REQUIRE(result[0] == "m[0] = (dt*(mInf-m[0])+mTau*m[0])/mTau");
}
}
GIVEN("Derivative block with ODE, 1 state var in array, solver method cnexp") {
std::string nmodl_text = R"(
STATE {
m[1]
}
BREAKPOINT {
SOLVE states METHOD cnexp
}
DERIVATIVE states {
m'[0] = (mInf-m[0])/mTau
}
)";
THEN("Construct forwards Euler solutions") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 1);
REQUIRE(result[0] == "m[0] = mInf-(mInf-m[0])*exp(-dt/mTau)");
}
}
GIVEN("Derivative block with linear ODES, solver method cnexp") {
std::string nmodl_text = R"(
BREAKPOINT {
SOLVE states METHOD cnexp
}
DERIVATIVE states {
m' = (mInf-m)/mTau
z = a*b + c
h' = hInf/hTau - h/hTau
}
)";
THEN("Integrate equations analytically") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 2);
REQUIRE(result[0] == "m = mInf-(-m+mInf)*exp(-dt/mTau)");
REQUIRE(result[1] == "h = hInf-(-h+hInf)*exp(-dt/hTau)");
}
}
GIVEN("Derivative block including non-linear but solvable ODES, solver method cnexp") {
std::string nmodl_text = R"(
BREAKPOINT {
SOLVE states METHOD cnexp
}
DERIVATIVE states {
m' = (mInf-m)/mTau
h' = c2 * h*h
}
)";
THEN("Integrate equations analytically") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 2);
REQUIRE(result[0] == "m = mInf-(-m+mInf)*exp(-dt/mTau)");
REQUIRE(result[1] == "h = -h/(c2*dt*h-1.0)");
}
}
GIVEN("Derivative block including array of 2 state vars, solver method cnexp") {
std::string nmodl_text = R"(
BREAKPOINT {
SOLVE states METHOD cnexp
}
STATE {
X[2]
}
DERIVATIVE states {
X'[0] = (mInf-X[0])/mTau
X'[1] = c2 * X[1]*X[1]
}
)";
THEN("Integrate equations analytically") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 2);
REQUIRE(result[0] == "X[0] = mInf-(mInf-X[0])*exp(-dt/mTau)");
REQUIRE(result[1] == "X[1] = -X[1]/(c2*dt*X[1]-1.0)");
}
}
GIVEN("Derivative block including loop over array vars, solver method cnexp") {
std::string nmodl_text = R"(
DEFINE N 3
BREAKPOINT {
SOLVE states METHOD cnexp
}
ASSIGNED {
mTau[N]
}
STATE {
X[N]
}
DERIVATIVE states {
FROM i=0 TO N-1 {
X'[i] = (mInf-X[i])/mTau[i]
}
}
)";
THEN("Integrate equations analytically") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 3);
REQUIRE(result[0] == "X[0] = mInf-(mInf-X[0])*exp(-dt/mTau[0])");
REQUIRE(result[1] == "X[1] = mInf-(mInf-X[1])*exp(-dt/mTau[1])");
REQUIRE(result[2] == "X[2] = mInf-(mInf-X[2])*exp(-dt/mTau[2])");
}
}
GIVEN("Derivative block including loop over array vars, solver method euler") {
std::string nmodl_text = R"(
DEFINE N 3
BREAKPOINT {
SOLVE states METHOD euler
}
ASSIGNED {
mTau[N]
}
STATE {
X[N]
}
DERIVATIVE states {
FROM i=0 TO N-1 {
X'[i] = (mInf-X[i])/mTau[i]
}
}
)";
THEN("Integrate equations analytically") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 3);
REQUIRE(result[0] == "X[0] = (dt*(mInf-X[0])+X[0]*mTau[0])/mTau[0]");
REQUIRE(result[1] == "X[1] = (dt*(mInf-X[1])+X[1]*mTau[1])/mTau[1]");
REQUIRE(result[2] == "X[2] = (dt*(mInf-X[2])+X[2]*mTau[2])/mTau[2]");
}
}
GIVEN("Derivative block including ODES that can't currently be solved, solver method cnexp") {
std::string nmodl_text = R"(
BREAKPOINT {
SOLVE states METHOD cnexp
}
DERIVATIVE states {
z' = a/z + b/z/z
h' = c2 * h*h
x' = a
y' = c3 * y*y*y
}
)";
THEN("Integrate equations analytically where possible, otherwise leave untouched") {
auto result = run_sympy_solver_visitor(nmodl_text);
REQUIRE(result.size() == 4);
/// sympy 1.9 able to solve ode but not older versions
REQUIRE((result[0] == "z' = a/z+b/z/z" ||
result[0] ==
"z = (0.5*pow(a, 2)*pow(z, 2)-a*b*z+pow(b, 2)*log(a*z+b))/pow(a, 3)"));
REQUIRE(result[1] == "h = -h/(c2*dt*h-1.0)");
REQUIRE(result[2] == "x = a*dt+x");
/// sympy 1.4 able to solve ode but not older versions
REQUIRE((result[3] == "y' = c3*y*y*y" ||
result[3] == "y = sqrt(-pow(y, 2)/(2.0*c3*dt*pow(y, 2)-1.0))"));
}
}
GIVEN("Derivative block with cnexp solver method, AST after SympySolver pass") {
std::string nmodl_text = R"(
BREAKPOINT {
SOLVE states METHOD cnexp
}
DERIVATIVE states {
m' = (mInf-m)/mTau
}
)";
// construct AST from text
NmodlDriver driver;
auto ast = driver.parse_string(nmodl_text);
// construct symbol table from AST
SymtabVisitor().visit_program(*ast);
// run SympySolver on AST
SympySolverVisitor().visit_program(*ast);
std::string AST_string = ast_to_string(*ast);
THEN("More SympySolver passes do nothing to the AST and don't throw") {
REQUIRE_NOTHROW(run_sympy_visitor_passes(*ast));
REQUIRE(AST_string == ast_to_string(*ast));
}
}
}
SCENARIO("Solve ODEs with derivimplicit method using SympySolverVisitor",
"[visitor][sympy][derivimplicit]") {
GIVEN("Derivative block with derivimplicit solver method and conditional block") {
std::string nmodl_text = R"(
STATE {
m
}
BREAKPOINT {
SOLVE states METHOD derivimplicit
}
DERIVATIVE states {
IF (mInf == 1) {
mInf = mInf+1
}
m' = (mInf-m)/mTau
}
)";
std::string expected_result = R"(
DERIVATIVE states {
EIGEN_NEWTON_SOLVE[1]{
LOCAL old_m
}{
IF (mInf == 1) {
mInf = mInf+1
}
old_m = m
}{
nmodl_eigen_x[0] = m
}{
nmodl_eigen_f[0] = (-nmodl_eigen_x[0]*dt+dt*mInf+mTau*(-nmodl_eigen_x[0]+old_m))/mTau
nmodl_eigen_j[0] = -(dt+mTau)/mTau
}{
m = nmodl_eigen_x[0]
}{
}
})";
THEN("SympySolver correctly inserts ode to block") {
CAPTURE(nmodl_text);
auto result =
run_sympy_solver_visitor(nmodl_text, false, false, AstNodeType::DERIVATIVE_BLOCK);
compare_blocks(result[0], reindent_text(expected_result));
}
}
GIVEN("Derivative block, sparse, print in order") {
std::string nmodl_text = R"(
STATE {
x y
}
BREAKPOINT {
SOLVE states METHOD sparse
}
DERIVATIVE states {
LOCAL a, b
y' = a
x' = b
})";
std::string expected_result = R"(
DERIVATIVE states {
EIGEN_NEWTON_SOLVE[2]{
LOCAL a, b, old_y, old_x
}{
old_y = y
old_x = x
}{
nmodl_eigen_x[0] = x
nmodl_eigen_x[1] = y
}{
nmodl_eigen_f[0] = -nmodl_eigen_x[1]+a*dt+old_y
nmodl_eigen_j[0] = 0
nmodl_eigen_j[2] = -1.0
nmodl_eigen_f[1] = -nmodl_eigen_x[0]+b*dt+old_x
nmodl_eigen_j[1] = -1.0
nmodl_eigen_j[3] = 0
}{
x = nmodl_eigen_x[0]
y = nmodl_eigen_x[1]
}{
}
})";
THEN("Construct & solve linear system for backwards Euler") {
auto result =
run_sympy_solver_visitor(nmodl_text, false, false, AstNodeType::DERIVATIVE_BLOCK);
compare_blocks(reindent_text(result[0]), reindent_text(expected_result));
}
}
GIVEN("Derivative block, sparse, print in order, vectors") {
std::string nmodl_text = R"(
STATE {
M[2]
}
BREAKPOINT {
SOLVE states METHOD sparse
}
DERIVATIVE states {
LOCAL a, b
M'[1] = a
M'[0] = b
})";
std::string expected_result = R"(
DERIVATIVE states {
EIGEN_NEWTON_SOLVE[2]{
LOCAL a, b, old_M_1, old_M_0
}{
old_M_1 = M[1]
old_M_0 = M[0]
}{
nmodl_eigen_x[0] = M[0]
nmodl_eigen_x[1] = M[1]
}{
nmodl_eigen_f[0] = -nmodl_eigen_x[1]+a*dt+old_M_1
nmodl_eigen_j[0] = 0
nmodl_eigen_j[2] = -1.0
nmodl_eigen_f[1] = -nmodl_eigen_x[0]+b*dt+old_M_0
nmodl_eigen_j[1] = -1.0
nmodl_eigen_j[3] = 0
}{
M[0] = nmodl_eigen_x[0]
M[1] = nmodl_eigen_x[1]
}{
}
})";
THEN("Construct & solve linear system for backwards Euler") {
auto result =
run_sympy_solver_visitor(nmodl_text, false, false, AstNodeType::DERIVATIVE_BLOCK);
compare_blocks(reindent_text(result[0]), reindent_text(expected_result));
}
}
GIVEN("Derivative block, sparse, derivatives mixed with local variable reassignment") {
std::string nmodl_text = R"(
STATE {
x y
}
BREAKPOINT {
SOLVE states METHOD sparse
}
DERIVATIVE states {
LOCAL a, b
x' = a
b = b + 1
y' = b
})";
std::string expected_result = R"(
DERIVATIVE states {
EIGEN_NEWTON_SOLVE[2]{
LOCAL a, b, old_x, old_y
}{
old_x = x
old_y = y
}{
nmodl_eigen_x[0] = x
nmodl_eigen_x[1] = y
}{
nmodl_eigen_f[0] = -nmodl_eigen_x[0]+a*dt+old_x
nmodl_eigen_j[0] = -1.0
nmodl_eigen_j[2] = 0
b = b+1
nmodl_eigen_f[1] = -nmodl_eigen_x[1]+b*dt+old_y
nmodl_eigen_j[1] = 0
nmodl_eigen_j[3] = -1.0
}{
x = nmodl_eigen_x[0]
y = nmodl_eigen_x[1]
}{
}
})";
THEN("Construct & solve linear system for backwards Euler") {
auto result =
run_sympy_solver_visitor(nmodl_text, false, false, AstNodeType::DERIVATIVE_BLOCK);
compare_blocks(reindent_text(result[0]), reindent_text(expected_result));
}
}
GIVEN(
"Throw exception during derivative variable reassignment interleaved in the differential "
"equation set") {
std::string nmodl_text = R"(
STATE {
x y
}
BREAKPOINT {
SOLVE states METHOD sparse
}
DERIVATIVE states {
LOCAL a, b
x' = a
x = x + 1
y' = b + x
})";
THEN(
"Throw an error because state variable assignments are not allowed inside the system "
"of differential "
"equations") {
REQUIRE_THROWS_WITH(
run_sympy_solver_visitor(nmodl_text, false, false, AstNodeType::DERIVATIVE_BLOCK),
Catch::Matchers::Contains("State variable assignment(s) interleaved in system of "
"equations/differential equations") &&
Catch::Matchers::StartsWith("SympyReplaceSolutionsVisitor"));
}
}
GIVEN("Derivative block in control flow block") {
std::string nmodl_text = R"(
STATE {
x y
}
BREAKPOINT {
SOLVE states METHOD sparse
}
DERIVATIVE states {
LOCAL a, b
if (a == 1) {
x' = a
y' = b
}
})";
std::string expected_result = R"(
DERIVATIVE states {
LOCAL a, b
IF (a == 1) {
EIGEN_NEWTON_SOLVE[2]{
LOCAL old_x, old_y
}{
old_x = x
old_y = y
}{
nmodl_eigen_x[0] = x
nmodl_eigen_x[1] = y
}{
nmodl_eigen_f[0] = -nmodl_eigen_x[0]+a*dt+old_x
nmodl_eigen_j[0] = -1.0
nmodl_eigen_j[2] = 0
nmodl_eigen_f[1] = -nmodl_eigen_x[1]+b*dt+old_y
nmodl_eigen_j[1] = 0
nmodl_eigen_j[3] = -1.0
}{
x = nmodl_eigen_x[0]
y = nmodl_eigen_x[1]
}{
}
}
})";
THEN("Construct & solve linear system for backwards Euler") {
auto result =
run_sympy_solver_visitor(nmodl_text, false, false, AstNodeType::DERIVATIVE_BLOCK);
compare_blocks(reindent_text(result[0]), reindent_text(expected_result));
}
}
GIVEN(
"Derivative block, sparse, coupled derivatives mixed with reassignment and control flow "
"block") {
std::string nmodl_text = R"(
STATE {
x y
}
BREAKPOINT {
SOLVE states METHOD sparse
}
DERIVATIVE states {
LOCAL a, b
x' = a * y+b
if (b == 1) {
a = a + 1
}
y' = x + a*y
})";
std::string expected_result = R"(
DERIVATIVE states {
EIGEN_NEWTON_SOLVE[2]{
LOCAL a, b, old_x, old_y
}{
old_x = x
old_y = y
}{
nmodl_eigen_x[0] = x
nmodl_eigen_x[1] = y
}{
nmodl_eigen_f[0] = -nmodl_eigen_x[0]+nmodl_eigen_x[1]*a*dt+b*dt+old_x
nmodl_eigen_j[0] = -1.0
nmodl_eigen_j[2] = a*dt
IF (b == 1) {
a = a+1
}
nmodl_eigen_f[1] = nmodl_eigen_x[0]*dt+nmodl_eigen_x[1]*a*dt-nmodl_eigen_x[1]+old_y
nmodl_eigen_j[1] = dt
nmodl_eigen_j[3] = a*dt-1.0
}{
x = nmodl_eigen_x[0]
y = nmodl_eigen_x[1]
}{
}
})";
std::string expected_result_cse = R"(
DERIVATIVE states {
EIGEN_NEWTON_SOLVE[2]{
LOCAL a, b, old_x, old_y
}{
old_x = x
old_y = y
}{
nmodl_eigen_x[0] = x
nmodl_eigen_x[1] = y
}{
nmodl_eigen_f[0] = -nmodl_eigen_x[0]+nmodl_eigen_x[1]*a*dt+b*dt+old_x
nmodl_eigen_j[0] = -1.0
nmodl_eigen_j[2] = a*dt
IF (b == 1) {
a = a+1
}
nmodl_eigen_f[1] = nmodl_eigen_x[0]*dt+nmodl_eigen_x[1]*a*dt-nmodl_eigen_x[1]+old_y
nmodl_eigen_j[1] = dt
nmodl_eigen_j[3] = a*dt-1.0
}{
x = nmodl_eigen_x[0]
y = nmodl_eigen_x[1]
}{
}
})";
THEN("Construct & solve linear system for backwards Euler") {
auto result =
run_sympy_solver_visitor(nmodl_text, false, false, AstNodeType::DERIVATIVE_BLOCK);
auto result_cse =
run_sympy_solver_visitor(nmodl_text, true, true, AstNodeType::DERIVATIVE_BLOCK);
compare_blocks(reindent_text(result[0]), reindent_text(expected_result));
compare_blocks(reindent_text(result_cse[0]), reindent_text(expected_result_cse));
}
}
GIVEN("Derivative block of coupled & linear ODES, solver method sparse") {
std::string nmodl_text = R"(
STATE {
x y z
}
BREAKPOINT {
SOLVE states METHOD sparse
}
DERIVATIVE states {
LOCAL a, b, c, d, h
x' = a*z + b*h
y' = c + 2*x
z' = d*z - y
}
)";
std::string expected_result = R"(
DERIVATIVE states {
EIGEN_NEWTON_SOLVE[3]{
LOCAL a, b, c, d, h, old_x, old_y, old_z
}{
old_x = x
old_y = y
old_z = z
}{
nmodl_eigen_x[0] = x
nmodl_eigen_x[1] = y
nmodl_eigen_x[2] = z
}{
nmodl_eigen_f[0] = -nmodl_eigen_x[0]+nmodl_eigen_x[2]*a*dt+b*dt*h+old_x
nmodl_eigen_j[0] = -1.0
nmodl_eigen_j[3] = 0
nmodl_eigen_j[6] = a*dt
nmodl_eigen_f[1] = 2.0*nmodl_eigen_x[0]*dt-nmodl_eigen_x[1]+c*dt+old_y
nmodl_eigen_j[1] = 2.0*dt
nmodl_eigen_j[4] = -1.0
nmodl_eigen_j[7] = 0
nmodl_eigen_f[2] = -nmodl_eigen_x[1]*dt+nmodl_eigen_x[2]*d*dt-nmodl_eigen_x[2]+old_z
nmodl_eigen_j[2] = 0
nmodl_eigen_j[5] = -dt
nmodl_eigen_j[8] = d*dt-1.0
}{
x = nmodl_eigen_x[0]
y = nmodl_eigen_x[1]
z = nmodl_eigen_x[2]
}{
}
})";
std::string expected_cse_result = R"(
DERIVATIVE states {
EIGEN_NEWTON_SOLVE[3]{
LOCAL a, b, c, d, h, old_x, old_y, old_z
}{
old_x = x
old_y = y
old_z = z
}{
nmodl_eigen_x[0] = x
nmodl_eigen_x[1] = y
nmodl_eigen_x[2] = z