Esempio n. 1
0
// this copies a block of memory from a numpy array to a memory address
static PyObject*
pymappedndf_numpytondf(NDFMapped *self, PyObject *args)
{
	PyObject *npy, *ptrobj;
	PyArrayObject *npyarray;
	npy_intp el;
	size_t bytes;

	if(!PyArg_ParseTuple(args, "O:pyndfmapped_numpytondf",&npy))
		return NULL;
	void *ptr = self->_pntr;
	el = self->nelem;
	if (el <= 0 || ptr == NULL) {
          PyErr_SetString( PyExc_ValueError,
                           "ndf.mapped object does not have mapped pointer or element count");
          return NULL;
        }

        int npytype = ndftype2numpy( self->type, &bytes );
        if (npytype == 0) return NULL;
        npyarray = (PyArrayObject*) PyArray_FROM_OTF(npy, npytype, NPY_IN_ARRAY | NPY_FORCECAST);
        if (!npyarray) return NULL;

        /* Verify the number of elements */
        if ( PyArray_Size(npyarray) != el ) {
          PyErr_Format( PyExc_ValueError,
                        "Number of elements in numpy array (%zu) differs from number of elements mapped (%zu)",
                        (size_t)PyArray_Size(npyarray), (size_t)el );
          Py_DECREF(npyarray);
          return NULL;
        }
        memcpy(ptr,PyArray_DATA(npyarray),el*bytes);
	Py_DECREF(npyarray);
	Py_RETURN_NONE;
}
Esempio n. 2
0
File: main.cpp Progetto: banados/lsd
static PyObject *Py_table_join(PyObject *self, PyObject *args)
{
	PyObject *ret = NULL;

	PyObject *id1 = NULL, *id2 = NULL, *m1 = NULL, *m2 = NULL;
	const char *join_type = NULL;

	try
	{
		PyObject *id1_, *id2_, *m1_, *m2_;
		if (! PyArg_ParseTuple(args, "OOOOs", &id1_, &id2_, &m1_, &m2_, &join_type))	throw E(PyExc_Exception, "Wrong number or type of args");

		if ((id1 = PyArray_ContiguousFromAny(id1_, PyArray_UINT64, 1, 1)) == NULL)	throw E(PyExc_Exception, "id1 is not a 1D uint64 NumPy array");
		if ((id2 = PyArray_ContiguousFromAny(id2_, PyArray_UINT64, 1, 1)) == NULL)	throw E(PyExc_Exception, "Could not cast the value of id2 to 1D NumPy array");
		if ((m1  = PyArray_ContiguousFromAny(m1_,  PyArray_UINT64, 1, 1)) == NULL)	throw E(PyExc_Exception, "Could not cast the value of m1 to 1D NumPy array");
		if ((m2  = PyArray_ContiguousFromAny(m2_,  PyArray_UINT64, 1, 1)) == NULL)	throw E(PyExc_Exception, "Could not cast the value of m2 to 1D NumPy array");

		if (PyArray_DIM(m1, 0) != PyArray_DIM(m2, 0))  throw E(PyExc_Exception, "The sizes of len(m1) and len(m2) must be the same");

		#define DATAPTR(type, obj) ((type*)PyArray_DATA(obj))
		PyOutput o;
		table_join(
			o,
			DATAPTR(uint64_t, id1), PyArray_Size(id1),
			DATAPTR(uint64_t, id2), PyArray_Size(id2),
			DATAPTR(uint64_t, m1), DATAPTR(uint64_t, m2), PyArray_Size(m2),
			join_type
		);
		#undef DATAPTR
		o.resize(o.size);

		ret = PyTuple_New(4);
		// because PyTuple will take ownership (and PyOutput will do a DECREF on destruction).
		Py_INCREF(o.o_idx1);
		Py_INCREF(o.o_idx2);
		Py_INCREF(o.o_idxLink);
		Py_INCREF(o.o_isnull);
		PyTuple_SetItem(ret, 0, (PyObject *)o.o_idx1);
		PyTuple_SetItem(ret, 1, (PyObject *)o.o_idx2);
		PyTuple_SetItem(ret, 2, (PyObject *)o.o_idxLink);
		PyTuple_SetItem(ret, 3, (PyObject *)o.o_isnull);
	}
	catch(const E& e)
	{
		ret = NULL;
	}

	Py_XDECREF(id1);
	Py_XDECREF(id2);
	Py_XDECREF(m1);
	Py_XDECREF(m2);

	return ret;
}
Esempio n. 3
0
static PyObject * computeMean(PyObject *obj, PyObject *args)
{
    PyObject *oimage;
    PyArrayObject *image;
    int status=0;
    int numGoodPixels;
    float clipmin, clipmax, mean, stddev, minValue, maxValue;

    if (!PyArg_ParseTuple(args,"Off:computeMean",&oimage, &clipmin, &clipmax))
	    return NULL;

    image = (PyArrayObject *)PyArray_ContiguousFromObject(oimage, NPY_FLOAT32, 1, 2);

    if (!image) return NULL;

    mean = 0;
    stddev = 0;
    numGoodPixels = 0;
    minValue = 0;
    maxValue = 0;

    status = computeMean_((float *)PyArray_DATA(image), PyArray_Size((PyObject*)image),
			  clipmin, clipmax,
			  &numGoodPixels, &mean, &stddev, &minValue, &maxValue);
    Py_XDECREF(image);

    return Py_BuildValue("iffff",numGoodPixels,mean,stddev,minValue,maxValue);
}
Esempio n. 4
0
static void f2py_report_on_array_copy(PyArrayObject* arr) {
    const long arr_size = PyArray_Size((PyObject *)arr);
    if (arr_size>F2PY_REPORT_ON_ARRAY_COPY) {
        fprintf(stderr,"copied an array: size=%ld, elsize=%d\n",
                arr_size, PyArray_ITEMSIZE(arr));
    }
}
// =============================================================================
Epetra_Map & Epetra_NumPyVector::getMap(PyObject * pyObject)
{
  if (!tmp_array) getArray(pyObject);
  if (!tmp_map)
  {
    const int totalLength = PyArray_Size((PyObject *)tmp_array);
    tmp_map = new Epetra_Map(totalLength,0,defaultComm);
  }
  return *tmp_map;
}
Esempio n. 6
0
 std::valarray<T> convert2valarray(boost::python::object arr)
 {
   import();                 // ### WARNING: forgetting this will end up in segmentation fault!
   
   std::size_t vec_size = PyArray_Size(arr.ptr());
   T * data = (T *) PyArray_DATA(arr.ptr());
   std::valarray<T> vec(vec_size);
   memcpy(&vec[0],data, PyArray_ITEMSIZE((PyArrayObject*) arr.ptr()) * vec_size);
   return vec;
 }
Esempio n. 7
0
void dump_attrs(const PyArrayObject* arr) {
    int rank = arr->nd;
    npy_intp size = PyArray_Size((PyObject *)arr);
    printf("\trank = %d, flags = %d, size = %" NPY_INTP_FMT  "\n",
           rank,arr->flags,size);
    printf("\tstrides = ");
    dump_dims(rank,arr->strides);
    printf("\tdimensions = ");
    dump_dims(rank,arr->dimensions);
}
// =============================================================================
Epetra_Map & Epetra_NumPyMultiVector::getMap(PyObject * pyObject)
{
  if (!tmp_array) getArray(pyObject);
  if (!tmp_map)
  {
    const int totalLength = PyArray_Size((PyObject *)tmp_array);
    const int numVectors  = PyArray_DIMS(tmp_array)[0];
    tmp_map = new Epetra_Map(totalLength/numVectors,0,defaultComm);
  }
  return *tmp_map;
}
Esempio n. 9
0
void dump_attrs(const PyArrayObject* obj) {
    const PyArrayObject_fields *arr = (const PyArrayObject_fields*) obj;
    int rank = PyArray_NDIM(arr);
    npy_intp size = PyArray_Size((PyObject *)arr);
    printf("\trank = %d, flags = %d, size = %" NPY_INTP_FMT  "\n",
           rank,arr->flags,size);
    printf("\tstrides = ");
    dump_dims(rank,arr->strides);
    printf("\tdimensions = ");
    dump_dims(rank,arr->dimensions);
}
Esempio n. 10
0
void
copy_array_to_c_double(
    PyArrayObject* array,
    double* dest) {

  npy_intp size = 1;
  double*  data = NULL;

  size = PyArray_Size((PyObject*)array);
  data = (double*)PyArray_DATA(array);

  memcpy(dest, data, size * sizeof(double));
}
Esempio n. 11
0
void
copy_array_to_c_int(
    PyArrayObject* array,
    int* dest) {

  npy_intp size = 1;
  int*     data = NULL;

  size = PyArray_Size((PyObject*)array);
  data = (int*)PyArray_DATA(array);

  memcpy(dest, data, size * sizeof(int));
}
Esempio n. 12
0
void
unoffset_array(
    PyArrayObject* array,
    int value) {

  npy_intp  size;
  double   *data;

  if (value == 1) {
    return;
  }

  size = PyArray_Size((PyObject*)array);
  data = (double*)PyArray_DATA(array);
  offset_c_array(data, size, (double)-(1 - value));
}
Esempio n. 13
0
// Get sweep infornation from file header block. Returns:
//   0 ... performed normally
//   1 ... error occurred
// Arguments:
//   debugMode   ... debug messages flag
//   sweep       ... acquired sweep parameter name, new reference created
//   buf         ... header string
//   sweepSize   ... acquired number of sweep points
//   sweepValues ... sweep points array, new reference created
//   faSweep     ... pointer to fast access structure for sweep array
int getSweepInfo(int debugMode, int postVersion, PyObject **sweep, char *buf, int *sweepSize,
        PyObject **sweepValues, struct FastArray *faSweep)
{
    char *sweepName = NULL;
    npy_intp dims;
    sweepName = strtok(NULL, " \t\n");    // Get sweep parameter name.
    if(sweepName == NULL)
    {
        if(debugMode)
            fprintf(debugFile, "HSpiceRead: failed to extract sweep name.\n");
        return 1;
    }
    *sweep = PyString_FromString(sweepName);
    if(*sweep == NULL)
    {
        if(debugMode)
            fprintf(debugFile, "HSpiceRead: failed to create sweep name string.\n");
        return 1;
    }

    // Get number of sweep points.
    if(postVersion == 2001)
        *sweepSize = atoi(&buf[sweepSizePosition1]);
    else *sweepSize = atoi(&buf[sweepSizePosition2]);

    // Create array for sweep parameter values.
    dims=*sweepSize;
    *sweepValues = PyArray_SimpleNew(1, &dims, PyArray_DOUBLE);
    if(*sweepValues == NULL)
    {
        if(debugMode) fprintf(debugFile, "HSpiceRead: failed to create array.\n");
        return 1;
    }

    // Prepare fast access structure.
    faSweep->data = ((PyArrayObject *)(*sweepValues))->data;
    faSweep->pos = ((PyArrayObject *)(*sweepValues))->data;
    faSweep->stride =
        ((PyArrayObject *)(*sweepValues))->strides[((PyArrayObject *)(*sweepValues))->nd -
        1];
    faSweep->length = PyArray_Size(*sweepValues);

    return 0;
}
Esempio n. 14
0
int getSize2( void* arr ) {
	return (int) PyArray_Size( (PyObject *) arr );
//	return (int) (((PyArrayObject *)(arr))->nd));
}
Esempio n. 15
0
/*
 * Converts a numpy ndarray to a Java primitive array.
 *
 * @param env          the JNI environment
 * @param param        the ndarray to convert
 * @param desiredType  the desired type of the resulting primitive array, or
 *                          NULL if it should determine type based on the dtype
 *
 * @return a Java primitive array, or NULL if there were errors
 */
jarray convert_pyndarray_jprimitivearray(JNIEnv* env,
        PyObject *param,
        jclass desiredType)
{
    jarray         arr    = NULL;
    PyArrayObject *copy   = NULL;
    enum NPY_TYPES paType;
    jsize          sz;

    if (!npy_array_check(param)) {
        PyErr_Format(PyExc_TypeError, "convert_pyndarray must receive an ndarray");
        return NULL;
    }

    // determine what we can about the pyarray that is to be converted
    sz = (jsize) PyArray_Size(param);
    paType = PyArray_TYPE((PyArrayObject *) param);

    if (desiredType == NULL) {
        if (paType == NPY_BOOL) {
            desiredType = JBOOLEAN_ARRAY_TYPE;
        } else if (paType == NPY_BYTE) {
            desiredType = JBYTE_ARRAY_TYPE;
        } else if (paType == NPY_INT16) {
            desiredType = JSHORT_ARRAY_TYPE;
        } else if (paType == NPY_INT32) {
            desiredType = JINT_ARRAY_TYPE;
        } else if (paType == NPY_INT64) {
            desiredType = JLONG_ARRAY_TYPE;
        } else if (paType == NPY_FLOAT32) {
            desiredType = JFLOAT_ARRAY_TYPE;
        } else if (paType == NPY_FLOAT64) {
            desiredType = JDOUBLE_ARRAY_TYPE;
        } else {
            PyErr_Format(PyExc_TypeError,
                         "Unable to determine corresponding Java type for ndarray");
            return NULL;
        }
    }

    /*
     * TODO we could speed this up if we could skip the copy, but the copy makes
     * it safer by enforcing the correct length in bytes for the type
     */

    copy = (PyArrayObject *) PyArray_CopyFromObject(param, paType, 0, 0);
    if ((*env)->IsSameObject(env, desiredType, JBOOLEAN_ARRAY_TYPE)
            && (paType == NPY_BOOL)) {
        arr = (*env)->NewBooleanArray(env, sz);
    } else if ((*env)->IsSameObject(env, desiredType, JBYTE_ARRAY_TYPE)
               && (paType == NPY_BYTE)) {
        arr = (*env)->NewByteArray(env, sz);
    } else if ((*env)->IsSameObject(env, desiredType, JSHORT_ARRAY_TYPE)
               && (paType == NPY_INT16)) {
        arr = (*env)->NewShortArray(env, sz);
    } else if ((*env)->IsSameObject(env, desiredType, JINT_ARRAY_TYPE)
               && (paType == NPY_INT32)) {
        arr = (*env)->NewIntArray(env, sz);
    } else if ((*env)->IsSameObject(env, desiredType, JLONG_ARRAY_TYPE)
               && (paType == NPY_INT64)) {
        arr = (*env)->NewLongArray(env, sz);
    } else if ((*env)->IsSameObject(env, desiredType, JFLOAT_ARRAY_TYPE)
               && (paType == NPY_FLOAT32)) {
        arr = (*env)->NewFloatArray(env, sz);
    } else if ((*env)->IsSameObject(env, desiredType, JDOUBLE_ARRAY_TYPE)
               && (paType == NPY_FLOAT64)) {
        arr = (*env)->NewDoubleArray(env, sz);
    } else {
        Py_XDECREF(copy);
        PyErr_Format(PyExc_RuntimeError,
                     "Error matching ndarray.dtype to Java primitive type");
        return NULL;
    }

    /*
     * java exception could potentially be OutOfMemoryError if it
     * couldn't allocate the array
     */
    if (process_java_exception(env) || !arr) {
        Py_XDECREF(copy);
        return NULL;
    }

    // if arr was allocated, we already know it matched the python array type
    if (paType == NPY_BOOL) {
        (*env)->SetBooleanArrayRegion(env, arr, 0, sz,
                                      (const jboolean *) PyArray_DATA(copy));
    } else if (paType == NPY_BYTE) {
        (*env)->SetByteArrayRegion(env, arr, 0, sz, (const jbyte *) PyArray_DATA(copy));
    } else if (paType == NPY_INT16) {
        (*env)->SetShortArrayRegion(env, arr, 0, sz,
                                    (const jshort *) PyArray_DATA(copy));
    } else if (paType == NPY_INT32) {
        (*env)->SetIntArrayRegion(env, arr, 0, sz, (const jint *) PyArray_DATA(copy));
    } else if (paType == NPY_INT64) {
        (*env)->SetLongArrayRegion(env, arr, 0, sz, (const jlong *) PyArray_DATA(copy));
    } else if (paType == NPY_FLOAT32) {
        (*env)->SetFloatArrayRegion(env, arr, 0, sz,
                                    (const jfloat *) PyArray_DATA(copy));
    } else if (paType == NPY_FLOAT64) {
        (*env)->SetDoubleArrayRegion(env, arr, 0, sz,
                                     (const jdouble *) PyArray_DATA(copy));
    }

    Py_XDECREF(copy);

    if (process_java_exception(env)) {
        PyErr_Format(PyExc_RuntimeError, "Error setting Java primitive array region");
        return NULL;
    }

    return arr;
}
Esempio n. 16
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;
}
Esempio n. 17
0
DimensionDictionary::DimensionDictionary(PyObject * dim_dict)
{
  // Check that dim_dict is a dictionary
  if (!PyDict_Check(dim_dict))
  {
    PyErr_SetString(PyExc_TypeError,
                    "'dim_dict' element is not a dictionary");
    throw PythonException();
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "dim_dict = " << PyString_AsString(PyObject_Str(dim_dict))
            << std::endl;
#endif

  ////////////////////////////////
  // Get the 'dist_type' attribute
  ////////////////////////////////
  PyObject * distTypeObj = PyDict_GetItemString(dim_dict, "dist_type");
  if (distTypeObj == NULL)
  {
    PyErr_SetString(PyExc_KeyError,
                    "'dim_dict' has no 'dist_type' key");
    throw PythonException();
  }
  if (!PyString_Check(distTypeObj))
  {
    PyErr_SetString(PyExc_TypeError,
                    "'dist_type' is not a string");
    throw PythonException();
  }
  char * distTypeStr = PyString_AsString(distTypeObj);
  if (strcmp(distTypeStr, "b") == 0)
    dist_type = BLOCK;
  else if (strcmp(distTypeStr, "c") == 0)
    dist_type = CYCLIC;
  else if (strcmp(distTypeStr, "u") == 0)
    dist_type = UNSTRUCTURED;
  else
  {
    PyErr_Format(PyExc_ValueError,
                 "'dist_type' value '%s' is unrecognized",
                 distTypeStr);
    throw PythonException();
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  dist_type = '" << distTypeStr << "'" << std::endl;
#endif

  ///////////////////////////
  // Get the 'size' attribute
  ///////////////////////////
  PyObject * sizeObj = PyDict_GetItemString(dim_dict, "size");
  if (sizeObj == NULL)
  {
    PyErr_SetString(PyExc_KeyError,
                    "'dim_dict' required key 'size' not present");
    throw PythonException();
  }
  if (!PyInt_Check(sizeObj))
  {
    PyErr_Format(PyExc_TypeError, "'size' is not an int");
    throw PythonException();
  }
  size = PyInt_AsLong(sizeObj);
  if (size < 0)
  {
    PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'size' = %d is less "
                 "than zero", size);
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  size = " << size << std::endl;
#endif

  /////////////////////////////////////
  // Get the 'proc_grid_size' attribute
  /////////////////////////////////////
  PyObject * commDimObj = PyDict_GetItemString(dim_dict, "proc_grid_size");
  if (commDimObj == NULL)
  {
    PyErr_SetString(PyExc_KeyError,
                    "'dim_dict' required key 'proc_grid_size' not present");
    throw PythonException();
  }
  if (!PyInt_Check(commDimObj))
  {
    PyErr_Format(PyExc_TypeError,
                 "'proc_grid_size' is not an int");
    throw PythonException();
  }
  proc_grid_size = PyInt_AsLong(commDimObj);
  if (proc_grid_size < 1)
  {
    PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'proc_grid_size' = "
                 "%d is less than one", proc_grid_size);
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  proc_grid_size = " << proc_grid_size << std::endl;
#endif

  /////////////////////////////////////
  // Get the 'proc_grid_rank' attribute
  /////////////////////////////////////
  PyObject * commRankObj = PyDict_GetItemString(dim_dict, "proc_grid_rank");
  if (commRankObj == NULL)
  {
    PyErr_SetString(PyExc_KeyError,
                    "'dim_dict' required key 'proc_grid_rank' not present");
    throw PythonException();
  }
  if (!PyInt_Check(commRankObj))
  {
    PyErr_Format(PyExc_TypeError,
                 "'proc_grid_rank' is not an int");
    throw PythonException();
  }
  proc_grid_rank = PyInt_AsLong(commRankObj);
  if ((proc_grid_rank < 0) || (proc_grid_rank >= proc_grid_size))
  {
    PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'proc_grid_rank' = "
                 "%d is out of range [0, %d)", proc_grid_rank, proc_grid_size);
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  proc_grid_rank = " << proc_grid_rank << std::endl;
#endif

  ////////////////////////////
  // Get the 'start' attribute
  ////////////////////////////
  PyObject * startObj = PyDict_GetItemString(dim_dict, "start");
  if (startObj == NULL)
  {
    if ((dist_type == BLOCK) || (dist_type == CYCLIC))
    {
      PyErr_SetString(PyExc_KeyError,
                      "'dim_dict' is of type BLOCK or CYCLIC but has no "
                      "'start' key");
      throw PythonException();
    }
    else
    {
      start = -1;
    }
  }
  else
  {
    if (!PyInt_Check(startObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'start' is not an int");
      throw PythonException();
    }
    start = PyInt_AsLong(startObj);
    if ((start < 0) || (start > size))
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'start' = "
                   "%d is out of range [0, %d]", start, size);
    }
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  start = " << start << std::endl;
#endif

  ///////////////////////////
  // Get the 'stop' attribute
  ///////////////////////////
  PyObject * stopObj = PyDict_GetItemString(dim_dict, "stop");
  if (stopObj == NULL)
  {
    if (dist_type == BLOCK)
    {
      PyErr_SetString(PyExc_KeyError,
                      "'dim_dict' is of type BLOCK but has no 'stop' key");
      throw PythonException();
    }
    else
    {
      stop = -1;
    }
  }
  else
  {
    if (!PyInt_Check(stopObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'stop' for axis %d is not an int");
      throw PythonException();
    }
    stop = PyInt_AsLong(stopObj);
    if ((stop < 0) || (stop > size))
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'stop' = "
                   "%d is out of range [0, %d]", stop, size);
    }
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  stop = " << stop << std::endl;
#endif

  /////////////////////////////////
  // Get the 'block_size' attribute
  /////////////////////////////////
  PyObject * blockSizeObj = PyDict_GetItemString(dim_dict, "block_size");
  if (blockSizeObj == NULL)
  {
    block_size = 1;
  }
  else
  {
    if (!PyInt_Check(blockSizeObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'block_size' is not an int");
      throw PythonException();
    }
    block_size = PyInt_AsLong(stopObj);
    if (block_size < 1)
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'block_size' = "
                   "%d is less than one", block_size);
    }
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  block_size = " << block_size << std::endl;
#endif

  //////////////////////////////
  // Get the 'padding' attribute
  //////////////////////////////
  PyObject * paddingObj = PyDict_GetItemString(dim_dict, "padding");
  if (paddingObj == NULL)
  {
    padding[0] = 0;
    padding[1] = 0;
  }
  else
  {
    if (!PySequence_Check(paddingObj))
    {
      PyErr_SetString(PyExc_ValueError, "'padding' attribute must be a "
                      "sequence of two integers");
      throw PythonException();
    }
    if (PySequence_Size(paddingObj) != 2)
    {
      PyErr_SetString(PyExc_ValueError, "'padding' attribute must be a "
                      "sequence of two integers");
      throw PythonException();
    }
    PyObject * padObj = PySequence_GetItem(padObj, 0);
    if (!PyInt_Check(padObj))
    {
      PyErr_SetString(PyExc_TypeError, "Lower 'padding' object is not an "
                      "integer");
      throw PythonException();
    }
    padding[0] = PyInt_AsLong(padObj);
    if (padding[0] < 0)
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'padding'[0] = "
                   "%d is less than zero", padding[0]);
    }
    padObj = PySequence_GetItem(padObj, 1);
    if (!PyInt_Check(padObj))
    {
      PyErr_SetString(PyExc_TypeError, "Upper 'padding' object is not an "
                      "integer");
      throw PythonException();
    }
    padding[1] = PyInt_AsLong(padObj);
    if (padding[1] < 0)
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'padding'[1] = "
                   "%d is less than zero", padding[1]);
    }
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  padding = " << padding << std::endl;
#endif

  ///////////////////////////////
  // Get the 'periodic' attribute
  ///////////////////////////////
  PyObject * periodicObj = PyDict_GetItemString(dim_dict, "periodic");
  if (periodicObj == NULL)
  {
    periodic = false;
  }
  else
  {
    if (!PyBool_Check(periodicObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'periodic' is not a bool");
      throw PythonException();
    }
    if (periodicObj == Py_True) periodic = true;
    else                        periodic = false;
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  periodic = " << (periodic ? "true" : "false") << std::endl;
#endif

  /////////////////////////////////
  // Get the 'one_to_one' attribute
  /////////////////////////////////
  PyObject * oneToOneObj = PyDict_GetItemString(dim_dict, "one_to_one");
  if (oneToOneObj == NULL)
  {
    one_to_one = false;
  }
  else
  {
    if (!PyBool_Check(oneToOneObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'one_to_one' is not a bool");
      throw PythonException();
    }
    if (oneToOneObj == Py_True) one_to_one = true;
    else                        one_to_one = false;
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  one_to_one = " << (one_to_one ? "true" : "false")
            << std::endl;
#endif

  //////////////////////////////
  // Get the 'indices' attribute
  //////////////////////////////
  PyObject * indicesObj = PyDict_GetItemString(dim_dict, "indices");
  if (indicesObj == NULL)
  {
    if (dist_type == UNSTRUCTURED)
    {
      PyErr_SetString(PyExc_KeyError, "'dim_dict' with type UNSTRUCTURED "
                      "requires 'indices' key");
      throw PythonException();
    }
  }
  else
  {
    PyObject * indicesArray =
      PyArray_ContiguousFromAny(indicesObj, NPY_INT, 1, 1);
    if (indicesArray == NULL)
    {
      PyErr_SetString(PyExc_ValueError, "'dim_dict' attribute 'indices' "
                      "specified illegally");
      throw PythonException();
    }
    npy_intp numIndices = PyArray_Size(indicesArray);
    indices.resize(numIndices);
    int * source = (int*) PyArray_DATA((PyArrayObject*)indicesArray);
    for (IndicesType::size_type i = 0; i < numIndices; ++i)
      indices[i] = *(source++);
    Py_DECREF(indicesArray);
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  indices = " << indices() << std::endl;
#endif
}
Esempio n. 18
0
static PyObject * GcTrace_wrap(PyObject *self, PyObject *args)
{
  long ntotal;
  PyObject *oxp, *oyp, *onp;
  PyArrayObject *xcpdata, *ycpdata, *npdata;
  int npsize, n, p, start = 0, end = 0;
  PyObject *point, *contourList, *all_contours;

  if (!PyArg_ParseTuple(args,"OOO", &onp, &oxp, &oyp))
    return NULL;

  npdata = (PyArrayObject *) PyArray_ContiguousFromObject(onp, 'l', 1, 1);
  xcpdata = (PyArrayObject *) PyArray_ContiguousFromObject(oxp, 'd', 1, 1);
  ycpdata = (PyArrayObject *) PyArray_ContiguousFromObject(oyp, 'd', 1, 1 );

  if (npdata->nd != 1)
  {
     PyErr_SetString(PyExc_ValueError, "Argument np must be a 1D array");   
     return NULL;
  }

  if (xcpdata->nd != 1)
  {
     PyErr_SetString(PyExc_ValueError, "Argument xp must be a 1D array");   
     return NULL;
  }

  if (ycpdata->nd != 1)
  {
     PyErr_SetString(PyExc_ValueError, "Argument yp must be a 1D array");
     return NULL;
  }


  ntotal = GcTrace( (long *) npdata->data, (double *) xcpdata->data, (double *) ycpdata->data);
  npsize = PyArray_Size((PyObject *) npdata);

  all_contours = PyList_New(0);

  for (n = 0; n<npsize; n++)
     {
	start = end;
	end = start + ((long *) npdata->data)[n];
	contourList = PyList_New(0);	
	for (p = start; p<end; p++)
	{
	   point = Py_BuildValue("(d,d)", ((double *) xcpdata->data)[p],((double *) ycpdata->data)[p]);
	   if (PyList_Append(contourList, point))     	
	   {
	      printf ("Error in appending to list\n");
	      return NULL;
	      }
	  }
	if (PyList_Append(all_contours, contourList))
	  {
	    printf ("error in appending to all_contours\n");
	    return NULL;
	  }
	}
return Py_BuildValue("O", all_contours);  
}
Esempio n. 19
0
// Read one table for one sweep value. Returns:
//   0 ... performed normally
//   1 ... error occurred
// Arguments:
//   f              ... pointer to file for reading
//   debugMode      ... debug messages flag
//   fileName       ... name of the file
//   sweep          ... sweep parameter name
//   numOfVariables ... number of variables in table
//   type           ... type of variables with exeption of scale
//   numOfVectors   ... number of variables and probes in table
//   faSweep        ... pointer to fast access structure for sweep array
//   tmpArray       ... array of pointers to arrays
//   faPtr          ... array of fast access structures for vector arrays
//   scale          ... scale name
//   name           ... array of vector names
//   dataList       ... list of data dictionaries
int readTable(FILE *f, int debugMode, int postVersion,
        const char *fileName, PyObject *sweep,
        int numOfVariables, int type, int numOfVectors,
        struct FastArray *faSweep, PyObject **tmpArray,
        struct FastArray *faPtr, char *scale, char **name, PyObject *dataList)
{
    int i, j, num, offset = 0, numOfColumns = numOfVectors;
    npy_intp dims;
    float *rawDataPos, *rawData = NULL;
    PyObject *data = NULL;

    // Read raw data blocks.
    do num = readDataBlock(f, debugMode, postVersion, fileName, &rawData, &offset);
    while(num == 0);
    if(num > 0) goto readTableFailed;

    data = PyDict_New();    // Create an empty dictionary.
    if(data == NULL)
    {
        if(debugMode)
            fprintf(debugFile, "HSpiceRead: failed to create data dictionary.\n");
        goto readTableFailed;
    }

    // Increase number of columns if variables with exeption of scale are complex.
    if(type == complex_var) numOfColumns = numOfColumns + numOfVariables - 1;

    rawDataPos = rawData;


    // TODO check sweeps with postVersion == 2001
    if(postVersion == 2001)
    {
        if(sweep == NULL) num = (offset - 1) / numOfColumns
            / 2;    // Number of rows.
        else
        {
            num = (offset - 2) / numOfColumns / 2;
            *((npy_double *)(faSweep->pos)) = *((double*)rawDataPos);
                // Save sweep value.
            rawDataPos = rawDataPos + 2;
            faSweep->pos = faSweep->pos + faSweep->stride;
        }
    }
    else
    {
        if(sweep == NULL) num = (offset - 1) / numOfColumns;    // Number of rows.
        else
        {
            num = (offset - 2) / numOfColumns;
            *((npy_double *)(faSweep->pos)) = *rawDataPos;    // Save sweep value.
            rawDataPos = rawDataPos + 1;
            faSweep->pos = faSweep->pos + faSweep->stride;
        }
    }

    if(debugMode) fprintf(debugFile, "num=%d\n", num);

    for(i = 0; i < numOfVectors; i++)
    {
        // Create array for i-th vector.
        dims=num;
        if(type == complex_var && i > 0 && i < numOfVariables)
            tmpArray[i] = PyArray_SimpleNew(1, &dims, PyArray_CDOUBLE);
        else
            tmpArray[i] = PyArray_SimpleNew(1, &dims, PyArray_DOUBLE);
        if(tmpArray[i] == NULL)
        {
            if(debugMode)
                fprintf(debugFile, "HSpiceRead: failed to create array.\n");
            for(j = 0; j < i + 1; j++) Py_XDECREF(tmpArray[j]);
            goto readTableFailed;
        }
    }

    for(i = 0; i < numOfVectors; i++)    // Prepare fast access structures.
    {
        faPtr[i].data = ((PyArrayObject *)(tmpArray[i]))->data;
        faPtr[i].pos = ((PyArrayObject *)(tmpArray[i]))->data;
        faPtr[i].stride =
            ((PyArrayObject *)(tmpArray[i]))->strides[((PyArrayObject *)(tmpArray[i]))->nd -
            1];
        faPtr[i].length = PyArray_Size(tmpArray[i]);
    }


    if(postVersion == 2001)
    {
        for(i = 0; i < num; i++)    // Save raw data.
        {
            struct FastArray *faPos = faPtr;
            for(j = 0; j < numOfVectors; j++)
            {
                if(type == complex_var && j > 0 && j < numOfVariables)
                {
                    ((npy_cdouble *)(faPos->pos))->real = *((double *)rawDataPos);
                    rawDataPos = rawDataPos + 2;
                    ((npy_cdouble *)(faPos->pos))->imag = *((double *)rawDataPos);
                } else *((npy_double *)(faPos->pos)) = *((double *)rawDataPos);
                rawDataPos = rawDataPos + 2;
                faPos->pos = faPos->pos + faPos->stride;
                faPos = faPos + 1;
            }
        }
    }
    else
    {
        for(i = 0; i < num; i++)    // Save raw data.
        {
            struct FastArray *faPos = faPtr;
            for(j = 0; j < numOfVectors; j++)
            {
                if(type == complex_var && j > 0 && j < numOfVariables)
                {
                    ((npy_cdouble *)(faPos->pos))->real = *rawDataPos;
                    rawDataPos = rawDataPos + 1;
                    ((npy_cdouble *)(faPos->pos))->imag = *rawDataPos;
                } else *((npy_double *)(faPos->pos)) = *rawDataPos;
                rawDataPos = rawDataPos + 1;
                faPos->pos = faPos->pos + faPos->stride;
                faPos = faPos + 1;
            }
        }
    }
    PyMem_Free(rawData);
    rawData = NULL;

    // Insert vectors into dictionary.
    num = PyDict_SetItemString(data, scale, tmpArray[0]);
    i = -1;
    if(num == 0) for(i = 0; i < numOfVectors - 1; i++)
    {
        num = PyDict_SetItemString(data, name[i], tmpArray[i + 1]);
        if(num != 0) break;
    }
    for(j = 0; j < numOfVectors; j++) Py_XDECREF(tmpArray[j]);
    if(num)
    {
        if(debugMode) {
            if(i == -1) fprintf(debugFile,
                    "HSpiceRead: failed to insert vector %s into dictionary.\n",
                    scale);
            else fprintf(debugFile,
                    "HSpiceRead: failed to insert vector %s into dictionary.\n",
                    name[i]);
        }

        goto readTableFailed;
    }

    // Insert table into the list of data dictionaries.
    num = PyList_Append(dataList, data);
    if(num)
    {
        if(debugMode) fprintf(debugFile,
                "HSpiceRead: failed to append table to the list of data dictionaries.\n");
        goto readTableFailed;
    }
    Py_XDECREF(data);
    data = NULL;

    return 0;

readTableFailed:
    PyMem_Free(rawData);
    Py_XDECREF(data);
    return 1;
}
Esempio n. 20
0
static PyObject *
odepack_odeint(PyObject *dummy, PyObject *args, PyObject *kwdict)
{
    PyObject *fcn, *y0, *p_tout, *o_rtol = NULL, *o_atol = NULL;
    PyArrayObject *ap_y = NULL, *ap_yout = NULL;
    PyArrayObject *ap_rtol = NULL, *ap_atol = NULL;
    PyArrayObject *ap_tout = NULL;
    PyObject *extra_args = NULL;
    PyObject *Dfun = Py_None;
    int neq, itol = 1, itask = 1, istate = 1, iopt = 0, lrw, *iwork, liw, jt = 4;
    double *y, t, *tout, *rtol, *atol, *rwork;
    double h0 = 0.0, hmax = 0.0, hmin = 0.0;
    int ixpr = 0, mxstep = 0, mxhnil = 0, mxordn = 12, mxords = 5, ml = -1, mu = -1;
    PyObject *o_tcrit = NULL;
    PyArrayObject *ap_tcrit = NULL;
    PyArrayObject *ap_hu = NULL, *ap_tcur = NULL, *ap_tolsf = NULL, *ap_tsw = NULL;
    PyArrayObject *ap_nst = NULL, *ap_nfe = NULL, *ap_nje = NULL, *ap_nqu = NULL;
    PyArrayObject *ap_mused = NULL;
    int imxer = 0, lenrw = 0, leniw = 0, col_deriv = 0;
    npy_intp out_sz = 0, dims[2];
    int k, ntimes, crit_ind = 0;
    int allocated = 0, full_output = 0, numcrit = 0;
    double *yout, *yout_ptr, *tout_ptr, *tcrit;
    double *wa;
    static char *kwlist[] = {"fun", "y0", "t", "args", "Dfun", "col_deriv",
                             "ml", "mu", "full_output", "rtol", "atol", "tcrit",
                             "h0", "hmax", "hmin", "ixpr", "mxstep", "mxhnil",
                             "mxordn", "mxords", NULL};
    odepack_params save_params;

    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "OOO|OOiiiiOOOdddiiiii", kwlist,
                                     &fcn, &y0, &p_tout, &extra_args, &Dfun,
                                     &col_deriv, &ml, &mu, &full_output, &o_rtol, &o_atol,
                                     &o_tcrit, &h0, &hmax, &hmin, &ixpr, &mxstep, &mxhnil,
                                     &mxordn, &mxords)) {
        return NULL;
    }

    if (o_tcrit == Py_None) {
        o_tcrit = NULL;
    }
    if (o_rtol == Py_None) {
        o_rtol = NULL;
    }
    if (o_atol == Py_None) {
        o_atol = NULL;
    }

    /* Set up jt, ml, and mu */
    if (Dfun == Py_None) {
        /* set jt for internally generated */
        jt++;
    }
    if (ml < 0 && mu < 0) {
        /* neither ml nor mu given, mark jt for full jacobian */
        jt -= 3;
    }
    if (ml < 0) {
        /* if one but not both are given */
        ml = 0;
    }
    if (mu < 0) {
        mu = 0;
    }

    /* Stash the current global_params in save_params. */
    memcpy(&save_params, &global_params, sizeof(save_params));

    if (extra_args == NULL) {
        if ((extra_args = PyTuple_New(0)) == NULL) {
            goto fail;
        }
    }
    else {
        Py_INCREF(extra_args);   /* We decrement on exit. */
    }
    if (!PyTuple_Check(extra_args)) {
        PYERR(odepack_error, "Extra arguments must be in a tuple");
    }
    if (!PyCallable_Check(fcn) || (Dfun != Py_None && !PyCallable_Check(Dfun))) {
        PYERR(odepack_error, "The function and its Jacobian must be callable functions.");
    }

    /* Set global_params from the function arguments. */
    global_params.python_function = fcn;
    global_params.extra_arguments = extra_args;
    global_params.python_jacobian = Dfun;
    global_params.jac_transpose = !(col_deriv);
    global_params.jac_type = jt;

    /* Initial input vector */
    ap_y = (PyArrayObject *) PyArray_ContiguousFromObject(y0, NPY_DOUBLE, 0, 0);
    if (ap_y == NULL) {
        goto fail;
    }
    if (PyArray_NDIM(ap_y) > 1) {
        PyErr_SetString(PyExc_ValueError, "Initial condition y0 must be one-dimensional.");
        goto fail;
    }
    y = (double *) PyArray_DATA(ap_y);
    neq = PyArray_Size((PyObject *) ap_y);
    dims[1] = neq;

    /* Set of output times for integration */
    ap_tout = (PyArrayObject *) PyArray_ContiguousFromObject(p_tout, NPY_DOUBLE, 0, 0);
    if (ap_tout == NULL) {
        goto fail;
    }
    if (PyArray_NDIM(ap_tout) > 1) {
        PyErr_SetString(PyExc_ValueError, "Output times t must be one-dimensional.");
        goto fail;
    }
    tout = (double *) PyArray_DATA(ap_tout);
    ntimes = PyArray_Size((PyObject *)ap_tout);
    dims[0] = ntimes;
    t = tout[0];

    /* Setup array to hold the output evaluations*/
    ap_yout= (PyArrayObject *) PyArray_SimpleNew(2,dims,NPY_DOUBLE);
    if (ap_yout== NULL) {
        goto fail;
    }
    yout = (double *) PyArray_DATA(ap_yout);
    /* Copy initial vector into first row of output */
    memcpy(yout, y, neq*sizeof(double));  /* copy initial value to output */
    yout_ptr = yout + neq;    /* set output pointer to next position */

    itol = setup_extra_inputs(&ap_rtol, o_rtol, &ap_atol, o_atol, &ap_tcrit,
                              o_tcrit, &numcrit, neq);
    if (itol < 0 ) {
        goto fail;  /* Something didn't work */
    }
    rtol = (double *) PyArray_DATA(ap_rtol);
    atol = (double *) PyArray_DATA(ap_atol);
    if (o_tcrit != NULL) {
        tcrit = (double *)(PyArray_DATA(ap_tcrit));
    }

    /* Find size of working arrays*/
    if (compute_lrw_liw(&lrw, &liw, neq, jt, ml, mu, mxordn, mxords) < 0) {
        goto fail;
    }

    if ((wa = (double *)malloc(lrw*sizeof(double) + liw*sizeof(int)))==NULL) {
        PyErr_NoMemory();
        goto fail;
    }
    allocated = 1;
    rwork = wa;
    iwork = (int *)(wa + lrw);

    iwork[0] = ml;
    iwork[1] = mu;

    if (h0 != 0.0 || hmax != 0.0 || hmin != 0.0 || ixpr != 0 || mxstep != 0 ||
            mxhnil != 0 || mxordn != 0 || mxords != 0) {
        rwork[4] = h0;
        rwork[5] = hmax;
        rwork[6] = hmin;
        iwork[4] = ixpr;
        iwork[5] = mxstep;
        iwork[6] = mxhnil;
        iwork[7] = mxordn;
        iwork[8] = mxords;
        iopt = 1;
    }
    istate = 1;
    k = 1;

    /* If full output make some useful output arrays */
    if (full_output) {
        out_sz = ntimes-1;
        ap_hu = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_DOUBLE);
        ap_tcur = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_DOUBLE);
        ap_tolsf = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_DOUBLE);
        ap_tsw = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_DOUBLE);
        ap_nst = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        ap_nfe = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        ap_nje = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        ap_nqu = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        ap_mused = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        if (ap_hu == NULL || ap_tcur == NULL || ap_tolsf == NULL ||
                ap_tsw == NULL || ap_nst == NULL || ap_nfe == NULL ||
                ap_nje == NULL || ap_nqu == NULL || ap_mused == NULL) {
            goto fail;
        }
    }

    if (o_tcrit != NULL) {
        /* There are critical points */
        itask = 4;
        rwork[0] = *tcrit;
    }
    while (k < ntimes && istate > 0) {    /* loop over desired times */

        tout_ptr = tout + k;
        /* Use tcrit if relevant */
        if (itask == 4 && *tout_ptr > *(tcrit + crit_ind)) {
            crit_ind++;
            rwork[0] = *(tcrit+crit_ind);
        }
        if (crit_ind >= numcrit) {
            itask = 1;  /* No more critical values */
        }

        LSODA(ode_function, &neq, y, &t, tout_ptr, &itol, rtol, atol, &itask,
              &istate, &iopt, rwork, &lrw, iwork, &liw,
              ode_jacobian_function, &jt);
        if (full_output) {
            *((double *)PyArray_DATA(ap_hu) + (k-1)) = rwork[10];
            *((double *)PyArray_DATA(ap_tcur) + (k-1)) = rwork[12];
            *((double *)PyArray_DATA(ap_tolsf) + (k-1)) = rwork[13];
            *((double *)PyArray_DATA(ap_tsw) + (k-1)) = rwork[14];
            *((int *)PyArray_DATA(ap_nst) + (k-1)) = iwork[10];
            *((int *)PyArray_DATA(ap_nfe) + (k-1)) = iwork[11];
            *((int *)PyArray_DATA(ap_nje) + (k-1)) = iwork[12];
            *((int *)PyArray_DATA(ap_nqu) + (k-1)) = iwork[13];
            if (istate == -5 || istate == -4) {
                imxer = iwork[15];
            }
            else {
                imxer = -1;
            }
            lenrw = iwork[16];
            leniw = iwork[17];
            *((int *)PyArray_DATA(ap_mused) + (k-1)) = iwork[18];
        }
        if (PyErr_Occurred()) {
            goto fail;
        }
        memcpy(yout_ptr, y, neq*sizeof(double));  /* copy integration result to output*/
        yout_ptr += neq;
        k++;
    }

    /* Restore global_params from the previously stashed save_params. */
    memcpy(&global_params, &save_params, sizeof(save_params));

    Py_DECREF(extra_args);
    Py_DECREF(ap_atol);
    Py_DECREF(ap_rtol);
    Py_XDECREF(ap_tcrit);
    Py_DECREF(ap_y);
    Py_DECREF(ap_tout);
    free(wa);

    /* Do Full output */
    if (full_output) {
        return Py_BuildValue("N{s:N,s:N,s:N,s:N,s:N,s:N,s:N,s:N,s:i,s:i,s:i,s:N}i",
                    PyArray_Return(ap_yout),
                    "hu", PyArray_Return(ap_hu),
                    "tcur", PyArray_Return(ap_tcur),
                    "tolsf", PyArray_Return(ap_tolsf),
                    "tsw", PyArray_Return(ap_tsw),
                    "nst", PyArray_Return(ap_nst),
                    "nfe", PyArray_Return(ap_nfe),
                    "nje", PyArray_Return(ap_nje),
                    "nqu", PyArray_Return(ap_nqu),
                    "imxer", imxer,
                    "lenrw", lenrw,
                    "leniw", leniw,
                    "mused", PyArray_Return(ap_mused),
                    istate);
    }
    else {
        return Py_BuildValue("Ni", PyArray_Return(ap_yout), istate);
    }

fail:
    /* Restore global_params from the previously stashed save_params. */
    memcpy(&global_params, &save_params, sizeof(save_params));

    Py_XDECREF(extra_args);
    Py_XDECREF(ap_y);
    Py_XDECREF(ap_rtol);
    Py_XDECREF(ap_atol);
    Py_XDECREF(ap_tcrit);
    Py_XDECREF(ap_tout);
    Py_XDECREF(ap_yout);
    if (allocated) {
        free(wa);
    }
    if (full_output) {
        Py_XDECREF(ap_hu);
        Py_XDECREF(ap_tcur);
        Py_XDECREF(ap_tolsf);
        Py_XDECREF(ap_tsw);
        Py_XDECREF(ap_nst);
        Py_XDECREF(ap_nfe);
        Py_XDECREF(ap_nje);
        Py_XDECREF(ap_nqu);
        Py_XDECREF(ap_mused);
    }
    return NULL;
}
Esempio n. 21
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);
}
Esempio n. 22
0
void
ode_function(int *n, double *t, double *y, double *ydot)
{
    /*
    This is the function called from the Fortran code it should
        -- use call_python_function to get a multiarrayobject result
        -- check for errors and set *n to -1 if any
        -- otherwise place result of calculation in ydot
    */

    PyArrayObject *result_array = NULL;
    PyObject *arg1, *arglist;

    /* Append t to argument list */
    if ((arg1 = PyTuple_New(1)) == NULL) {
        *n = -1;
        return;
    }
    PyTuple_SET_ITEM(arg1, 0, PyFloat_FromDouble(*t));
    /* arg1 now owns newly created reference */
    if ((arglist = PySequence_Concat(arg1, global_params.extra_arguments)) == NULL) {
        *n = -1;
        Py_DECREF(arg1);
        return;
    }
    Py_DECREF(arg1);    /* arglist has reference */

    result_array = (PyArrayObject *)call_python_function(global_params.python_function,
                                                    *n, y, arglist, odepack_error);
    if (result_array == NULL) {
        *n = -1;
        Py_DECREF(arglist);
        return;
    }

    if (PyArray_NDIM(result_array) > 1) {
        *n = -1;
        PyErr_Format(PyExc_RuntimeError,
                "The array return by func must be one-dimensional, but got ndim=%d.",
                PyArray_NDIM(result_array));
        Py_DECREF(arglist);
        Py_DECREF(result_array);
        return;
    }

    if (PyArray_Size((PyObject *)result_array) != *n) {
        PyErr_Format(PyExc_RuntimeError,
            "The size of the array returned by func (%ld) does not match "
            "the size of y0 (%d).",
            PyArray_Size((PyObject *)result_array), *n);
        *n = -1;
        Py_DECREF(arglist);
        Py_DECREF(result_array);
        return;
    }

    memcpy(ydot, PyArray_DATA(result_array), (*n)*sizeof(double));
    Py_DECREF(result_array);
    Py_DECREF(arglist);
    return;
}
Esempio n. 23
0
int
setup_extra_inputs(PyArrayObject **ap_rtol, PyObject *o_rtol,
                   PyArrayObject **ap_atol, PyObject *o_atol,
                   PyArrayObject **ap_tcrit, PyObject *o_tcrit,
                   int *numcrit, int neq)
{
    int itol = 0;
    double tol = 1.49012e-8;
    npy_intp one = 1;

    /* Setup tolerances */
    if (o_rtol == NULL) {
        *ap_rtol = (PyArrayObject *) PyArray_SimpleNew(1, &one, NPY_DOUBLE);
        if (*ap_rtol == NULL) {
            PYERR2(odepack_error,"Error constructing relative tolerance.");
        }
        *(double *) PyArray_DATA(*ap_rtol) = tol;                /* Default */
    }
    else {
        *ap_rtol = (PyArrayObject *) PyArray_ContiguousFromObject(o_rtol,
                                                            NPY_DOUBLE, 0, 1);
        if (*ap_rtol == NULL) {
            PYERR2(odepack_error,"Error converting relative tolerance.");
        }
        /* XXX Fix the following. */
        if (PyArray_NDIM(*ap_rtol) == 0); /* rtol is scalar */
        else if (PyArray_DIMS(*ap_rtol)[0] == neq) {
            itol |= 2;      /* Set rtol array flag */
        }
        else {
            PYERR(odepack_error, "Tolerances must be an array of the same length as the\n     number of equations or a scalar.");
        }
    }

    if (o_atol == NULL) {
        *ap_atol = (PyArrayObject *) PyArray_SimpleNew(1, &one, NPY_DOUBLE);
        if (*ap_atol == NULL) {
            PYERR2(odepack_error,"Error constructing absolute tolerance");
        }
        *(double *)PyArray_DATA(*ap_atol) = tol;
    }
    else {
        *ap_atol = (PyArrayObject *) PyArray_ContiguousFromObject(o_atol, NPY_DOUBLE, 0, 1);
        if (*ap_atol == NULL) {
            PYERR2(odepack_error,"Error converting absolute tolerance.");
        }
        /* XXX Fix the following. */
        if (PyArray_NDIM(*ap_atol) == 0); /* atol is scalar */
        else if (PyArray_DIMS(*ap_atol)[0] == neq) {
            itol |= 1;        /* Set atol array flag */
        }
        else {
            PYERR(odepack_error,"Tolerances must be an array of the same length as the\n     number of equations or a scalar.");
        }
    }
    itol++;             /* increment to get correct value */

    /* Setup t-critical */
    if (o_tcrit != NULL) {
        *ap_tcrit = (PyArrayObject *) PyArray_ContiguousFromObject(o_tcrit, NPY_DOUBLE, 0, 1);
        if (*ap_tcrit == NULL) {
            PYERR2(odepack_error,"Error constructing critical times.");
        }
        *numcrit = PyArray_Size((PyObject *) (*ap_tcrit));
    }
    return itol;

fail:       /* Needed for use of PYERR */
    return -1;
}
Esempio n. 24
0
PyObject *wrap_vis_sim(PyObject *self, PyObject *args){
	PyArrayObject *baseline, *src_dir, *src_int, *src_index, *freqs, *mfreqs, *beam_arr;
	PyArrayObject *vis_array;
	npy_intp N_fq, N_src, d0, d1, N_beam_fq, l, m;
	npy_float lmin, lmax, mmin, mmax, beamfqmin, beamfqmax;

	if(!PyArg_ParseTuple(args, "O!O!O!O!O!O!O!ffffff",   &PyArray_Type, &baseline, 
                                                         &PyArray_Type, &src_dir, 
                                                         &PyArray_Type, &src_int,
                                                         &PyArray_Type, &src_index,
                             				 &PyArray_Type, &freqs,
                                                         &PyArray_Type, &mfreqs,
                                                         &PyArray_Type, &beam_arr, 
                                                         &lmin, &lmax, &mmin, &mmax, 
                                                         &beamfqmin, &beamfqmax)){
	return NULL;
	}

	N_fq = PyArray_Size((PyObject *)freqs);
	N_src = PyArray_Size((PyObject *)src_int);

    //if the baseline is not 3 numbers, raise an error
    if (PyArray_Size((PyObject *)baseline) != 3){
        PyErr_Format(PyExc_ValueError, "Baseline vector length must be 3");
        return NULL;
    }
    
    //Check that there is one src_index for each source
    if (PyArray_Size((PyObject *)src_index) != N_src){
        PyErr_Format(PyExc_ValueError, "src_index.size != src_int.size");
        return NULL;
    }

    //Check that the length of mfreqs = the number of sources
    if (PyArray_Size((PyObject *)mfreqs) != N_src){
        PyErr_Format(PyExc_ValueError, "mfreqs.size != src_int.size");
        return NULL;
    }

    //Check that src_dir is 2 dimensional, and one dimension is 3 long and the other is equal to N_src
    if (PyArray_NDIM(src_dir) != 2){
        PyErr_Format(PyExc_ValueError, "src_dir must be 2 dimensional");
        return NULL;
        }
    else{
        d0 = PyArray_DIM(src_dir, 0);
        d1 = PyArray_DIM(src_dir, 1);
        }

    if (!((d0 == N_src) && (d1 == (npy_intp) 3))){
        PyErr_Format(PyExc_ValueError, "src_dir must have 0th dimension = the length of src_int, and 1st dimension = 3");
        return NULL;
        }

    //Check that beam_arr is 3 dimensional.  If it is, set l, m, and N_beam_fq
    if (PyArray_NDIM(beam_arr) != 3){
        PyErr_Format(PyExc_ValueError, "beam_arr must be 3 dimensional");
        return NULL;
        }
    else{
        l         = PyArray_DIM(beam_arr, 0);
        m         = PyArray_DIM(beam_arr, 1);
        N_beam_fq = PyArray_DIM(beam_arr, 2);
        }

    //Check the type of the array inputs
    if (! (PyArray_ISFLOAT((PyObject *) baseline) && (PyArray_ISFLOAT((PyObject *) src_dir)) && (PyArray_ISFLOAT((PyObject *) src_int)) && (PyArray_ISFLOAT((PyObject *) src_index)) && (PyArray_ISFLOAT((PyObject *) freqs)) && (PyArray_ISFLOAT((PyObject *) mfreqs)) && (PyArray_ISFLOAT((PyObject *) beam_arr)))){
        PyErr_Format(PyExc_ValueError, "All arrays must be of floats");
        return NULL;
    }

    //Create the array to hold the output
	vis_array     = (PyArrayObject *) PyArray_SimpleNew(PyArray_NDIM(freqs),    PyArray_DIMS(freqs),    NPY_CFLOAT);

	vis_sim(
	(float *)PyArray_DATA(baseline), // access pointer to data buffer, cast as floats
	(float *)PyArray_DATA(src_dir),
	(float *)PyArray_DATA(src_int),
	(float *)PyArray_DATA(src_index),
	(float *)PyArray_DATA(freqs),
	(float *)PyArray_DATA(mfreqs),
	(float *)PyArray_DATA(vis_array), 
	(float *)PyArray_DATA(beam_arr),
    l, m, N_beam_fq, lmin, lmax, mmin, mmax, beamfqmin, beamfqmax,
    N_fq, N_src // pass pointer to sum buffer to hold result
	);

	return PyArray_Return(vis_array);
	}
Esempio n. 25
0
static PyObject *AscanfCall( ascanf_Function *af, PyObject *arglist, long repeats, int asarray, int deref,
						PAO_Options *opts, char *caller )
{ int fargs= 0, aargc= 0, volatile_args= 0;
  double result= 0, *aresult=NULL;
  static double *AARGS= NULL;
  static char *ATYPE= NULL;
  static ascanf_Function *LAF= NULL;
  static size_t LAFN= 0;
  double *aargs= NULL;
  char *atype= NULL;
  ascanf_Function *laf= NULL, *af_array= NULL;
  size_t lafN= 0;
  PyObject *ret= NULL;
  static ascanf_Function *nDindex= NULL;
  int aV = ascanf_verbose;

	if( arglist ){
		if( PyList_Check(arglist) ){
			if( !(arglist= PyList_AsTuple(arglist)) ){
 				PyErr_SetString( XG_PythonError, "unexpected failure converting argument list to tuple" );
// 				PyErr_SetString( PyExc_RuntimeError, "unexpected failure converting argument list to tuple" );
				return(NULL);
			}
		}
		if( !PyTuple_Check(arglist) ){
			PyErr_SetString(
 				XG_PythonError,
// 				PyExc_SyntaxError,
				"arguments to the ascanf method should be passed as a tuple or list\n"
				" NB: a 1-element tuple is specified as (value , ) !!\n"
			);
			return(NULL);
		}

		aargc= PyTuple_Size(arglist);
	}
	else{
		aargc= 0;
	}
	if( !af ){
		goto PAC_ESCAPE;
	}
	if( af->type!= _ascanf_procedure && af->Nargs> 0 ){
	  /* procedures can have as many arguments as MaxArguments, which is probably too much to allocate here.
	   \ However, we know how many arguments a function can get (if all's well...), and we can assure that
	   \ it will have space for those arguments
	   \ 20061015: unless it also has MaxArguments, i.e. Nargs<0 ...
	   */
		fargs= af->Nargs;
	}
	{ long n= (aargc+fargs+1)*2;
		if( opts->call_reentrant ){
			lafN= n;
			aargs= (double*) calloc( lafN, sizeof(double) );
			atype= (char*)  calloc( lafN, sizeof(char) );
			if( !aargs || !atype || !(laf= (ascanf_Function*) calloc( lafN, sizeof(ascanf_Function) )) ){
				PyErr_NoMemory();
				return(NULL);
			}
		}
		else{
			if( !LAF ){
				LAFN= n;
				AARGS= (double*) calloc( LAFN, sizeof(double) );
				ATYPE= (char*) calloc( LAFN, sizeof(char) );
				if( !AARGS || !ATYPE || !(LAF= (ascanf_Function*) calloc( LAFN, sizeof(ascanf_Function) )) ){
					PyErr_NoMemory();
					return(NULL);
				}
			}
			else if( n> LAFN ){
				AARGS= (double*) realloc( AARGS, n * sizeof(double) );
				ATYPE= (char*) realloc( ATYPE, n * sizeof(char) );
				if( !AARGS || !ATYPE || !(LAF= (ascanf_Function*) realloc( LAF, n * sizeof(ascanf_Function) )) ){
					PyErr_NoMemory();
					return(NULL);
				}
				else{
					for( ; LAFN< n; LAFN++ ){
						AARGS[LAFN]= 0;
						memset( &LAF[LAFN], 0, sizeof(ascanf_Function) );
					}
				}
				LAFN= n;
			}
			aargs= AARGS;
			atype= ATYPE;
			laf= LAF;
			lafN= LAFN;
		}
	}

	{ int a= 0, i;
		if( opts->verbose > 1 ){
			ascanf_verbose = 1;
		}
		if( af->type== _ascanf_array ){
			if( !nDindex ){
				nDindex= Py_getNamedAscanfVariable("nDindex");
			}
			if( nDindex ){
				af_array= af;
				aargs[a]= (af->own_address)? af->own_address : take_ascanf_address(af);
				af= nDindex;
				a+= 1;
			}
		}
		for( i= 0; i< aargc; i++, a++ ){
		  PyObject *arg= PyTuple_GetItem(arglist, i);
		  ascanf_Function *aaf;

			if( PyFloat_Check(arg) ){
				aargs[a]= PyFloat_AsDouble(arg);
				atype[a]= 1;
			}
#ifdef USE_COBJ
			else if( PyCObject_Check(arg) ){
				if( (aaf= PyCObject_AsVoidPtr(arg)) && (PyCObject_GetDesc(arg)== aaf->function) ){
					aargs[a]= (aaf->own_address)? aaf->own_address : take_ascanf_address(aaf);
					atype[a]= 2;
				}
				else{
 					PyErr_SetString( XG_PythonError, "unsupported PyCObject type does not contain ascanf pointer" );
// 					PyErr_SetString( PyExc_TypeError, "unsupported PyCObject type does not contain ascanf pointer" );
					goto PAC_ESCAPE;
				}
			}
#else
			else if( PyAscanfObject_Check(arg) ){
				if( (aaf= PyAscanfObject_AsAscanfFunction(arg)) ){
					aargs[a]= (aaf->own_address)? aaf->own_address : take_ascanf_address(aaf);
					atype[a]= 2;
				}
				else{
 					PyErr_SetString( XG_PythonError, "invalid PyAscanfObject type does not contain ascanf pointer" );
// 					PyErr_SetString( PyExc_TypeError, "invalid PyAscanfObject type does not contain ascanf pointer" );
					goto PAC_ESCAPE;
				}
			}
#endif
			else if( PyInt_Check(arg) || PyLong_Check(arg) ){
				aargs[a]= PyInt_AsLong(arg);
				atype[a]= 3;
			}
			else if( PyBytes_Check(arg)
#ifdef IS_PY3K
				|| PyUnicode_Check(arg)
#endif
			){
			  static char *AFname= "AscanfCall-Static-StringPointer";
			  ascanf_Function *saf= &laf[a];
				memset( saf, 0, sizeof(ascanf_Function) );
				saf->type= _ascanf_variable;
				saf->function= ascanf_Variable;
				if( !(saf->name= PyObject_Name(arg)) ){
					saf->name= XGstrdup(AFname);
				}
				saf->is_address= saf->take_address= True;
				saf->is_usage= saf->take_usage= True;
				saf->internal= True;
#ifdef IS_PY3K
				if( PyUnicode_Check(arg) ){
				  PyObject *bytes = NULL;
				  char *str = NULL;
					PYUNIC_TOSTRING( arg, bytes, str );
					if( !str ){
						if( bytes ){
							Py_XDECREF(bytes);
						}
						goto PAC_ESCAPE;
					}
					saf->usage= parse_codes( XGstrdup(str) );
					Py_XDECREF(bytes);
				}
				else
#endif
				{
					saf->usage= parse_codes( XGstrdup( PyBytes_AsString(arg) ) );
				}
				aargs[a]= take_ascanf_address(saf);
				atype[a]= 4;
				if( i && af_array ){
					volatile_args+= 1;
				}
			}
			else if( PyArray_Check(arg)
				|| PyTuple_Check(arg)
				|| PyList_Check(arg)
			){
			  static char *AFname= "AscanfCall-Static-ArrayPointer";
			  ascanf_Function *saf= &laf[a];
			  PyArrayObject *parray;
				atype[a]= 6;
				if( PyList_Check(arg) ){
					if( !(arg= PyList_AsTuple(arg)) ){
 						PyErr_SetString( XG_PythonError, "unexpected failure converting argument to tuple" );
// 						PyErr_SetString( PyExc_RuntimeError, "unexpected failure converting argument to tuple" );
						goto PAC_ESCAPE;
/* 						return(NULL);	*/
					}
					else{
						atype[a]= 5;
					}
				}
				memset( saf, 0, sizeof(ascanf_Function) );
				saf->type= _ascanf_array;
				saf->function= ascanf_Variable;
				if( !(saf->name= PyObject_Name(arg)) ){
					saf->name= XGstrdup(AFname);
				}
				saf->is_address= saf->take_address= True;
				saf->internal= True;
				if( a ){
					saf->car= &laf[a-1];
				}
				else{
					saf->car= &laf[lafN-1];
				}
				if( PyTuple_Check(arg) ){
					saf->N= PyTuple_Size(arg);
					parray= NULL;
				}
				else{
					saf->N= PyArray_Size(arg);
					parray= (PyArrayObject*) arg;
					atype[a]= 7;
				}
				if( (saf->array= (double*) malloc( saf->N * sizeof(double) )) ){
				  int j;
					if( parray ){
					  PyArrayObject* xd= NULL;
					  double *PyArrayBuf= NULL;
					  PyArrayIterObject *it;
						if( (xd = (PyArrayObject*) PyArray_ContiguousFromObject( (PyObject*) arg, PyArray_DOUBLE, 0, 0 )) ){
							PyArrayBuf= (double*)PyArray_DATA(xd); /* size would be N*sizeof(double) */
						}
						else{
							it= (PyArrayIterObject*) PyArray_IterNew(arg);
						}
						if( PyArrayBuf ){
// 							for( j= 0; j< saf->N; j++ ){
// 								  /* 20061016: indices used to be i?!?! */
// 								saf->array[j]= PyArrayBuf[j];
// 							}
							if( saf->array != PyArrayBuf ){
								memcpy( saf->array, PyArrayBuf, saf->N * sizeof(double) );
							}
						}
						else{
							for( j= 0; j< saf->N; j++ ){
								saf->array[j]= PyFloat_AsDouble( PyArray_DESCR(parray)->f->getitem( it->dataptr, arg) );
								PyArray_ITER_NEXT(it);
							}
						}
						if( xd ){
							Py_XDECREF(xd);
						}
						else{
							Py_DECREF(it);
						}
					}
					else{
						for( j= 0; j< saf->N; j++ ){
							saf->array[j]= PyFloat_AsDouble( PyTuple_GetItem(arg,j) );
						}
					}
					aargs[a]= take_ascanf_address(saf);
					if( i && af_array ){
						volatile_args+= 1;
					}
				}
				else{
					PyErr_NoMemory();
					goto PAC_ESCAPE;
				}
			}
#if 0
			else{
 				PyErr_SetString( XG_PythonError, "arguments should be scalars, strings, arrays or ascanf pointers" );
// 				PyErr_SetString( PyExc_SyntaxError, "arguments should be scalars, strings, arrays or ascanf pointers" );
				goto PAC_ESCAPE;
			}
#else
			else{
			  static char *AFname= "AscanfCall-Static-PyObject";
			  ascanf_Function *saf= &laf[a];
				memset( saf, 0, sizeof(ascanf_Function) );
				saf->function= ascanf_Variable;
				saf->internal= True;
				saf= make_ascanf_python_object( saf, arg, "AscanfCall" );
				if( !saf->name ){
					if( saf->PyObject_Name ){
						saf->name= XGstrdup(saf->PyObject_Name);
					}
					else{
						saf->name= XGstrdup(AFname);
					}
				}
				aargs[a]= take_ascanf_address(saf);
				atype[a]= 4;
				if( i && af_array ){
					volatile_args+= 1;
				}
			}
#endif
		}
		if( a> aargc ){
			aargc= a;
		}
	}
 const unsigned size() { return PyArray_Size(obj.get()); }
Esempio n. 27
0
int getSize1( void* arr ) {
	return (int) PyArray_Size( (PyObject *) arr );
}
// =============================================================================
int Epetra_NumPyMultiVector::getRangeLen(PyObject * range,
					 const Epetra_MultiVector & source)
{
  if (!tmp_range) getRange(range, source);
  return PyArray_Size((PyObject*)tmp_range);
}
Esempio n. 29
0
static PyObject * enz_vnmpocnp(PyObject *self, PyObject *args,
			       PyObject *keywds)
{
	static char *kwlist[] = { "r",		 "f",		"n",	       "m",	"L_max",
				  "bessel_name", "ncpus",	"verb",	       NULL };
	long syscpus = sysconf(_SC_NPROCESSORS_ONLN);

	PyObject *r_o, *f_o, *n_o, *m_o;
	PyObject *r = NULL;
	PyObject *f = NULL;
	PyObject *n = NULL;
	PyObject *m = NULL;
	const char *error = NULL;
	npy_intp r_n, f_n, beta_n;

	PyObject *vnm = NULL;
	npy_intp vnm_dims[3];

	double *datar = NULL;
	complex double *dataf = NULL;
	int *datan = NULL;
	int *datam = NULL;
	complex double *datap = NULL;

	int kL_max = 35;
	int kncpus = -1;
	int kverb = 0;
	char *kbessel_name = "jn";
	int ret;

	if (syscpus <= 0)
		syscpus = 1;

	if (!PyArg_ParseTupleAndKeywords(args, keywds, "O!O!O!O!|isii",
					 kwlist,
					 &PyArray_Type, &r_o,
					 &PyArray_Type, &f_o,
					 &PyArray_Type, &n_o,
					 &PyArray_Type, &m_o,
					 &kL_max, &kbessel_name, &kncpus, &kverb)) {
		PyErr_SetString(PyExc_SyntaxError, "failed to parse args");
		return NULL;
	}

	r = PyArray_FROM_OTF(r_o, NPY_FLOAT64, NPY_ARRAY_IN_ARRAY);
	f = PyArray_FROM_OTF(f_o, NPY_COMPLEX128, NPY_ARRAY_IN_ARRAY);
	n = PyArray_FROM_OTF(n_o, NPY_INT64, NPY_ARRAY_IN_ARRAY);
	m = PyArray_FROM_OTF(m_o, NPY_INT64, NPY_ARRAY_IN_ARRAY);

	if (!r) {
		PyErr_SetString(PyExc_ValueError, "cannot convert r to PyArray");
		return NULL;
	}
	if (!f) {
		PyErr_SetString(PyExc_ValueError, "cannot convert f to PyArray");
		return NULL;
	}
	if (!n) {
		PyErr_SetString(PyExc_ValueError, "cannot convert n to PyArray");
		return NULL;
	}
	if (!m) {
		PyErr_SetString(PyExc_ValueError, "cannot convert m to PyArray");
		return NULL;
	}

	if (!r || not_vect(r) || PyArray_TYPE((PyArrayObject*)r) != NPY_FLOAT64) {
		error = "r is not a vector of doubles";
		goto exit_decrement;
	}
	r_n = PyArray_DIM((PyArrayObject*)r, 0);

	if (!f || not_vect(f) ||
	    PyArray_TYPE((PyArrayObject*)f) != NPY_COMPLEX128) {
		error = "f is not a vector of complex numbers";
		goto exit_decrement;
	}
	f_n = PyArray_DIM((PyArrayObject*)f, 0);

	if (!n || not_vect(n) || PyArray_TYPE((PyArrayObject*)n) != NPY_INT64) {
		error = "n is not a vector of integers";
		goto exit_decrement;
	}
	if (!m || not_vect(m) || PyArray_TYPE((PyArrayObject*)m) != NPY_INT64) {
		error = "m is not a vector of integers";
		goto exit_decrement;
	}
	if (PyArray_DIM((PyArrayObject*)n, 0) !=
	    PyArray_DIM((PyArrayObject*)m, 0)) {
		error = "n and m must have the same length";
		goto exit_decrement;
	}
	beta_n = PyArray_DIM((PyArrayObject*)n, 0);

	vnm_dims[0] = r_n;
	vnm_dims[1] = f_n;
	vnm_dims[2] = beta_n;

	vnm = PyArray_New(&PyArray_Type, 3, vnm_dims, NPY_COMPLEX128, NULL, NULL,
			  0, NPY_ARRAY_F_CONTIGUOUS | NPY_ARRAY_ALIGNED, NULL);

	if (!vnm) {
		error = "cannot create vnm";
		goto exit_decrement;
	}

	PyArray_CLEARFLAGS((PyArrayObject*)vnm, NPY_ARRAY_C_CONTIGUOUS);

	assert(PyArray_Size(vnm) == (r_n * f_n * beta_n));
	assert(PyArray_NBYTES(vnm) == (r_n * f_n * beta_n * sizeof(double complex)));
	datap = PyArray_DATA((PyArrayObject*)vnm);

	if (kncpus < 0)
		kncpus = beta_n < syscpus ? beta_n : syscpus;
	else
		kncpus = kncpus > syscpus ? syscpus : kncpus;

	if ((r_n * f_n * beta_n) != 0) {
		datar = PyArray_DATA((PyArrayObject*)r);
		dataf = PyArray_DATA((PyArrayObject*)f);
		datan = PyArray_DATA((PyArrayObject*)n);
		datam = PyArray_DATA((PyArrayObject*)m);
		Py_BEGIN_ALLOW_THREADS
			ret = vnmpocnp(r_n, datar,
				       f_n, dataf,
				       beta_n,
				       datan, datam,
				       kL_max, kbessel_name,
				       kncpus,
				       kverb, datap, &error);
		Py_END_ALLOW_THREADS
		if (ret) {
			Py_XDECREF(vnm);
			goto exit_decrement;
		}
	}
Esempio n. 30
0
static
int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *dims) {
    /*
      This function fills in blanks (that are -1\'s) in dims list using
      the dimensions from arr. It also checks that non-blank dims will
      match with the corresponding values in arr dimensions.
    */
    const npy_intp arr_size = (PyArray_NDIM(arr))?PyArray_Size((PyObject *)arr):1;
#ifdef DEBUG_COPY_ND_ARRAY
    dump_attrs(arr);
    printf("check_and_fix_dimensions:init: dims=");
    dump_dims(rank,dims);
#endif
    if (rank > PyArray_NDIM(arr)) { /* [1,2] -> [[1],[2]]; 1 -> [[1]]  */
        npy_intp new_size = 1;
        int free_axe = -1;
        int i;
        npy_intp d;
        /* Fill dims where -1 or 0; check dimensions; calc new_size; */
        for(i=0;i<PyArray_NDIM(arr);++i) {
            d = PyArray_DIM(arr,i);
            if (dims[i] >= 0) {
                if (d>1 && dims[i]!=d) {
                    fprintf(stderr,"%d-th dimension must be fixed to %" NPY_INTP_FMT
                            " but got %" NPY_INTP_FMT "\n",
                            i,dims[i], d);
                    return 1;
                }
                if (!dims[i]) dims[i] = 1;
            } else {
                dims[i] = d ? d : 1;
            }
            new_size *= dims[i];
        }
        for(i=PyArray_NDIM(arr);i<rank;++i)
            if (dims[i]>1) {
                fprintf(stderr,"%d-th dimension must be %" NPY_INTP_FMT
                        " but got 0 (not defined).\n",
                        i,dims[i]);
                return 1;
            } else if (free_axe<0)
                free_axe = i;
            else
                dims[i] = 1;
        if (free_axe>=0) {
            dims[free_axe] = arr_size/new_size;
            new_size *= dims[free_axe];
        }
        if (new_size != arr_size) {
            fprintf(stderr,"unexpected array size: new_size=%" NPY_INTP_FMT
                    ", got array with arr_size=%" NPY_INTP_FMT " (maybe too many free"
                    " indices)\n", new_size,arr_size);
            return 1;
        }
    } else if (rank==PyArray_NDIM(arr)) {
        npy_intp new_size = 1;
        int i;
        npy_intp d;
        for (i=0; i<rank; ++i) {
	    d = PyArray_DIM(arr,i);
            if (dims[i]>=0) {
                if (d > 1 && d!=dims[i]) {
                    fprintf(stderr,"%d-th dimension must be fixed to %" NPY_INTP_FMT
                            " but got %" NPY_INTP_FMT "\n",
                            i,dims[i],d);
                    return 1;
                }
                if (!dims[i]) dims[i] = 1;
            } else dims[i] = d;
            new_size *= dims[i];
        }
        if (new_size != arr_size) {
            fprintf(stderr,"unexpected array size: new_size=%" NPY_INTP_FMT
                    ", got array with arr_size=%" NPY_INTP_FMT "\n", new_size,arr_size);
            return 1;
        }
    } else { /* [[1,2]] -> [[1],[2]] */
        int i,j;
        npy_intp d;
        int effrank;
        npy_intp size;
        for (i=0,effrank=0;i<PyArray_NDIM(arr);++i)
            if (PyArray_DIM(arr,i)>1) ++effrank;
        if (dims[rank-1]>=0)
            if (effrank>rank) {
                fprintf(stderr,"too many axes: %d (effrank=%d), expected rank=%d\n",
                        PyArray_NDIM(arr),effrank,rank);
                return 1;
            }

        for (i=0,j=0;i<rank;++i) {
            while (j<PyArray_NDIM(arr) && PyArray_DIM(arr,j)<2) ++j;
            if (j>=PyArray_NDIM(arr)) d = 1;
            else d = PyArray_DIM(arr,j++);
            if (dims[i]>=0) {
                if (d>1 && d!=dims[i]) {
                    fprintf(stderr,"%d-th dimension must be fixed to %" NPY_INTP_FMT
                            " but got %" NPY_INTP_FMT " (real index=%d)\n",
                            i,dims[i],d,j-1);
                    return 1;
                }
                if (!dims[i]) dims[i] = 1;
            } else
                dims[i] = d;
        }

        for (i=rank;i<PyArray_NDIM(arr);++i) { /* [[1,2],[3,4]] -> [1,2,3,4] */
            while (j<PyArray_NDIM(arr) && PyArray_DIM(arr,j)<2) ++j;
            if (j>=PyArray_NDIM(arr)) d = 1;
            else d = PyArray_DIM(arr,j++);
            dims[rank-1] *= d;
        }
        for (i=0,size=1;i<rank;++i) size *= dims[i];
        if (size != arr_size) {
            fprintf(stderr,"unexpected array size: size=%" NPY_INTP_FMT ", arr_size=%" NPY_INTP_FMT
                    ", rank=%d, effrank=%d, arr.nd=%d, dims=[",
                    size,arr_size,rank,effrank,PyArray_NDIM(arr));
            for (i=0;i<rank;++i) fprintf(stderr," %" NPY_INTP_FMT,dims[i]);
            fprintf(stderr," ], arr.dims=[");
            for (i=0;i<PyArray_NDIM(arr);++i) fprintf(stderr," %" NPY_INTP_FMT,PyArray_DIM(arr,i));
            fprintf(stderr," ]\n");
            return 1;
        }
    }
#ifdef DEBUG_COPY_ND_ARRAY
    printf("check_and_fix_dimensions:end: dims=");
    dump_dims(rank,dims);
#endif
    return 0;
}