From aeb034581d7b5d3a5d6a591d7798f7bde6af6c1b Mon Sep 17 00:00:00 2001 From: Anna Bergamaschi Date: Wed, 17 May 2023 18:21:05 +0200 Subject: [PATCH] better implementation --- README.md | 104 +++++++--------------------------- setup.py | 14 +++++ src/Makefile.test | 3 + src/cluster_reader.cpp | 53 ++++++++--------- src/cluster_reader.h | 5 +- src/cluster_reader_module.cpp | 65 ++++++++++----------- src/main.cpp | 35 ++++++++++++ tester.py | 52 +++++++++++++++++ 8 files changed, 184 insertions(+), 147 deletions(-) create mode 100644 setup.py create mode 100644 src/main.cpp create mode 100644 tester.py diff --git a/README.md b/README.md index 3b8f13e..8aa90f8 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,30 @@ -# python_cluster_reader +# python_cpp_example + +Minimal example building a C++ python extension. + +Useful links: + * [Using NumPy C-API](https://numpy.org/doc/stable/user/c-info.html) +### Build instructions -## Getting started +```bash -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +#build in place and use from the same folder +#sometimes necessary to remove build folder and .so +#by hand +python setup.py build_ext --inplace -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: ``` -cd existing_repo -git remote add origin https://git.psi.ch/sls_detectors_software/python_cluster_reader.git -git branch -M main -git push -uf origin main + +To use make sure that the .so and potentially python files are in PYTHONPATH (or installed in developer mode) + +```bash +#conda +conda develop install . + +#or with pip +pip install --editable . ``` -## Integrate with your tools - -- [ ] [Set up project integrations](https://git.psi.ch/sls_detectors_software/python_cluster_reader/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..a98474a --- /dev/null +++ b/setup.py @@ -0,0 +1,14 @@ +import setuptools +import numpy + +c_ext = setuptools.Extension("cluster_reader_cpp", + sources=["src/cluster_reader_module.cpp", "src/cluster_reader.cpp"], + extra_compile_args=['-std=c++11', '-Wall'], + include_dirs=[numpy.get_include()]) +c_ext.language = 'c++' +setuptools.setup( + name='cluster_reader_cpp', + version='0.1', + description='Tools to read cluster files.', + ext_modules=[c_ext], +) diff --git a/src/Makefile.test b/src/Makefile.test index a263aba..de60b8c 100644 --- a/src/Makefile.test +++ b/src/Makefile.test @@ -1,2 +1,5 @@ + + + test: main.cpp cluster_reader.cpp cluster_reader.h g++ -o test main.cpp cluster_reader.cpp -std=c++11 diff --git a/src/cluster_reader.cpp b/src/cluster_reader.cpp index a65e46d..5724680 100644 --- a/src/cluster_reader.cpp +++ b/src/cluster_reader.cpp @@ -1,13 +1,14 @@ #include "cluster_reader.h" #include -#include "single_photon_hit.h" #include FILE *f; int ph_left; + void cpp_open_cluster_file(char *fname, int &ok){ f=fopen(fname,"r"); + ph_left=0; if (f) ok=1; else @@ -17,50 +18,50 @@ void cpp_open_cluster_file(char *fname, int &ok){ void cpp_close_cluster_file(int &ok){ if (f){ fclose(f); + ph_left=0; f=NULL; ok=1; } else ok=0; } - - - -void cpp_read_clusters(int &iiph, std::vector &v, int &ok, int maxframes) { +void cpp_read_clusters(struct cluster *clust, int &iiph, int &nframes, int &ok, int maxph){ iiph=0; int iframe, iff, nph; - //std::vector v={}; - struct cluster *clust; - single_photon_hit cl; - ph_left=0; + ph_left=0; iff=0; ok=0; + iiph=0; + int nn; if (f) { ok=1; while (fread((void*)&iframe, 1, sizeof(int), f)) { if (fread((void*)&nph, 1, sizeof(int), f)) { - ph_lft=nph; + ph_left=nph; if (nph>0) { - for (int iph=0; iphx=cl.x; - clust->y=cl.y; - for (int ix=0; ix<3; ix++) - for (int iy=0; iy<3; iy++) - clust->data[iy*3+ix]=cl.data[iy*3+ix]; - v.push_back(*clust); - iiph++; + // for (int iph=0; iphnph) nn=nph; + else nn=(maxph-iiph); + + if ( fread( (void*)(clust+iiph), sizeof(struct cluster), nn, f) ) { + ph_left=nph-nn; + // if ( fread( (void*)&x, sizeof(int16_t), 1, myFile) ) { //reads x + // if ( fread( (void*)&y, sizeof(int16_t), 1, myFile ) ) //reads y + // return fread( (void*)data, sizeof(int), dx*dy, myFile ); + + + + iiph+=nn; + nframes=iff; + if (iiph>=maxph) + break; } - } } - } iff++; - if (maxframes>0 && iff>maxframes) - break; + } } + //return v; } - //return v; } diff --git a/src/cluster_reader.h b/src/cluster_reader.h index 49a96b3..3460748 100644 --- a/src/cluster_reader.h +++ b/src/cluster_reader.h @@ -1,9 +1,10 @@ #ifndef CLUSTER_READER_H #define CLUSTER_READER_H #include -#include #include +#define MAXPH 100000000 + struct cluster { int16_t x; int16_t y; @@ -11,7 +12,7 @@ struct cluster { int32_t data[9]; } ; -void cpp_read_clusters(int &iiph, std::vector &v, int &ok, int maxframes=-1); +void cpp_read_clusters(struct cluster *clust, int &iiph, int &nframes, int &ok, int maxph=MAXPH); void cpp_open_cluster_file(char *fname, int &ok); diff --git a/src/cluster_reader_module.cpp b/src/cluster_reader_module.cpp index 39c8578..e2c8026 100644 --- a/src/cluster_reader_module.cpp +++ b/src/cluster_reader_module.cpp @@ -1,5 +1,5 @@ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION -#include "function.h" //this is the function that we want to call +#include "cluster_reader.h" //this is the function that we want to call #include #include #include @@ -44,13 +44,15 @@ PyDoc_STRVAR(close_cluster_file_doc, "Read cluster file.\n\n" // Declare functions that should go into the module static PyObject *read_clusters(PyObject *self, PyObject *args); +static PyObject *open_cluster_file(PyObject *self, PyObject *args); +static PyObject *close_cluster_file(PyObject *self, PyObject *args); // This is the module itself static PyMethodDef module_methods[] = {{"open_cluster_file", (PyCFunction)open_cluster_file, METH_VARARGS, open_cluster_file_doc},{"close_cluster_file", (PyCFunction)close_cluster_file, METH_VARARGS, close_cluster_file_doc},{"read_clusters", (PyCFunction)read_clusters, METH_VARARGS, read_clusters_doc}, {NULL, NULL, 0, NULL}}; // Don't touch except the name -static struct PyModuleDef mymod_def = {PyModuleDef_HEAD_INIT, "cluster_reader_mod", +static struct PyModuleDef cluster_reader_module_def = {PyModuleDef_HEAD_INIT, "cluster_reader_module", module_docstring, -1, module_methods}; // Don't touch @@ -63,13 +65,13 @@ PyMODINIT_FUNC PyInit_cluster_reader_cpp(void) { return m; } -static int open_cluster_file(PyObject *self, PyObject *args) { +static PyObject *open_cluster_file(PyObject *self, PyObject *args) { // cout << "Hello there" << endl; // General Kenobi // Python offers a lot of flexibility so the first thing we need to do // is to parse the arguments and make sure we are called with correct // parameters - char *fname; + char *fname=""; if (!PyArg_ParseTuple(args, "s", fname)) return NULL; @@ -77,10 +79,10 @@ static int open_cluster_file(PyObject *self, PyObject *args) { int ok; cpp_open_cluster_file(fname,ok); - return ok; + return Py_BuildValue("i",ok); } -static int close_cluster_file(PyObject *self, PyObject *args) { +static PyObject *close_cluster_file(PyObject *self, PyObject *args) { // cout << "Hello there" << endl; // General Kenobi // Python offers a lot of flexibility so the first thing we need to do @@ -91,7 +93,7 @@ static int close_cluster_file(PyObject *self, PyObject *args) { int ok; cpp_close_cluster_file(ok); - return ok; + return Py_BuildValue("i",ok); } @@ -101,54 +103,45 @@ static PyObject *read_clusters(PyObject *self, PyObject *args) { // Python offers a lot of flexibility so the first thing we need to do // is to parse the arguments and make sure we are called with correct // parameters - PyObject *fname_obj; - PyObject *maxframes_obj; - if (!PyArg_ParseTuple(args, "OO", &_obj, &b_obj)) + PyObject *clust_obj; + //PyObject *maxframes_obj; + if (!PyArg_ParseTuple(args, "O", &clust_obj)) return NULL; // Create two numpy arrays from the passed objects, if possible numpy will // use the underlying buffer, otherwise it will create a copy, for example // if data type is different or we pass in a list. The // NPY_ARRAY_C_CONTIGUOUS flag ensures that we have contiguous memory. - PyObject *a_array = - PyArray_FROM_OTF(a_obj, NPY_UINT16, NPY_ARRAY_C_CONTIGUOUS); - PyObject *d_array = - PyArray_FROM_OTF(b_obj, NPY_UINT64, NPY_ARRAY_C_CONTIGUOUS); - - // If parsing of a or b fails we throw an exception in Python - if (a_array == NULL || d_array == NULL) { + PyObject *clust_array = + PyArray_FROM_OTF(clust_obj, NPY_OBJECT, NPY_ARRAY_C_CONTIGUOUS); + // npy_intp ind=0; + // void* clust_ptr = PyArray_GetPtr((PyArrayObject*)clust_obj, &ind); + + // If parsing of a or b fails we throw an exception in Python + if (clust_array == NULL) { PyErr_SetString( PyExc_TypeError, "Could not convert one of the arguments to a numpy array."); return NULL; } - + int N=MAXPH; + // int N = (int)PyArray_DIM(clust_array, 0); //npy_intp dims[2] = { 400, 400 }; // Create array for return values - PyObject *cluster_array = PyArray_SimpleNew(1, dims, NPY_UINT16); - + // For the C++ function call we need pointers (or another C++ type/data // structure) - uint16_t *a = reinterpret_cast( - PyArray_DATA(reinterpret_cast(a_array))); - uint64_t*b = reinterpret_cast( - PyArray_DATA(reinterpret_cast(d_array))); - uint16_t *result_analog = reinterpret_cast( - PyArray_DATA(reinterpret_cast(result_analog_array))); - uint8_t *result_digital = reinterpret_cast( - PyArray_DATA(reinterpret_cast(result_digital_array))); + struct cluster *clust = reinterpret_cast( + PyArray_DATA(reinterpret_cast(clust_array))); + int nph, nframes,ok; // Now call add wih pointers and size - cpp_decode(a, b, result_analog, result_digital); + cpp_read_clusters(clust,nph,nframes,ok,N); // Clean up - Py_DECREF(a_array); - Py_DECREF(d_array); + Py_DECREF(clust_array); - PyObject *result_tuple = PyTuple_New(2); - PyTuple_SetItem(result_tuple, 0, result_analog_array); - PyTuple_SetItem(result_tuple, 1, result_digital_array); -// return result_analog_array; - return result_tuple; +// return result; + return Py_BuildValue("iii",nph,nframes,ok); } diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..733230f --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,35 @@ +#include "cluster_reader.h" +#include + +using namespace std; + +int main(int argc, char* argv[]) { + + int nph, nframes; + int ok; + struct cluster *clust=new struct cluster[MAXPH]; + cout << "Clusters allocated " << endl; + cpp_open_cluster_file("/mnt/moench_data/Moench_LGAD_SIM_Nov22/moenchLGAD202211/clustW17new/beam_En800eV_-40deg_300V_10us_d0_f5_0.clust",ok); + cout << "File opened " << endl; + cpp_read_clusters(clust, nph,nframes,ok); + cout << "Clusters read " << endl; + cpp_close_cluster_file(ok); + cout << "File closed " << endl; + int iph=0; + // for (int iph=0; iphdata[iy*3+ix]; + // //std::cout << cl.data[iy*3+ix] << "\t"; + // // std::cout << endl; + // } + + // // if (tot>500) + // // std::cout << iph << "\t" << (clust+iph)->x << "\t" << (clust+iph)->y << "\t" << tot << endl; + + // } + cout << nph << "\t"<< nframes<