#!/usr/bin/env python
"""
Transient Laplace equation (heat/diffusion equation) with constant initial conditions
given by a function

In the SfePy top-level directory the following command executes the script

python time_poisson_explicity_1d.py
"""

from __future__ import absolute_import
import sys
from six.moves import range
sys.path.append('.')
from argparse import ArgumentParser, RawDescriptionHelpFormatter

import numpy as nm
import matplotlib.pyplot as plt

def main():

    from sfepy.base.base import output
    from sfepy.base.conf import ProblemConf, get_standard_keywords
    from sfepy.discrete import (FieldVariable, Material, Integral, Function,
                            Equation, Equations, Problem, Domain, State)
    # from sfepy.base.plotutils import plt
    from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver
    from sfepy.solvers.ls import ScipyDirect
    from sfepy.solvers.nls import Newton
    import sfepy.solvers.ts

    # required, other = get_standard_keywords()
    ### Use this file as the input file.
    conf = ProblemConf.from_file('time_poisson_explicit_1d.py')

    #### Create problem instance, but do not set equations.
    problemInstance = Problem.from_conf(conf)
    problemInstance.setup_default_output()

    # initializing simple time step solver from configurationf ile
    tss = SimpleTimeSteppingSolver(problemInstance.ts_conf, problem=problemInstance)
    tss.init_time()

    print ("initial problem/solver configured....")

    print ("")

    print ("problemInstance.ts_conf: " + str(problemInstance.ts_conf))
    print ("problemInstance.ts.t0: " + str(problemInstance.ts.t0))
    print ("problemInstance.ts.t1: " + str(problemInstance.ts.t1))
    print ("problemInstance.ts.dt: " + str(problemInstance.ts.dt))
    print ("")
    print ("tss.ts.t0: " + str(tss.ts.t0))
    print ("tss.ts.t1: " + str(tss.ts.t1))
    print ("tss.ts.dt: " + str(tss.ts.dt))
    print ("")

    # Solve the problem using the time stepping solver.
    suffix = tss.ts.suffix

    genpath = "output/"


    #### initialize state for problem from sfepy.solvers.ts_solvers
    #### def get_initial_state(problem) calls...
    state0 = problemInstance.create_state()
    problemInstance.setup_ics()
    state0.apply_ic()
    # Initialize variables with history.
    state0.init_history()
    print (state0.vec)
    staten1 = state0.copy(deep=True)


    #### file containing time step and the concentration
    #### at the left most node...for comparison with the
    #### opposing script
    filename = "sfepy.c0.dat"
    c0dat = open(filename, "w")


    ### plot every 3rd step
    plotstep = 3
    ##### MAIN LOOP #####
    for sfestep, sfetime in tss.ts.iter_from(0):

        ##### print current step and concentration profile
        print("------------------------------sfestep: " + str(sfestep))
        conc = state0.get_parts()['c']
        c0dat.write(str(sfestep) + " " + str(conc[0]) + "\n")
        print (conc)

        #### manual plotting of every plotstep after convergent or divergent criteria
        #### where the next timestep has been solved for
        if (sfestep%plotstep == 0):

            ### plotting
            conc = state0.get_parts()['c']
            fn = genpath + "sfepy." + str(sfestep) + ".dat"
            f = open(fn, "w")
            for i in range(len(conc)):
                f.write(str(conc[i]) + "\n")
            f.close()

        ### solving commands
        state = tss.solve_step(tss.ts, state0)
        state0 = state.copy(deep=True)
        problemInstance.advance(tss.ts)

        #### breaking condition for endtime
        if (sfestep ==15):
            break


    c0dat.close()



if __name__ == '__main__':
    main()
