Why pybind11 converts double to int? - python

I created .pyd file:
#include <pybind11/pybind11.h>
#include <iostream>
#include <typeinfo>
namespace py = pybind11;
int add(int num) {
float a = 1.0;
for (int i = 0; i <= num; i = i + 1) {
a = (a + i)/a;
}
std::cout << "dll is typing: " << a << '\n';
std::cout << typeid(a).name() << std::endl;
return a;
}
PYBIND11_MODULE(py_dll, m) {
m.doc() = "pybind11 py_dll plugin"; // optional module docstring
m.def("add", &add, "Add function", py::arg("num"));
}
I call it from python:
import py_dll
num = 500
a = py_dll.add(num)
print ('python is typing: ', a)
It prints:
Why digit became int? I speak about 22. I expect it to be float 22.8722

This function
int add(int num)
takes an int as parameter and returns an int. The "problem" is not with pybind. Try this to see:
int main() {
auto x = add(42);
std::cout << "return value: " << x << '\n';
std::cout << typeid(x).name() << std::endl;
}
If the function should return a float you have to declare that it returns a float:
float add(int num)

Related

How can I translate this python function to c++?

I am trying to translate a python function to c++ without success. Can someone help me?
The python function receives as input a string S and 2 integers (fragment_size and jump).
The aim of this function is to slice the string S in a number of fragments of length equal to the first integer given by the input (fragment_size) and traverse the whole string S with a step equal to the second integer given by the input (jump).
import sys
# First we read the input and asign it to 3 different variables
S = sys.stdin.readline().strip()
fragment_size = sys.stdin.readline().strip()
jump = sys.stdin.readline().strip()
def window(S, fragment_size, jump):
word = S[:fragment_size]
if len(word)< fragment_size:
return []
else:
return [word] + window(S[jump:], fragment_size, jump)
# We check that S is not an empty string and that fragment_size and jump are bigger than 0.
if len(S) > 0 and int(fragment_size) > 0 and int(jump) > 0:
# We print the results
for i in window(S, int(fragment_size), int(jump)):
print(i)
For example:
Input
ACGGTAGACCT
3
1
Output
ACG
CGG
GGT
GTA
TAG
AGA
GAC
ACC
CCT
Example 2:
Input
ACGGTAGACCT
3
3
Output
ACG
GTA
GAC
I know how to solve this in c++ returning a string in the window function. But I really need to return a list, like the one I am returning in the python program.
Right now, I have this C++ code:
# include <iostream>
# include <vector>
# include <string>
using namespace std;
vector<string> window_list(string word, vector<vector<string>>& outp_list){
outp_list.push_back(word);
}
vector<string> window(string s, int len_suf, int jump){
string word;
vector<vector<string>> outp_list;
word = s.substr(0, len_suf);
if(word.length() < len_suf){
return vector<string> window_list();
}
else {
window_list(word, outp_list);
return window(s.substr(jump), len_suf, jump);
}
}
int main(){
// We define the variables
string s;
int len_suf, jump;
// We read the input and store it to 3 different variables
cin >> s;
cin >> len_suf;
cin >> jump;
// We print the result
vector<string> ans = window(s, len_suf, jump);
for(auto& x: ans){
cout << x << endl;
}
return 0;
}
Thanks!
It does the job, but as I'm not very into C++ Alexandros Palacios approach might be better anyways. This is just a blunt translation of your Python code.
#include <strings.h>
#include <iostream>
#include <vector>
std::string window(std::string S, int fragment_size, int jump) {
for (int i = 0; i <= S.length(); jump) {
std::string word = S.substr(i, i+fragment_size);
if (word.length() < fragment_size) {
return "";
}
else {
return word + " " + window(S.substr(jump, S.length()-1), fragment_size, jump);
}
}
}
int main(int argc, char const *argv[])
{
std::string S;
std::cout << "Enter DNA sequence: ";
std::cin >> S;
int fragment_size;
std::cout << "Enter fragment size: ";
std::cin >> fragment_size;
int jump;
std::cout << "Enter jump size: ";
std::cin >> jump;
std::vector<std::string> data;
std::string result;
if (S.length() > 0 && fragment_size > 0 && jump > 0) {
result = window(S, fragment_size, jump);
} else {
return 1;
}
size_t pos;
std::string delimiter = " ";
while ((pos = result.find(delimiter)) != std::string::npos) {
data.push_back(result.substr(0, pos));
result.erase(0, pos + delimiter.length());
}
for (const auto &str : data) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
Using the string data type you can achieve it without so much problems. Instead of the python [:] operator, you can use the substr method:
#include <iostream>
#include <string.h>
using namespace std;
string S = "";
int fragment_size = 0;
int jump = 0;
char a_result[1024];
string window(string s) {
if (s.length() < fragment_size)
return "";
else
return s.substr(0, fragment_size) + " " + window(s.substr(jump));
}
int main(int argc, char *argv[]) {
cin >> S;
cin >> fragment_size;
cin >> jump;
if (S.length() && fragment_size > 0 && jump > 0) {
string result = window(S);
cout << endl
<< result;
// Get array from the string
strncpy(a_result, result.c_str(), sizeof(a_result));
a_result[sizeof(a_result) - 1] = 0;
}
return 0;
}
Also, in your window function, you have an extra for loop that isn't needed since you return a value after the first iteration.
You can use the program shown in the below example:
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> stringFragmenter(const std::string &inputString, int len, int stepSize)
{
std::string::const_iterator currentBegin = inputString.begin();
std::string::const_iterator end = inputString.end();
std::string::const_iterator currentPosition = currentBegin;
std::vector<std::string> output;
std::string pushedString;
while(currentPosition + len <= end)
{
currentBegin = currentPosition;
std::string::const_iterator currentEnd = currentBegin + len;
while(currentBegin != currentEnd)
{
pushedString+= *currentBegin;
++currentBegin;
}
output.push_back(pushedString);
currentPosition = currentPosition + stepSize;
//clear the pushedString for next iteration
pushedString.clear();
}
return output;
}
int main()
{
std::string inputString;
std::cin >> inputString;
int length;//this denotes the length of string that has to be displayed(stored) at each time
std::cin >> length;
int stepSize;
std::cin >>stepSize;//this denotes the jump size
std::vector<std::string> fragmentedString = stringFragmenter(inputString, length, stepSize);
//print out the elements of the returned vector so that we can confirm if it contains the correct elements
for(const std::string &elem: fragmentedString)
{
std::cout<<elem<<std::endl;
}
return 0;
}
The output of the above program matches with both of your input cases as can be seen here.
In the above program, to enter your input case 1 you should first enter the string ACGGTAGACCT and then the length 3 and then finally the stepSize(or jump size) 1 and the input/output would look like:
ACGGTAGACCT
3
1
ACG
CGG
GGT
GTA
TAG
AGA
GAC
ACC
CCT
which matches with your desired output. Similarly for your input case 2. Check out the output here.

How do i fix a throw error when integrating Python and C++ Code? Is the issue with the way that I am calling the function from Python to c++?

Ok so I am trying to run a program that uses C++ and Python. The C++ code calls functions from the Python code. The code in C++ that is above main() was already provided and is not supposed to be edited. However, I keep getting the following error: Unhandled exception thrown: write access violation.
pValue was nullptr. When running the code with options 1 & 2. How do I fix this?
C++ Code
#include <Python.h>
#include <iostream>
#include <Windows.h>
#include <cmath>
#include <string>
#include <string.h>
using namespace std;
void CallProcedure(string pName)
{
char* procname = new char[pName.length() + 1];
std::strcpy(procname, pName.c_str());
Py_Initialize();
PyObject* my_module = PyImport_ImportModule("PythonCode");
PyErr_Print();
PyObject* my_function = PyObject_GetAttrString(my_module, procname);
PyObject* my_result = PyObject_CallObject(my_function, NULL);
Py_Finalize();
delete[] procname;
}
int callIntFunc(string proc, string param)
{
char* procname = new char[proc.length() + 1];
std::strcpy(procname, proc.c_str());
char* paramval = new char[param.length() + 1];
std::strcpy(paramval, param.c_str());
PyObject* pName, * pModule, * pDict, * pFunc, * pValue = nullptr, * presult = nullptr;
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyUnicode_FromString((char*)"PythonCode");
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, procname);
if (PyCallable_Check(pFunc))
{
pValue = Py_BuildValue("(z)", paramval);
PyErr_Print();
presult = PyObject_CallObject(pFunc, pValue);
PyErr_Print();
}
else
{
PyErr_Print();
}
//printf("Result is %d\n", _PyLong_AsInt(presult));
Py_DECREF(pValue);
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
// clean
delete[] procname;
delete[] paramval;
return _PyLong_AsInt(presult);
}
int callIntFunc(string proc, int param)
{
char* procname = new char[proc.length() + 1];
std::strcpy(procname, proc.c_str());
PyObject* pName, * pModule, * pDict, * pFunc, * pValue = nullptr, * presult = nullptr;
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyUnicode_FromString((char*)"PythonCode");
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, procname);
if (PyCallable_Check(pFunc))
{
pValue = Py_BuildValue("(i)", param);
PyErr_Print();
presult = PyObject_CallObject(pFunc, pValue);
PyErr_Print();
}
else
{
PyErr_Print();
}
//printf("Result is %d\n", _PyLong_AsInt(presult));
Py_DECREF(pValue);
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
// clean
delete[] procname;
return _PyLong_AsInt(presult);
}
void main()
{
int clicked = 0;
do {
int n = 0;
cout << "1: Display a Multiplication Table" << endl << "2: Double a Value" << endl << "3:
Exit" << endl;
cin >> clicked;
switch (clicked) {
case 1:
{ cout << "Please enter a numerical value . . ."<< endl;
cin >> n;
cout << callIntFunc("(MultiplicationTable)",n); }
break;
case 2:
{cout << "Please enter a numerical value . . ."<< endl;
cin >> n;
int dValue = callIntFunc("(DoubleValue)",n);
cout << "Doubled Value: " << dValue << endl; }
break;
case 3:
cout << "You are now exiting the program!" << endl;
break;
default:
cout << "Please enter a valid selection . . ."<< endl;
break;
}
} while (clicked != 3);
}
Python code
import re
import string
def printsomething():
print("Hello from python!")
def PrintMe(v):
print("You sent me: " + v)
return 100
def MultiplicationTable(v):
v = int(v)
for i in range(1, 11):
print(v, " x ", i, " = ", (v * i))
def DoubleValue(v):
return v * 2
def SquareValue(v):
return v * v
Just modify the python function to return 0 as follows;
def MultiplicationTable(v):
v = int(v)
for i in range(1, 11):
print(v, " x ", i, " = ", (v * i))
return 0

Using Boost to exchange python and C Numpy Array

I followed the tutorial on boost::python::numpy, found that numpy's ndarray and array could be shared inside C ++ code, and I found that using the Boost python example, I could call a python function in C ++ with arguments and return.
My goal is that boost python and python exchange numpy array values.
First, I tried to pass the numpy array to the python code with boost python. However, I only found a way to set the pylist to PyList_SET_ITEM by creating a pylist instead of a numpy array.
In C++
//https://docs.python.org/2.0/ext/buildValue.html
PyObject *Convert_Big_Array(long arr[], int length) {
PyObject *pylist, *item;
pylist = PyList_New(length);
if (pylist != NULL)
for (int i = 0; i < length; i++) {
item = PyLong_FromLong(arr[i]);
PyList_SET_ITEM(pylist, i, item);
}
return pylist;
}
int main() {
long arr[5] = { 4,3,2,6,10 };
// Python 3.x Version
Py_SetPythonHome(L"C:\\Users\\User\\Anaconda3");
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *presult;
Py_Initialize();
return 0;
}
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, (char*)"someFunction");
if (PyCallable_Check(pFunc)) {
pValue = Py_BuildValue("(O)", Convert_Big_Array(arr, 5));
PyErr_Print();
presult = PyObject_CallObject(pFunc, pValue);
PyErr_Print();
}
else {
PyErr_Print();
return 0;
}
boost::python::handle<> handle(presult);
std::cout << std::endl << "Python ndarray :" << p::extract<char const *>(p::str(handle)) << std::endl;
Py_DECREF(pValue);
Py_DECREF(pModule);
Py_DECREF(pName);
Py_Finalize();
return 0;
}
In Python
import numpy as np
def someFunction(text):
print(text)
return np.array([1,2,3])
With this code I find it very difficult to pass a very large C int array to Python. Is there a more efficient way?
First, if I can convert a C ++ array to ndarray using np :: from_data and then convert it to PyObject, I think I can pass this object itself to python.
Second, I want to convert PyObject (presult) created with PyObject_CallObject to np :: ndarray format. Now the code is just an example and the output is successful.
In other words, do you know how to convert ndarray (C ++) -> PyObject (C ++), PyObject (numpy c ++) -> ndarray (c ++)?
I got a answer, and post Here for others...
thank you.
//#include <Python.h>
#include <stdlib.h>
#include <boost/python/numpy.hpp>
#include <boost/python.hpp>
#include <iostream>
//
////#define BOOST_PYTHON_STATIC_LIB
//
using namespace boost::python;
namespace np = boost::python::numpy;
//https://stackoverflow.com/questions/10701514/how-to-return-numpy-array-from-boostpython/14232897#14232897
np::ndarray mywrapper() {
std::vector<short> v;
v.push_back(3);
v.push_back(5);
Py_intptr_t shape[1] = { v.size() };
np::ndarray result = np::zeros(1, shape, np::dtype::get_builtin<short>());
std::copy(v.begin(), v.end(), reinterpret_cast<short*>(result.get_data()));
//std::cout <<"C++ Memory Addr : " << std::dec << &result << std::endl;
return result;
}
//https://stackoverflow.com/questions/54904448/boost-python-nullptr-while-extracting-ndarray
int main() {
double t_end = 7;
long arr[5] = { 4,3,2,6,10 };
// Python 3.x Version
Py_SetPythonHome(L"C:\\Users\\YangwooKim\\Anaconda3");
//PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *presult;
Py_Initialize();
np::initialize();
object module = import("__main__");
object name_space = module.attr("__dict__");
exec_file("arbName.py", name_space, name_space);
object MyFunc = name_space["someFunction"];
object result;
//for(int i=0; i<1000000; i++)
result = MyFunc(mywrapper());
//printf("Result is %d\n", PyLong_AsLong(presult));
//np::ndarray py_array = np::from_object(boost::python::object(handle));
//auto k = extract<np::ndarray>();
//np::ndarray k = np::from_object(object);
//np::ndarray k = p::extract<np::ndarray>(object);
//const np::ndarray& ret = k();
auto result_array = extract<numpy::ndarray>(result);
const numpy::ndarray& ret = result_array();
int input_size = ret.shape(0);
short* input_ptr = reinterpret_cast<short*>(ret.get_data());
//std::cout << std::endl
// << "Python ndarray :" << p::extract<char const *>(p::str(object)) << std::endl;
std::cout << std::endl << "Python ndarray :" << input_size << std::endl;
for (int i = 0; i < input_size; ++i)
std::cout <<" " <<*(input_ptr + i) <<std::endl;
//Py_Finalize();
//Py_Finalize();
return 0;
}

How to get strings values from numpy.ndarray of NPY_OBJECT

I am trying to get the names of columns in pandas.DataFrame using C API for python and numpy. I am using Microsoft Visual Studio 2015 under Windows 7 and 64 bit python v3.6. I am able to get to the df.axes[1].values, however when I use PyArray_GETPTR1, the result seems to be invalid.
Here is my code:
// Initialize python
Py_SetPythonHome(L"C:\\Program Files\\Python36");
Py_Initialize();
// Initialize numpy
import_array();
// Build script
PyCompilerFlags flags;
flags.cf_flags = PyCF_SOURCE_IS_UTF8;
PyObject* compiled = Py_CompileStringFlags(
"import numpy as np\n"
"import pandas as pd\n"
"def ReturnDataFrame():\n"
" df = pd.DataFrame({'AAA' : [4,5,6,7], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]})\n"
" return df\n",
"test.py", Py_file_input, &flags
);
PyObject* codeModule = PyImport_ExecCodeModule("test.py", compiled);
// Call the function
PyObject* pFunc = PyObject_GetAttrString(codeModule, "ReturnDataFrame");
PyObject* pReturn = PyObject_CallObject(pFunc, nullptr);
Py_XDECREF(pFunc);
// Display column headers
PyObject* axes = PyObject_GetAttrString(pReturn, "axes");
PyObject* columnLabelsIndex = PyList_GET_ITEM(axes, 1);
PyObject* columns = PyObject_GetAttrString(columnLabelsIndex, "values");
const char* typeName = columns->ob_type->tp_name; // == "numpy.ndarray"
PyArrayObject* columnArray = (PyArrayObject*)columns;
int length = PyArray_DIMS(columnArray)[0];
int elementType = PyArray_TYPE(columnArray); // == NPY_OBJECT
for (int i = 0; i < length; i++)
{
PyObject* pElementValue = (PyObject*)PyArray_GETPTR1(columnArray, i);
typeName = pElementValue->ob_type->tp_name; // invalid
char* str = PyUnicode_AsUTF8(pElementValue);
std::cout << str;
std::cout << " ";
}
std::cout << "\n";
I would appreciate any input on why these values are invalid.

How to use coordinates from an input file with prim's algorithm in order to create circles using pygraphics and C++?

I have looked at many many examples of Prim's Algorithm on here and Google and found no real answer to this question... Please excuse my structure of this problem. I'm terrible with how S/O prints things out.
I have an input file "SmallGraph.txt" that contains a set of coordinates and the number of vertices at the top:
9
50 100
100 150
200 150
300 150
350 100
300 50
200 50
100 50
150 100
I'm having a lot of trouble trying to figure out how to get these input items read so that my while loop will be able to print a "circle" for every vertice mentioned above so I can run Prim's algorithm for a minimum spanning tree.
What code I have so far of me attempting to get something printed out with a while loop. Also, a few classes to implement Prim's algorithm with those points I need to plot through python:
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstring>
#include <math.h> /* pow() function */
// This line allows commonly-used functions to be used without specifying the
// library in which that function is defined. For instance, this line allows
// the use of "cout" rather than the full specification "cout"
using namespace std;
class SetOfIntegers
{
public:
// Constructor. Any setup operation you wish for the class.
SetOfIntegers()
{
members.clear();
} // end constructor
void add(int m) // Add members to set WITHOUT repetition
{
for (auto i : members)
{
if (i == m) return; // no addition of existing member
}
members.push_back(m);
}
int size() { return members.size(); }
void show() { for (auto i: members) cout << i << " "; cout << endl; }
bool isMember(int m)
{
//cout << "isMember(" << m << ") is ";
for (auto i : members)
{
if (i == m)
{
//cout << " true" << endl;
return true;
}
}
//cout << " false" << endl;
return false;
}
private:
vector<int> members;
};
//--------------------------------------------------------------------------
class Point
{
public:
// Constructor. Any setup operation you wish for the class.
Point()
{
x = 0; y = 0;
} // end constructor
Point(int a, int b, int id)
{
x = a; y = b; pointID = id;
} // end constructor
int getX() { return x; }
int getY() { return y; }
int getID() { return pointID; }
private:
int x = 0;
int y = 0;
int pointID = 0;
}; // end class Point
//--------------------------------------------------------------------------
class Edge
{
public:
// Constructor. Any setup operation you wish for the class.
Edge()
{
} // end constructor
Edge(Point ptA, Point ptB)
{
pointA = ptA;
pointB = ptB;
length = sqrt(pow(abs(pointA.getX() - pointB.getX() ), 2) + pow(abs(pointA.getY() - pointB.getY() ), 2) );
} // end constructor
Point getPtA() { return pointA; }
Point getPtB() { return pointB; }
double getLen() { return length; }
int getPtAID() { return pointA.getID(); }
int getPtBID() { return pointB.getID(); }
private:
Point pointA;
Point pointB;
double length;
}; // end class Edge
// NOTE: DO NOT declare with empty parentheses, as vector<Point> myPointvector();
vector<Point> myPointvector; // vector will expand as needed
vector<Edge> MinSpanTree;
// Pass arguments or parameters from command-line execution. argc is the count of
// those parameters, including the executable filename. argv[] is an array of the
// parameters.
int main (int argc, char *argv[])
{
string token;
int xValue, yValue;
ifstream fin;
int coordPairs; // number of coordinate pairs in the file
int ptX, ptY;
vector<Edge> unsortedEdgeVector;
vector<Edge> sortedEdgeVector;
int loopCounter;
int pointCounter = 0;
double MSTLength = 0.0;
// Check the number of arguments. Expected: filename of a file
if (argc != 2) // This check is often hardcoded
{ // If failure in parameters, offer advice for correction
cout << "\nThis program uses command-line argument.\n";
cout << "Usage: a.exe <filename>\n";
exit(0);
}
try // All lines within this block are part of the same exception handler
{
fin.open(argv[1]);
}
catch (exception& ex)
{
cout << ex.what(); // display standard explanation of the exception
exit(0); // exit the program
}
// Read from the file, one token at a time. If the type of token is known, it
// can be read into a corresponding variable type, such as
// in >> x; // Read the first item into an integer variable x.
// in >> str; // Read the next item into a string variable str.
//for (int i = 0; 1 != 10; i++) {
// fin >> ptX[2] >> ptY[2];
//}
//cout << ptX << endl;
// This line provides the graphic window setup.
cout << "800 600 white" << endl;
fin >> coordPairs;
while (fin >> ptX)
{
// Do something with the element read from the file
cout << ptX << endl;
fin >> ptY;
cout << ptY << endl;
cout << "circle " << ptX << " " << ptY << " " << 20 << " seagreen" << endl;
/*
Point dummyPoint(ptX, ptY, pointCounter++);
myPointvector.push_back(dummyPoint); // vector will expand as needed
cout << "Now myPointvector has size " << myPointvector.size() << endl;
*/
} // end while
fin.close();
}
As you can see... I have a while loop in my main function that is attempting to create a "circle" based on ptX and ptY. That's what I'm having trouble with.. How do I read from this input file in order to get these points and get them to create a circle through python? If you notice.. I've attempted a for loop that is currently commented out for reading the file.
I was using the wrong command for requesting information from the input file. I was using the commands:
g++ -std=c++11 PrimMSTAlgor.cpp (Compile the code)
a PrimMSTAlgor.cpp > PrimData.dat (Put data into primData.dat from the .cpp file)
python BearPlot.py PrimData.dat (use python to apply graphics)
The second command is incorrect. I need to use the .txt file as the argument for "a" (the execution).
a SmallGraph.txt > PrimData.dat
What I have is already set up to put the input into the .dat file this way, I just couldn't see it...

Categories

Resources