better implementation

This commit is contained in:
bergamaschi 2023-05-17 18:21:05 +02:00
parent 569ac6715f
commit aeb034581d
8 changed files with 184 additions and 147 deletions

104
README.md
View File

@ -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.

14
setup.py Normal file
View File

@ -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],
)

View File

@ -1,2 +1,5 @@
test: main.cpp cluster_reader.cpp cluster_reader.h
g++ -o test main.cpp cluster_reader.cpp -std=c++11

View File

@ -1,13 +1,14 @@
#include "cluster_reader.h"
#include <iostream>
#include "single_photon_hit.h"
#include <vector>
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<struct cluster> &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<struct cluster> 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; iph<nph; iph++){
ph_lft--;
if (cl.read(f)) {
clust=new cluster;
clust->x=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++;
}
}
}
}
iff++;
if (maxframes>0 && iff>maxframes)
// for (int iph=0; iph<nph; iph++){
std::cout << iframe << " " << nph << std::endl;
if ((maxph-iiph)>nph) 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++;
}
}
//return v;
}
}

View File

@ -1,9 +1,10 @@
#ifndef CLUSTER_READER_H
#define CLUSTER_READER_H
#include <stdint.h>
#include <vector>
#include <cstdio>
#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<struct cluster> &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);

View File

@ -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 <Python.h>
#include <numpy/arrayobject.h>
#include<iostream>
@ -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);
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 (a_array == NULL || d_array == NULL) {
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<uint16_t *>(
PyArray_DATA(reinterpret_cast<PyArrayObject *>(a_array)));
uint64_t*b = reinterpret_cast<uint64_t *>(
PyArray_DATA(reinterpret_cast<PyArrayObject *>(d_array)));
uint16_t *result_analog = reinterpret_cast<uint16_t *>(
PyArray_DATA(reinterpret_cast<PyArrayObject *>(result_analog_array)));
uint8_t *result_digital = reinterpret_cast<uint8_t *>(
PyArray_DATA(reinterpret_cast<PyArrayObject *>(result_digital_array)));
struct cluster *clust = reinterpret_cast<struct cluster *>(
PyArray_DATA(reinterpret_cast<PyArrayObject *>(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);
}

35
src/main.cpp Normal file
View File

@ -0,0 +1,35 @@
#include "cluster_reader.h"
#include <iostream>
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; iph<nph; iph++){
// int tot=0;
// for (int iy=0; iy<3; iy++) {
// for (int ix=0; ix<3; ix++)
// tot+=(clust+iph)->data[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<<endl;
return 0;
}

52
tester.py Normal file
View File

@ -0,0 +1,52 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pytest
import numpy as np
import mymod
def test_add_two_int():
a = 5
b = 7
#Check for types to make sure that the test is ok
assert type(a) is int
assert type(b) is int
#This is actually what we want to test
assert mymod.add(a,b) == 12
def test_add_int_float():
a = 723
b = 4.98
assert type(a) is int
assert type(b) is float
assert mymod.add(a,b) == pytest.approx(727.98)
def test_add_two_float():
a = 309.123
b = 4.98
assert type(a) is float
assert type(b) is float
assert mymod.add(a,b) == pytest.approx(314.103)
def test_add_two_arrays():
a = np.array((3,4,5))
b = np.array((9,1,3))
c = mymod.add(a,b)
for aa,bb,cc in zip(a,b,c):
assert cc == aa+bb
def test_throws_on_string():
with pytest.raises(TypeError):
mymod.add('a', 7)
def test_throws_when_dims_disagree():
with pytest.raises(ValueError):
mymod.add(3, (4,5))
def test_throws_when_dims_disagree():
a = np.arange(10).reshape(2,5)
b = np.arange(10).reshape(5,2)
with pytest.raises(ValueError):
mymod.add(a, b)