int main(int argc, char **argv) { int status; char* env = NULL; env = getenv("GPAW_OFFLOAD"); if (env) { errno = 0; gpaw_offload_enabled = strtol(env, NULL, 10); if (errno) { fprintf(stderr, "Wrong value for for GPAW_OFFLOAD.\nShould be either 0 or 1, but was %s\n", env); } } fprintf(stderr, "GPAW info: GPAW_OFFLOAD=%d\n", gpaw_offload_enabled); #ifdef CRAYPAT PAT_region_begin(1, "C-Initializations"); #endif #ifndef GPAW_OMP MPI_Init(&argc, &argv); #else int granted; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &granted); if(granted != MPI_THREAD_MULTIPLE) exit(1); #endif // GPAW_OMP // Get initial timing double t0 = MPI_Wtime(); #ifdef GPAW_PERFORMANCE_REPORT gpaw_perf_init(); #endif #ifdef GPAW_MPI_MAP int tag = 99; int myid, numprocs, i, procnamesize; char procname[MPI_MAX_PROCESSOR_NAME]; MPI_Comm_size(MPI_COMM_WORLD, &numprocs ); MPI_Comm_rank(MPI_COMM_WORLD, &myid ); MPI_Get_processor_name(procname, &procnamesize); if (myid > 0) { MPI_Send(&procnamesize, 1, MPI_INT, 0, tag, MPI_COMM_WORLD); MPI_Send(procname, procnamesize, MPI_CHAR, 0, tag, MPI_COMM_WORLD); } else { printf("MPI_COMM_SIZE is %d \n", numprocs); printf("%s \n", procname); for (i = 1; i < numprocs; ++i) { MPI_Recv(&procnamesize, 1, MPI_INT, i, tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(procname, procnamesize, MPI_CHAR, i, tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("%s \n", procname); } } #endif // GPAW_MPI_MAP #ifdef GPAW_MPI_DEBUG // Default Errhandler is MPI_ERRORS_ARE_FATAL MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN); #endif // Progname seems to be needed in some circumstances to resolve // correct default sys.path Py_SetProgramName(argv[0]); Py_Initialize(); #pragma offload target(mic) if(gpaw_offload_enabled) { init_openmp(); } if (PyType_Ready(&MPIType) < 0) return -1; if (PyType_Ready(&LFCType) < 0) return -1; if (PyType_Ready(&LocalizedFunctionsType) < 0) return -1; if (PyType_Ready(&OperatorType) < 0) return -1; if (PyType_Ready(&SplineType) < 0) return -1; if (PyType_Ready(&TransformerType) < 0) return -1; if (PyType_Ready(&XCFunctionalType) < 0) return -1; if (PyType_Ready(&lxcXCFunctionalType) < 0) return -1; PyObject* m = Py_InitModule3("_gpaw", functions, "C-extension for GPAW\n\n...\n"); if (m == NULL) return -1; Py_INCREF(&MPIType); PyModule_AddObject(m, "Communicator", (PyObject *)&MPIType); // Add initial time to _gpaw object PyModule_AddObject(m, "time0", PyFloat_FromDouble(t0)); Py_INCREF(&LFCType); Py_INCREF(&LocalizedFunctionsType); Py_INCREF(&OperatorType); Py_INCREF(&SplineType); Py_INCREF(&TransformerType); Py_INCREF(&XCFunctionalType); Py_INCREF(&lxcXCFunctionalType); #ifdef GPAW_WITH_HDF5 init_gpaw_hdf5(); #endif import_array1(-1); MPI_Barrier(MPI_COMM_WORLD); #ifdef CRAYPAT PAT_region_end(1); PAT_region_begin(2, "all other"); #endif status = Py_Main(argc, argv); #ifdef CRAYPAT PAT_region_end(2); #endif #ifdef GPAW_PERFORMANCE_REPORT gpaw_perf_finalize(); #endif MPI_Finalize(); return status; }
inline int import_numpy() { #ifdef NUMPY_IMPORT_ARRAY import_array1(-1); import_umath1(-1); #endif return 0; }
Bool eval_jac_g(Index n, Number * x, Bool new_x, Index m, Index nele_jac, Index * iRow, Index * jCol, Number * values, UserDataPtr data) { logger("[Callback:E] eval_jac_g"); DispatchData *myowndata = (DispatchData *) data; UserDataPtr user_data = (UserDataPtr) myowndata->userdata; int i; long *rowd = NULL; long *cold = NULL; /* int dims[1]; */ npy_intp dims[1]; dims[0] = n; double *tempdata; if (myowndata->eval_grad_f_python == NULL) /* Why??? */ PyErr_Print(); if (values == NULL) { /* import_array (); */ import_array1(FALSE); PyObject *arrayx = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); if (!arrayx) return FALSE; PyObject *arglist; if (user_data != NULL) arglist = Py_BuildValue("(OOO)", arrayx, Py_True, (PyObject *) user_data); else arglist = Py_BuildValue("(OO)", arrayx, Py_True); PyObject *result = PyObject_CallObject(myowndata->eval_jac_g_python, arglist); if (!result) { logger("[PyIPOPT] return from eval_jac_g is null\n"); /* TODO: need to deal with reference counting here */ return FALSE; } if (!PyTuple_Check(result)) { PyErr_Print(); } PyArrayObject *row = (PyArrayObject *) PyTuple_GetItem(result, 0); PyArrayObject *col = (PyArrayObject *) PyTuple_GetItem(result, 1); if (!row || !col || !PyArray_Check(row) || !PyArray_Check(col)) { logger ("[Error] there are problems with row or col in eval_jac_g.\n"); PyErr_Print(); } rowd = (long *)row->data; cold = (long *)col->data; for (i = 0; i < nele_jac; i++) { iRow[i] = (Index) rowd[i]; jCol[i] = (Index) cold[i]; } Py_CLEAR(arrayx); Py_DECREF(result); Py_CLEAR(arglist); logger("[Callback:R] eval_jac_g(1)"); } else { PyObject *arrayx = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); if (!arrayx) return FALSE; if (new_x && myowndata->apply_new_python) { /* Call the python function to applynew */ PyObject *arg1 = Py_BuildValue("(O)", arrayx); PyObject *tempresult = PyObject_CallObject(myowndata->apply_new_python, arg1); if (!tempresult) { logger ("[Error] Python function apply_new returns a None\n"); Py_DECREF(arg1); return FALSE; } Py_DECREF(arg1); Py_DECREF(tempresult); } PyObject *arglist; if (user_data != NULL) arglist = Py_BuildValue("(OOO)", arrayx, Py_False, (PyObject *) user_data); else arglist = Py_BuildValue("(OO)", arrayx, Py_False); PyArrayObject *result = (PyArrayObject *) PyObject_CallObject(myowndata->eval_jac_g_python, arglist); if (!result || !PyArray_Check(result)) PyErr_Print(); /* * Code is buggy here. We assume that result is a double * array */ assert(result->descr->type == 'd'); tempdata = (double *)result->data; for (i = 0; i < nele_jac; i++) values[i] = tempdata[i]; Py_DECREF(result); Py_CLEAR(arrayx); Py_CLEAR(arglist); logger("[Callback:R] eval_jac_g(2)"); } logger("[Callback:R] eval_jac_g"); return TRUE; }
Bool eval_g(Index n, Number * x, Bool new_x, Index m, Number * g, UserDataPtr data) { logger("[Callback:E] eval_g"); DispatchData *myowndata = (DispatchData *) data; UserDataPtr user_data = (UserDataPtr) myowndata->userdata; if (myowndata->eval_g_python == NULL) PyErr_Print(); /* int dims[1]; */ npy_intp dims[1]; int i; double *tempdata; dims[0] = n; // import_array (); import_array1(FALSE); /* * PyObject *arrayx = PyArray_FromDimsAndData(1, dims, PyArray_DOUBLE * , (char*) x); */ PyObject *arrayx = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); if (!arrayx) return FALSE; if (new_x && myowndata->apply_new_python) { /* Call the python function to applynew */ PyObject *arg1 = Py_BuildValue("(O)", arrayx); PyObject *tempresult = PyObject_CallObject(myowndata->apply_new_python, arg1); if (!tempresult) { logger ("[Error] Python function apply_new returns a None\n"); Py_DECREF(arg1); return FALSE; } Py_DECREF(arg1); Py_DECREF(tempresult); } PyObject *arglist; if (user_data != NULL) arglist = Py_BuildValue("(OO)", arrayx, (PyObject *) user_data); else arglist = Py_BuildValue("(O)", arrayx); PyArrayObject *result = (PyArrayObject *) PyObject_CallObject(myowndata->eval_g_python, arglist); if (!result) PyErr_Print(); if (!PyArray_Check(result)) PyErr_Print(); tempdata = (double *)result->data; for (i = 0; i < m; i++) { g[i] = tempdata[i]; } Py_DECREF(result); Py_CLEAR(arrayx); Py_CLEAR(arglist); logger("[Callback:R] eval_g"); return TRUE; }
Bool eval_f(Index n, Number * x, Bool new_x, Number * obj_value, UserDataPtr data) { logger("[Callback:E] eval_f"); npy_intp dims[1]; dims[0] = n; DispatchData *myowndata = (DispatchData *) data; UserDataPtr user_data = (UserDataPtr) myowndata->userdata; // import_array (); import_array1(FALSE); PyObject *arrayx = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); if (!arrayx) return FALSE; if (new_x && myowndata->apply_new_python) { /* Call the python function to applynew */ PyObject *arg1; arg1 = Py_BuildValue("(O)", arrayx); PyObject *tempresult = PyObject_CallObject(myowndata->apply_new_python, arg1); if (!tempresult) { logger ("[Error] Python function apply_new returns a None\n"); Py_DECREF(arg1); return FALSE; } Py_DECREF(arg1); Py_DECREF(tempresult); } PyObject *arglist; if (user_data != NULL) arglist = Py_BuildValue("(OO)", arrayx, (PyObject *) user_data); else arglist = Py_BuildValue("(O)", arrayx); PyObject *result = PyObject_CallObject(myowndata->eval_f_python, arglist); if (!result) { PyErr_Print(); Py_DECREF(result); Py_DECREF(arrayx); Py_CLEAR(arglist); return FALSE; } if (!PyFloat_Check(result)) { PyErr_Print(); Py_DECREF(result); Py_DECREF(arrayx); Py_CLEAR(arglist); return FALSE; } *obj_value = PyFloat_AsDouble(result); Py_DECREF(result); Py_DECREF(arrayx); Py_CLEAR(arglist); logger("[Callback:R] eval_f"); return TRUE; }
bool mitk::PythonService::CopyToPythonAsCvImage( mitk::Image* image, const std::string& stdvarName ) { QString varName = QString::fromStdString( stdvarName ); QString command; unsigned int* imgDim = image->GetDimensions(); int npy_nd = 1; // access python module PyObject *pyMod = PyImport_AddModule((char*)"__main__"); // global dictionary PyObject *pyDict = PyModule_GetDict(pyMod); mitk::PixelType pixelType = image->GetPixelType(); PyObject* npyArray = nullptr; mitk::ImageReadAccessor racc(image); void* array = (void*) racc.GetData(); // save the total number of elements here (since the numpy array is one dimensional) npy_intp* npy_dims = new npy_intp[1]; npy_dims[0] = imgDim[0]; /** * Build a string in the format [1024,1028,1] * to describe the dimensionality. This is needed for simple itk * to know the dimensions of the image */ QString dimensionString; dimensionString.append(QString("[")); dimensionString.append(QString::number(imgDim[0])); // ToDo: check if we need this for (unsigned i = 1; i < 3; ++i) // always three because otherwise the 3d-geometry gets destroyed // (relevant for backtransformation of simple itk image to mitk. { dimensionString.append(QString(",")); dimensionString.append(QString::number(imgDim[i])); npy_dims[0] *= imgDim[i]; } dimensionString.append("]"); // the next line is necessary for vectorimages npy_dims[0] *= pixelType.GetNumberOfComponents(); // default pixeltype: unsigned short NPY_TYPES npy_type = NPY_USHORT; if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { npy_type = NPY_DOUBLE; } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { npy_type = NPY_FLOAT; } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { npy_type = NPY_SHORT; } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { npy_type = NPY_BYTE; } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { npy_type = NPY_INT; } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { npy_type = NPY_LONG; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { npy_type = NPY_UBYTE; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { npy_type = NPY_UINT; } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { npy_type = NPY_LONG; } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { npy_type = NPY_USHORT; } else { MITK_WARN << "not a recognized pixeltype"; return false; } // creating numpy array import_array1 (true); npyArray = PyArray_SimpleNewFromData(npy_nd,npy_dims,npy_type,array); // add temp array it to the python dictionary to access it in python code const int status = PyDict_SetItemString( pyDict,QString("%1_numpy_array") .arg(varName).toStdString().c_str(), npyArray ); // sanity check if ( status != 0 ) return false; command.append( QString("import numpy as np\n")); //command.append( QString("if '%1' in globals():\n").arg(varName)); //command.append( QString(" del %1\n").arg(varName)); command.append( QString("%1_array_tmp=%1_numpy_array.copy()\n").arg(varName)); command.append( QString("%1_array_tmp=%1_array_tmp.reshape(%2,%3,%4)\n").arg( varName, QString::number(imgDim[1]), QString::number(imgDim[0]), QString::number(pixelType.GetNumberOfComponents()))); command.append( QString("%1 = %1_array_tmp[:,...,::-1]\n").arg(varName)); command.append( QString("del %1_numpy_array\n").arg(varName) ); command.append( QString("del %1_array_tmp").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute( command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); return true; }
bool mitk::PythonService::CopyToPythonAsSimpleItkImage(mitk::Image *image, const std::string &stdvarName) { QString varName = QString::fromStdString( stdvarName ); QString command; unsigned int* imgDim = image->GetDimensions(); int npy_nd = 1; // access python module PyObject *pyMod = PyImport_AddModule((char*)"__main__"); // global dictionary PyObject *pyDict = PyModule_GetDict(pyMod); const mitk::Vector3D spacing = image->GetGeometry()->GetSpacing(); const mitk::Point3D origin = image->GetGeometry()->GetOrigin(); mitk::PixelType pixelType = image->GetPixelType(); itk::ImageIOBase::IOPixelType ioPixelType = image->GetPixelType().GetPixelType(); PyObject* npyArray = nullptr; mitk::ImageReadAccessor racc(image); void* array = (void*) racc.GetData(); mitk::Vector3D xDirection; mitk::Vector3D yDirection; mitk::Vector3D zDirection; const vnl_matrix_fixed<ScalarType, 3, 3> &transform = image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix(); mitk::Vector3D s = image->GetGeometry()->GetSpacing(); // ToDo: Check if this is a collumn or row vector from the matrix. // right now it works but not sure for rotated geometries mitk::FillVector3D(xDirection, transform[0][0]/s[0], transform[0][1]/s[1], transform[0][2]/s[2]); mitk::FillVector3D(yDirection, transform[1][0]/s[0], transform[1][1]/s[1], transform[1][2]/s[2]); mitk::FillVector3D(zDirection, transform[2][0]/s[0], transform[2][1]/s[1], transform[2][2]/s[2]); // save the total number of elements here (since the numpy array is one dimensional) npy_intp* npy_dims = new npy_intp[1]; npy_dims[0] = imgDim[0]; /** * Build a string in the format [1024,1028,1] * to describe the dimensionality. This is needed for simple itk * to know the dimensions of the image */ QString dimensionString; dimensionString.append(QString("[")); dimensionString.append(QString::number(imgDim[0])); for (unsigned i = 1; i < 3; ++i) // always three because otherwise the 3d-geometry gets destroyed // (relevant for backtransformation of simple itk image to mitk. { dimensionString.append(QString(",")); dimensionString.append(QString::number(imgDim[i])); npy_dims[0] *= imgDim[i]; } dimensionString.append("]"); // the next line is necessary for vectorimages npy_dims[0] *= pixelType.GetNumberOfComponents(); // default pixeltype: unsigned short NPY_TYPES npy_type = NPY_USHORT; std::string sitk_type = "sitkUInt8"; if( ioPixelType == itk::ImageIOBase::SCALAR ) { if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { npy_type = NPY_DOUBLE; sitk_type = "sitkFloat64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { npy_type = NPY_FLOAT; sitk_type = "sitkFloat32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { npy_type = NPY_SHORT; sitk_type = "sitkInt16"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { npy_type = NPY_BYTE; sitk_type = "sitkInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { npy_type = NPY_INT; sitk_type = "sitkInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { npy_type = NPY_LONG; sitk_type = "sitkInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { npy_type = NPY_UBYTE; sitk_type = "sitkUInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { npy_type = NPY_UINT; sitk_type = "sitkUInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { npy_type = NPY_LONG; sitk_type = "sitkUInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { npy_type = NPY_USHORT; sitk_type = "sitkUInt16"; } } else if ( ioPixelType == itk::ImageIOBase::VECTOR || ioPixelType == itk::ImageIOBase::RGB || ioPixelType == itk::ImageIOBase::RGBA ) { if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { npy_type = NPY_DOUBLE; sitk_type = "sitkVectorFloat64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { npy_type = NPY_FLOAT; sitk_type = "sitkVectorFloat32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { npy_type = NPY_SHORT; sitk_type = "sitkVectorInt16"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { npy_type = NPY_BYTE; sitk_type = "sitkVectorInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { npy_type = NPY_INT; sitk_type = "sitkVectorInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { npy_type = NPY_LONG; sitk_type = "sitkVectorInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { npy_type = NPY_UBYTE; sitk_type = "sitkVectorUInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { npy_type = NPY_UINT; sitk_type = "sitkVectorUInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { npy_type = NPY_LONG; sitk_type = "sitkVectorUInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { npy_type = NPY_USHORT; sitk_type = "sitkVectorUInt16"; } } else { MITK_WARN << "not a recognized pixeltype"; return false; } // creating numpy array import_array1 (true); npyArray = PyArray_SimpleNewFromData(npy_nd,npy_dims,npy_type,array); // add temp array it to the python dictionary to access it in python code const int status = PyDict_SetItemString( pyDict,QString("%1_numpy_array") .arg(varName).toStdString().c_str(), npyArray ); // sanity check if ( status != 0 ) return false; command.append( QString("%1 = sitk.Image(%2,sitk.%3,%4)\n").arg(varName) .arg(dimensionString) .arg(QString(sitk_type.c_str())).arg(QString::number(pixelType.GetNumberOfComponents())) ); command.append( QString("%1.SetSpacing([%2,%3,%4])\n").arg(varName) .arg(QString::number(spacing[0])) .arg(QString::number(spacing[1])) .arg(QString::number(spacing[2])) ); command.append( QString("%1.SetOrigin([%2,%3,%4])\n").arg(varName) .arg(QString::number(origin[0])) .arg(QString::number(origin[1])) .arg(QString::number(origin[2])) ); command.append( QString("%1.SetDirection([%2,%3,%4,%5,%6,%7,%8,%9,%10])\n").arg(varName) .arg(QString::number(xDirection[0])) .arg(QString::number(xDirection[1])) .arg(QString::number(xDirection[2])) .arg(QString::number(yDirection[0])) .arg(QString::number(yDirection[1])) .arg(QString::number(yDirection[2])) .arg(QString::number(zDirection[0])) .arg(QString::number(zDirection[1])) .arg(QString::number(zDirection[2])) ); // directly access the cpp api from the lib command.append( QString("_SimpleITK._SetImageFromArray(%1_numpy_array,%1)\n").arg(varName) ); command.append( QString("del %1_numpy_array").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute( command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); return true; }
void CMAC_net::plot_contourf() { Py_Initialize(); import_array1(); PyObject* p_name, *p_module, *p_dict, *p_func, *p_value, *format_expression, *run_expression, *run_script, *traceback_module, *python_module, *traceback_dictionary, *python_dictionary; traceback_module = PyImport_ImportModule("traceback"); python_module = PyImport_ImportModule("python_fun"); if (traceback_module && python_module) { traceback_dictionary = PyModule_GetDict(traceback_module); python_dictionary = PyModule_GetDict(python_module); format_expression = PyDict_GetItemString(traceback_dictionary, "format_expression"); run_expression = PyDict_GetItemString(python_dictionary, "run_expression"); run_script = PyDict_GetItemString(python_dictionary, "run_script"); if (format_expression && run_expression && run_script) { if (PyCallable_Check(format_expression) && PyCallable_Check(run_expression) && PyCallable_Check(run_script)) { } } } fexcp = PyDict_GetItemString(dict1) const int res = 4; float** x = new float* [res]; float** y = new float* [res]; float** z = new float* [res]; x[0] = new float[res]; x[1] = x[0] + res; x[2] = x[1] + res; y[0] = new float[res]; y[1] = y[0] + res; y[2] = y[1] + res; z[0] = new float[res]; z[1] = z[0] + res; z[2] = z[1] + res; int mdim[] = {res, res}; float x_step = interval_width[0] * (float)_tile_resolution / ((float)res - 1); float y_step = interval_width[1] * (float)_tile_resolution / ((float)res - 1); float input_vals[2]; std::ofstream fout; fout.open("plot_contourf_tmp.txt"); for (int i = 0; i < res; i++) { for (int j = 0; j < res; j++) { x[i][j] = _range_inputs[0][0] + x_step * (float)i; y[i][j] = _range_inputs[0][0] + y_step * (float)j; input_vals[0] = x[i][j]; input_vals[1] = y[i][j]; sim(&z[i][j], input_vals); fout << x[i][j] << "," << y[i][j] << "," << z[i][j]; printf("(%.2f,%.2f,%.2f)", x[i][j], y[i][j], z[i][j]); if (j < res - 1) { fout << ","; std::cout << ","; } } fout << std::endl; printf("\n"); } fout.close(); PyObject* x_mat = PyArray_SimpleNewFromData(2, mdim, PyArray_DOUBLE, x[0]); char full_path[256]; char p_path[256]; getcwd(full_path, 255); strcpy(p_path, "sys.path.append(\""); strcat(p_path, full_path); strcat(p_path, "\")"); PyRun_SimpleString("import sys"); PyRun_SimpleString(p_path); p_name = PyString_FromString("py_plot"); p_module = PyImport_Import(p_name); if (p_module == NULL) { printf("Failed to open py_plot.py"); } p_dict = PyModule_GetDict(p_module); p_func = PyDict_GetItemString(p_dict, "plot_contourf"); if (PyCallable_Check(p_func)) { PyObject_CallObject(p_func, NULL); } else { PyErr_Print(); } Py_DECREF(p_module); Py_DECREF(p_name); Py_Finalize(); }
bool mitk::PythonService::CopyToPythonAsSimpleItkImage(mitk::Image *image, const std::string &stdvarName) { QString varName = QString::fromStdString( stdvarName ); QString command; unsigned int* imgDim = image->GetDimensions(); int npy_nd = 1; npy_intp* npy_dims = new npy_intp[1]; npy_dims[0] = imgDim[0] * imgDim[1] * imgDim[2]; // access python module PyObject *pyMod = PyImport_AddModule((char*)"__main__"); // global dictionarry PyObject *pyDict = PyModule_GetDict(pyMod); const mitk::Vector3D spacing = image->GetGeometry()->GetSpacing(); const mitk::Point3D origin = image->GetGeometry()->GetOrigin(); mitk::PixelType pixelType = image->GetPixelType(); itk::ImageIOBase::IOPixelType ioPixelType = image->GetPixelType().GetPixelType(); PyObject* npyArray = NULL; mitk::ImageReadAccessor racc(image); void* array = (void*) racc.GetData(); // default pixeltype: unsigned short NPY_TYPES npy_type = NPY_USHORT; std::string sitk_type = "sitkUInt8"; if( ioPixelType == itk::ImageIOBase::SCALAR ) { if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { npy_type = NPY_DOUBLE; sitk_type = "sitkFloat64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { npy_type = NPY_FLOAT; sitk_type = "sitkFloat32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { npy_type = NPY_SHORT; sitk_type = "sitkInt16"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { npy_type = NPY_BYTE; sitk_type = "sitkInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { npy_type = NPY_INT; sitk_type = "sitkInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { npy_type = NPY_LONG; sitk_type = "sitkInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { npy_type = NPY_UBYTE; sitk_type = "sitkUInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { npy_type = NPY_UINT; sitk_type = "sitkUInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { npy_type = NPY_LONG; sitk_type = "sitkUInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { npy_type = NPY_USHORT; sitk_type = "sitkUInt16"; } } else { MITK_WARN << "not a scalar pixeltype"; return false; } // creating numpy array import_array1 (true); npyArray = PyArray_SimpleNewFromData(npy_nd,npy_dims,npy_type,array); // add temp array it to the python dictionary to access it in python code const int status = PyDict_SetItemString( pyDict,QString("%1_numpy_array") .arg(varName).toStdString().c_str(), npyArray ); // sanity check if ( status != 0 ) return false; command.append( QString("%1 = sitk.Image(%2,%3,%4,sitk.%5)\n").arg(varName) .arg(QString::number(imgDim[0])) .arg(QString::number(imgDim[1])) .arg(QString::number(imgDim[2])) .arg(QString(sitk_type.c_str())) ); command.append( QString("%1.SetSpacing([%2,%3,%4])\n").arg(varName) .arg(QString::number(spacing[0])) .arg(QString::number(spacing[1])) .arg(QString::number(spacing[2])) ); command.append( QString("%1.SetOrigin([%2,%3,%4])\n").arg(varName) .arg(QString::number(origin[0])) .arg(QString::number(origin[1])) .arg(QString::number(origin[2])) ); // directly access the cpp api from the lib command.append( QString("_SimpleITK._SetImageFromArray(%1_numpy_array,%1)\n").arg(varName) ); command.append( QString("del %1_numpy_array").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute( command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); return true; }
bool ImgProc::initNumPy() { import_array1(false); return true; }