예제 #1
0
def smc(model, t0=0):

    import sympy
    from sympy.printing import fcode
    cmodel = model.compile_model()
    template = fortran_model  #open('fortran_model.f90').read()
    write_prior_file(cmodel.prior, '.')

    system_matrices = model.python_sims_matrices(matrix_format='symbolic')
    npara = len(model.parameters)
    para = sympy.IndexedBase('para', shape=(npara + 1, ))

    fortran_subs = dict(
        zip([sympy.symbols('garbage')] + model.parameters, para))
    fortran_subs[0] = 0.0
    fortran_subs[1] = 1.0
    fortran_subs[100] = 100.0
    fortran_subs[2] = 2.0
    fortran_subs[400] = 400.0
    fortran_subs[4] = 4.0

    context = dict([(p.name, p)
                    for p in model.parameters + model['other_para']])
    context['exp'] = sympy.exp
    context['log'] = sympy.log

    to_replace = {}
    for p in model['other_para']:
        to_replace[p] = eval(str(model['para_func'][p.name]), context)

    to_replace = list(to_replace.items())
    print(to_replace)
    from itertools import combinations, permutations

    edges = [(i, j) for i, j in permutations(to_replace, 2)
             if type(i[1]) not in [float, int] and i[1].has(j[0])]

    from sympy import default_sort_key, topological_sort
    para_func = topological_sort([to_replace, edges], default_sort_key)

    to_write = [
        'GAM0', 'GAM1', 'PSI', 'PPI', 'self%QQ', 'DD2', 'self%ZZ', 'self%HH'
    ]
    fmats = [
        fcode((mat.subs(para_func)).subs(fortran_subs),
              assign_to=n,
              source_format='free',
              standard=95,
              contract=False) for mat, n in zip(system_matrices, to_write)
    ]
    sims_mat = '\n\n'.join(fmats)
    template = template.format(model=model,
                               yy=cmodel.yy,
                               p0='',
                               t0=t0,
                               sims_mat=sims_mat)

    return template
예제 #2
0
def test_Module():
    x = Symbol('x', real=True)
    v_x = Variable.deduced(x)
    sq = FunctionDefinition(real, 'sqr', [v_x], [Return(x**2)])
    mod_sq = Module('mod_sq', [], [sq])
    sq_call = FunctionCall('sqr', [42.])
    prg_sq = Program(
        'foobar',
        [use('mod_sq', only=['sqr']),
         Print(['"Square of 42 = "', sq_call])])
    if not has_fortran():
        skip("No fortran compiler found.")
    (stdout, stderr), info = compile_run_strings(
        [('mod_sq.f90', fcode(mod_sq, standard=90)),
         ('main.f90', fcode(prg_sq, standard=90))],
        clean=True)
    assert '42' in stdout
    assert str(42**2) in stdout
    assert stderr == ''
예제 #3
0
def test_Subroutine():
    # Code to generate the subroutine in the example from
    # http://www.fortran90.org/src/best-practices.html#arrays
    r = Symbol('r', real=True)
    i = Symbol('i', integer=True)
    v_r = Variable.deduced(r, attrs=(dimension(assumed_extent), intent_out))
    v_i = Variable.deduced(i)
    v_n = Variable('n', integer)
    do_loop = Do([
        Assignment(Element(r, [i]), literal_dp(1)/i**2)
    ], i, 1, v_n)
    sub = Subroutine("f", [v_r], [
        Declaration(v_n),
        Declaration(v_i),
        Assignment(v_n, size(r)),
        do_loop
    ])
    x = Symbol('x', real=True)
    v_x3 = Variable.deduced(x, attrs=[dimension(3)])
    mod = Module('mymod', definitions=[sub])
    prog = Program('foo', [
        use(mod, only=[sub]),
        Declaration(v_x3),
        SubroutineCall(sub, [v_x3]),
        Print([sum_(v_x3), v_x3])
    ])

    if not has_fortran():
        skip("No fortran compiler found.")

    (stdout, stderr), info = compile_run_strings([
        ('a.f90', fcode(mod, standard=90)),
        ('b.f90', fcode(prog, standard=90))
    ], clean=True)
    ref = [1.0/i**2 for i in range(1, 4)]
    assert str(sum(ref))[:-3] in stdout
    for _ in ref:
        assert str(_)[:-3] in stdout
    assert stderr == ''
예제 #4
0
def test_Program():
    x = Symbol('x', real=True)
    vx = Variable.deduced(x, 42)
    decl = Declaration(vx)
    prnt = Print([x, x+1])
    prog = Program('foo', [decl, prnt])
    if not has_fortran():
        skip("No fortran compiler found.")

    (stdout, stderr), info = compile_run_strings([('main.f90', fcode(prog, standard=90))], clean=True)
    assert '42' in stdout
    assert '43' in stdout
    assert stderr == ''
    assert info['exit_status'] == os.EX_OK
예제 #5
0
def test_ImpliedDoLoop():
    if not has_fortran():
        skip("No fortran compiler found.")

    a, i = symbols('a i', integer=True)
    idl = ImpliedDoLoop(i**3, i, -3, 3, 2)
    ac = ArrayConstructor([-28, idl, 28])
    a = array(a, dim=[':'], attrs=[allocatable])
    prog = Program(
        'idlprog',
        [a.as_Declaration(), Assignment(a, ac),
         Print([a])])
    fsrc = fcode(prog, standard=2003, source_format='free')
    (stdout, stderr), info = compile_run_strings([('main.f90', fsrc)],
                                                 clean=True)
    for numstr in '-28 -27 -1 1 27 28'.split():
        assert numstr in stdout
    assert stderr == ''
    assert info['exit_status'] == os.EX_OK
예제 #6
0
    def convert_to_fortran(self):
        """Returns a list with the fortran source code for the SymPy expressions

        Examples
        ========

        >>> from sympy.parsing.sym_expr import SymPyExpression
        >>> src2 = '''
        ... integer :: a, b, c, d
        ... real :: p, q, r, s
        ... c = a/b
        ... d = c/a
        ... s = p/q
        ... r = q/p
        ... '''
        >>> p = SymPyExpression(src2, 'f')
        >>> p.convert_to_fortran()
        ['      integer*4 a', '      integer*4 b', '      integer*4 c', '      integer*4 d', '      real*8 p', '      real*8 q', '      real*8 r', '      real*8 s', '      c = a/b', '      d = c/a', '      s = p/q', '      r = q/p']

        """
        self._fcode = []
        for iter in self._expr:
            self._fcode.append(fcode(iter))
        return self._fcode
예제 #7
0
def test_size():
    x = Symbol('x', real=True)
    sx = size(x)
    assert fcode(sx, source_format='free') == 'size(x)'
예제 #8
0
def test_literal_dp():
    assert fcode(literal_dp(0), source_format='free') == '0d0'
예제 #9
0
def test_dsign():
    x = Symbol('x')
    assert unchanged(dsign, 1, x)
    assert fcode(dsign(literal_dp(1), x), standard=95,
                 source_format='free') == 'dsign(1d0, x)'
예제 #10
0
def test_isign():
    x = Symbol('x', integer=True)
    assert unchanged(isign, 1, x)
    assert fcode(isign(1, x), standard=95,
                 source_format='free') == 'isign(1, x)'
예제 #11
0
파일: translate.py 프로젝트: eph/dsge
def smc(model, t0=0):

    import sympy
    from sympy.printing import fcode

    cmodel = model.compile_model()
    template = fortran_model  # open('fortran_model.f90').read()
    write_prior_file(cmodel.prior, ".")

    system_matrices = model.python_sims_matrices(matrix_format="symbolic")
    npara = len(model.parameters)
    para = sympy.IndexedBase("para", shape=(npara + 1,))

    from .symbols import Parameter

    fortran_subs = dict(
        zip(
            [sympy.symbols("garbage")] + [Parameter(px) for px in model.parameters],
            para,
        )
    )
    fortran_subs[0] = 0.0
    fortran_subs[1] = 1.0
    fortran_subs[100] = 100.0
    fortran_subs[2] = 2.0
    fortran_subs[400] = 400.0
    fortran_subs[4] = 4.0

    context_tuple = [(p, Parameter(p)) for p in model.parameters] + [
        (p.name, p) for p in model["other_para"]
    ]

    context = dict(context_tuple)
    context["exp"] = sympy.exp
    context["log"] = sympy.log

    to_replace = {}
    for p in model["other_para"]:
        to_replace[p] = eval(str(model["para_func"][p.name]), context)

    to_replace = list(to_replace.items())
    print(to_replace)
    from itertools import combinations, permutations

    edges = [
        (i, j)
        for i, j in permutations(to_replace, 2)
        if type(i[1]) not in [float, int] and i[1].has(j[0])
    ]

    from sympy import default_sort_key, topological_sort

    para_func = topological_sort([to_replace, edges], default_sort_key)

    to_write = ["GAM0", "GAM1", "PSI", "PPI", "self%QQ", "DD2", "self%ZZ", "self%HH"]
    fmats = [
        fcode(
            (mat.subs(para_func)).subs(fortran_subs),
            assign_to=n,
            source_format="free",
            standard=95,
            contract=False,
        )
        for mat, n in zip(system_matrices, to_write)
    ]
    sims_mat = "\n\n".join(fmats)
    template = template.format(
        model=model, yy=cmodel.yy, p0="", t0=t0, sims_mat=sims_mat
    )

    return template