void list_keys(py::dict dict) { std::cout << py::len(dict.items()) << " keys in dict:" << std::endl; for(int i=0; i<py::len(dict.items()); ++i) { std::cout << std::string(py::extract<std::string>(dict.items()[i][0])) << std::endl; } }
INT_VECT EmbedMultipleConfs( ROMol &mol, unsigned int numConfs, unsigned int maxAttempts, int seed, bool clearConfs, bool useRandomCoords, double boxSizeMult, bool randNegEig, unsigned int numZeroFail, double pruneRmsThresh, python::dict &coordMap, double forceTol, bool ignoreSmoothingFailures, bool enforceChirality, int numThreads, bool useExpTorsionAnglePrefs, bool useBasicKnowledge, bool printExpTorsionAngles) { std::map<int, RDGeom::Point3D> pMap; python::list ks = coordMap.keys(); unsigned int nKeys = python::extract<unsigned int>(ks.attr("__len__")()); for (unsigned int i = 0; i < nKeys; ++i) { unsigned int id = python::extract<unsigned int>(ks[i]); pMap[id] = python::extract<RDGeom::Point3D>(coordMap[id]); } std::map<int, RDGeom::Point3D> *pMapPtr = 0; if (nKeys) { pMapPtr = &pMap; } INT_VECT res; { NOGIL gil; DGeomHelpers::EmbedMultipleConfs( mol, res, numConfs, numThreads, maxAttempts, seed, clearConfs, useRandomCoords, boxSizeMult, randNegEig, numZeroFail, pruneRmsThresh, pMapPtr, forceTol, ignoreSmoothingFailures, enforceChirality, useExpTorsionAnglePrefs, useBasicKnowledge, printExpTorsionAngles); } return res; }
boost::shared_ptr<ecto::module_<T> > inspect(boost::python::tuple args, boost::python::dict kwargs) { typedef ecto::module_<T> module_t; namespace bp = boost::python; //SHOW(); boost::shared_ptr<module_t> mm(new module_t()); ecto::module * m = mm.get(); m->declare_params(); bp::list l = kwargs.items(); for (int j = 0; j < bp::len(l); ++j) { bp::object key = l[j][0]; bp::object value = l[j][1]; std::string keystring = bp::extract<std::string>(key); std::string valstring = bp::extract<std::string>(value.attr("__repr__")()); m->parameters.at(keystring).set(value); } m->declare_io(); return mm; }
static void writeKeyValueMap( PolymorphicSharedPtr<KeyspaceStorage>& inStorage, boost::python::dict& keysAndValues ) { map<SharedState::Key, KeyState> state; boost::python::list keys = keysAndValues.keys(); long len = boost::python::len(keys); for (long k = 0; k < len; k++) { state[boost::python::extract<SharedState::Key>(keys[k])()] = KeyState( null() << ValueType( null() << PythonWrapper<SharedState::View>::pyToJsonOrError(keysAndValues[keys[k]]), UniqueId() ), null() << UniqueId(), std::map<UniqueId, PartialEvent>() ); } inStorage->writeStateExternal(state); }
/** * If an output workspace was created then extract it from the given dictionary * @param locals A dictionary possibly containing an 'output' reference * @return A pointer to the output workspace if created, otherwise an empty * pointer */ boost::shared_ptr<API::Workspace> RunPythonScript::extractOutputWorkspace( const boost::python::dict &locals) const { using namespace API; using namespace boost::python; // Might be None, string or a workspace object auto pyoutput = locals.get("output"); if (isNone(pyoutput)) return Workspace_sptr(); auto ptrExtract = ExtractWorkspace(pyoutput); if (ptrExtract.check()) { return ptrExtract(); } else { extract<std::string> extractString(pyoutput); if (extractString.check()) { // Will raise an error if the workspace does not exist as the user // requested // an output workspace // but didn't create one. return AnalysisDataService::Instance().retrieve(extractString()); } else { throw std::runtime_error( "Invalid type assigned to 'output' variable. Must " "be a string or a Workspace object"); } } }
unsigned int Compute2DCoords(RDKit::ROMol &mol, bool canonOrient, bool clearConfs, python::dict &coordMap, unsigned int nFlipsPerSample = 3, unsigned int nSamples = 100, int sampleSeed = 100, bool permuteDeg4Nodes = false, double bondLength = -1.0) { RDGeom::INT_POINT2D_MAP cMap; cMap.clear(); python::list ks = coordMap.keys(); for (unsigned int i = 0; i < python::extract<unsigned int>(ks.attr("__len__")()); i++) { unsigned int id = python::extract<unsigned int>(ks[i]); if (id >= mol.getNumAtoms()) { throw_value_error("atom index out of range"); } cMap[id] = python::extract<RDGeom::Point2D>(coordMap[id]); } double oBondLen = RDDepict::BOND_LEN; if (bondLength > 0) { RDDepict::BOND_LEN = bondLength; } unsigned int res; res = RDDepict::compute2DCoords(mol, &cMap, canonOrient, clearConfs, nFlipsPerSample, nSamples, sampleSeed, permuteDeg4Nodes); if (bondLength > 0) { RDDepict::BOND_LEN = oBondLen; } return res; }
void Serializable::pyUpdateAttrs(const boost::python::dict& d){ boost::python::list l=d.items(); size_t ll=boost::python::len(l); if(ll==0) return; for(size_t i=0; i<ll; i++){ boost::python::tuple t=boost::python::extract<boost::python::tuple>(l[i]); string key=boost::python::extract<string>(t[0]); pySetAttr(key,t[1]); } callPostLoad(); }
/** * @param mapping A Python dictionary instance * @return A new C++ PropertyManager instance */ boost::shared_ptr<Kernel::PropertyManager> createPropertyManager(const boost::python::dict &mapping) { auto pmgr = boost::make_shared<PropertyManager>(); #if PY_MAJOR_VERSION >= 3 object view(mapping.attr("items")()); object itemIter(handle<>(PyObject_GetIter(view.ptr()))); #else object itemIter(mapping.attr("iteritems")()); #endif auto length = len(mapping); for (ssize_t i = 0; i < length; ++i) { const object keyValue(handle<>(PyIter_Next(itemIter.ptr()))); const std::string cppkey = extract<std::string>(keyValue[0])(); pmgr->declareProperty(PropertyWithValueFactory::create(cppkey, keyValue[1], Direction::Input)); } return pmgr; }
void clientW::connect(const std::string& uri, const boost::python::dict& query){ std::map<std::string, std::string> newmap; int len = boost::python::len(query); boost::python::list keys = query.keys(); for(int i=0; i < len; i++) { std::string k = boost::python::extract<std::string>(keys[i]); newmap[k] = boost::python::extract<std::string>(query[k]); } this->client::connect(uri,newmap); }
map<string,double> extract_solution(boost::python::dict pySol) { boost::python::list sol_keys = pySol.keys(); map<string,double> sol; for(int iter = 0; iter < len(sol_keys); ++iter) { boost::python::extract<std::string> key(sol_keys[iter]); boost::python::extract<double> value(pySol[sol_keys[iter]]); sol[key] = value; } return sol; }
static mapnik::attributes dict2attr(boost::python::dict const& d) { using namespace boost::python; mapnik::attributes vars; mapnik::transcoder tr_("utf8"); boost::python::list keys=d.keys(); for (int i=0; i < len(keys); ++i) { std::string key = extract<std::string>(keys[i]); object obj = d[key]; if (PyUnicode_Check(obj.ptr())) { PyObject* temp = PyUnicode_AsUTF8String(obj.ptr()); if (temp) { #if PY_VERSION_HEX >= 0x03000000 char* c_str = PyBytes_AsString(temp); #else char* c_str = PyString_AsString(temp); #endif vars[key] = tr_.transcode(c_str); Py_DecRef(temp); } continue; } extract<std::string> ex0(obj); if (ex0.check()) { vars[key] = tr_.transcode(ex0().c_str()); continue; } extract<mapnik::value_integer> ex2(obj); if (ex2.check()) { vars[key] = ex2(); continue; } extract<double> ex3(obj); if (ex3.check()) { vars[key] = ex3(); continue; } extract<mapnik::value_bool> ex1(obj); if (ex1.check()) { vars[key] = ex1(); continue; } } return vars; }
map<string,Vec4d> extract_targets(boost::python::dict target_positions) { boost::python::list target_keys = target_positions.keys(); map<string,Vec4d> target; for( int iter = 0; iter < len(target_keys); ++iter) { boost::python::extract<std::string> key(target_keys[iter]); boost::python::list value = boost::python::extract<boost::python::list>(target_positions[target_keys[iter]]); Vec4d v; assert(len(value) == 4); for(int jter = 0; jter < len(value); ++jter) v.values[jter] = boost::python::extract<double>(value[jter]); target[key] = v; } return target; }
//--------------------------------------------------------------------------- boost::property_tree::ptree make_ptree(const boost::python::dict &args) { using namespace boost::python; boost::property_tree::ptree p; for(stl_input_iterator<tuple> arg(args.items()), end; arg != end; ++arg) { const char *name = extract<const char*>((*arg)[0]); const char *type = extract<const char*>((*arg)[1].attr("__class__").attr("__name__")); if (strcmp(type, "int") == 0) p.put(name, extract<int>((*arg)[1])); else p.put(name, extract<float>((*arg)[1])); } return p; }
const std::string PugAPI::map(const std::string node, const boost::python::dict& d) const { QVariantMap qmap; boost::python::list keys = (boost::python::list)d.iterkeys(); for (int i = 0; i < boost::python::len(keys); i++) { boost::python::object obj = d[keys[i]]; if (PyString_Check(obj.ptr())) { qmap[QString::fromStdString(boost::python::extract<std::string>(keys[i]))] = QString::fromStdString(boost::python::extract<std::string>(obj)); } else if (PyInt_Check(obj.ptr())) { qmap[QString::fromStdString(boost::python::extract<std::string>(keys[i]))] = QVariant(boost::python::extract<int>(obj)); } // ignore things we can't convert } QString qresult = m_root->map(QString::fromStdString(node), qmap); return qresult.toStdString(); }
void add_mrfenergy_class(py::dict cls_dict, py::object key, const std::string& suffix) { typedef typename T::LocalSize LocalSize; typedef typename T::NodeData NodeData; typedef typename T::EdgeData EdgeData; // NodeId is a pointer to a private struct Node. These lines // mask NodeId as an integer value (numeric_pointer). typedef numeric_pointer (MRFEnergy<T>::*add_node_type)(LocalSize, NodeData); typedef void (MRFEnergy<T>::*add_edge_type)(numeric_pointer, numeric_pointer, EdgeData); // Export the MRFEnergy class for the given T. py::object c = py::class_<MRFEnergy<T> >(("MRFEnergy"+suffix).c_str(), "MRF energy representation.", py::init<typename T::GlobalSize>()) .def("add_node", (add_node_type)(&MRFEnergy<T>::AddNode), (py::arg("local_size"), py::arg("node_data"))) .def("add_edge", (add_edge_type)(&MRFEnergy<T>::AddEdge), (py::arg("nodeid1"), py::arg("nodeid2"), py::arg("edge_data"))) .def("minimize_trw", &minimize_trw<T>, "Minimize the energy of the MRF using TRW.", (py::arg("self"), py::arg("eps")=-1, py::arg("itermax")=50, py::arg("printiter")=5, py::arg("printminiter")=0, py::arg("details")=false)) .def("minimize_bp", &minimize_bp<T>, "Minimize the energy of the MRF using BP.", (py::arg("self"), py::arg("eps")=-1, py::arg("itermax")=50, py::arg("printiter")=5, py::arg("printminiter")=0, py::arg("details")=false)) .def("zero_messages", &MRFEnergy<T>::ZeroMessages) .def("set_automatic_ordering", &MRFEnergy<T>::SetAutomaticOrdering) .def("add_grid_nodes", &add_grid_nodes<T>, (py::arg("unary_terms"), py::arg("axis")=0)) .def("add_grid_edges", &add_grid_edges<T>, (py::arg("nodeids"), py::arg("edge_data"))) .def("add_grid_edges_direction", &add_grid_edges_direction<T>, (py::arg("nodeis"), py::arg("edge_data"), py::arg("direction"))) .def("add_grid_edges_direction_local", &add_grid_edges_direction_local<T>, (py::arg("nodeis"), py::arg("edge_data"), py::arg("direction"), py::arg("axis")=0)) .def("get_solution", &get_solution<T>, (py::arg("nodeids"))); cls_dict.attr("__setitem__")(key, c); }
PXR_NAMESPACE_OPEN_SCOPE bool SdfFileFormatArgumentsFromPython( const boost::python::dict& dict, SdfLayer::FileFormatArguments* args, std::string* errMsg) { SdfLayer::FileFormatArguments argsMap; typedef SdfLayer::FileFormatArguments::key_type ArgKeyType; typedef SdfLayer::FileFormatArguments::mapped_type ArgValueType; const boost::python::object items = dict.items(); for (boost::python::ssize_t i = 0; i < len(items); ++i) { boost::python::extract<ArgKeyType> keyExtractor(items[i][0]); if (!keyExtractor.check()) { if (errMsg) { *errMsg = "All file format argument keys must be strings"; } return false; } boost::python::extract<ArgValueType> valueExtractor(items[i][1]); if (!valueExtractor.check()) { if (errMsg) { *errMsg = "All file format argument values must be strings"; } return false; } argsMap[keyExtractor()] = valueExtractor(); } args->swap(argsMap); return true; }