Sandbox

For playing around during development.


In [7]:
%pylab inline
#import pysd
#print pysd.__version__
#print pysd.__file__
#import pandas as pd
#import os
import xarray as xr
import numpy as np


Populating the interactive namespace from numpy and matplotlib

In [1]:
class Components(object):
    """
    This class implements the 'components' namespace for a Model object,
    which allows the model to have a namespace of its own with no additional
    functions that may conflict with model names.

    Implementing this as a class rather than a module allows this components
    namespace to have access to its containing namespaces to access things
    like the universal time, or functions defined externally
    """

    def __init__(self, py_model_file):
        from functions import cache  # this will be used in the call to exec
        import functions
        #component_ns = dict()
        #func_globals = globals().copy()
        #func_globals.update(locals())


        with open(py_model_file) as f:
            code = compile(f.read(), py_model_file, 'exec')
            #exec(code, func_globals, component_ns)
            exec(code, globals(), locals())
            #exec(code)
        self.__dict__.update(locals())

In [2]:
my_ns = {}

In [56]:
def f():
    return 5

a = lambda: f

In [59]:
a()


Out[59]:
5

In [8]:
def g():
    print 5

In [9]:
def f():
    exec('g()', globals(), my_ns)

In [11]:
a = {'hi':5}
b = {'number':1}

In [53]:
my_ns = dict()
code_str = """
def f1():
    return self.f2()

def f2():
    return 5
"""
code = compile(code_str, 'dummy', 'exec')
exec (code, globals(), my_ns)

In [54]:
class Bunch:
    def __init__(self, ns):
        self.__dict__.update(ns)
        
a = Bunch(my_ns)

In [55]:
a.f1()


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-55-1c74751ad4be> in <module>()
----> 1 a.f1()

dummy in f1()

NameError: global name 'self' is not defined

In [47]:
my_ns['f1']()


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-47-2d4c0d245b3f> in <module>()
----> 1 my_ns['f1']()

dummy in f1()

NameError: global name 'f2' is not defined

In [14]:
z = a.copy()
z.update(b)
z


Out[14]:
{'hi': 5, 'number': 1}

In [1]:
in_file = "tests/test-models/tests/macro_expression/expression_macro.py"
my_ns = dict()
with open(in_file) as f:
    code = compile(f.read(), in_file, 'exec')
    exec(code, globals(), my_ns)

In [13]:
! cat $in_file


"""
Python model test-models/tests/macro_expression/expression_macro.py
Translated using PySD version 0.7.2
"""
from __future__ import division
import numpy as np
from pysd import utils
import xarray as xr

from pysd.functions import cache
from pysd import functions

_subscript_dict = {}

_namespace = {
    'input': 'input',
    'Time': 'time',
    'parameter': 'parameter',
    'EXPRESSION MACRO': 'expression_macro',
    'TIME': 'time'}


@cache('step')
def time():
    """
    TIME
    ----
    (time)
    None
    The time of the model
    """
    return _t


@cache('step')
def expression_macro():
    """
    EXPRESSION MACRO
    ----------------
    (expression_macro)
    input
    tests basic macro containing no stocks and having no output
    """
    return input() * parameter()


def time():
    return _t
functions.time = time
functions._stage = lambda: _stage

In [6]:
my_ns['expression_macro']()


hsadj
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-3e871d4b074c> in <module>()
----> 1 my_ns['expression_macro']()

/Users/houghton/Google_Drive/Academic Projects/PYSD/pysd/pysd/functions.py in cached(*args)
     66                 assert hasattr(cached, 'cache_val')
     67             except (AssertionError, AttributeError):
---> 68                 cached.cache_val = func(*args)
     69                 cached.cache_t = func.__globals__['_t']
     70             return cached.cache_val

/Users/houghton/Google_Drive/Academic Projects/PYSD/pysd/tests/test-models/tests/macro_expression/expression_macro.py in expression_macro()
     43     tests basic macro containing no stocks and having no output
     44     """
---> 45     return input() * parameter()
     46 
     47 

/Users/houghton/anaconda/lib/python2.7/site-packages/ipykernel/ipkernel.pyc in <lambda>(prompt)
    139             self._sys_eval_input = builtin_mod.input
    140             builtin_mod.raw_input = self.raw_input
--> 141             builtin_mod.input = lambda prompt='': eval(self.raw_input(prompt))
    142         self._save_getpass = getpass.getpass
    143         getpass.getpass = self.getpass

/Users/houghton/anaconda/lib/python2.7/site-packages/ipykernel/ipkernel.pyc in <module>()

NameError: name 'hsadj' is not defined

In [7]:
class Bunch:
    def __init__(self, ns):
        self.__dict__.update(ns)

In [11]:
_t = 5

In [8]:
a = Bunch(my_ns)

In [12]:
a.time()


Out[12]:
5

In [1]:
import pysd

In [2]:
pysd.__version__


Out[2]:
'0.7.1'

In [3]:
model = pysd.read_vensim('tests/test-models/samples/teacup/teacup.mdl')

In [4]:
model.doc()


Out[4]:
Real Name Py Name Unit Comment
0 Characteristic Time characteristic_time Minutes
1 FINAL TIME final_time Minute The final time for the simulation.\n
2 Heat Loss to Room heat_loss_to_room Degrees/Minute This is the rate at which heat flows from the ...
3 INITIAL TIME initial_time Minute The initial time for the simulation.\n
4 Room Temperature room_temperature
5 SAVEPER saveper Minute [0,?] The frequency with which output is stored.\n
6 Teacup Temperature teacup_temperature Degrees
7 TIME STEP time_step Minute [0,?] The time step for the simulation.\n

In [5]:
def myfunc():
    return [func() for func in myfunc.subfuncs]
myfunc.subfuncs = []

myfunc.subfuncs.append(lambda: 5)
myfunc.subfuncs.append(lambda: 6)

In [6]:
myfunc()


Out[6]:
[5, 6]

In [13]:
a = [xr.DataArray(range(3)), xr.DataArray(range(5))]
a


Out[13]:
[<xarray.DataArray (dim_0: 3)>
 array([0, 1, 2])
 Coordinates:
   * dim_0    (dim_0) int64 0 1 2, <xarray.DataArray (dim_0: 5)>
 array([0, 1, 2, 3, 4])
 Coordinates:
   * dim_0    (dim_0) int64 0 1 2 3 4]

In [14]:
b = np.array(a)
b


Out[14]:
array([ <xarray.DataArray (dim_0: 3)>
array([0, 1, 2])
Coordinates:
  * dim_0    (dim_0) int64 0 1 2,
       <xarray.DataArray (dim_0: 5)>
array([0, 1, 2, 3, 4])
Coordinates:
  * dim_0    (dim_0) int64 0 1 2 3 4], dtype=object)

In [16]:
c = b*2
c


Out[16]:
array([ <xarray.DataArray (dim_0: 3)>
array([0, 2, 4])
Coordinates:
  * dim_0    (dim_0) int64 0 1 2,
       <xarray.DataArray (dim_0: 5)>
array([0, 2, 4, 6, 8])
Coordinates:
  * dim_0    (dim_0) int64 0 1 2 3 4], dtype=object)

In [ ]:
order = 3
init =

In [18]:
d = np.roll(b, 1)
d[0] = xr.DataArray(range(2))
d


Out[18]:
array([ <xarray.DataArray (dim_0: 2)>
array([0, 1])
Coordinates:
  * dim_0    (dim_0) int64 0 1,
       <xarray.DataArray (dim_0: 3)>
array([0, 1, 2])
Coordinates:
  * dim_0    (dim_0) int64 0 1 2], dtype=object)

In [19]:
getattr(a, 'hi')


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-19-2eb1b8b4ee59> in <module>()
----> 1 getattr(a, 'hi')

AttributeError: 'list' object has no attribute 'hi'

In [20]:
a.update()


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-20-f827106214b2> in <module>()
----> 1 a.update()

AttributeError: 'list' object has no attribute 'update'

In [ ]: