Commit 53c3f600 authored by Steffen Schotthöfer's avatar Steffen Schotthöfer
Browse files

first tests to python integration, not working rn

parent 9e3944a7
#ifndef MLOPTIMIZER_H
#define MLOPTIMIZER_H
#include "optimizerbase.h"
class MLOptimizer : public OptimizerBase
{
public:
MLOptimizer( Config* settings );
inline ~MLOptimizer() {}
void Solve( Vector& lambda, Vector& u, VectorVector& moments, unsigned idx_cell = 0 ) override;
private:
};
#endif // MLOPTIMIZER_H
#ifndef PYHELPER_HPP
#define PYHELPER_HPP
#pragma once
#include <Python.h>
class CPyInstance
{
public:
CPyInstance() { Py_Initialize(); }
~CPyInstance() { Py_Finalize(); }
};
class CPyObject
{
private:
PyObject* p;
public:
CPyObject() : p( NULL ) {}
CPyObject( PyObject* _p ) : p( _p ) {}
~CPyObject() { Release(); }
PyObject* getObject() { return p; }
PyObject* setObject( PyObject* _p ) { return ( p = _p ); }
PyObject* AddRef() {
if( p ) {
Py_INCREF( p );
}
return p;
}
void Release() {
if( p ) {
Py_DECREF( p );
}
p = NULL;
}
PyObject* operator->() { return p; }
bool is() { return p ? true : false; }
operator PyObject*() { return p; }
PyObject* operator=( PyObject* pp ) {
p = pp;
return p;
}
operator bool() { return p ? true : false; }
};
#endif
% This is a comment
%%%%%%%%%%%%%%%%%%%%%%
% Example config file
%
% ---- File specifications ----
%
% Output directory
OUTPUT_DIR = ../result
% Output file
OUTPUT_FILE = example_IC3_lCFL
% Log directory
LOG_DIR = ../result/logs
% Mesh File
MESH_FILE = linesource.su2
%
PROBLEM = ELECTRONRT
%
% ---- Solver specifications ----
%
% Solver type
SOLVER = SN_SOLVER
% Slowing down approximation
CONTINUOUS_SLOWING_DOWN = YES
% CFL number
CFL_NUMBER = 0.9
% Final time for simulation
TIME_FINAL = 0.5
%
CLEAN_FLUX_MATRICES = NO
% ---- Boundary Conditions ----
% Example: BC_DIRICLET = (dummyMarker1, dummyMarker2)
% Dirichlet Boundary
BC_DIRICHLET = ( void )
%
%% Quadrature Specifications
% Quadrature Type
QUAD_TYPE = MONTE_CARLO
% Quadrature Order
QUAD_ORDER = 2
% ---- File specifications ----
OUTPUT_DIR = ../result
OUTPUT_FILE = linesource
LOG_DIR = ../result/logs
MESH_FILE = linesource.su2
% ---- Solver specifications ----
CFL_NUMBER = 0.3
TIME_FINAL = 0.1
PROBLEM = LINESOURCE
RECONS_ORDER = 1
% ---- Boundary Conditions ----
BC_NEUMANN = ( void )
QUAD_TYPE = LEBEDEV
QUAD_ORDER = 47
#imports
import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
# make the network a gobal variable here
#model = tf.python.keras.engine.sequential.Sequential()
#tf.keras.Model()
def call_network(input):
inputNP = np.asarray([input])
model = tf.keras.models.load_model('saved_model/my_model')
print("input")
print(inputNP)
predictions = model.predict(inputNP)
print("network called")
print(predictions)
print(predictions[0])
print("python out")
print(predictions[0].shape)
print(np.zeros(4).shape)
output = np.zeros(4)
for i in range(0, 3):
output[i] = predictions[0, i]
return output
def initialize_network():
# Load model
model = tf.keras.models.load_model('saved_model/my_model')
# Check its architecture
model.summary()
print("network initizalized")
return 0
def main():
input = [0,1,2,3]
initialize_network()
call_network(input)
return 0
if __name__ == '__main__':
main()
......@@ -29,6 +29,8 @@
#include "mesh.h"
#include "settings/config.h"
#include "settings/typedef.h"
using vtkPointsSP = vtkSmartPointer<vtkPoints>;
using vtkUnstructuredGridSP = vtkSmartPointer<vtkUnstructuredGrid>;
using vtkTriangleSP = vtkSmartPointer<vtkTriangle>;
......
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#include "toolboxes/errormessages.h"
#include <mpi.h>
#include "io.h"
......@@ -11,22 +17,19 @@
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
// ----
int main( int argc, char** argv ) {
MPI_Init( &argc, &argv );
// wchar_t* program = Py_DecodeLocale( argv[0], NULL );
// Py_SetProgramName( program );
std::string filename = ParseArguments( argc, argv );
// CD Load Settings from File
Config* config = new Config( filename );
// Test the physics reader
// Physics testPhysic();
// testPhysic.ReadENDL( "ENDL_H.txt" );
// Print input file and run info to file
PrintLogHeader( filename );
......@@ -37,7 +40,85 @@ int main( int argc, char** argv ) {
solver->Solve();
solver->Save();
// if( Py_IsInitialized() ) Py_Finalize();
MPI_Finalize();
return EXIT_SUCCESS;
// // Initialize the Python Interpreter
// std::string pyPath = RTSN_PYTHON_PATH;
//
// if( !Py_IsInitialized() ) {
// Py_InitializeEx( 0 );
// if( !Py_IsInitialized() ) {
// ErrorMessages::Error( "Python init failed!", CURRENT_FUNCTION );
// }
// PyRun_SimpleString( ( "import sys\nsys.path.append('" + pyPath + "')" ).c_str() );
// }
//
// PyObject *pArgs, *pReturn, *pModule, *pFunc;
// PyArrayObject* np_ret;
//
// std::string moduleName = "callNN";
// pModule = PyImport_ImportModule( moduleName.c_str() );
// if( !pModule ) {
// PyErr_Print();
// ErrorMessages::Error( "'" + moduleName + "' can not be imported!", CURRENT_FUNCTION );
// }
//
// // pFunc = PyObject_GetAttrString( pModule, "initialize_network" );
// // if( !pFunc || !PyCallable_Check( pFunc ) ) {
// // PyErr_Print();
// // Py_DecRef( pModule );
// // Py_DecRef( pFunc );
// // ErrorMessages::Error( "'initialize_network' is null or not callable!", CURRENT_FUNCTION );
// // }
// //
// // // pArgs = PyTuple_New(); // No arguments ==> need empty tuple as arguments
// // PyObject_CallObject( pFunc, NULL ); // No return value
//
// pFunc = PyObject_GetAttrString( pModule, "call_network" );
// if( !pFunc || !PyCallable_Check( pFunc ) ) {
// PyErr_Print();
// Py_DecRef( pModule );
// Py_DecRef( pFunc );
// ErrorMessages::Error( "'call_network' is null or not callable!", CURRENT_FUNCTION );
// }
//
// // -----------------
// // std::string imageName = "testimageName";
// // std::string SU2Filename = "SU2Filenametest";
// //
// // auto image = PyUnicode_FromString( imageName.c_str() );
//
// double solutionOneCell[4] = { 0.0, 0.1, 0.2, 0.3 };
//
// const long int dims[1] = { 4 };
//
// import_array();
// PyObject* inputArray = PyArray_SimpleNewFromData( 1, dims, NPY_DOUBLE, (void*)solutionOneCell );
//
// pArgs = PyTuple_New( 1 );
// PyTuple_SetItem( pArgs, 0, reinterpret_cast<PyObject*>( inputArray ) );
//
// // -------------
// pReturn = PyObject_CallObject( pFunc, pArgs ); // PyObject
//
// np_ret = reinterpret_cast<PyArrayObject*>( pReturn ); // Cast from PyObject to PyArrayObject
//
// // size_t m{ static_cast<size_t>( PyArray_SHAPE( np_ret )[0] ) };
// // size_t n{ static_cast<size_t>( PyArray_SHAPE( np_ret )[1] ) };
// double* c_out = reinterpret_cast<double*>( PyArray_DATA( np_ret ) );
//
// for( unsigned i = 0; i < 4; i++ ) {
// std::cout << c_out[i] << std::endl;
// }
//
// // Finalizing
// Py_DecRef( pFunc );
// Py_DecRef( pModule );
// Py_DECREF( np_ret );
//
// // Finish the Python Interpreter
//
// Py_Finalize();
//
return 0;
}
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#include "optimizers/mloptimizer.h"
#include "settings/config.h"
#include "toolboxes/errormessages.h"
MLOptimizer::MLOptimizer( Config* settings ) : OptimizerBase( settings ) {
// test
// Test
}
void MLOptimizer::Solve( Vector& lambda, Vector& u, VectorVector& moments, unsigned idx_cell ) {
// Initialize the Python Interpreter
std ::string pyPath = RTSN_PYTHON_PATH;
if( !Py_IsInitialized() ) {
Py_InitializeEx( 0 );
if( !Py_IsInitialized() ) {
ErrorMessages::Error( "Python init failed!", CURRENT_FUNCTION );
}
PyRun_SimpleString( ( "import sys\nsys.path.append('" + pyPath + "')" ).c_str() );
}
import_array(); // Dont know what it does, but otherwise we get a segfault DOUBLE CHECK
if( PyErr_Occurred() ) std::cout << "error!!!\n";
// Declare Objects
PyObject *pArgs, *pReturn, *pModule, *pFunc;
PyArrayObject* np_ret;
// Import module
std::string moduleName = "callNN";
pModule = PyImport_ImportModule( moduleName.c_str() );
if( !pModule ) {
PyErr_Print();
ErrorMessages::Error( "'" + moduleName + "' can not be imported!", CURRENT_FUNCTION );
}
// Call the Neural Network as a function
pFunc = PyObject_GetAttrString( pModule, "call_network" );
if( !pFunc || !PyCallable_Check( pFunc ) ) {
PyErr_Print();
Py_DecRef( pModule );
Py_DecRef( pFunc );
ErrorMessages::Error( "'call_network' is null or not callable!", CURRENT_FUNCTION );
}
// REPLACE THAT BY A PROPER CAST
double cell_solution[4];
const long int dims[1] = { 4 };
for( unsigned idx_sys = 0; idx_sys < u.size(); idx_sys++ ) {
cell_solution[idx_sys] = u[idx_sys];
std::cout << "," << u[idx_sys] << " ";
}
std::cout << std::endl;
// double solutionOneCell[4] = { 0.0, 0.1, 0.2, 0.3 };
//
// const long int dims[1] = { 4 };
std::cout << "check\n";
std::cout << "check1\n";
// Cast solution array to a Python object
PyObject* inputArray = PyArray_SimpleNewFromData( 1, dims, NPY_DOUBLE, (void*)cell_solution );
std::cout << "check2\n";
// Pack arguments for function call
pArgs = PyTuple_New( 1 );
PyTuple_SetItem( pArgs, 0, reinterpret_cast<PyObject*>( inputArray ) );
// Call the Function
pReturn = PyObject_CallObject( pFunc, pArgs ); // PyObject
// Prepare output ArrayObject
np_ret = reinterpret_cast<PyArrayObject*>( pReturn ); // Cast from PyObject to PyArrayObject
// Cast ArrayObject to c-array
double* tempArrayOutput;
std::cout << "check\n";
tempArrayOutput = reinterpret_cast<double*>( PyArray_DATA( np_ret ) );
std::cout << "check\n";
// Write Back to Vector ==> REPLACE BY PROPER CAST
// for( unsigned idx_sys = 0; idx_sys < u.size(); idx_sys++ ) {
// lambda[idx_sys] = tempArrayOutput[idx_sys];
//}
// Finalizing
Py_DecRef( pFunc );
Py_DecRef( pModule );
Py_DECREF( np_ret );
// Finish the Python Interpreter
Py_Finalize();
delete[] cell_solution;
delete[] tempArrayOutput;
}
#include "optimizers/optimizerbase.h"
#include "optimizers/mloptimizer.h"
#include "optimizers/newtonoptimizer.h"
#include "settings/config.h"
OptimizerBase::OptimizerBase( Config* settings ) {
......@@ -10,7 +12,10 @@ OptimizerBase::OptimizerBase( Config* settings ) {
OptimizerBase* OptimizerBase::Create( Config* settings ) {
switch( settings->GetOptimizerName() ) {
case NEWTON: return new NewtonOptimizer( settings );
// extend to other optimizers
case ML:
return new MLOptimizer( settings );
// extend to other optimizers
default: return new NewtonOptimizer( settings );
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment