njzjz / Pyforce

A custom package for LAMMPS, adding a fix command for calculating forces with Python.
0 stars 1 forks source link

use a Python C++ wrapper #8

Closed njzjz closed 4 years ago

njzjz commented 5 years ago

refer https://github.com/njzjz/deepmd-kit/blob/esoinn/source/lmp/pair_nnp_esoinn.cpp#353-392

  // jinzhe start esoinn
  PyObject *pmodule = PyImport_ImportModule("force");
  PyObject *pfunc = PyObject_GetAttrString(pmodule, "printforce");
  PyObject *pyarg = PyTuple_New(3);
  PyObject *py_x  = PyList_New(nall*3);
  for (int i = 0; i < nall; i++){
    for (int j = 0; j < 3; j++){
      PyList_SetItem(py_x, i*3+j, PyFloat_FromDouble(x[i][j]));
    }
  }
  PyTuple_SetItem(pyarg, 0, py_x);
  PyObject *py_type = PyList_New(nall);
  for (int i = 0; i < nall; i++){
    PyList_SetItem(py_type, i, PyLong_FromLong(type[i]));
  }
  PyTuple_SetItem(pyarg, 1, py_type);
  PyObject *py_all_force = PyList_New(all_force.size()*all_force[0].size());
  int i=0;
  for (unsigned ii = 0; ii < all_force.size(); ++ii){
    for (unsigned jj = 0; jj < all_force[ii].size(); ++jj){
      PyList_SetItem(py_all_force, i++, PyFloat_FromDouble(all_force[ii][jj]));
    }
  }
  PyTuple_SetItem(pyarg, 2, py_all_force);
  PyObject *pyfesoinn = PyObject_CallObject(pfunc, pyarg);
  if(!pyfesoinn){
     PyErr_Print();
     PyErr_Clear();
     error->all(FLERR,"python error.");
  }
  if(PyList_Check(pyfesoinn)){
    for (int ii = 0; ii < nall; ++ii){
      for (int dd = 0; dd < 3; ++dd){
        dforce[3*ii+dd] = PyFloat_AsDouble(PyList_GetItem(pyfesoinn, 3*ii+dd));
      }
    }
  } else error->all(FLERR,"no forces returned.");
  Py_DECREF(pyfesoinn);
  Py_DECREF(pyarg);
  // jinzhe end
ghost commented 5 years ago

Thanks for opening an issue. I see you haven"t provided all of the information in the list. Please update the issue to include more information.