Exemplo n.º 1
0
static PyObject * rotate_vecs_about_axis(PyObject * self, PyObject * args)
{
  PyArrayObject *angles, *axes, *vecs;
  PyArrayObject *rVecs;
  int da, dax, dv;
  npy_intp na, nax0, nax1, nv0, nv1;
  double *aPtr, *axesPtr, *vecsPtr;
  double *rPtr;

  /* Parse arguments */
  if ( !PyArg_ParseTuple(args,"OOO", &angles,&axes,&vecs)) return(NULL);
  if ( angles == NULL || axes == NULL || vecs == NULL ) return(NULL);

  /* Verify shape of input arrays */
  da  = PyArray_NDIM(angles);
  dax = PyArray_NDIM(axes);
  dv  = PyArray_NDIM(vecs);
  assert( da == 1 && dax == 2 && dv == 2 );

  /* Verify dimensions of input arrays */
  na   = PyArray_DIMS(angles)[0];
  nax0 = PyArray_DIMS(axes)[0];
  nax1 = PyArray_DIMS(axes)[1];
  nv0  = PyArray_DIMS(vecs)[0];
  nv1  = PyArray_DIMS(vecs)[1];
  assert( na == 1   || na == nv0 );
  assert( nax0 == 1 || nax0 == nv0 );
  assert( nax1 == 3 && nv1 == 3 );

  /* Allocate the result vectors with appropriate dimensions and type */
  rVecs = (PyArrayObject*)PyArray_EMPTY(2,PyArray_DIMS(vecs),NPY_DOUBLE,0.0);
  assert( rVecs != NULL );

  /* Grab pointers to the various data arrays */
  aPtr    = (double*)PyArray_DATA(angles);
  axesPtr = (double*)PyArray_DATA(axes);
  vecsPtr = (double*)PyArray_DATA(vecs);
  rPtr    = (double*)PyArray_DATA(rVecs);

  /* Call the actual function */
  rotate_vecs_about_axis_cfunc(na,aPtr,nax0,axesPtr,nv0,vecsPtr,rPtr);

  return((PyObject*)rVecs);
}
Exemplo n.º 2
0
static PyObject * makeOscillRotMatArray(PyObject * self, PyObject * args)
{
  PyObject *chiObj;
  double chi;
  PyArrayObject *omeArray, *rMat;
  int doa;
  npy_intp i, no, dims[3];
  double *oPtr, *rPtr;

  /* Parse arguments */
  if ( !PyArg_ParseTuple(args,"OO", &chiObj, &omeArray)) return(NULL);
  if ( chiObj == NULL ) return(NULL);
  if ( omeArray == NULL ) return(NULL);

  /* Get chi */
  chi = PyFloat_AsDouble(chiObj);
  if (chi == -1 && PyErr_Occurred()) return(NULL);

  /* Verify shape of input arrays */
  doa = PyArray_NDIM(omeArray);
  assert( doa == 1 );

  /* Verify dimensions of input arrays */
  no = PyArray_DIMS(omeArray)[0];

  /* Allocate the result matrix with appropriate dimensions and type */
  dims[0] = no; dims[1] = 3; dims[2] = 3;
  rMat = (PyArrayObject*)PyArray_EMPTY(3,dims,NPY_DOUBLE,0);

  /* Grab pointers to the various data arrays */
  oPtr = (double*)PyArray_DATA(omeArray);
  rPtr = (double*)PyArray_DATA(rMat);

  /* Call the actual function repeatedly */
  for (i = 0; i < no; ++i) {
      makeOscillRotMat_cfunc(chi, oPtr[i], rPtr + i*9);
  }

  return((PyObject*)rMat);
}
Exemplo n.º 3
0
/*
    Takes a list of unit reciprocal lattice vectors in crystal frame to the
    specified detector-relative frame, subject to the conditions:

    1) the reciprocal lattice vector must be able to satisfy a bragg condition
    2) the associated diffracted beam must intersect the detector plane

    Required Arguments:
    gVec_c -- (n, 3) ndarray of n reciprocal lattice vectors in the CRYSTAL FRAME
    rMat_d -- (3, 3) ndarray, the COB taking DETECTOR FRAME components to LAB FRAME
    rMat_s -- (3, 3) ndarray, the COB taking SAMPLE FRAME components to LAB FRAME
    rMat_c -- (3, 3) ndarray, the COB taking CRYSTAL FRAME components to SAMPLE FRAME
    tVec_d -- (3, 1) ndarray, the translation vector connecting LAB to DETECTOR
    tVec_s -- (3, 1) ndarray, the translation vector connecting LAB to SAMPLE
    tVec_c -- (3, 1) ndarray, the translation vector connecting SAMPLE to CRYSTAL

    Outputs:
    (m, 2) ndarray containing the intersections of m <= n diffracted beams
    associated with gVecs
*/
static PyObject * gvecToDetectorXY(PyObject * self, PyObject * args)
{
  PyArrayObject *gVec_c,
                *rMat_d, *rMat_s, *rMat_c,
                *tVec_d, *tVec_s, *tVec_c,
                *beamVec;
  PyArrayObject *result;

  int dgc, drd, drs, drc, dtd, dts, dtc, dbv;
  npy_intp npts, dims[2];

  double *gVec_c_Ptr,
         *rMat_d_Ptr, *rMat_s_Ptr, *rMat_c_Ptr,
         *tVec_d_Ptr, *tVec_s_Ptr, *tVec_c_Ptr,
         *beamVec_Ptr;
  double *result_Ptr;

  /* Parse arguments */
  if ( !PyArg_ParseTuple(args,"OOOOOOOO",
			 &gVec_c,
			 &rMat_d, &rMat_s, &rMat_c,
			 &tVec_d, &tVec_s, &tVec_c,
			 &beamVec)) return(NULL);
  if ( gVec_c  == NULL ||
       rMat_d  == NULL || rMat_s == NULL || rMat_c == NULL ||
       tVec_d  == NULL || tVec_s == NULL || tVec_c == NULL ||
       beamVec == NULL ) return(NULL);

  /* Verify shape of input arrays */
  dgc = PyArray_NDIM(gVec_c);
  drd = PyArray_NDIM(rMat_d);
  drs = PyArray_NDIM(rMat_s);
  drc = PyArray_NDIM(rMat_c);
  dtd = PyArray_NDIM(tVec_d);
  dts = PyArray_NDIM(tVec_s);
  dtc = PyArray_NDIM(tVec_c);
  dbv = PyArray_NDIM(beamVec);
  assert( dgc == 2 );
  assert( drd == 2 && drs == 2 && drc == 2 );
  assert( dtd == 1 && dts == 1 && dtc == 1 );
  assert( dbv == 1 );

  /* Verify dimensions of input arrays */
  npts = PyArray_DIMS(gVec_c)[0];

  assert( PyArray_DIMS(gVec_c)[1]  == 3 );
  assert( PyArray_DIMS(rMat_d)[0]  == 3 && PyArray_DIMS(rMat_d)[1] == 3 );
  assert( PyArray_DIMS(rMat_s)[0]  == 3 && PyArray_DIMS(rMat_s)[1] == 3 );
  assert( PyArray_DIMS(rMat_c)[0]  == 3 && PyArray_DIMS(rMat_c)[1] == 3 );
  assert( PyArray_DIMS(tVec_d)[0]  == 3 );
  assert( PyArray_DIMS(tVec_s)[0]  == 3 );
  assert( PyArray_DIMS(tVec_c)[0]  == 3 );
  assert( PyArray_DIMS(beamVec)[0] == 3 );

  /* Allocate C-style array for return data */
  // result_Ptr  = malloc(2*npts*sizeof(double));
  dims[0] = npts; dims[1] = 2;
  result = (PyArrayObject*)PyArray_EMPTY(2,dims,NPY_DOUBLE,0);

  /* Grab data pointers into various arrays */
  gVec_c_Ptr  = (double*)PyArray_DATA(gVec_c);

  rMat_d_Ptr  = (double*)PyArray_DATA(rMat_d);
  rMat_s_Ptr  = (double*)PyArray_DATA(rMat_s);
  rMat_c_Ptr  = (double*)PyArray_DATA(rMat_c);

  tVec_d_Ptr  = (double*)PyArray_DATA(tVec_d);
  tVec_s_Ptr  = (double*)PyArray_DATA(tVec_s);
  tVec_c_Ptr  = (double*)PyArray_DATA(tVec_c);

  beamVec_Ptr = (double*)PyArray_DATA(beamVec);

  result_Ptr     = (double*)PyArray_DATA(result);

  /* Call the computational routine */
  gvecToDetectorXY_cfunc(npts, gVec_c_Ptr,
			 rMat_d_Ptr, rMat_s_Ptr, rMat_c_Ptr,
			 tVec_d_Ptr, tVec_s_Ptr, tVec_c_Ptr,
			 beamVec_Ptr,
			 result_Ptr);

  /* Use the returned pointer to build the result object */
  /* We do this since nadm may be less than npts and the result_Ptr
     may not be the same as the one allocated earlier. */

  /* if ( nadm < npts ) { */
  /*   new_result_Ptr = (double*)realloc(result_Ptr,2*nadm*sizeof(double)); */
  /*   if ( new_result_Ptr != NULL ) result_Ptr = new_result_Ptr; */
  /*   else */
  /*     assert( false ); /\* This really should never happen *\/ */
  /* } */

  /* dims[0] = nadm; */
  /* dims[1] = 2; */
  /* result = (PyArrayObject*)PyArray_SimpleNewFromData(2,dims,NPY_DOUBLE,result_Ptr); */

  /* Build and return the nested data structure */
  return((PyObject*)result);
}
Exemplo n.º 4
0
static PyObject * oscillAnglesOfHKLs(PyObject * self, PyObject * args)
{
  PyArrayObject *hkls, *rMat_c, *bMat,
                *vInv_s, *beamVec, *etaVec;
  PyFloatObject *chi, *wavelength;
  PyArrayObject *oangs0, *oangs1;

  int dhkls, drc, dbm, dvi, dbv, dev;
  npy_intp npts, dims[2];

  double *hkls_Ptr, chi_d,
         *rMat_c_Ptr, *bMat_Ptr, wavelen_d,
         *vInv_s_Ptr, *beamVec_Ptr, *etaVec_Ptr;
  double *oangs0_Ptr, *oangs1_Ptr;

  /* Parse arguments */
  if ( !PyArg_ParseTuple(args,"OOOOOOOO",
			 &hkls, &chi,
			 &rMat_c, &bMat, &wavelength,
			 &vInv_s, &beamVec, &etaVec)) return(NULL);
  if ( hkls    == NULL || chi == NULL ||
       rMat_c  == NULL || bMat == NULL || wavelength == NULL ||
       vInv_s  == NULL || beamVec == NULL || etaVec == NULL ) return(NULL);

  /* Verify shape of input arrays */
  dhkls = PyArray_NDIM(hkls);
  drc   = PyArray_NDIM(rMat_c);
  dbm   = PyArray_NDIM(bMat);
  dvi   = PyArray_NDIM(vInv_s);
  dbv   = PyArray_NDIM(beamVec);
  dev   = PyArray_NDIM(etaVec);
  assert( dhkls == 2 && drc == 2 && dbm == 2 &&
	  dvi   == 1 && dbv == 1 && dev == 1);

  /* Verify dimensions of input arrays */
  npts = PyArray_DIMS(hkls)[0];

  assert( PyArray_DIMS(hkls)[1]    == 3 );
  assert( PyArray_DIMS(rMat_c)[0]  == 3 && PyArray_DIMS(rMat_c)[1] == 3 );
  assert( PyArray_DIMS(bMat)[0]    == 3 && PyArray_DIMS(bMat)[1]   == 3 );
  assert( PyArray_DIMS(vInv_s)[0]  == 6 );
  assert( PyArray_DIMS(beamVec)[0] == 3 );
  assert( PyArray_DIMS(etaVec)[0]  == 3 );

  /* Allocate arrays for return values */
  dims[0] = npts; dims[1] = 3;
  oangs0 = (PyArrayObject*)PyArray_EMPTY(2,dims,NPY_DOUBLE,0);
  oangs1 = (PyArrayObject*)PyArray_EMPTY(2,dims,NPY_DOUBLE,0);

  /* Grab data pointers into various arrays */
  hkls_Ptr    = (double*)PyArray_DATA(hkls);

  chi_d       = PyFloat_AsDouble((PyObject*)chi);
  wavelen_d   = PyFloat_AsDouble((PyObject*)wavelength);

  rMat_c_Ptr  = (double*)PyArray_DATA(rMat_c);
  bMat_Ptr    = (double*)PyArray_DATA(bMat);

  vInv_s_Ptr  = (double*)PyArray_DATA(vInv_s);

  beamVec_Ptr = (double*)PyArray_DATA(beamVec);
  etaVec_Ptr  = (double*)PyArray_DATA(etaVec);

  oangs0_Ptr  = (double*)PyArray_DATA(oangs0);
  oangs1_Ptr  = (double*)PyArray_DATA(oangs1);

  /* Call the computational routine */
  oscillAnglesOfHKLs_cfunc(npts, hkls_Ptr, chi_d,
			   rMat_c_Ptr, bMat_Ptr, wavelen_d,
			   vInv_s_Ptr, beamVec_Ptr, etaVec_Ptr,
			   oangs0_Ptr, oangs1_Ptr);

  // printf("chi = %g, wavelength = %g\n",PyFloat_AsDouble((PyObject*)chi),PyFloat_AsDouble((PyObject*)wavelength));
  /*
np.ascontiguousarray(hkls),chi,rMat_c,bMat,wavelength,
                                               beamVec.flatten(),etaVec.flatten()
  */
  /* Build and return the list data structure */
  return(Py_BuildValue("OO",oangs0,oangs1));
}
Exemplo n.º 5
0
/*
    Takes a list cartesian (x, y) pairs in the detector coordinates and calculates
    the associated reciprocal lattice (G) vectors and (bragg angle, azimuth) pairs
    with respect to the specified beam and azimth (eta) reference directions

    Required Arguments:
    xy_det -- (n, 2) ndarray or list-like input of n detector (x, y) points
    rMat_d -- (3, 3) ndarray, the COB taking DETECTOR FRAME components to LAB FRAME
    rMat_s -- (3, 3) ndarray, the COB taking SAMPLE FRAME components to LAB FRAME
    tVec_d -- (3, 1) ndarray, the translation vector connecting LAB to DETECTOR
    tVec_s -- (3, 1) ndarray, the translation vector connecting LAB to SAMPLE
    tVec_c -- (3, 1) ndarray, the translation vector connecting SAMPLE to CRYSTAL

    Optional Keyword Arguments:
    beamVec -- (1, 3) mdarray containing the incident beam direction components in the LAB FRAME
    etaVec  -- (1, 3) mdarray containing the reference azimuth direction components in the LAB FRAME

    Outputs:
    (n, 2) ndarray containing the (tTh, eta) pairs associated with each (x, y)
    (n, 3) ndarray containing the associated G vector directions in the LAB FRAME
    associated with gVecs
*/
static PyObject * detectorXYToGvec(PyObject * self, PyObject * args)
{
  PyArrayObject *xy_det, *rMat_d, *rMat_s,
		*tVec_d, *tVec_s, *tVec_c,
                *beamVec, *etaVec;
  PyArrayObject *tTh, *eta, *gVec_l;

  int dxy, drd, drs, dtd, dts, dtc, dbv, dev;
  npy_intp npts, dims[2];

  double *xy_Ptr, *rMat_d_Ptr, *rMat_s_Ptr,
         *tVec_d_Ptr, *tVec_s_Ptr, *tVec_c_Ptr,
         *beamVec_Ptr, *etaVec_Ptr;
  double *tTh_Ptr, *eta_Ptr, *gVec_l_Ptr;

  /* Parse arguments */
  if ( !PyArg_ParseTuple(args,"OOOOOOOO",
			 &xy_det,
			 &rMat_d, &rMat_s,
			 &tVec_d, &tVec_s, &tVec_c,
			 &beamVec, &etaVec)) return(NULL);
  if ( xy_det  == NULL || rMat_d == NULL || rMat_s == NULL ||
       tVec_d  == NULL || tVec_s == NULL || tVec_c == NULL ||
       beamVec == NULL || etaVec == NULL ) return(NULL);

  /* Verify shape of input arrays */
  dxy = PyArray_NDIM(xy_det);
  drd = PyArray_NDIM(rMat_d);
  drs = PyArray_NDIM(rMat_s);
  dtd = PyArray_NDIM(tVec_d);
  dts = PyArray_NDIM(tVec_s);
  dtc = PyArray_NDIM(tVec_c);
  dbv = PyArray_NDIM(beamVec);
  dev = PyArray_NDIM(etaVec);
  assert( dxy == 2 && drd == 2 && drs == 2 &&
	  dtd == 1 && dts == 1 && dtc == 1 &&
	  dbv == 1 && dev == 1);

  /* Verify dimensions of input arrays */
  npts = PyArray_DIMS(xy_det)[0];

  assert( PyArray_DIMS(xy_det)[1]  == 2 );
  assert( PyArray_DIMS(rMat_d)[0]  == 3 && PyArray_DIMS(rMat_d)[1] == 3 );
  assert( PyArray_DIMS(rMat_s)[0]  == 3 && PyArray_DIMS(rMat_s)[1] == 3 );
  assert( PyArray_DIMS(tVec_d)[0]  == 3 );
  assert( PyArray_DIMS(tVec_s)[0]  == 3 );
  assert( PyArray_DIMS(tVec_c)[0]  == 3 );
  assert( PyArray_DIMS(beamVec)[0] == 3 );
  assert( PyArray_DIMS(etaVec)[0]  == 3 );

  /* Allocate arrays for return values */
  dims[0] = npts; dims[1] = 3;
  gVec_l = (PyArrayObject*)PyArray_EMPTY(2,dims,NPY_DOUBLE,0);

  tTh    = (PyArrayObject*)PyArray_EMPTY(1,&npts,NPY_DOUBLE,0);
  eta    = (PyArrayObject*)PyArray_EMPTY(1,&npts,NPY_DOUBLE,0);

  /* Grab data pointers into various arrays */
  xy_Ptr      = (double*)PyArray_DATA(xy_det);
  gVec_l_Ptr  = (double*)PyArray_DATA(gVec_l);

  tTh_Ptr     = (double*)PyArray_DATA(tTh);
  eta_Ptr     = (double*)PyArray_DATA(eta);

  rMat_d_Ptr  = (double*)PyArray_DATA(rMat_d);
  rMat_s_Ptr  = (double*)PyArray_DATA(rMat_s);

  tVec_d_Ptr  = (double*)PyArray_DATA(tVec_d);
  tVec_s_Ptr  = (double*)PyArray_DATA(tVec_s);
  tVec_c_Ptr  = (double*)PyArray_DATA(tVec_c);

  beamVec_Ptr = (double*)PyArray_DATA(beamVec);
  etaVec_Ptr  = (double*)PyArray_DATA(etaVec);

  /* Call the computational routine */
  detectorXYToGvec_cfunc(npts, xy_Ptr,
			 rMat_d_Ptr, rMat_s_Ptr,
			 tVec_d_Ptr, tVec_s_Ptr, tVec_c_Ptr,
			 beamVec_Ptr, etaVec_Ptr,
			 tTh_Ptr, eta_Ptr, gVec_l_Ptr);

  /* Build and return the nested data structure */
  return(Py_BuildValue("OO",Py_BuildValue("OO",tTh,eta),gVec_l));
}
Exemplo n.º 6
0
static PyObject* w_store_get(PyObject *dummy, PyObject *args) {
    PyObject *capsule;
    uint64_t irecord;
    store_t *store;
    gf_dtype *adata;
    trace_t trace;
    PyArrayObject *array = NULL;
    npy_intp array_dims[1] = {0};
    int32_t itmin;
    int32_t nsamples;
    int i;
    store_error_t err;

    (void)dummy; /* silence warning */

    if (!PyArg_ParseTuple(args, "OKii", &capsule, &irecord, &itmin, &nsamples)) {
        PyErr_SetString(StoreExtError, "usage store_get(cstore, irecord, itmin, nsamples)");
        return NULL;
    }
#ifdef HAVE_CAPSULE
    if (!PyCapsule_IsValid(capsule, NULL)) {
#else
    if (!PyCObject_Check(capsule)) {
#endif
        PyErr_SetString(StoreExtError, "invalid cstore argument");
        return NULL;
    }
    if (!inlimits(itmin)) {
        PyErr_SetString(StoreExtError, "invalid itmin argument");
        return NULL;
    }
    if (!(inposlimits(nsamples) || -1 == nsamples)) {
        PyErr_SetString(StoreExtError, "invalid nsamples argument");
        return NULL;
    }

#ifdef HAVE_CAPSULE
    store = (store_t*)PyCapsule_GetPointer(capsule, NULL);
#else
    store = (store_t*)PyCObject_AsVoidPtr(capsule);
#endif

    err = store_get(store, irecord, &trace);
    if (SUCCESS != err) {
        PyErr_SetString(StoreExtError, store_error_names[err]);
        return NULL;
    }

    if (-1 != nsamples) {
        trace_trim(&trace, itmin, nsamples);
    }

    array_dims[0] = trace.nsamples;
    array = (PyArrayObject*)PyArray_EMPTY(1, array_dims, NPY_FLOAT32, 0);
    adata = (gf_dtype*)PyArray_DATA(array);
    for (i=0; i<trace.nsamples; i++) {
        adata[i] = fe32toh(trace.data[i]);
    }

    return Py_BuildValue("Nififf", array, trace.itmin, store->deltat,
                         trace.is_zero, trace.begin_value, trace.end_value);
}

static PyObject* w_store_sum(PyObject *dummy, PyObject *args) {
    PyObject *capsule, *irecords_arr, *delays_arr, *weights_arr;
    store_t *store;
    gf_dtype *adata;
    trace_t result;
    PyArrayObject *array = NULL;
    npy_intp array_dims[1] = {0};
    PyArrayObject *c_irecords_arr, *c_delays_arr, *c_weights_arr;
    uint64_t *irecords;
    float32_t *delays, *weights;
    npy_intp n, n1, n2;
    int32_t itmin;
    int32_t nsamples;
    store_error_t err;

    (void)dummy; /* silence warning */

    if (!PyArg_ParseTuple(args, "OOOOii", &capsule, &irecords_arr, &delays_arr,
                                     &weights_arr, &itmin, &nsamples)) {
        PyErr_SetString(StoreExtError,
            "usage: store_sum(cstore, irecords, delays, weights, itmin, nsamples)");

        return NULL;
    }

#ifdef HAVE_CAPSULE
    if (!PyCapsule_IsValid(capsule, NULL)) {
#else
    if (!PyCObject_Check(capsule)) {
#endif
        PyErr_SetString(StoreExtError, "invalid cstore argument");
        return NULL;
    }
    if (!PyArray_Check(irecords_arr) ||
            NPY_UINT64 != PyArray_TYPE((PyArrayObject*)irecords_arr)) {
        PyErr_SetString(StoreExtError,
            "store_sum: 'irecords' must be a NumPy array of type uint64");
        return NULL;
    }
    if (!PyArray_Check(delays_arr) ||
            NPY_FLOAT32 != PyArray_TYPE((PyArrayObject*)delays_arr)) {
        PyErr_SetString(StoreExtError,
            "store_sum: 'delays' must be a NumPy array of type float32");
        return NULL;
    }
    if (!PyArray_Check(weights_arr) ||
            NPY_FLOAT32 != PyArray_TYPE((PyArrayObject*)weights_arr)) {
        PyErr_SetString(StoreExtError,
            "store_sum: 'weights' must be a NumPy array of type float32");
        return NULL;
    }
    if (!inlimits(itmin)) {
        PyErr_SetString(StoreExtError, "invalid itmin argument");
        return NULL;
    }
    if (!(inposlimits(nsamples) || -1 == nsamples)) {
        PyErr_SetString(StoreExtError, "invalid nsamples argument");
        return NULL;
    }
#ifdef HAVE_CAPSULE
    store = (store_t*)PyCapsule_GetPointer(capsule, NULL);
#else
    store = (store_t*)PyCObject_AsVoidPtr(capsule);
#endif

    c_irecords_arr = PyArray_GETCONTIGUOUS((PyArrayObject*)irecords_arr);
    c_delays_arr = PyArray_GETCONTIGUOUS((PyArrayObject*)delays_arr);
    c_weights_arr = PyArray_GETCONTIGUOUS((PyArrayObject*)weights_arr);

    n = PyArray_SIZE(c_irecords_arr);
    n1 = PyArray_SIZE(c_delays_arr);
    n2 = PyArray_SIZE(c_weights_arr);

    if (n != n1 || n != n2) {
        PyErr_SetString(StoreExtError,
            "store_sum: 'irecords', 'delays', and 'weights' must have same length");
        return NULL;
    }

    irecords = PyArray_DATA(c_irecords_arr);
    delays = PyArray_DATA(c_delays_arr);
    weights = PyArray_DATA(c_weights_arr);

    err = store_sum(store, irecords, delays, weights, n, itmin, nsamples, &result);
    if (SUCCESS != err) {
        PyErr_SetString(StoreExtError, store_error_names[err]);
        return NULL;
    }

    Py_DECREF(c_irecords_arr);
    Py_DECREF(c_delays_arr);
    Py_DECREF(c_weights_arr);

    array_dims[0] = result.nsamples;
    array = (PyArrayObject*)PyArray_EMPTY(1, array_dims, NPY_FLOAT32, 0);
    adata = (gf_dtype*)PyArray_DATA(array);
    memcpy(adata, result.data, result.nsamples*sizeof(gf_dtype));
    free(result.data);

    return Py_BuildValue("Nififf", array, result.itmin, store->deltat,
                         result.is_zero, result.begin_value, result.end_value);
}


static PyMethodDef StoreExtMethods[] = {
    {"store_init",  w_store_init, METH_VARARGS,
        "Initialize store struct." },

    {"store_get", w_store_get, METH_VARARGS,
        "Get a GF trace." },

    {"store_sum", w_store_sum, METH_VARARGS,
        "Get weight-and-delay-sum of GF traces." },

    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC
initstore_ext(void)
{
    PyObject *m;

    m = Py_InitModule("store_ext", StoreExtMethods);
    if (m == NULL) return;
    import_array();

    StoreExtError = PyErr_NewException("store_ext.error", NULL, NULL);
    Py_INCREF(StoreExtError);  /* required, because other code could remove `error`
                               from the module, what would create a dangling
                               pointer. */
    PyModule_AddObject(m, "StoreExtError", StoreExtError);
}
Exemplo n.º 7
0
static PyObject *py_kmeans_cuda(PyObject *self, PyObject *args, PyObject *kwargs) {
  uint32_t clusters_size = 0, seed = static_cast<uint32_t>(time(NULL)), device = 0;
  int32_t verbosity = 0;
  float tolerance = .0, yinyang_t = .1;
  PyObject *kmpp = Py_False;
  PyObject *samples_obj;
  static const char *kwlist[] = {"samples", "clusters", "tolerance", "kmpp",
                                 "yinyang_t", "seed", "device", "verbosity", NULL};

  /* Parse the input tuple */
  if (!PyArg_ParseTupleAndKeywords(
      args, kwargs, "OI|fO!fIIi", const_cast<char**>(kwlist),
      &samples_obj, &clusters_size, &tolerance, &PyBool_Type, &kmpp, &yinyang_t,
      &seed, &device, &verbosity)) {
    return NULL;
  }
  if (clusters_size < 2 || clusters_size == UINT32_MAX) {
    PyErr_SetString(PyExc_ValueError, "\"clusters\" must be greater than 1 and "
                                      "less than (1 << 32) - 1");
    return NULL;
  }
  pyobj samples_array(PyArray_FROM_OTF(samples_obj, NPY_FLOAT32, NPY_ARRAY_IN_ARRAY));
  if (samples_array == NULL) {
    PyErr_SetString(PyExc_TypeError, "\"samples\" must be a 2D numpy array");
    return NULL;
  }
  auto ndims = PyArray_NDIM(reinterpret_cast<PyArrayObject*>(samples_array.get()));
  if (ndims != 2) {
    PyErr_SetString(PyExc_ValueError, "\"samples\" must be a 2D numpy array");
    return NULL;
  }
  auto dims = PyArray_DIMS(reinterpret_cast<PyArrayObject*>(samples_array.get()));
  uint32_t samples_size = static_cast<uint32_t>(dims[0]);
  uint32_t features_size = static_cast<uint32_t>(dims[1]);
  if (features_size > UINT16_MAX) {
    char msg[128];
    sprintf(msg, "\"samples\": more than %" PRIu32 " features is not supported",
            features_size);
    PyErr_SetString(PyExc_ValueError, msg);
    return NULL;
  }
  float *samples = reinterpret_cast<float*>(PyArray_DATA(
      reinterpret_cast<PyArrayObject*>(samples_array.get())));
  npy_intp centroid_dims[] = {clusters_size, features_size, 0};
  auto centroids_array = PyArray_EMPTY(2, centroid_dims, NPY_FLOAT32, false);
  float *centroids = reinterpret_cast<float*>(PyArray_DATA(
      reinterpret_cast<PyArrayObject*>(centroids_array)));
  npy_intp assignments_dims[] = {samples_size, 0};
  auto assignments_array = PyArray_EMPTY(1, assignments_dims, NPY_UINT32, false);
  uint32_t *assignments = reinterpret_cast<uint32_t*>(PyArray_DATA(
      reinterpret_cast<PyArrayObject*>(assignments_array)));

  int result;
  Py_BEGIN_ALLOW_THREADS
  result = kmeans_cuda(
      kmpp == Py_True, tolerance, yinyang_t, samples_size,
      static_cast<uint16_t>(features_size), clusters_size, seed, device,
      verbosity, -1, samples, centroids, assignments);
  Py_END_ALLOW_THREADS

  switch (result) {
    case kmcudaInvalidArguments:
      PyErr_SetString(PyExc_ValueError,
                      "Invalid arguments were passed to kmeans_cuda");
      return NULL;
    case kmcudaNoSuchDevice:
      PyErr_SetString(PyExc_ValueError, "No such CUDA device exists");
      return NULL;
    case kmcudaMemoryAllocationFailure:
      PyErr_SetString(PyExc_MemoryError,
                      "Failed to allocate memory on GPU");
      return NULL;
    case kmcudaMemoryCopyError:
      PyErr_SetString(PyExc_RuntimeError, "cudaMemcpy failed");
      return NULL;
    case kmcudaRuntimeError:
      PyErr_SetString(PyExc_AssertionError, "kmeans_cuda failure (bug?)");
      return NULL;
    case kmcudaSuccess:
      return Py_BuildValue("OO", centroids_array, assignments_array);
    default:
      PyErr_SetString(PyExc_AssertionError,
                      "Unknown error code returned from kmeans_cuda");
      return NULL;
  }
}
Exemplo n.º 8
0
static PyObject * anglesToGVec(PyObject * self, PyObject * args)
{
  PyArrayObject *angs, *bHat_l, *eHat_l, *rMat_c;
  PyArrayObject *gVec_c;
  double chi;
  npy_intp nvecs, rdims[2];

  int nangs, nbhat, nehat, nrmat;
  int da1, db1, de1, dr1, dr2;

  double *angs_ptr, *bHat_l_ptr, *eHat_l_ptr, *rMat_c_ptr;
  double *gVec_c_ptr;

  /* Parse arguments */
  if ( !PyArg_ParseTuple(args,"OOOdO",
			 &angs,
			 &bHat_l, &eHat_l,
			 &chi, &rMat_c)) return(NULL);
  if ( angs == NULL ) return(NULL);

  /* Verify shape of input arrays */
  nangs = PyArray_NDIM(angs);
  nbhat = PyArray_NDIM(bHat_l);
  nehat = PyArray_NDIM(eHat_l);
  nrmat = PyArray_NDIM(rMat_c);

  assert( nangs==2 && nbhat==1 && nehat==1 && nrmat==2 );

  /* Verify dimensions of input arrays */
  nvecs = PyArray_DIMS(angs)[0]; //rows
  da1   = PyArray_DIMS(angs)[1]; //cols

  db1   = PyArray_DIMS(bHat_l)[0];
  de1   = PyArray_DIMS(eHat_l)[0];
  dr1   = PyArray_DIMS(rMat_c)[0];
  dr2   = PyArray_DIMS(rMat_c)[1];

  assert( da1 == 3 );
  assert( db1 == 3 && de1 == 3);
  assert( dr1 == 3 && dr2 == 3);

  /* Allocate C-style array for return data */
  rdims[0] = nvecs; rdims[1] = 3;
  gVec_c = (PyArrayObject*)PyArray_EMPTY(2,rdims,NPY_DOUBLE,0);

  /* Grab pointers to the various data arrays */
  angs_ptr   = (double*)PyArray_DATA(angs);
  bHat_l_ptr = (double*)PyArray_DATA(bHat_l);
  eHat_l_ptr = (double*)PyArray_DATA(eHat_l);
  rMat_c_ptr = (double*)PyArray_DATA(rMat_c);
  gVec_c_ptr = (double*)PyArray_DATA(gVec_c);

  /* Call the actual function */
  anglesToGvec_cfunc(nvecs, angs_ptr,
		     bHat_l_ptr, eHat_l_ptr,
		     chi, rMat_c_ptr,
		     gVec_c_ptr);

  /* Build and return the nested data structure */
  return((PyObject*)gVec_c);
}
Exemplo n.º 9
0
PyObject* 
PyThunk_EvaluateBlock(PyThunkObject *thunk, size_t block) {
	if (PyThunk_IsEvaluated(thunk) || PyThunk_IsEvaluatedBlock(thunk, block)) {
		Py_RETURN_NONE;
	}
    size_t start = block * BLOCK_SIZE;
    size_t end = min((block + 1) * BLOCK_SIZE, thunk->cardinality);

	if (PyThunkUnaryPipeline_CheckExact(thunk->operation)) {
        PyArrayObject *arrays[NPY_MAXARGS];
		PyThunkOperation_UnaryPipeline *operation = (PyThunkOperation_UnaryPipeline*)thunk->operation;
		UnaryPipelineFunction function = (UnaryPipelineFunction)(operation->function);
		if (PyThunk_CheckExact(operation->left)) {
			PyThunk_EvaluateBlock((PyThunkObject*)operation->left, block);
		}
		if (thunk->storage == NULL) {
			// no storage, have to obtain storage from somewhere
			if (PyThunk_MatchingStorage(thunk, operation->left)) {
				// the referenced object has only one reference (from here)
				// this means it will get destroyed after this operation
				// since it has the same type, we can use its storage directly
				thunk->storage = ((PyThunkObject*)operation->left)->storage;
                Py_INCREF(thunk->storage);
			} else {
				// we have to create storage for the operation
				thunk->storage = (PyArrayObject*)PyArray_EMPTY(1, (npy_intp[1]) { thunk->cardinality }, thunk->type, 0);
			}
		}
        arrays[0] = (PyArrayObject*) PyThunk_AsUnevaluatedArray(operation->left);
        arrays[1] = thunk->storage;
		function(arrays, start, end);
		PyBlockMask_SetBlock(thunk->blockmask, block);
        PyThunk_FinalizeEvaluation(thunk);
	} else if (PyThunkBinaryPipeline_CheckExact(thunk->operation)) {
        PyArrayObject *arrays[NPY_MAXARGS];
		PyThunkOperation_BinaryPipeline *operation = (PyThunkOperation_BinaryPipeline*)thunk->operation;
		BinaryPipelineFunction function = (BinaryPipelineFunction)(operation->function);
		if (PyThunk_CheckExact(operation->left)) {
			PyThunk_EvaluateBlock((PyThunkObject*)operation->left, block);
		}
		if (PyThunk_CheckExact(operation->right)) {
			PyThunk_EvaluateBlock((PyThunkObject*)operation->right, block);
		}
		if (thunk->storage == NULL) {
			// no storage, have to obtain storage from somewhere
		    if (PyThunk_MatchingStorage(thunk, operation->left)) {
				thunk->storage = ((PyThunkObject*)operation->left)->storage;
                Py_INCREF(thunk->storage);
			} else if (PyThunk_MatchingStorage(thunk, operation->right)) {
				thunk->storage = ((PyThunkObject*)operation->right)->storage;
                Py_INCREF(thunk->storage);
			} else {
				thunk->storage = (PyArrayObject*)PyArray_EMPTY(1, (npy_intp[1]) { thunk->cardinality }, thunk->type, 0);
			}
		}
        arrays[0] = (PyArrayObject*) PyThunk_AsUnevaluatedArray(operation->left);
        arrays[1] = (PyArrayObject*) PyThunk_AsUnevaluatedArray(operation->right);
        arrays[2] = thunk->storage;
		function(arrays, start, end);
		PyBlockMask_SetBlock(thunk->blockmask, block);
        PyThunk_FinalizeEvaluation(thunk);
	} else {
		PyThunk_Evaluate(thunk);
	}

	Py_RETURN_NONE;
}
Exemplo n.º 10
0
PyObject* 
PyThunk_Evaluate(PyThunkObject *thunk) {
	if (PyThunk_IsEvaluated(thunk)) {
		Py_RETURN_NONE;
	}
	if (PyThunkUnaryPipeline_CheckExact(thunk->operation) || PyThunkBinaryPipeline_CheckExact(thunk->operation)) {
        size_t blocks = PyThunk_BlockCount(thunk);
		for(size_t i = 0; i < blocks; i++) {
			PyThunk_EvaluateBlock(thunk, i);
		}
	} else if (PyThunkUnaryFunction_CheckExact(thunk->operation)) {
        PyArrayObject *arrays[NPY_MAXARGS];
		PyThunkOperation_UnaryFunction *operation = (PyThunkOperation_UnaryFunction*)thunk->operation;
		UnaryFunction function = (UnaryFunction)(operation->function);
        if (PyThunk_CheckExact(operation->left)) {
            PyThunk_Evaluate((PyThunkObject*)operation->left);
        }
		if (thunk->storage == NULL) {
			// no storage, have to obtain storage from somewhere
			if (PyThunk_MatchingStorage(thunk, operation->left)) {
				// the referenced object has only one reference (from here)
				// this means it will get destroyed after this operation
				// since it has the same type, we can use its storage directly
				thunk->storage = ((PyThunkObject*)operation->left)->storage;
                Py_INCREF(thunk->storage);
			} else {
				// we have to create storage for the operation
				thunk->storage = (PyArrayObject*)PyArray_EMPTY(1, (npy_intp[1]) { thunk->cardinality }, thunk->type, 0);
			}
		}
        arrays[0] = (PyArrayObject*) PyThunk_AsUnevaluatedArray(operation->left);
        arrays[1] = thunk->storage;
        function(arrays);
        thunk->evaluated = true;
        PyThunk_FinalizeEvaluation(thunk);
	} else if (PyThunkBinaryFunction_CheckExact(thunk->operation)) {
        PyArrayObject *arrays[NPY_MAXARGS];
		PyThunkOperation_BinaryFunction *operation = (PyThunkOperation_BinaryFunction*)thunk->operation;
		BinaryFunction function = (BinaryFunction)(operation->function);
        if (PyThunk_CheckExact(operation->left)) {
            PyThunk_Evaluate((PyThunkObject*)operation->left);
        }
        if (PyThunk_CheckExact(operation->right)) {
            PyThunk_Evaluate((PyThunkObject*)operation->right);
        }
		if (thunk->storage == NULL) {
			// no storage, have to obtain storage from somewhere
			if (PyThunk_MatchingStorage(thunk, operation->left)) {
				thunk->storage = ((PyThunkObject*)operation->left)->storage;
                Py_INCREF(thunk->storage);
			} else if (PyThunk_MatchingStorage(thunk, operation->right)) {
				thunk->storage = ((PyThunkObject*)operation->right)->storage;
                Py_INCREF(thunk->storage);
			} else {
				thunk->storage = (PyArrayObject*)PyArray_EMPTY(1, (npy_intp[1]) { thunk->cardinality }, thunk->type, 0);
			}
		}
        arrays[0] = (PyArrayObject*) PyThunk_AsUnevaluatedArray(operation->left);
        arrays[1] = (PyArrayObject*) PyThunk_AsUnevaluatedArray(operation->right);
        arrays[2] = thunk->storage;
		function(arrays);
        thunk->evaluated = true;
        PyThunk_FinalizeEvaluation(thunk);
	} else if (PyThunkAggregationPipeline_CheckExact(thunk->operation)) {
        PyThunkOperation_AggregationPipeline *operation = (PyThunkOperation_AggregationPipeline*)thunk->operation;
        size_t blocks = PyThunk_BlockCount((PyThunkObject*)operation->left);
        PyObject *list = PyList_New(blocks);
        PyObject *result = NULL;
        PyArrayObject *array;
        for(size_t i = 0; i < blocks; i++) {
            size_t start = i * BLOCK_SIZE;
            size_t end = min((i + 1) * BLOCK_SIZE, ((PyThunkObject*)operation->left)->cardinality);

            PyThunk_EvaluateBlock((PyThunkObject*)operation->left, i);
            PyReduceFunc_ExecuteBlock(operation->function, ((PyThunkObject*)operation->left)->storage, &result, start, end);
            if (result == NULL) {
                return NULL;
            }
            PyList_SetItem(list, i, result);
        }
        array = (PyArrayObject*) PyArray_FromAny(list, NULL, 0, 0, 0, NULL);
        PyReduceFunc_Execute(operation->function, array, &result);
        Py_DECREF(array);
        Py_DECREF(list);

        thunk->storage = (PyArrayObject*) PyArray_FromAny(result, NULL, 0, 0, 0, NULL);
    }
	Py_RETURN_NONE;
}
Exemplo n.º 11
0
/// Wraps PyArray_SimpleNew
PyObject* NumPyArray_EMPTY(int nd, npy_intp* dims, int typenum, int fortran)
{
    return PyArray_EMPTY(nd, dims, typenum,fortran);
}
Exemplo n.º 12
0
/*
    Takes a list of unit reciprocal lattice vectors in crystal frame to the
    specified detector-relative frame, subject to the conditions:

    1) the reciprocal lattice vector must be able to satisfy a bragg condition
    2) the associated diffracted beam must intersect the detector plane

    Required Arguments:
    gVec_c -- (n, 3) ndarray of n reciprocal lattice vectors in the CRYSTAL FRAME
    rMat_d -- (3, 3) ndarray, the COB taking DETECTOR FRAME components to LAB FRAME
    rMat_s -- (n, 3, 3) ndarray, the COB taking SAMPLE FRAME components to LAB FRAME
    rMat_c -- (3, 3) ndarray, the COB taking CRYSTAL FRAME components to SAMPLE FRAME
    tVec_d -- (3, 1) ndarray, the translation vector connecting LAB to DETECTOR
    tVec_s -- (3, 1) ndarray, the translation vector connecting LAB to SAMPLE
    tVec_c -- (3, 1) ndarray, the translation vector connecting SAMPLE to CRYSTAL

    Outputs:
    (m, 2) ndarray containing the intersections of m <= n diffracted beams
    associated with gVecs
*/
static PyObject * gvecToDetectorXYArray(PyObject * self, PyObject * args)
{
  PyArrayObject *gVec_c,
		*rMat_d, *rMat_s, *rMat_c,
		*tVec_d, *tVec_s, *tVec_c,
		*beamVec;
  PyArrayObject *result;

  int dgc, drd, drs, drc, dtd, dts, dtc, dbv;
  npy_intp npts, dims[2];

  double *gVec_c_Ptr,
	 *rMat_d_Ptr, *rMat_s_Ptr, *rMat_c_Ptr,
	 *tVec_d_Ptr, *tVec_s_Ptr, *tVec_c_Ptr,
	 *beamVec_Ptr;
  double *result_Ptr;

  /* Parse arguments */
  if ( !PyArg_ParseTuple(args,"OOOOOOOO",
			 &gVec_c,
			 &rMat_d, &rMat_s, &rMat_c,
			 &tVec_d, &tVec_s, &tVec_c,
			 &beamVec)) return(NULL);
  if ( gVec_c  == NULL ||
       rMat_d  == NULL || rMat_s == NULL || rMat_c == NULL ||
       tVec_d  == NULL || tVec_s == NULL || tVec_c == NULL ||
       beamVec == NULL ) return(NULL);

  /* Verify shape of input arrays */
  dgc = PyArray_NDIM(gVec_c);
  drd = PyArray_NDIM(rMat_d);
  drs = PyArray_NDIM(rMat_s);
  drc = PyArray_NDIM(rMat_c);
  dtd = PyArray_NDIM(tVec_d);
  dts = PyArray_NDIM(tVec_s);
  dtc = PyArray_NDIM(tVec_c);
  dbv = PyArray_NDIM(beamVec);
  assert( dgc == 2 );
  assert( drd == 2 && drs == 3 && drc == 2 );
  assert( dtd == 1 && dts == 1 && dtc == 1 );
  assert( dbv == 1 );

  /* Verify dimensions of input arrays */
  npts = PyArray_DIMS(gVec_c)[0];

  if (npts != PyArray_DIM(rMat_s, 0)) {
    PyErr_Format(PyExc_ValueError, "gVec_c and rMat_s length mismatch %d vs %d",
		 (int)PyArray_DIM(gVec_c, 0), (int)PyArray_DIM(rMat_s, 0));
    return NULL;
  }
  assert( PyArray_DIMS(gVec_c)[1]  == 3 );
  assert( PyArray_DIMS(rMat_d)[0]  == 3 && PyArray_DIMS(rMat_d)[1] == 3 );
  assert( PyArray_DIMS(rMat_s)[1]  == 3 && PyArray_DIMS(rMat_s)[2] == 3 );
  assert( PyArray_DIMS(rMat_c)[0]  == 3 && PyArray_DIMS(rMat_c)[1] == 3 );
  assert( PyArray_DIMS(tVec_d)[0]  == 3 );
  assert( PyArray_DIMS(tVec_s)[0]  == 3 );
  assert( PyArray_DIMS(tVec_c)[0]  == 3 );
  assert( PyArray_DIMS(beamVec)[0] == 3 );

  /* Allocate C-style array for return data */
  dims[0] = npts; dims[1] = 2;
  result = (PyArrayObject*)PyArray_EMPTY(2,dims,NPY_DOUBLE,0);

  /* Grab data pointers into various arrays */
  gVec_c_Ptr  = (double*)PyArray_DATA(gVec_c);

  rMat_d_Ptr  = (double*)PyArray_DATA(rMat_d);
  rMat_s_Ptr  = (double*)PyArray_DATA(rMat_s);
  rMat_c_Ptr  = (double*)PyArray_DATA(rMat_c);

  tVec_d_Ptr  = (double*)PyArray_DATA(tVec_d);
  tVec_s_Ptr  = (double*)PyArray_DATA(tVec_s);
  tVec_c_Ptr  = (double*)PyArray_DATA(tVec_c);

  beamVec_Ptr = (double*)PyArray_DATA(beamVec);

  result_Ptr     = (double*)PyArray_DATA(result);

  /* Call the computational routine */
  gvecToDetectorXYArray_cfunc(npts, gVec_c_Ptr,
			 rMat_d_Ptr, rMat_s_Ptr, rMat_c_Ptr,
			 tVec_d_Ptr, tVec_s_Ptr, tVec_c_Ptr,
			 beamVec_Ptr,
			 result_Ptr);

  /* Build and return the nested data structure */
  return((PyObject*)result);
}