Skip to content

Commit a2106f8

Browse files
author
Dilawar Singh
committed
Updated tests.
1 parent c2f1fdc commit a2106f8

File tree

3 files changed

+109
-29
lines changed

3 files changed

+109
-29
lines changed

builtins/Function.cpp

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -482,11 +482,9 @@ void Function::addVariable(const string& name)
482482

483483
void Function::callbackAddSymbol(const string& name)
484484
{
485-
cout << "callback Adding " << name << endl;
485+
// Add only if doesn't exist.
486486
if(varIndex_.find(name) == varIndex_.end())
487487
addXByName(name);
488-
else
489-
cerr << name << " already exists." << endl;
490488
}
491489

492490
/* --------------------------------------------------------------------------*/

python/moose/wrapper.py

Lines changed: 46 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
# -*- coding: utf-8 -*-
2-
# Wrappers around _moose.so classes.
3-
42
from __future__ import print_function, division, absolute_import
53

6-
__author__ = "Dilawar Singh"
7-
__copyright__ = "Copyright 2019-, Dilawar Singh"
8-
__maintainer__ = "Dilawar Singh"
9-
__email__ = "[email protected]"
4+
# Wrappers around _moose.so classes.
5+
6+
__author__ = "Dilawar Singh"
7+
__copyright__ = "Copyright 2019-, Dilawar Singh"
8+
__maintainer__ = "Dilawar Singh"
9+
__email__ = "[email protected]"
1010

11-
import sys
1211
import difflib
1312
import moose._moose as _moose
1413
import pprint
@@ -35,14 +34,16 @@ def _didYouMean(v, options):
3534
"""
3635
return ' or '.join(difflib.get_close_matches(v, list(options), n=2))
3736

37+
3838
def _eval(expr):
3939
try:
40-
if isinstance(expr, (int,float)):
40+
if isinstance(expr, (int, float)):
4141
return expr
4242
return eval(str(expr))
4343
except Exception:
4444
return expr
4545

46+
4647
def _prettifyExpr(expr):
4748
global sympyFound_
4849
if not sympyFound_:
@@ -55,19 +56,23 @@ def _prettifyExpr(expr):
5556

5657
# Generic wrapper around moose.Neutral
5758
class Neutral(_moose.Neutral):
58-
59-
def __init__(self, path, n=1, g=0, dtype='Neutral'):
59+
def __init__(self, path, n=1, g=0, dtype='Neutral', **kwargs):
6060
super(_moose.Neutral, self).__init__(path, n, g, dtype)
61+
for k in kwargs:
62+
try:
63+
setattr(self, k, kwargs[k])
64+
except AttributeError:
65+
logging.warn("Attribute %s is not found. Ignoring..." % k)
6166

62-
def __new__(cls, pathOrObject, n=1, g=0, dtype='Neutral'):
67+
def __new__(cls, pathOrObject, n=1, g=0, dtype='Neutral', **kwargs):
6368
path = pathOrObject
6469
if not isinstance(pathOrObject, str):
65-
path = pathOrObject.path;
70+
path = pathOrObject.path
6671
if _moose.exists(path):
6772
# logger.info("%s already exists. Returning old element."%path)
6873
return _moose.element(path)
69-
return super(_moose.Neutral, cls).__new__(cls, pathOrObject, n, g, dtype)
70-
74+
return super(_moose.Neutral, cls).__new__(cls, pathOrObject, n, g,
75+
dtype)
7176

7277
def connect(self, srcField, dest, destField):
7378
"""Wrapper around moose.connect.
@@ -82,7 +87,8 @@ def connect(self, srcField, dest, destField):
8287
if dym:
8388
logger.warn("\tDid you mean %s?" % dym)
8489
else:
85-
logger.warn(': Available options: %s' % ', '.join(allSrcFields))
90+
logger.warn(': Available options: %s' %
91+
', '.join(allSrcFields))
8692
raise NameError("Failed to connect")
8793
if destField not in allDestFields:
8894
logger.error("Could not find '{0}' in {1} destFields.".format(
@@ -91,7 +97,8 @@ def connect(self, srcField, dest, destField):
9197
if dym:
9298
logger.warn("\tDid you mean %s?" % dym)
9399
else:
94-
logger.warn(': Available options: %s' % ', '.join(allDestFields))
100+
logger.warn(': Available options: %s' %
101+
', '.join(allDestFields))
95102
raise NameError("Failed to connect")
96103

97104
# Everything looks fine. Connect now.
@@ -108,11 +115,13 @@ class Function(_moose.Function):
108115
def __init__(self, path, n=1, g=0, dtype='Function', **kwargs):
109116
super(_moose.Function, self).__init__(path, n, g, dtype)
110117
for k in kwargs:
111-
setattr(self, k, kwargs[k])
118+
try:
119+
setattr(self, k, kwargs[k])
120+
except AttributeError:
121+
logging.warn("Attribute %s is not found. Ignoring..." % k)
112122

113123
def __getitem__(self, key):
114-
"""Override [] operator.
115-
FIXME: This function is tricky. Fix it later.
124+
"""Override [] operator. It returns the linked variable by name.
116125
"""
117126
assert self.numVars > 0
118127
return self.x[self.xindex[key]]
@@ -122,11 +131,13 @@ def compile(self, expr, constants={}, variables=[], mode=0, **kwargs):
122131
"""
123132
__expr = expr
124133
# Replace constants.
125-
constants = { k: v for k, v in
126-
sorted(constants.items(), key=lambda x: len(x)) }
134+
constants = {
135+
k: v
136+
for k, v in sorted(constants.items(), key=lambda x: len(x))
137+
}
127138
for i, constName in enumerate(constants):
128139
# replace constName with 'c%d' % i
129-
mooseConstName = 'c%d'%i
140+
mooseConstName = 'c%d' % i
130141
expr = expr.replace(constName, mooseConstName)
131142
self.c[mooseConstName] = _eval(constants[constName])
132143

@@ -141,7 +152,7 @@ def compile(self, expr, constants={}, variables=[], mode=0, **kwargs):
141152
msg += _prettifyExpr(__expr)
142153
msg += "\nto, \n"
143154
msg += _prettifyExpr(expr)
144-
logging.warn( msg.replace('\n', '\n ﹅ '))
155+
logging.warn(msg.replace('\n', '\n ﹅ '))
145156

146157
# alias
147158
setExpr = compile
@@ -155,3 +166,15 @@ def printUsingSympy(self):
155166
"""
156167
import sympy
157168
sympy.pprint(self.sympyExpr())
169+
170+
171+
class StimulusTable(Neutral):
172+
"""StimulusTable
173+
"""
174+
def __init__(self, path, n=1, g=0, dtype='StimulusTable', **kwargs):
175+
super(Neutral, self).__init__(path, n, g, dtype)
176+
for k in kwargs:
177+
try:
178+
setattr(self, k, kwargs[k])
179+
except AttributeError:
180+
logging.warn("Attribute %s is not found. Ignoring..." % k)

tests/py_moose/test_wrapper.py

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,65 @@
66
__email__ = "[email protected]"
77

88
import moose
9-
print('[INFO] Using moose from %s' % moose.about())
9+
import numpy as np
10+
print( "[INFO ] Using moose %s form %s" % (moose.version(), moose.__file__) )
11+
12+
def create_func( funcname, expr ):
13+
f = moose.Function( funcname )
14+
f.expr = expr
15+
t = moose.Table( funcname + 'tab' )
16+
t.connect('requestOut', f, 'getValue')
17+
moose.setClock( f.tick, 0.1)
18+
moose.setClock( t.tick, 0.1)
19+
return f, t
20+
21+
def test_function():
22+
nsteps = 5
23+
simtime = nsteps
24+
dt = 1.0
25+
fn1 = moose.Function('/fn1', expr = 'B+A+y0+y1')
26+
inputs = np.arange(0, nsteps+1, 1.0)
27+
x0 = moose.StimulusTable('/x0', vector=inputs, startTime = 0.0
28+
, stopTime = simtime, stepPosition = 0.0)
29+
print('x0', x0.vector)
30+
inputs /= 10
31+
x1 = moose.StimulusTable('/x1', vector=inputs, startTime=0.0
32+
, stopTime=simtime, stepPosition=0.0, k = 11)
33+
print('x1', x1.vector)
34+
inputs /= 10
35+
y0 = moose.StimulusTable('/y0', vector=inputs, startTime=0.0
36+
, stopTime=simtime, stepPosition=0.0)
37+
print('y0', y0.vector)
38+
inputs /= 10
39+
y1 = moose.StimulusTable('/y1', vector=inputs, startTime=0.0
40+
, stopTime=simtime, stepPosition=0.0)
41+
print('y1', y1.vector)
42+
x0.connect('output', fn1['A'], 'input')
43+
x1.connect('output', fn1['B'], 'input')
44+
fn1.connect('requestOut', y0, 'getOutputValue')
45+
fn1.connect('requestOut', y1, 'getOutputValue')
46+
47+
z1 = moose.Table('/z1')
48+
z1.connect('requestOut', fn1, 'getValue')
49+
for ii in range(32):
50+
moose.setClock(ii, dt)
51+
moose.reinit()
52+
moose.start(simtime)
53+
expected = [0, 1.1, 2.211, 3.322, 4.433, 5.544]
54+
assert np.allclose(z1.vector, expected), "Excepted %s, got %s" % (expected, z1.vector )
55+
print( 'Passed order vars' )
56+
57+
58+
def test_dynamic_lookup():
59+
f, t = create_func( 'fmod', 'A+(B/2.0)' )
60+
moose.reinit()
61+
moose.start(20)
62+
y = t.vector
63+
assert (np.fmod(y, 2) == y).all()
64+
assert(np.isclose(np.max(y), 1.9)), "Expected 1.9 got %s" % np.max(y)
65+
assert(np.isclose(np.min(y), 0.0)), "Expected 0.0 got %s" % np.min(y)
66+
print('Passed fmod(t,2)')
67+
1068

1169
def test_creation():
1270
a1 = moose.Neutral('a')
@@ -19,6 +77,7 @@ def test_creation():
1977

2078
def test_print():
2179
a = moose.Function('f', expr='sqrt(sin(x0))+cos(x1)^2+ln(20+sin(t))')
80+
2281
# Get equivalent sympy expression. And do whatever you like with it.
2382
sympyExpr = a.sympyExpr()
2483
print('Sympy expression is:', sympyExpr)
@@ -31,11 +90,11 @@ def test_basic():
3190
f.expr = 'A+B+sqrt(B)+zhadu(q)'
3291
print(f)
3392

34-
3593
def main():
94+
test_function()
95+
test_basic()
3696
test_creation()
3797
test_print()
38-
test_basic()
3998

4099
if __name__ == '__main__':
41100
main()

0 commit comments

Comments
 (0)