boost::python::object NotepadPlusWrapper::prompt(boost::python::object promptObj, boost::python::object title, boost::python::object initial)
{
	PromptDialog promptDlg(m_hInst, m_nppHandle);
	const char *cPrompt = NULL;
	const char *cTitle = NULL;
	const char *cInitial = NULL;
	if (!promptObj | !promptObj.is_none())
		cPrompt = (const char *)boost::python::extract<const char *>(promptObj.attr("__str__")());
	if (!title | !title.is_none())
		cTitle= (const char *)boost::python::extract<const char *>(title.attr("__str__")());

	if (!initial | !initial.is_none())
		cInitial = (const char *)boost::python::extract<const char *>(initial.attr("__str__")());

	PromptDialog::PROMPT_RESULT result;
	GILRelease release;
	result = promptDlg.showPrompt(cPrompt, cTitle, cInitial);

    release.reacquire();
	if (PromptDialog::RESULT_OK == result)
	{
		return boost::python::str(promptDlg.getText());
	}
	else
	{
		return boost::python::object();
	}

}
예제 #2
0
    void update(boost::python::object source)
    {
        // See if we have a dictionary-like object.
        if (py_hasattr(source, "items"))
        {
            return this->update(source.attr("items")());
        }
        if (!py_hasattr(source, "__iter__")) {
            THROW_EX(ValueError, "Must provide a dictionary-like object to update()");
        }

        object iter = source.attr("__iter__")();
        while (true) {
            PyObject *pyobj = PyIter_Next(iter.ptr());
            if (!pyobj) break;
            if (PyErr_Occurred()) {
                throw_error_already_set();
            }

            object obj = object(handle<>(pyobj));

            tuple tup = extract<tuple>(obj);
            std::string attr = extract<std::string>(tup[0]);
            std::string value = extract<std::string>(tup[1]);
            setitem(attr, value);
        }
    }
예제 #3
0
/** Converts a one-dimensional numpy vector to eigen VectorXd. */
Eigen::VectorXd fromNumpyVector(py::object vec) {
	assert(("Input numpy matrix is not one dimensional.", py::extract<int>(vec.attr("ndim"))==1));
	vec = np_mod.attr("array")(vec, "float64");
	int size = py::extract<int>(vec.attr("size"));

	double* vec_data = getPointer<double>(vec);
	return Eigen::Map<Eigen::VectorXd>(vec_data, size);
}
예제 #4
0
static Eigen::MatrixXd fromNP(py::object arr) {
  arr = np_mod.attr("array")(arr, "float64");
  int rows = py::extract<int>(arr.attr("shape")[0]);
  int cols = py::extract<int>(arr.attr("shape")[1]);
  Eigen::MatrixXd mat(rows, cols);
  double* p = getPointer<double>(arr);
  memcpy(&mat(0,0), p,  rows*cols*sizeof(double));
  return mat;
}
예제 #5
0
 static void from2dArray(PointCloudT* cloud, py::object arr) {
   arr = np_mod.attr("array")(arr, "float32");
   int npoints = py::extract<int>(arr.attr("shape")[0]);
   int floatfields = py::extract<int>(arr.attr("shape")[1]);
   FAIL_IF_FALSE(floatfields == sizeof(T)/4);
   cloud->resize(npoints);
   float* p = getPointer<float>(arr);
   memcpy(&cloud->points[0], p,  npoints*floatfields*sizeof(float));
 }
예제 #6
0
/** Converts a two-dimensional numpy matrix to eigen MatrixXd. */
Eigen::MatrixXd fromNumpy(py::object mat) {
	assert(("Input numpy matrix is not two dimensional.", py::extract<int>(mat.attr("ndim"))==2));
	mat = np_mod.attr("array")(mat, "float64");
	int rows = py::extract<int>(mat.attr("shape")[0]);
	int cols = py::extract<int>(mat.attr("shape")[1]);

	double* mat_data = getPointer<double>(mat);
	return Eigen::Map<Eigen::MatrixXd>(mat_data, rows, cols);
}
예제 #7
0
 static void from3dArray(PointCloudT* cloud, py::object arr) {
   arr = np_mod.attr("array")(arr, "float32");
   int height = py::extract<int>(arr.attr("shape")[0]);
   int width = py::extract<int>(arr.attr("shape")[1]);
   int floatfields = py::extract<int>(arr.attr("shape")[2]);
   FAIL_IF_FALSE(floatfields==sizeof(T)/4);
   cloud->resize(width*height);
   cloud->height = height;
   cloud->width = width;
   float* p = getPointer<float>(arr);
   memcpy(&cloud->points[0], p,  width*height*floatfields*sizeof(float));
 }
예제 #8
0
파일: numpy.hpp 프로젝트: capoe/soapxx
	/** Constructor. dtype_name determines type of matrices created. */
	numpy_converter( const char * dtype_name = "float64" )
	{
		PyObject* module = ::PyImport_Import( boost::python::object( "numpy" ).ptr() );
		if( ! module  )
		{
			throw std::logic_error( "Could not import numpy" );
		}
		numpy = boost::python::object( boost::python::handle<>( module ) );
		array_type = numpy.attr( "ndarray" );
		array_function = numpy.attr( "array" );
		set_dtype( dtype_name );
	}
예제 #9
0
 static
 void
 setstate(boost::python::object w_obj, boost::python::tuple state)
 {
     using namespace boost::python;
     world& w = extract<world&>(w_obj)();
     
     if (len(state) != 2)
     {
       PyErr_SetObject(PyExc_ValueError,
                       ("expected 2-item tuple in call to __setstate__; got %s"
                        % state).ptr()
           );
       throw_error_already_set();
     }
     
     // restore the object's __dict__
     dict d = extract<dict>(w_obj.attr("__dict__"))();
     d.update(state[0]);
     
     // restore the internal state of the C++ object
     long number = extract<long>(state[1]);
     if (number != 42)
         w.set_secret_number(number);
 }
예제 #10
0
// REVIEW: the poolSize can be pulled from the numeric array
RDKit::INT_VECT MaxMinPicks(MaxMinPicker *picker, python::object distMat,
                            int poolSize, int pickSize,
                            python::object firstPicks, int seed) {
  if (pickSize >= poolSize) {
    throw ValueErrorException("pickSize must be less than poolSize");
  }

  if (!PyArray_Check(distMat.ptr())) {
    throw ValueErrorException("distance mat argument must be a numpy matrix");
  }

  PyArrayObject *copy;
  copy = (PyArrayObject *)PyArray_ContiguousFromObject(distMat.ptr(),
                                                       PyArray_DOUBLE, 1, 1);
  double *dMat = (double *)copy->data;

  RDKit::INT_VECT firstPickVect;
  for (unsigned int i = 0;
       i < python::extract<unsigned int>(firstPicks.attr("__len__")()); ++i) {
    firstPickVect.push_back(python::extract<int>(firstPicks[i]));
  }
  RDKit::INT_VECT res =
      picker->pick(dMat, poolSize, pickSize, firstPickVect, seed);
  Py_DECREF(copy);
  return res;
}
예제 #11
0
T
read_or_default(const boost::python::object &o,
                const char *key,
                T default_value)
{
  // Remember AttributeError for later comparison
  //     boost::python::object attributeError =
  //     boost::python::import("AttributeError");
  try
  {
    const boost::python::object &o2 = o.attr(key);

    boost::python::extract< T > extractor(o2);
    if (extractor.check())
    {
      return extractor;
    }
    else
    {
      return default_value;
    }
  } catch (const boost::python::error_already_set &)
  {
    // https://misspent.wordpress.com/2009/10/11/
    // boost-python-and-handling-python-exceptions/
    PyObject *e, *v, *t;
    PyErr_Fetch(&e, &v, &t);

    return default_value;
  }

  return default_value;
}
예제 #12
0
void SystemMatrix::setToSolution(escript::Data& out, escript::Data& in,
                                 boost::python::object& options) const
{
    if (in.isComplex() || out.isComplex())
    {
        throw PasoException("SystemMatrix::setToSolution: complex arguments not supported.");
    }
    options.attr("resetDiagnostics")();
    Options paso_options(options);
    if (out.getDataPointSize() != getColumnBlockSize()) {
        throw PasoException("solve: column block size does not match the number of components of solution.");
    } else if (in.getDataPointSize() != getRowBlockSize()) {
        throw PasoException("solve: row block size does not match the number of components of  right hand side.");
    } else if (out.getFunctionSpace() != getColumnFunctionSpace()) {
        throw PasoException("solve: column function space and function space of solution don't match.");
    } else if (in.getFunctionSpace() != getRowFunctionSpace()) {
        throw PasoException("solve: row function space and function space of right hand side don't match.");
    }
    out.expand();
    in.expand();
    out.requireWrite();
    in.requireWrite();
    double* out_dp = out.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();        
    double* in_dp = in.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();                
    solve(out_dp, in_dp, &paso_options);
    paso_options.updateEscriptDiagnostics(options);
}
예제 #13
0
void fill_alpha3D_complex(bp::object points, bp::object complex)
{
    typedef     std::map<AlphaSimplex3D::Vertex, unsigned>      ASPointMap;

    Delaunay3D  Dt;
    ASPointMap  point_map;
    unsigned i = 0;
    for (bp::stl_input_iterator<bp::list> pt = points; pt != bp::stl_input_iterator<bp::list>(); ++pt)
    {
        double x = bp::extract<double>((*pt)[0]);
        double y = bp::extract<double>((*pt)[1]);
        double z = bp::extract<double>((*pt)[2]);
        point_map[Dt.insert(Point(x,y,z))] = i++;
    }

    AlphaSimplex3D::SimplexSet simplices;
    fill_simplex_set(Dt, simplices);

    for (AlphaSimplex3D::SimplexSet::const_iterator cur = simplices.begin(); cur != simplices.end(); ++cur)
    {
        
        dp::SimplexVD s;
        for (AlphaSimplex3D::VertexContainer::const_iterator vcur  = cur->vertices().begin(); 
                                                             vcur != cur->vertices().end(); ++vcur)
            s.add(point_map[*vcur]);
        
        s.data() = bp::object(std::make_pair(cur->value(), !cur->attached()));      // regular/critical rather than attached
        complex.attr("append")(s);
    }
}
예제 #14
0
 boost::python::object call_(const char* name,Args... args){
     using namespace boost::python;
     try {
         return context_.attr(name)(args...);
     }
     catch(error_already_set const &){
         PyObject *type,*value,*traceback;
         PyErr_Fetch(&type,&value,&traceback);
         // Construct a message
         std::string message;
         if(value){
             extract<std::string> value_string(value);
             // Check a string can be extracted from the PyObject
             if(value_string.check()){
                 message += value_string() +":\n";
             }
         }
         // There may not be a traceback (e.g. if a syntax error)
         if(value and traceback){
             handle<> type_handle(type);
             handle<> value_handle(allow_null(value));
             handle<> traceback_handle(allow_null(traceback));
             object formatted_list = import("traceback").attr("format_exception")(type_handle,value_handle,traceback_handle);
             for(int i=0;i<len(formatted_list);i++){
                 extract<std::string> line_string(formatted_list[i]);
                 // Check a string can be extracted from the PyObject
                 if(line_string.check()){
                     message += line_string();
                 }
             }
         }
         throw PythonException(message);
     }
 }
예제 #15
0
		static void	toCPP(boost::python::object o, ImmutableTreeMap<T1, T2>& outT)
			{
			outT = ImmutableTreeMap<T1, T2>();

			boost::python::object it = o.attr("__iter__")();

			while(1)
				{
				T1 t1;
				T2 t2;
				
				boost::python::object key;
				try {
					key = it.attr("next")();
					}
				catch(...)
					{
					PyErr_Clear();
					return;
					}

				Converter<T1>::toCPP(key, t1);
				Converter<T2>::toCPP(o[key], t2);
				
				outT = outT + make_pair(t1, t2);
				}
			}
예제 #16
0
    static void set_errors(Tango::DataReadyEventData &event_data, 
	                   boost::python::object &dev_failed)
    {
        Tango::DevFailed df;
        boost::python::object errors = dev_failed.attr("args");
        sequencePyDevError_2_DevErrorList(errors.ptr(), event_data.errors);
    }
예제 #17
0
void TransportProblem::setToSolution(escript::Data& out, escript::Data& u0,
                                     escript::Data& source, double dt,
                                     bp::object& options)
{
    if (out.isComplex() || u0.isComplex() || source.isComplex())
    {
        throw ValueError("setToSolution: complex arguments not supported");
    }
  
    Options paso_options(options);
    options.attr("resetDiagnostics")();
    if (out.getDataPointSize() != getBlockSize()) {
        throw ValueError("setToSolution: block size of solution does not match block size of transport problems.");
    } else if (source.getDataPointSize() != getBlockSize()) {
        throw ValueError("setToSolution: block size of source term does not match block size of transport problems.");
    } else if (out.getFunctionSpace() != getFunctionSpace()) {
        throw ValueError("setToSolution: function spaces of solution and of transport problem don't match.");
    } else if (source.getFunctionSpace() != getFunctionSpace()) {
        throw ValueError("setToSolution: function spaces of source term and of transport problem don't match.");
    } else if (dt <= 0.) {
        throw ValueError("setToSolution: time increment dt needs to be positive.");
    }
    out.expand();
    source.expand();
    u0.expand();
    out.requireWrite();
    source.requireWrite();
    u0.requireWrite();
    double* out_dp = out.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();
    double* u0_dp = u0.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();
    double* source_dp = source.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();
    solve(out_dp, dt, u0_dp, source_dp, &paso_options);
    paso_options.updateEscriptDiagnostics(options);
}
PythonInterpreter::PythonInterpreter() {
  // private constructor
  
  Py_Initialize();
  main_module = import("__main__");
  main_namespace = main_module.attr("__dict__");
  
}
예제 #19
0
    boost::python::object call_(const char* name,Args... args){
        using namespace boost::python;

        // Get the Python GIL (Global Interpreter Lock). Ensure it
        // is released for any of the branches below.
        PyGILState_STATE py_gil_state = PyGILState_Ensure();
        try {
            // Call the Python side context method
            auto method = context_.attr(name);      
            auto result = method(args...);

            // Release the GIL
            PyGILState_Release(py_gil_state);            
            return result;
        }
        catch(error_already_set const &){
            // Get the error
            PyObject *type,*value,*traceback;
            PyErr_Fetch(&type,&value,&traceback);
            // Construct a message
            std::string message;
            if(value){
                extract<std::string> value_string(value);
                // Check a string can be extracted from the PyObject
                if(value_string.check()){
                    message += value_string() +":\n";
                }
            }
            // There may not be a traceback (e.g. if a syntax error)
            if(value and traceback){
                handle<> type_handle(type);
                handle<> value_handle(allow_null(value));
                handle<> traceback_handle(allow_null(traceback));
                object formatted_list = import("traceback").attr("format_exception")(type_handle,value_handle,traceback_handle);
                for(int i=0;i<len(formatted_list);i++){
                    extract<std::string> line_string(formatted_list[i]);
                    // Check a string can be extracted from the PyObject
                    if(line_string.check()){
                        message += line_string();
                    }
                }
            }

            // Release the GIL
            PyGILState_Release(py_gil_state);
            throw PythonException(message);
        }
        catch(const std::exception& exc){
            // Release the GIL
            PyGILState_Release(py_gil_state);
            throw PythonException(exc.what());
        }
        catch(...){
            // Release the GIL
            PyGILState_Release(py_gil_state);
            throw PythonException("Unknown exception");
        }
    }
예제 #20
0
std::string Serialisation::modulePath( boost::python::object &o )
{
	if( !PyObject_HasAttrString( o.ptr(), "__module__" ) )
	{
		return "";
	}
	std::string modulePath = extract<std::string>( o.attr( "__module__" ) );
	std::string objectName;
	if( PyType_Check( o.ptr() ) )
	{
		objectName = extract<std::string>( o.attr( "__name__" ) );
	}
	else
	{
		objectName = extract<std::string>( o.attr( "__class__" ).attr( "__name__" ) );
	}

	typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
	std::string sanitisedModulePath;
	Tokenizer tokens( modulePath, boost::char_separator<char>( "." ) );

	for( Tokenizer::iterator tIt=tokens.begin(); tIt!=tokens.end(); tIt++ )
	{
		if( tIt->compare( 0, 1, "_" )==0 )
		{
			// assume that module path components starting with _ are bogus, and are used only to bring
			// binary components into a namespace.
			continue;
		}
		Tokenizer::iterator next = tIt; next++;
		if( next==tokens.end() && *tIt == objectName )
		{
			// if the last module name is the same as the class name then assume this is just the file the
			// class has been implemented in.
			continue;
		}
		if( sanitisedModulePath.size() )
		{
			sanitisedModulePath += ".";
		}
		sanitisedModulePath += *tIt;
	}

	return sanitisedModulePath;
}
예제 #21
0
    static
    boost::python::tuple
    getstate(boost::python::object w_obj)
    {
        using namespace boost::python;
        world const& w = extract<world const&>(w_obj)();

        return make_tuple(w_obj.attr("__dict__"), w.get_secret_number());
    }
예제 #22
0
 static boost::python::tuple getstate(boost::python::object obj)
 {
     using namespace std;
     const T& tobj = boost::python::extract<const T&>(obj);
     string content = diffpy::serialization_tostring(tobj);
     boost::python::tuple rv = pickledict ?
         boost::python::make_tuple(content, obj.attr("__dict__")) :
         boost::python::make_tuple(content);
     return rv;
 }
예제 #23
0
 py::object GetTraj() {
   TrajArray &traj = m_result->traj;
   py::object out = np_mod.attr("empty")(py::make_tuple(traj.rows(), traj.cols()));
   for (int i = 0; i < traj.rows(); ++i) {
     for (int j = 0; j < traj.cols(); ++j) {
       out[i][j] = traj(i, j);
     }
   }
   return out;
 }
예제 #24
0
std::string Serialisation::classPath( boost::python::object &object )
{
    std::string result = modulePath( object );
    if( result.size() )
    {
        result += ".";
    }
    result += extract<std::string>( object.attr( "__class__" ).attr( "__name__" ) );
    return result;
}
예제 #25
0
    static
    boost::python::tuple
    getstate(boost::python::object w_obj)
    {
        world const& w = boost::python::extract<world const&>(w_obj)();

        return boost::python::make_tuple(
                   w_obj.attr("__dict__"),
                   w.get_secret_number());
    }
예제 #26
0
python::list BulkWrapper(const T &bv1,python::object bvs,double a,double b,
                         double (*metric)(const T &,const T &,double,double),
                         bool returnDistance){
  python::list res;
  unsigned int nbvs=python::extract<unsigned int>(bvs.attr("__len__")());
  for(unsigned int i=0;i<nbvs;++i){
    const T &bv2=python::extract<T>(bvs[i])();
    res.append(SimilarityWrapper(bv1,bv2,a,b,metric,returnDistance));
  }
  return res;
}
예제 #27
0
/** Must be called with GIL locked
 * */
std::string getStrFromPy(bp::object o) {
    PyObject* ptr = o.ptr();
    if (PyBytes_Check(ptr)) {
        return std::string(PyBytes_AsString(ptr),
                PyBytes_Size(ptr));
    }

    bp::object bytes = o.attr("encode")("utf-8");
    ptr = bytes.ptr();
    return std::string(PyBytes_AsString(ptr),
            PyBytes_Size(ptr));
}
예제 #28
0
    static void set_errors(Tango::EventData &event_data, boost::python::object &error)
    {
        PyObject* error_ptr = error.ptr();
        if (PyObject_IsInstance(error_ptr, PyTango_DevFailed.ptr()))
        {
            Tango::DevFailed df;
	    boost::python::object error_list = error.attr("args");
	    sequencePyDevError_2_DevErrorList(error_list.ptr(), event_data.errors);
        }
        else
        {
            sequencePyDevError_2_DevErrorList(error_ptr, event_data.errors);
        }
    }
예제 #29
0
RDKit::INT_VECT LazyMaxMinPicks(MaxMinPicker *picker, python::object distFunc,
                                int poolSize, int pickSize,
                                python::object firstPicks, int seed,
                                bool useCache) {
  RDKit::INT_VECT firstPickVect;
  for (unsigned int i = 0;
       i < python::extract<unsigned int>(firstPicks.attr("__len__")()); ++i) {
    firstPickVect.push_back(python::extract<int>(firstPicks[i]));
  }
  RDKit::INT_VECT res;
  pyobjFunctor functor(distFunc, useCache);
  res = picker->lazyPick(functor, poolSize, pickSize, firstPickVect, seed);
  return res;
}
예제 #30
0
 PythonContext(void){
     using namespace boost::python;
     // Initialise the interpreter
     Py_Initialize();
     // Get the __main__ module's namespace
     object main = import("__main__");
     object globals = main.attr("__dict__");
     // Execute the Python-side in the glabals namespace
     exec(str(code_()),globals);
     // Create a new Python-side Context
     context_ = globals["Context"]();
     // Bind to the callback
     context_.attr("bind")(raw_function(callback_));
 }