Ejemplo n.º 1
0
static PyObject*
particles_set_lees_edwards(particles_t *self, PyObject *value)
{
  PyObject *dx_arr, *dv_arr = NULL;
  double *dx, dv[3];

  int ierror = ERROR_NONE;

  if (!PyArg_ParseTuple(value, "O|O", &dx_arr, &dv_arr))
    return NULL;
    
  if (dv_arr == Py_None)
    dv_arr = NULL;
    
  dx_arr = PyArray_FROMANY(dx_arr, NPY_DOUBLE, 1, 1, 0);
    
  if (dv_arr) {
    dv_arr = PyArray_FROMANY(dv_arr, NPY_DOUBLE, 1, 1, 0);
    if (!dv_arr) {
      Py_DECREF(dx_arr);
      return NULL;
    }
  }

  if (PyArray_DIM(dx_arr, 0) != 3) {
    PyErr_SetString(PyExc_TypeError, "dx needs to be 3 vector.");
    Py_DECREF(dx_arr);
    if (dv_arr) {
      Py_DECREF(dv_arr);
    }
    return NULL;
  }
  dx = (double *)  PyArray_DATA(dx_arr);

  dv[0] = 0.0;
  dv[1] = 0.0;
  dv[2] = 0.0;
  if (dv_arr) {
    if (PyArray_DIM(dv_arr, 0) != 3) {
      PyErr_SetString(PyExc_TypeError, "dv needs to be 3 vector.");
      Py_DECREF(dx_arr);
      Py_DECREF(dv_arr);
      return NULL;
    }
    dv[0] = ((double *)  PyArray_DATA(dv_arr))[0];
    dv[1] = ((double *)  PyArray_DATA(dv_arr))[1];
    dv[2] = ((double *)  PyArray_DATA(dv_arr))[2];
  }
  
  f_particles_set_lees_edwards(self->f90obj, dx, dv, &ierror);
  if (error_to_py(ierror))
      return NULL;

  Py_DECREF(dx_arr);
  if (dv_arr) {
    Py_DECREF(dv_arr);
  }

  Py_RETURN_NONE;
}
Ejemplo n.º 2
0
static PyObject*
particles_set_cell(particles_t *self, PyObject *args)
{
  PyObject *Abox_obj, *pbc_obj = NULL;
  PyArrayObject *Abox_arr;
  PyArrayObject *pbc_arr = NULL;
  double *Abox;
  npy_bool *pbc;
  BOOL pbc_for[3];
  int ierror = ERROR_NONE;

  if (!PyArg_ParseTuple(args, "O|O", &Abox_obj, &pbc_obj))
    return NULL;

  Abox_arr = (PyArrayObject *) PyArray_FROMANY(Abox_obj, NPY_DOUBLE, 2, 2,
                                               NPY_C_CONTIGUOUS);
  if (!Abox_arr)
    return NULL;
  Abox = DOUBLEP(Abox_arr);

  pbc_for[0] = 1;
  pbc_for[1] = 1;
  pbc_for[2] = 1;
  if (pbc_obj) {
    pbc_arr = (PyArrayObject *) PyArray_FROMANY(pbc_obj, NPY_BOOL, 1, 1,
                                                NPY_C_CONTIGUOUS);
    if (!pbc_arr)
      return NULL;
    pbc = (npy_bool *) BOOLP(pbc_arr);

    pbc_for[0] = pbc[0];
    pbc_for[1] = pbc[1];
    pbc_for[2] = pbc[2];
  }

#ifdef DEBUG
  printf("[particles_set_cell] pbc_for %i, %i, %i\n", pbc_for[0], pbc_for[1],
	 pbc_for[2]);
#endif
  f_particles_set_cell(self->f90obj, Abox, pbc_for, &ierror);
  if (error_to_py(ierror))
    return NULL;

  Py_RETURN_NONE;
}
Ejemplo n.º 3
0
static PyObject* phocount_count(PyObject *self, PyObject *args){
  PyObject *_input = NULL;
  PyArrayObject *input = NULL;
  PyArrayObject *stddev = NULL;
  PyArrayObject *out = NULL;
  npy_intp *dims;
  int ndims;
  float thresh[2], mean_filter[2];
  int sum_max;
  int nan = 0;

  if(!PyArg_ParseTuple(args, "O(ff)(ff)i|p", &_input, &thresh[0], &thresh[1],
                                             &mean_filter[0], &mean_filter[1], 
                                             &sum_max, &nan)){
    return NULL;
  }

  if(sum_max <= 0 || sum_max > 9){
    PyErr_SetString(PyExc_ValueError, "Maximum sum value must be between 0 and 9");
    goto error;
  }

  input = (PyArrayObject*)PyArray_FROMANY(_input, NPY_FLOAT, 3, 0,NPY_ARRAY_IN_ARRAY);
  if(!input){
    goto error;
  }

  ndims = PyArray_NDIM(input);
  dims = PyArray_DIMS(input);

  out = (PyArrayObject*)PyArray_SimpleNew(ndims, dims, NPY_FLOAT);
  if(!out){
    goto error;
  }

  stddev = (PyArrayObject*)PyArray_SimpleNew(ndims, dims, NPY_FLOAT);
  if(!stddev){
    goto error;
  }
  
  
  count((data_t*)PyArray_DATA(input), (data_t*)PyArray_DATA(out),
        (data_t*)PyArray_DATA(stddev),
        ndims, dims, thresh, mean_filter, sum_max, nan);

  Py_XDECREF(input);
  return Py_BuildValue("(NN)", out, stddev);

error:
  Py_XDECREF(input);
  Py_XDECREF(out);
  Py_XDECREF(stddev);
  return NULL;
}
Ejemplo n.º 4
0
/*
 * digitize(x, bins, right=False) returns an array of integers the same length
 * as x. The values i returned are such that bins[i - 1] <= x < bins[i] if
 * bins is monotonically increasing, or bins[i - 1] > x >= bins[i] if bins
 * is monotonically decreasing.  Beyond the bounds of bins, returns either
 * i = 0 or i = len(bins) as appropriate. If right == True the comparison
 * is bins [i - 1] < x <= bins[i] or bins [i - 1] >= x > bins[i]
 */
NPY_NO_EXPORT PyObject *
arr_digitize(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds)
{
    PyObject *obj_x = NULL;
    PyObject *obj_bins = NULL;
    PyArrayObject *arr_x = NULL;
    PyArrayObject *arr_bins = NULL;
    PyObject *ret = NULL;
    npy_intp len_bins;
    int monotonic, right = 0;
    NPY_BEGIN_THREADS_DEF

    static char *kwlist[] = {"x", "bins", "right", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist,
                                     &obj_x, &obj_bins, &right)) {
        goto fail;
    }

    /* PyArray_SearchSorted will make `x` contiguous even if we don't */
    arr_x = (PyArrayObject *)PyArray_FROMANY(obj_x, NPY_DOUBLE, 0, 0,
                                             NPY_ARRAY_CARRAY_RO);
    if (arr_x == NULL) {
        goto fail;
    }

    /* TODO: `bins` could be strided, needs change to check_array_monotonic */
    arr_bins = (PyArrayObject *)PyArray_FROMANY(obj_bins, NPY_DOUBLE, 1, 1,
                                               NPY_ARRAY_CARRAY_RO);
    if (arr_bins == NULL) {
        goto fail;
    }

    len_bins = PyArray_SIZE(arr_bins);
    if (len_bins == 0) {
        PyErr_SetString(PyExc_ValueError, "bins must have non-zero length");
        goto fail;
    }

    NPY_BEGIN_THREADS_THRESHOLDED(len_bins)
    monotonic = check_array_monotonic((const double *)PyArray_DATA(arr_bins),
                                      len_bins);
    NPY_END_THREADS

    if (monotonic == 0) {
        PyErr_SetString(PyExc_ValueError,
                        "bins must be monotonically increasing or decreasing");
        goto fail;
    }

    /* PyArray_SearchSorted needs an increasing array */
    if (monotonic == - 1) {
        PyArrayObject *arr_tmp = NULL;
        npy_intp shape = PyArray_DIM(arr_bins, 0);
        npy_intp stride = -PyArray_STRIDE(arr_bins, 0);
        void *data = (void *)(PyArray_BYTES(arr_bins) - stride * (shape - 1));

        arr_tmp = (PyArrayObject *)PyArray_New(&PyArray_Type, 1, &shape,
                                               NPY_DOUBLE, &stride, data, 0,
                                               PyArray_FLAGS(arr_bins), NULL);
        if (!arr_tmp) {
            goto fail;
        }

        if (PyArray_SetBaseObject(arr_tmp, (PyObject *)arr_bins) < 0) {

            Py_DECREF(arr_tmp);
            goto fail;
        }
        arr_bins = arr_tmp;
    }

    ret = PyArray_SearchSorted(arr_bins, (PyObject *)arr_x,
                               right ? NPY_SEARCHLEFT : NPY_SEARCHRIGHT, NULL);
    if (!ret) {
        goto fail;
    }

    /* If bins is decreasing, ret has bins from end, not start */
    if (monotonic == -1) {
        npy_intp *ret_data =
                        (npy_intp *)PyArray_DATA((PyArrayObject *)ret);
        npy_intp len_ret = PyArray_SIZE((PyArrayObject *)ret);

        NPY_BEGIN_THREADS_THRESHOLDED(len_ret)
        while (len_ret--) {
            *ret_data = len_bins - *ret_data;
            ret_data++;
        }
        NPY_END_THREADS
    }
Ejemplo n.º 5
0
static PyObject* gridder_3D(PyObject *self, PyObject *args, PyObject *kwargs){
  PyObject *gridout = NULL, *Nout = NULL, *standarderror = NULL;
  PyObject *gridI = NULL;
  PyObject *_I;
  
  static char *kwlist[] = { "data", "xrange", "yrange", "zrange", "norm", NULL };
  
  npy_intp data_size;
  npy_intp dims[3];
  
  double grid_start[3];
  double grid_stop[3];
  int grid_nsteps[3];
  int norm_data = 0;
  
  unsigned long n_outside;
  
  if(!PyArg_ParseTupleAndKeywords(args, kwargs, "O(ddd)(ddd)(iii)|i", kwlist,
				  &_I, 
				  &grid_start[0], &grid_start[1], &grid_start[2],
				  &grid_stop[0], &grid_stop[1], &grid_stop[2],
				  &grid_nsteps[0], &grid_nsteps[1], &grid_nsteps[2],
				  &norm_data)){
    return NULL;
  }	
  
  gridI = PyArray_FROMANY(_I, NPY_DOUBLE, 0, 0, NPY_IN_ARRAY);
  if(!gridI){
    goto cleanup;
  }
  
  data_size = PyArray_DIM(gridI, 0);
  
  dims[0] = grid_nsteps[0];
  dims[1] = grid_nsteps[1];
  dims[2] = grid_nsteps[2];

  gridout = PyArray_ZEROS(3, dims, NPY_DOUBLE, 0);
  if(!gridout){
    goto cleanup;
  }
  Nout = PyArray_ZEROS(3, dims, NPY_ULONG, 0);
  if(!Nout){
    goto cleanup;
  }
  standarderror = PyArray_ZEROS(3, dims, NPY_DOUBLE, 0);
  if(!standarderror){
    goto cleanup;
  }
  
  n_outside = c_grid3d(PyArray_DATA(gridout), PyArray_DATA(Nout), 
		       PyArray_DATA(standarderror), PyArray_DATA(gridI),
		       grid_start, grid_stop, data_size, grid_nsteps, norm_data);
  
  Py_XDECREF(gridI);
  return Py_BuildValue("NNNl", gridout, Nout, standarderror, n_outside); 
  
 cleanup:
  Py_XDECREF(gridI);
  Py_XDECREF(gridout);
  Py_XDECREF(Nout);
  Py_XDECREF(standarderror);
  return NULL;
}
Ejemplo n.º 6
0
static PyObject* ccdToQ(PyObject *self, PyObject *args, PyObject *kwargs){
  static char *kwlist[] = { "angles", "mode", "ccd_size", "ccd_pixsize", 
			    "ccd_cen", "dist", "wavelength", 
			    "UBinv", "outarray", NULL };
  PyObject *angles = NULL;
  PyObject *_angles = NULL;
  PyObject *_ubinv = NULL;
  PyObject *ubinv = NULL;
  PyObject *_outarray = NULL;
  PyObject *qOut = NULL;
  CCD ccd;
  npy_intp dims[2];
  npy_intp nimages;
  int i, j, t, stride;
  int ndelgam;
  int mode;

  _float lambda;

  _float *anglesp;
  _float *qOutp;
  _float *ubinvp;
  _float UBI[3][3];

#ifdef USE_THREADS
  pthread_t thread[NTHREADS];
  int iret[NTHREADS];
#endif
  imageThreadData threadData[NTHREADS];

  if(!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi(ii)(dd)(dd)ddO|O", kwlist,
				  &_angles,
				  &mode,
				  &ccd.xSize, &ccd.ySize,
				  &ccd.xPixSize, &ccd.yPixSize, 
				  &ccd.xCen, &ccd.yCen,
				  &ccd.dist,
				  &lambda,
				  &_ubinv,
				  &_outarray)){
    return NULL;
  }

  angles = PyArray_FROMANY(_angles, NPY_DOUBLE, 2, 2, NPY_IN_ARRAY);
  if(!angles){
    PyErr_SetString(PyExc_ValueError, "angles must be a 2-D array of floats");
    goto cleanup;
  }
  
  ubinv = PyArray_FROMANY(_ubinv, NPY_DOUBLE, 2, 2, NPY_IN_ARRAY);
  if(!ubinv){
    PyErr_SetString(PyExc_ValueError, "ubinv must be a 2-D array of floats");
    goto cleanup;
  }

  ubinvp = (_float *)PyArray_DATA(ubinv);
  for(i=0;i<3;i++){
    UBI[i][0] = -1.0 * ubinvp[2];
    UBI[i][1] = ubinvp[1];
    UBI[i][2] = ubinvp[0];
    ubinvp+=3;
  }
  
  nimages = PyArray_DIM(angles, 0);
  ndelgam = ccd.xSize * ccd.ySize;

  dims[0] = nimages * ndelgam;
  dims[1] = 4;
  if(!_outarray){
    // Create new numpy array
    // fprintf(stderr, "**** Creating new array\n");
    qOut = PyArray_SimpleNew(2, dims, NPY_DOUBLE);
    if(!qOut){
      goto cleanup;
    }
  } else {
    qOut = PyArray_FROMANY(_outarray, NPY_DOUBLE, 2, 2, NPY_INOUT_ARRAY);
    if(!qOut){
      PyErr_SetString(PyExc_ValueError, "outarray must be a 2-D array of floats");
      goto cleanup;
    }
    if(PyArray_Size(qOut) != (4 * nimages * ndelgam)){
      PyErr_SetString(PyExc_ValueError, "outarray is of the wrong size");
      goto cleanup;
    }
  }
  anglesp = (_float *)PyArray_DATA(angles);
  qOutp = (_float *)PyArray_DATA(qOut);

  stride = nimages / NTHREADS;
  for(t=0;t<NTHREADS;t++){
    // Setup threads
    // Allocate memory for delta/gamma pairs
    
    threadData[t].ccd = &ccd;
    threadData[t].anglesp = anglesp;
    threadData[t].qOutp = qOutp;
    threadData[t].ndelgam = ndelgam;
    threadData[t].lambda = lambda;
    threadData[t].mode = mode;
    threadData[t].imstart = stride * t;
    for(i=0;i<3;i++){
      for(j=0;j<3;j++){
	threadData[t].UBI[j][i] = UBI[j][i];
      }
    }
    if(t == (NTHREADS - 1)){
      threadData[t].imend = nimages;
    } else {
      threadData[t].imend = stride * (t + 1);
    }

#ifdef USE_THREADS
    iret[t] = pthread_create( &thread[t], NULL, 
			      processImageThread, 
			      (void*) &threadData[t]);
#else
    processImageThread((void *) &threadData[t]);
#endif
    anglesp += (6 * stride);
    qOutp += (ndelgam * 4 * stride);
  }

#ifdef USE_THREADS
  for(t=0;t<NTHREADS;t++){
    if(pthread_join(thread[t], NULL)){
      fprintf(stderr, "ERROR : Cannot join thread %d", t);
    }
  }
#endif

  Py_XDECREF(ubinv);
  Py_XDECREF(angles);
  return Py_BuildValue("N", qOut);

 cleanup:
  Py_XDECREF(ubinv);
  Py_XDECREF(angles);
  Py_XDECREF(qOut);
  return NULL;
}
Ejemplo n.º 7
0
static PyObject* fastccd_correct_images(PyObject *self, PyObject *args){
  PyObject *_input = NULL;
  PyObject *_bgnd = NULL;
  PyObject *_flat = NULL;
  PyArrayObject *input = NULL;
  PyArrayObject *bgnd = NULL;
  PyArrayObject *flat = NULL;
  PyArrayObject *out = NULL;
  npy_intp *dims;
  npy_intp *dims_bgnd;
  npy_intp *dims_flat;
  int ndims;
  float gain[3];


  if(!PyArg_ParseTuple(args, "OOO(fff)", &_input, &_bgnd, &_flat,
                                         &gain[0], &gain[1], &gain[2])){
    return NULL;
  }

  input = (PyArrayObject*)PyArray_FROMANY(_input, NPY_UINT16, 3, 0,NPY_ARRAY_IN_ARRAY);
  if(!input){
    goto error;
  }
  bgnd = (PyArrayObject*)PyArray_FROMANY(_bgnd, NPY_FLOAT, 3, 3, NPY_ARRAY_IN_ARRAY);
  if(!bgnd){
    goto error;
  }

  flat = (PyArrayObject*)PyArray_FROMANY(_flat, NPY_FLOAT, 2,2, NPY_ARRAY_IN_ARRAY);
  if(!flat){
    goto error;
  }

  ndims = PyArray_NDIM(input);
  dims = PyArray_DIMS(input);
  dims_bgnd = PyArray_DIMS(bgnd);
  dims_flat = PyArray_DIMS(flat);

  // Check array dimensions 0 and 1 are the same
  if(dims_bgnd[0] != 3){
    PyErr_SetString(PyExc_ValueError, "Background array must have dimenion 0 = 3");
    goto error;
  }
  if((dims[ndims-2] != dims_bgnd[1]) && (dims[ndims-2] != dims_flat[0])){
    PyErr_SetString(PyExc_ValueError, "Dimensions of image array (0) do not match");
    goto error;
  }
  if((dims[ndims-1] != dims_bgnd[2]) && (dims[ndims-1] != dims_flat[1])){
    PyErr_SetString(PyExc_ValueError, "Dimensions of image array (1) do not match");
    goto error;
  }

  out = (PyArrayObject*)PyArray_SimpleNew(ndims, dims, NPY_FLOAT);
  if(!out){
    goto error;
  }
   
  correct_fccd_images((uint16_t*)PyArray_DATA(input), 
                      (data_t*)PyArray_DATA(out),
                      (data_t*)PyArray_DATA(bgnd),
                      (data_t*)PyArray_DATA(flat),
                      ndims, (index_t*)dims, (data_t*)gain);

  Py_XDECREF(input);
  Py_XDECREF(bgnd);
  Py_XDECREF(flat);
  return Py_BuildValue("N", out);

error:
  Py_XDECREF(input);
  Py_XDECREF(bgnd);
  Py_XDECREF(out);
  Py_XDECREF(flat);
  return NULL;
}
Ejemplo n.º 8
0
/* Computation functions */
static PyObject* ccdToQ(PyObject *self, PyObject *args, PyObject *kwargs){
  PyArrayObject *angles = NULL;
  PyObject *_angles = NULL;
  PyArrayObject *ubinv = NULL;
  PyObject *_ubinv = NULL;
  PyArrayObject *qOut = NULL;
  CCD ccd;
  npy_intp dims[2];
  npy_intp nimages;
  int retval;

  int mode;

  double lambda;

  double *anglesp = NULL;
  double *qOutp = NULL;
  double *ubinvp = NULL;
  double *delgam = NULL;

  static char *kwlist[] = { "angles", "mode", "ccd_size", "ccd_pixsize",
			                      "ccd_cen", "dist", "wavelength",
			                      "UBinv", NULL };

  if(!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi(ii)(dd)(dd)ddO", kwlist,
				                          &_angles,
				                          &mode,
				                          &ccd.xSize, &ccd.ySize,
				                          &ccd.xPixSize, &ccd.yPixSize,
				                          &ccd.xCen, &ccd.yCen,
				                          &ccd.dist,
				                          &lambda,
				                          &_ubinv)){

    return NULL;
  }

  ccd.size = ccd.xSize * ccd.ySize;

  angles = (PyArrayObject*)PyArray_FROMANY(_angles, NPY_DOUBLE, 2, 2, NPY_ARRAY_IN_ARRAY);
  if(!angles){
    goto cleanup;
  }

  ubinv = (PyArrayObject*)PyArray_FROMANY(_ubinv, NPY_DOUBLE, 2, 2, NPY_ARRAY_IN_ARRAY);
  if(!ubinv){
    goto cleanup;
  }

  ubinvp = (double *)PyArray_DATA(ubinv);

  nimages = PyArray_DIM(angles, 0);

  dims[0] = nimages * ccd.size;
  dims[1] = 3;

  qOut = (PyArrayObject*)PyArray_SimpleNew(2, dims, NPY_DOUBLE);
  if(!qOut){
    goto cleanup;
  }

  anglesp = (double *)PyArray_DATA(angles);
  qOutp = (double *)PyArray_DATA(qOut);

  // Now create the arrays for delta-gamma pairs
  delgam = (double*)malloc(nimages * ccd.size * sizeof(double) * 2);
  if(!delgam){
    goto cleanup;
  }

  // Ok now we don't touch Python Object ... Release the GIL
  Py_BEGIN_ALLOW_THREADS

  retval = processImages(delgam, anglesp, qOutp, lambda, mode, (unsigned long)nimages,
                         ubinvp, &ccd);

  // Now we have finished with the magic ... Obtain the GIL
  Py_END_ALLOW_THREADS

  if(retval){
    PyErr_SetString(PyExc_RuntimeError, "Error processing images");
    goto cleanup;
  }

  Py_XDECREF(ubinv);
  Py_XDECREF(angles);
  if(delgam) free(delgam);
  return Py_BuildValue("N", qOut);

 cleanup:
  Py_XDECREF(ubinv);
  Py_XDECREF(angles);
  Py_XDECREF(qOut);
  if(delgam) free(delgam);
  return NULL;
}
Ejemplo n.º 9
0
static PyObject* gridder_3D(PyObject *self, PyObject *args, PyObject *kwargs){
  PyArrayObject *gridout = NULL, *grid2out = NULL, *Nout = NULL, *stderror = NULL;
  PyArrayObject *gridI = NULL;
  PyObject *_dout = NULL, *_d2out = NULL, *_nout = NULL;
  PyObject *_I;

  npy_intp data_size;
  npy_intp dims[3];

  double grid_start[3];
  double grid_stop[3];
  unsigned long grid_nsteps[3];

  int ignore_nan = 0; 

  int retval;

  static char *kwlist[] = { "data", "xrange", "yrange", "zrange", "ignore_nan", 
                            "gridout", "grid2out", "nout", NULL }; 

  if(!PyArg_ParseTupleAndKeywords(args, kwargs, "O(ddd)(ddd)(lll)|dOOO", kwlist, 
				  &_I,
				  &grid_start[0], &grid_start[1], &grid_start[2],
				  &grid_stop[0], &grid_stop[1], &grid_stop[2],
				  &grid_nsteps[0], &grid_nsteps[1], &grid_nsteps[2],
          &ignore_nan, &_dout, &_d2out, &_nout)){
    return NULL;
  }

  gridI = (PyArrayObject*)PyArray_FROMANY(_I, NPY_DOUBLE, 0, 0, NPY_ARRAY_IN_ARRAY);
  if(!gridI){
    goto error;
  }

  data_size = PyArray_DIM(gridI, 0);
  if(PyArray_DIM(gridI, 1) != 4){
    PyErr_SetString(PyExc_ValueError, "Dimension 1 of array must be 4");
    goto error;
  }

  dims[0] = grid_nsteps[0];
  dims[1] = grid_nsteps[1];
  dims[2] = grid_nsteps[2];

  if(_dout == NULL){
    gridout = (PyArrayObject*)PyArray_ZEROS(3, dims, NPY_DOUBLE, 0);
  } else {
    gridout = (PyArrayObject*)PyArray_FROMANY(_dout, NPY_DOUBLE, 0, 0, NPY_ARRAY_IN_ARRAY);
  }
  if(!gridout){
    goto error;
  }

  if(_d2out == NULL){
    grid2out = (PyArrayObject*)PyArray_ZEROS(3, dims, NPY_DOUBLE, 0);
  } else {
    grid2out = (PyArrayObject*)PyArray_FROMANY(_d2out, NPY_DOUBLE, 0, 0, NPY_ARRAY_IN_ARRAY);
  }
  if(!grid2out){
    goto error;
  }

  if(_nout == NULL){
    Nout = (PyArrayObject*)PyArray_ZEROS(3, dims, NPY_ULONG, 0);
  } else {
    Nout = (PyArrayObject*)PyArray_FROMANY(_nout, NPY_ULONG, 0, 0, NPY_ARRAY_IN_ARRAY);
  }
  if(!Nout){
    goto error;
  }

  stderror = (PyArrayObject*)PyArray_SimpleNew(3, dims, NPY_DOUBLE);
  if(!stderror){
    goto error;
  }

  // Ok now we don't touch Python Object ... Release the GIL
  Py_BEGIN_ALLOW_THREADS

  retval = c_grid3d((double*)PyArray_DATA(gridout), (double *)PyArray_DATA(grid2out),
                    (unsigned long*)PyArray_DATA(Nout),
                    (double*)PyArray_DATA(stderror), (double*)PyArray_DATA(gridI),
		                grid_start, grid_stop, (unsigned long)data_size, grid_nsteps,
                    ignore_nan);

  // Ok now get the GIL back
  Py_END_ALLOW_THREADS

  if(retval){
    // We had a runtime error
    PyErr_SetString(PyExc_MemoryError, "Could not allocate memory in c_grid3d");
    goto error;
  }

  Py_XDECREF(gridI);
  return Py_BuildValue("NNNN", gridout, grid2out, Nout, stderror);

error:
  Py_XDECREF(gridI);
  Py_XDECREF(gridout);
  Py_XDECREF(grid2out);
  Py_XDECREF(Nout);
  Py_XDECREF(stderror);
  return NULL;
}
Ejemplo n.º 10
0
static PyObject *SuperLU_solve(SuperLUObject * self, PyObject * args,
			       PyObject * kwds)
{
    PyArrayObject *b, *x = NULL;
    SuperMatrix B = { 0 };
#ifndef NPY_PY3K
    char itrans = 'N';
#else
    int itrans = 'N';
#endif
    int info;
    trans_t trans;
    SuperLUStat_t stat = { 0 };

    static char *kwlist[] = { "rhs", "trans", NULL };

    if (!CHECK_SLU_TYPE(self->type)) {
	PyErr_SetString(PyExc_ValueError, "unsupported data type");
	return NULL;
    }

#ifndef NPY_PY3K
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|c", kwlist,
				     &PyArray_Type, &b, &itrans))
#else
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|C", kwlist,
				     &PyArray_Type, &b, &itrans))
#endif
	return NULL;

    /* solve transposed system: matrix was passed row-wise instead of
     * column-wise */
    if (itrans == 'n' || itrans == 'N')
	trans = NOTRANS;
    else if (itrans == 't' || itrans == 'T')
	trans = TRANS;
    else if (itrans == 'h' || itrans == 'H')
	trans = CONJ;
    else {
	PyErr_SetString(PyExc_ValueError, "trans must be N, T, or H");
	return NULL;
    }

    x = (PyArrayObject*)PyArray_FROMANY(
        (PyObject*)b, self->type, 1, 2,
        NPY_F_CONTIGUOUS | NPY_ENSURECOPY);
    if (x == NULL) {
        goto fail;
    }

    if (x->dimensions[0] != self->n) {
        PyErr_SetString(PyExc_ValueError, "b is of incompatible size");
	goto fail;
    }

    if (setjmp(_superlu_py_jmpbuf))
	goto fail;

    if (DenseSuper_from_Numeric(&B, (PyObject *)x))
	goto fail;

    StatInit(&stat);

    /* Solve the system, overwriting vector x. */
    gstrs(self->type,
	  trans, &self->L, &self->U, self->perm_c, self->perm_r, &B,
	  &stat, &info);

    if (info) {
	PyErr_SetString(PyExc_SystemError,
			"gstrs was called with invalid arguments");
	goto fail;
    }

    /* free memory */
    Destroy_SuperMatrix_Store(&B);
    StatFree(&stat);
    return (PyObject *) x;

  fail:
    XDestroy_SuperMatrix_Store(&B);
    XStatFree(&stat);
    Py_XDECREF(x);
    return NULL;
}
Ejemplo n.º 11
0
static PyObject *
_pylm_dlevmar_generic(PyObject *mod, PyObject *args, PyObject *kwds,
                     char *argstring, char *kwlist[],
                      int jacobian, int bounds) {
    
    
    PyObject *func			= NULL;
	PyObject *jacf			= NULL; 
	PyObject *initial		= NULL,	*initial_npy		= NULL;
	PyObject *measurements	= NULL, *measurements_npy	= NULL;
    PyObject *lower			= NULL, *lower_npy			= NULL;
	PyObject *upper			= NULL, *upper_npy			= NULL;
	
    PyObject *opts			= NULL, *opts_npy			= NULL;
	PyObject *covar			= NULL;
    PyObject *retval		= NULL;
	PyObject *info			= NULL;
	
	pylm_callback_data *pydata = NULL;
	
    double *c_initial		= NULL;
	double *c_measurements	= NULL;
	double *c_opts			= NULL;
    double *c_lower			= NULL;
	double *c_upper			= NULL;
	double *c_covar			= NULL;
	
    int	   max_iter = 0;
	int    run_iter = 0;
	int    m = 0, n = 0;
	
    double c_info[LM_INFO_SZ];
	
	int nopts;

	// If finite-difference approximate Jacobians are used, we
	// need 5 optional params; otherwise 4.
	if (jacobian){
		nopts = 4;
	} else {
		nopts = 5;
	}

    // parse arguments
    if (!bounds) {
        if (jacobian) {
            if (!PyArg_ParseTupleAndKeywords(args, kwds, argstring, kwlist,
                                             &func, &jacf, &initial,
                                             &measurements, &max_iter, 
                                             &opts, &covar)){
				return NULL;	
			}
        } else {
            if (!PyArg_ParseTupleAndKeywords(args, kwds, argstring, kwlist,
                                             &func, &initial,
                                             &measurements, &max_iter, 
                                             &opts, &covar)){
				return NULL;
			}
        }
    } else {
        if (jacobian) {
            if (!PyArg_ParseTupleAndKeywords(args, kwds, argstring, kwlist,
                                             &func, &jacf, &initial,
                                             &measurements, &lower, &upper, &max_iter, 
                                             &opts, &covar)){
                return NULL;
			}
        } else {
            if (!PyArg_ParseTupleAndKeywords(args, kwds, argstring, kwlist,
                                             &func, &initial,
                                             &measurements, &lower, &upper, &max_iter,
                                             &opts, &covar)){
				return NULL;	
			}
        }
    }
     
    // Check each variable type
	
    if (!PyCallable_Check(func)) {
        PyErr_SetString(PyExc_TypeError, "func must be a callable object");
        return NULL;
    }

    if (!PyArray_Check(initial)) {
        PyErr_SetString(PyExc_TypeError, "initial must be a numpy array");
        return NULL;
    }

    if (!PyArray_Check(measurements)) {
        PyErr_SetString(PyExc_TypeError, "measurements must be a numpy array");
        return NULL;
    }

    if (jacobian && !PyCallable_Check(jacf)) {
        PyErr_SetString(PyExc_TypeError, "jacf must be a callable object");
        return NULL;
    }        

    if (lower && !PyArray_Check(lower)) {
        PyErr_SetString(PyExc_TypeError, "lower bounds must be a numpy array");
        return NULL;
    }
    if (upper && !PyArray_Check(upper)) {
        PyErr_SetString(PyExc_TypeError, "upper bounds must be a numpy array");
        return NULL;
    }

    if (opts && !PyArray_Check(opts) && (PyArray_Size(opts) != nopts)) {
		if (nopts == 4){
			PyErr_SetString(PyExc_TypeError,
							"opts must be a numpy vector of length 4.");
		} else {
			PyErr_SetString(PyExc_TypeError,
							"opts must be a numpy vector of length 5.");
		}
        return NULL;
    }

    // convert python types into C
	
    pydata = PyMem_Malloc(sizeof(pydata));
	if(!pydata){
		PyErr_SetString(PyExc_RuntimeError,
						"Error in allocating memory for data.");	
		return NULL;	
	}
    pydata->func = func;
    pydata->jacf = jacf;
	
	initial_npy = PyArray_FROMANY(initial, NPY_DOUBLE, 0, 0, NPY_INOUT_ARRAY);
	measurements_npy = PyArray_FROMANY(measurements, NPY_DOUBLE, 0, 0, NPY_IN_ARRAY);
	
	if(!initial_npy || !measurements_npy){
		// Cannot create array
		PyErr_SetString(PyExc_RuntimeError,
						"Error in creating arrays from input data.");	
		//Py_XDECREF(initial_npy);
		//Py_XDECREF(measurements_npy);
		return NULL;
	}
	
    c_initial = (double *)PyArray_DATA(initial_npy);
	c_measurements = (double *)PyArray_DATA(measurements_npy);
	m = PyArray_SIZE(initial_npy);
	n = PyArray_SIZE(measurements_npy);
	
	npy_intp dims[2] = {m, m};
	covar = PyArray_SimpleNew(2, dims, NPY_DOUBLE);
	c_covar = PyArray_DATA(covar);
	
	
	if (lower){
		lower_npy = PyArray_FROMANY(lower, PyArray_DOUBLE, 0, 0, NPY_IN_ARRAY);
		c_lower = PyArray_DATA(lower_npy);
		// TODO check dims
	}
    if (upper){
		upper_npy = PyArray_FROMANY(upper, PyArray_DOUBLE, 0, 0, NPY_IN_ARRAY);
        c_upper = PyArray_DATA(upper_npy);
		// TODO check dims
	}

	if (opts) {
		opts_npy = PyArray_FROMANY(opts, PyArray_DOUBLE, 0, 0, NPY_IN_ARRAY);
        c_opts = PyArray_DATA(opts_npy);
		// TODO check dims
    }
    
    // call function to do the fitting
	
    if (!bounds) {
        if (jacobian) {
            run_iter =  dlevmar_der(_pylm_func_callback, _pylm_jacf_callback,
                                    c_initial, c_measurements, m, n,
									max_iter, c_opts, c_info, NULL, c_covar, pydata);
        } else {
            run_iter =  dlevmar_dif(_pylm_func_callback, c_initial, c_measurements,
                                    m, n, max_iter, c_opts, c_info, NULL, c_covar, pydata);
        }
    } else {
        if (jacobian) {
            run_iter =  dlevmar_bc_der(_pylm_func_callback, _pylm_jacf_callback,
                                       c_initial, c_measurements, m, n,
                                       c_lower, c_upper,
                                       max_iter, c_opts, c_info, NULL, c_covar, pydata);
        } else {
            run_iter =  dlevmar_bc_dif(_pylm_func_callback, c_initial, c_measurements,
                                       m, n, c_lower, c_upper,
                                       max_iter, c_opts, c_info, NULL, c_covar, pydata);
        }
    }

    // convert results back into python
	
    if (run_iter > 0) {
		npy_intp dims[1] = {m};
		retval = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, c_initial);
    } else {
        retval = Py_None;
        Py_INCREF(Py_None);
    }

	if (pydata) {
        PyMem_Free(pydata);
    }	
	
    // convert additional information into python
    info = Py_BuildValue("{s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d}",
                         "initial_e2", c_info[0],
                         "estimate_e2", c_info[1],
                         "estimate_Jt", c_info[2],
                         "estimate_Dp2", c_info[3],
                         "estimate_mu", c_info[4],
                         "iterations", c_info[5],
                         "termination", c_info[6],
                         "function_evaluations", c_info[7],
                         "jacobian_evaluations", c_info[8]);
	
	//Py_XDECREF(measurements_npy);
	//Py_XDECREF(initial_npy);
	//Py_XDECREF(lower_npy);
	//Py_XDECREF(upper_npy);
	//Py_XDECREF(opts_npy);

	return Py_BuildValue("(OOiO)", retval, covar, run_iter, info, NULL);
}