Skip to content

Common Python Interface of Applications for Users

Philipp Bucher edited this page Mar 23, 2018 · 32 revisions

Common Interface

This page describes a common set of functions to be implemented by the Analysis class of each application to make it possible to use the application as an object. This facilitates to combine applications in a single analysis, in a modular way, to do multi-physics and/or co-simulation.

Each application implements a Main Analysis Script (formerly implemented in the MainKratos.py). This script can then be used either for coupling applications or running regular simulation of an individual application.

The Analysis object of each application can be constructed (after importing the script) with ProjectParameters (a Kratos::Parameters object) or by passing the ProjectParameters JSON file.

Once the object of the Analysis for an application is constructed, the simulation can be run using a set of interface functions. These functions are aimed to provide different levels of control over a simulation.

Interface Functions for running a simulation using Analysis object of an application:

The following set of functions are aimed to provide a fine control over the simulation.

  • Initialize Initializes the analysis (called once at the beginning of the simulation)
  • InitializeTimeStep Initializes the Timestep (called once at the beginning of a timestep)
  • SolveTimeStep Solves the time step (can be called several times within a timestep (e.g. strong coupling in FSI) )
  • FinalizeTimeStep Finalizes the Timestep (called once at the end of a timestep)
  • Finalize Finalizes the analysis (called once at the end of the simulation)

In addition to the above mentioned functions, two more functions which allow to execute the whole simulation with less control over the simulation.

  • Run executes the entire analysis
  • RunMainTemporalLoop Executes the entire time loop

Base Class of the Analysis Object (in Kratos Core):

from __future__ import print_function, absolute_import, division  # makes KratosMultiphysics backward compatible with python 2.6 and 2.7

# Importing Kratos
import KratosMultiphysics

class BaseKratosAnalysis(object):
    """The base class for the analysis classes in the applications

    Deriving classes have to implement the _GetSolvingStrategy method
    """
    def __init__(self, project_parameters):
        """The constructor of the Analysis-Object.
        It obtains the project parameters used for the analysis
        This function is intended to be called from the constructor
        of deriving classes:
        super(DerivedAnalysis, self).__init__(project_parameters)
        """
        if (type(project_parameters) == str): # a file name is provided
            with open(project_parameters,'r') as parameter_file:
                self.ProjectParameters = KratosMultiphysics.Parameters(parameter_file.read())
        elif (type(project_parameters) == KratosMultiphysics.Parameters): # a Parameters object is provided
            self.ProjectParameters = project_parameters
        else:
            raise Exception("Input is expected to be provided as a Kratos Parameters object or a file name")

    #### Public functions to run the Analysis ####
    def Run(self):
        """This function executes the entire analysis
        It is NOT intended to be overridden in deriving classes!
        """
        self.Initialize()
        self.RunMainTemporalLoop()
        self.Finalize()

    def RunMainTemporalLoop(self):
        """This function executes the temporal loop of the analysis
        It is NOT intended to be overridden in deriving classes!
        """
        while self.time < self.end_time:
            self.InitializeTimeStep()
            self.SolveTimeStep()
            self.FinalizeTimeStep()

    def Initialize(self):
        """This function initializes the analysis
        Usage: It is designed to be called ONCE, BEFORE the execution of the time-loop
        This function IS intended to be overridden in deriving classes!
        """
        pass

    def InitializeTimeStep(self):
        """This function initializes the time-step
        Usage: It is designed to be called once at the beginning of EACH time-step
        This function IS intended to be overridden in deriving classes!
        """
        pass

    def SolveStep(self):
        """This function solves one step
        This is equivalent to calling "solving_strategy.Solve()" (without "Initialize")
        This function is NOT intended to be overridden in deriving classes!
        """
        solving_strategy = self._GetSolvingStrategy()
        solving_strategy.InitializeSolutionStep()
        solving_strategy.Predict()
        solving_strategy.SolveSolutionStep()
        solving_strategy.FinalizeSolutionStep()


    def FinalizeTimeStep(self):
        """This function finalizes the time-step
        Usage: It is designed to be called once at the end of EACH time-step
        This function IS intended to be overridden in deriving classes!
        """
        pass

    def Finalize(self):
        """This function finalizes the analysis
        Usage: It is designed to be called ONCE, AFTER the execution of the time-loop
        This function IS intended to be overridden in deriving classes!
        """
        pass

    #### Protected functions to run the Analysis ####
    def _GetSolvingStrategy(self):
        """This function returns the solving strategy of the analysis
        It has to be implemented by the deriving class
        """
        pass

The naming convention of this Main Analysis Script is the following: application_name_in_lower_case_analysis.py

e.g. structural_mechanics_analysis.py (for the StructuralMechanicsApplication) or fluid_dynamics_analysis.py (for the FluidDynamicsApplication)

The name of the main class is specified as ApplicationNameAnalysis, e.g. StructuralMechanicsAnalysis, which can be constructed with a Kratos::Parameters object or a project parameters JSON file.

Running an individual full simulation using the Main Analysis Script

The Main Analysis Script script can be also made callable, to perform an individual analysis can be performed by calling python on it.

The following example shows how it can be done (from: StructuralMechanicsApplication)

if __name__ == "__main__":
    from sys import argv

    if len(argv) > 2:
        err_msg =  'Too many input arguments!\n'
        err_msg += 'Use this script in the following way:\n'
        err_msg += '- With default ProjectParameters (read from "ProjectParameters.json"):\n'
        err_msg += '    "python3 structural_mechanics_analysis.py"\n'
        err_msg += '- With custom ProjectParameters:\n'
        err_msg += '    "python3 structural_mechanics_analysis.py CustomProjectParameters.json"\n'
        raise Exception(err_msg)

    if len(argv) == 2: # ProjectParameters is being passed from outside
        project_parameters_file_name = argv[1]
    else: # using default name
        project_parameters_file_name = "ProjectParameters.json"

    StructuralMechanicsAnalysis(project_parameters_file_name).Run()

Using Main Analysis Script in Co-Simulation or Multi-Physics simulation

One of the advantages of having the Main Analysis Script with the Analysis class with the interface functions defined above is that, it makes the usage of two or more Analyses together in a co-simulation. The following code snippet illustrates the same using StructuralMechanics and FluidDynamics analysis objects.

from KratosMultiphysics import *
from structural_mechanics_analysis import *
from fluid_dynamics_analysis import *

structural_analysis = StructuralMechanicsAnalysis(StructureProjectParameters.json)
fluid_analysis = FluidDynamicsAnalysis(FluidProjectParameters.json)

structural_analysis.Initialize()
fluid_analysis.Initialize()

while (time<time_end):
  structural_analysis.InitializeTimeStep()
  fluid_analysis.InitializeTimeStep()
  
  # Transfer data from structural_analysis to fluid_analysis

  fluid_analysis.SolveTimeStep()

  # Transfer data from fluid_analysis to structural_analysis

  structural_analysis.SolveTimeStep()

  structural_analysis.FinalizeTimeStep()
  fluid_analysis.FinalizeTimeStep()  



structural_analysis.Finalize()
fluid_analysis.Finalize() 

Note for developers

It is recommended to embed this script in the application tests in order to ensure that is is working properly

Project information

Getting Started

Tutorials

Developers

Kratos structure

Conventions

Solvers

Debugging, profiling and testing

HOW TOs

Utilities

Kratos API

Kratos Structural Mechanics API

Clone this wiki locally