static void
SWIG_Python_TypeError(const char *type, PyObject *obj)
{
  if (type) {
    if (!PyCObject_Check(obj)) {
      const char *otype = (obj ? obj->ob_type->tp_name : 0); 
      if (otype) {
	PyObject *str = PyObject_Str(obj);
	const char *cstr = str ? PyString_AsString(str) : 0;
	if (cstr) {
	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received",
		       type, otype, cstr);
	} else {
	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received",
		       type, otype);
	}
	Py_DECREF(str);
	return;
      }
    } else {
      const char *otype = (char *) PyCObject_GetDesc(obj);
      if (otype) {
	PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PyCObject(%s)' is received",
		     type, otype);
	return;
      }
    }   
    PyErr_Format(PyExc_TypeError, "a '%s' is expected", type);

  } else {
    PyErr_Format(PyExc_TypeError, "unexpected type is received");
  }
}
Example #2
0
static PyObject* diag(PyObject *self, PyObject *args)
{
    PyObject *F;
    matrix *d=NULL;
    cholmod_factor *L;
#if PY_MAJOR_VERSION >= 3
    const char *descr;
#else
    char *descr;
#endif
    int k, strt, incx=1, incy, nrows, ncols;

    if (!set_options()) return NULL;
    if (!PyArg_ParseTuple(args, "O", &F)) return NULL;

#if PY_MAJOR_VERSION >= 3
    if (!PyCapsule_CheckExact(F) || !(descr = PyCapsule_GetName(F)))
        err_CO("F");
    if (strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    L = (cholmod_factor *) PyCapsule_GetPointer(F, descr);
#else
    if (!PyCObject_Check(F)) err_CO("F");
    descr = PyCObject_GetDesc(F);
    if (!descr || strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    L = (cholmod_factor *) PyCObject_AsVoidPtr(F);
#endif

    /* Check factorization */
    if (L->xtype == CHOLMOD_PATTERN  || L->minor<L->n || !L->is_ll
        || !L->is_super)
        PY_ERR(PyExc_ValueError, "F must be a nonsingular supernodal "
            "Cholesky factor");
    if (!(d = Matrix_New(L->n,1,L->xtype == CHOLMOD_REAL ? DOUBLE :
        COMPLEX))) return PyErr_NoMemory();

    strt = 0;
    for (k=0; k<L->nsuper; k++){
	/* x[L->px[k], .... ,L->px[k+1]-1] is a dense lower-triangular
	 * nrowx times ncols matrix.  We copy its diagonal to
	 * d[strt, ..., strt+ncols-1] */

        ncols = (int)((int_t *) L->super)[k+1] -
            ((int_t *) L->super)[k];
        nrows = (int)((int_t *) L->pi)[k+1] - ((int_t *) L->pi)[k];
        incy = nrows+1;
        if (MAT_ID(d) == DOUBLE)
	    dcopy_(&ncols, ((double *) L->x) + ((int_t *) L->px)[k],
                &incy, MAT_BUFD(d)+strt, &incx);
        else
	    zcopy_(&ncols, ((double complex *) L->x) + ((int_t *) L->px)[k],
                &incy, MAT_BUFZ(d)+strt, &incx);
        strt += ncols;
    }
    return (PyObject *)d;
}
Example #3
0
static PyObject *Py_GeometricTransform(PyObject *obj, PyObject *args)
{
  PyArrayObject *input = NULL, *output = NULL;
  PyArrayObject *coordinates = NULL, *matrix = NULL, *shift = NULL;
  PyObject *fnc = NULL, *extra_arguments = NULL, *extra_keywords = NULL;
  int mode, order;
  double cval;
  void *func = NULL, *data = NULL;
  NI_PythonCallbackData cbdata;

  if (!PyArg_ParseTuple(args, "O&OO&O&O&O&iidOO", NI_ObjectToInputArray,
                        &input, &fnc, NI_ObjectToOptionalInputArray,
                        &coordinates, NI_ObjectToOptionalInputArray,
                        &matrix, NI_ObjectToOptionalInputArray, &shift,
                        NI_ObjectToOutputArray, &output, &order, &mode,
                        &cval, &extra_arguments, &extra_keywords))
    goto exit;

  if (fnc != Py_None) {
    if (!PyTuple_Check(extra_arguments)) {
      PyErr_SetString(PyExc_RuntimeError,
                      "extra_arguments must be a tuple");
      goto exit;
    }
    if (!PyDict_Check(extra_keywords)) {
      PyErr_SetString(PyExc_RuntimeError,
                      "extra_keywords must be a dictionary");
      goto exit;
    }
    if (PyCObject_Check(fnc)) {
      func = PyCObject_AsVoidPtr(fnc);
      data = PyCObject_GetDesc(fnc);
    } else if (PyCallable_Check(fnc)) {
      func = Py_Map;
      cbdata.function = fnc;
      cbdata.extra_arguments = extra_arguments;
      cbdata.extra_keywords = extra_keywords;
      data = (void*)&cbdata;
    } else {
      PyErr_SetString(PyExc_RuntimeError,
                      "function parameter is not callable");
      goto exit;
    }
  }

  if (!NI_GeometricTransform(input, func, data, matrix, shift, coordinates,
                          output, order, (NI_ExtendMode)mode, cval))
    goto exit;

exit:
  Py_XDECREF(input);
  Py_XDECREF(output);
  Py_XDECREF(coordinates);
  Py_XDECREF(matrix);
  Py_XDECREF(shift);
  return PyErr_Occurred() ? NULL : Py_BuildValue("");
}
Example #4
0
static PyObject *Py_GenericFilter(PyObject *obj, PyObject *args)
{
  PyArrayObject *input = NULL, *output = NULL, *footprint = NULL;
  PyObject *fnc = NULL, *extra_arguments = NULL, *extra_keywords = NULL;
  void *func = Py_FilterFunc, *data = NULL;
  NI_PythonCallbackData cbdata;
  int mode;
  maybelong *origin = NULL;
  double cval;

  if (!PyArg_ParseTuple(args, "O&OO&O&idO&OO", NI_ObjectToInputArray,
                        &input, &fnc, NI_ObjectToInputArray, &footprint,
                        NI_ObjectToOutputArray, &output, &mode, &cval,
                        NI_ObjectToLongSequence, &origin,
                        &extra_arguments, &extra_keywords))
    goto exit;
  if (!PyTuple_Check(extra_arguments)) {
    PyErr_SetString(PyExc_RuntimeError,
                    "extra_arguments must be a tuple");
    goto exit;
  }
  if (!PyDict_Check(extra_keywords)) {
    PyErr_SetString(PyExc_RuntimeError,
                    "extra_keywords must be a dictionary");
    goto exit;
  }
  if (PyCObject_Check(fnc)) {
    func = PyCObject_AsVoidPtr(fnc);
    data = PyCObject_GetDesc(fnc);
  } else if (PyCallable_Check(fnc)) {
    cbdata.function = fnc;
    cbdata.extra_arguments = extra_arguments;
    cbdata.extra_keywords = extra_keywords;
    data = (void*)&cbdata;
  } else {
    PyErr_SetString(PyExc_RuntimeError,
                    "function parameter is not callable");
    goto exit;
  }
  if (!NI_GenericFilter(input, func, data, footprint, output,
                        (NI_ExtendMode)mode, cval, origin))
    goto exit;
exit:
  Py_XDECREF(input);
  Py_XDECREF(output);
  Py_XDECREF(footprint);
  if (origin)
    free(origin);
  return PyErr_Occurred() ? NULL : Py_BuildValue("");
}
int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
    PyObject *d = 0;
    PyObject *cobj = 0;
    union {
        void (*fp)(void);
        void *p;
    } tmp;

    d = PyObject_GetAttrString(module, (char *)"__pyx_capi__");
    if (!d)
        goto bad;
    cobj = PyDict_GetItemString(d, funcname);
    if (!cobj) {
        PyErr_Format(PyExc_ImportError,
            "%s does not export expected C function %s",
                PyModule_GetName(module), funcname);
        goto bad;
    }
#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0)
    if (!PyCapsule_IsValid(cobj, sig)) {
        PyErr_Format(PyExc_TypeError,
            "C function %s.%s has wrong signature (expected %s, got %s)",
             PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj));
        goto bad;
    }
    tmp.p = PyCapsule_GetPointer(cobj, sig);
#else
    {const char *desc, *s1, *s2;
    desc = (const char *)PyCObject_GetDesc(cobj);
    if (!desc)
        goto bad;
    s1 = desc; s2 = sig;
    while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; }
    if (*s1 != *s2) {
        PyErr_Format(PyExc_TypeError,
            "C function %s.%s has wrong signature (expected %s, got %s)",
             PyModule_GetName(module), funcname, sig, desc);
        goto bad;
    }
    tmp.p = PyCObject_AsVoidPtr(cobj);}
#endif
    *f = tmp.fp;
    if (!(*f))
        goto bad;
    Py_DECREF(d);
    return 0;
bad:
    Py_XDECREF(d);
    return -1;
}
Example #6
0
static PyObject *show_ring(PyObject *self, PyObject *args) {
        PyObject *callback;
        if(!PyArg_ParseTuple(args, "O!", &PyCObject_Type, &callback))
        {
                return NULL;
        }
        if ((int)PyCObject_GetDesc(callback) != I_RING_CALLBACK)
        {
                PyErr_SetString(PyExc_StandardError, "Invalid callback");
                return NULL;
        }
        I_show_ring((i_ring_f)PyCObject_AsVoidPtr(callback));
        Py_RETURN_NONE;
}
Example #7
0
static PyObject* getfactor(PyObject *self, PyObject *args)
{
    PyObject *F;
    cholmod_factor *Lf;
    cholmod_sparse *Ls;
#if PY_MAJOR_VERSION >= 3
    const char *descr;
#else
    char *descr;
#endif

    if (!set_options()) return NULL;
    if (!PyArg_ParseTuple(args, "O", &F)) return NULL;

#if PY_MAJOR_VERSION >= 3
    if (!PyCapsule_CheckExact(F) || !(descr = PyCapsule_GetName(F)))
        err_CO("F");
    if (strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    Lf = (cholmod_factor *) PyCapsule_GetPointer(F, descr);
#else
    if (!PyCObject_Check(F)) err_CO("F");
    descr = PyCObject_GetDesc(F);
    if (!descr || strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    Lf = (cholmod_factor *) PyCObject_AsVoidPtr(F);
#endif

    /* Check factorization */
    if (Lf->xtype == CHOLMOD_PATTERN)
        PY_ERR(PyExc_ValueError, "F must be a numeric Cholesky factor");

    if (!(Ls = CHOL(factor_to_sparse)(Lf, &Common)))
        return PyErr_NoMemory();

    spmatrix *ret = SpMatrix_New(Ls->nrow, Ls->ncol, Ls->nzmax,
       (Ls->xtype == CHOLMOD_REAL ? DOUBLE : COMPLEX));
    if (!ret) {
        CHOL(free_sparse)(&Ls, &Common);
        return PyErr_NoMemory();
    }

    memcpy(SP_COL(ret), Ls->p, (Ls->ncol+1)*sizeof(int_t));
    memcpy(SP_ROW(ret), Ls->i, (Ls->nzmax)*sizeof(int_t));
    memcpy(SP_VAL(ret), Ls->x, (Ls->nzmax)*E_SIZE[SP_ID(ret)]);
    CHOL(free_sparse)(&Ls, &Common);

    return (PyObject *)ret;
}
SWIG_Python_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) {
  swig_type_info *tc;
  char  *c = 0;
  static PyObject *SWIG_this = 0;
  int    newref = 0;
  PyObject  *pyobj = 0;

  if (!obj) return 0;
  if (obj == Py_None) {
    *ptr = 0;
    return 0;
  }
#ifdef SWIG_COBJECT_TYPES
  if (!(PyCObject_Check(obj))) {
    if (!SWIG_this)
      SWIG_this = PyString_FromString("this");
    pyobj = obj;
    obj = PyObject_GetAttr(obj,SWIG_this);
    newref = 1;
    if (!obj) goto type_error;
    if (!PyCObject_Check(obj)) {
      Py_DECREF(obj);
      goto type_error;
    }
  }  
  *ptr = PyCObject_AsVoidPtr(obj);
  c = (char *) PyCObject_GetDesc(obj);
  if (newref) Py_DECREF(obj);
  goto cobject;
#else
  if (!(PyString_Check(obj))) {
    if (!SWIG_this)
      SWIG_this = PyString_FromString("this");
    pyobj = obj;
    obj = PyObject_GetAttr(obj,SWIG_this);
    newref = 1;
    if (!obj) goto type_error;
    if (!PyString_Check(obj)) {
      Py_DECREF(obj);
      goto type_error;
    }
  } 
  c = PyString_AsString(obj);
  /* Pointer values must start with leading underscore */
  if (*c != '_') {
    *ptr = (void *) 0;
    if (strcmp(c,"NULL") == 0) {
      if (newref) { Py_DECREF(obj); }
      return 0;
    } else {
      if (newref) { Py_DECREF(obj); }
      goto type_error;
    }
  }
  c++;
  c = SWIG_UnpackData(c,ptr,sizeof(void *));
  if (newref) { Py_DECREF(obj); }
#endif

#ifdef SWIG_COBJECT_TYPES
cobject:
#endif

  if (ty) {
    tc = SWIG_TypeCheck(c,ty);
    if (!tc) goto type_error;
    *ptr = SWIG_TypeCast(tc,(void*) *ptr);
  }

  if ((pyobj) && (flags & SWIG_POINTER_DISOWN)) {
    PyObject *zero = PyInt_FromLong(0);
    PyObject_SetAttrString(pyobj,(char*)"thisown",zero);
    Py_DECREF(zero);
  }
  return 0;

type_error:
  if (flags & SWIG_POINTER_EXCEPTION) {
    if (ty && c) {
      char *temp = (char *) malloc(64+strlen(ty->name)+strlen(c));
      sprintf(temp,"Type error. Got %s, expected %s", c, ty->name);
      PyErr_SetString(PyExc_TypeError, temp);
      free((char *) temp);
    } else {
      PyErr_SetString(PyExc_TypeError,"Expected a pointer");
    }
  }
  return -1;
}
Example #9
0
static PyObject* spsolve(PyObject *self, PyObject *args,
    PyObject *kwrds)
{
    spmatrix *B, *X=NULL;
    cholmod_sparse *Bc=NULL, *Xc=NULL;
    PyObject *F;
    cholmod_factor *L;
    int n, sys=0;
#if PY_MAJOR_VERSION >= 3
    const char *descr;
#else
    char *descr;
#endif
    char *kwlist[] = {"F", "B", "sys", NULL};
    int sysvalues[] = {CHOLMOD_A, CHOLMOD_LDLt, CHOLMOD_LD,
        CHOLMOD_DLt, CHOLMOD_L, CHOLMOD_Lt, CHOLMOD_D, CHOLMOD_P,
        CHOLMOD_Pt };

    if (!set_options()) return NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|i", kwlist, &F,
        &B, &sys)) return NULL;

#if PY_MAJOR_VERSION >= 3
    if (!PyCapsule_CheckExact(F) || !(descr = PyCapsule_GetName(F)))
        err_CO("F");
    if (strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    L = (cholmod_factor *) PyCapsule_GetPointer(F, descr);
#else
    if (!PyCObject_Check(F)) err_CO("F");
    descr = PyCObject_GetDesc(F);
    if (!descr || strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    L = (cholmod_factor *) PyCObject_AsVoidPtr(F);
#endif
    if (L->xtype == CHOLMOD_PATTERN)
        PY_ERR(PyExc_ValueError, "called with symbolic factor");
    n = L->n;
    if (L->minor<n) PY_ERR(PyExc_ArithmeticError, "singular matrix");

    if (sys < 0 || sys > 8)
         PY_ERR(PyExc_ValueError, "invalid value for sys");

    if (!SpMatrix_Check(B) ||
        (SP_ID(B) == DOUBLE  && L->xtype == CHOLMOD_COMPLEX) ||
        (SP_ID(B) == COMPLEX && L->xtype == CHOLMOD_REAL))
            PY_ERR_TYPE("B must a sparse matrix of the same "
                "numerical type as F");
    if (SP_NROWS(B) != n)
        PY_ERR(PyExc_ValueError, "incompatible dimensions for B");

    if (!(Bc = create_matrix(B))) return PyErr_NoMemory();
    Xc = CHOL(spsolve)(sysvalues[sys], L, Bc, &Common);
    free_matrix(Bc);
    if (Common.status == CHOLMOD_OUT_OF_MEMORY) return PyErr_NoMemory();
    if (Common.status != CHOLMOD_OK)
        PY_ERR(PyExc_ValueError, "solve step failed");

    if (!(X = SpMatrix_New(Xc->nrow, Xc->ncol,
        ((int_t*)Xc->p)[Xc->ncol], (L->xtype == CHOLMOD_REAL ? DOUBLE :
        COMPLEX)))) {
        CHOL(free_sparse)(&Xc, &Common);
        return PyErr_NoMemory();
    }
    memcpy(SP_COL(X), Xc->p, (Xc->ncol+1)*sizeof(int_t));
    memcpy(SP_ROW(X), Xc->i, ((int_t *)Xc->p)[Xc->ncol]*sizeof(int_t));
    memcpy(SP_VAL(X), Xc->x,
        ((int_t *) Xc->p)[Xc->ncol]*E_SIZE[SP_ID(X)]);
    CHOL(free_sparse)(&Xc, &Common);
    return (PyObject *) X;
}
Example #10
0
static PyObject* solve(PyObject *self, PyObject *args, PyObject *kwrds)
{
    matrix *B;
    PyObject *F;
    int i, n, oB=0, ldB=0, nrhs=-1, sys=0;
#if PY_MAJOR_VERSION >= 3
    const char *descr;
#else
    char *descr;
#endif
    char *kwlist[] = {"F", "B", "sys", "nrhs", "ldB", "offsetB", NULL};
    int sysvalues[] = { CHOLMOD_A, CHOLMOD_LDLt, CHOLMOD_LD,
        CHOLMOD_DLt, CHOLMOD_L, CHOLMOD_Lt, CHOLMOD_D, CHOLMOD_P,
        CHOLMOD_Pt };

    if (!set_options()) return NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|iiii", kwlist,
        &F, &B, &sys, &nrhs, &ldB, &oB)) return NULL;

#if PY_MAJOR_VERSION >= 3
    if (!PyCapsule_CheckExact(F) || !(descr = PyCapsule_GetName(F)))
        err_CO("F");
    if (strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    cholmod_factor *L = (cholmod_factor *) PyCapsule_GetPointer(F, descr);
#else
    if (!PyCObject_Check(F)) err_CO("F");
    descr = PyCObject_GetDesc(F);
    if (!descr || strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    cholmod_factor *L = (cholmod_factor *) PyCObject_AsVoidPtr(F);
#endif
    if (L->xtype == CHOLMOD_PATTERN)
        PY_ERR(PyExc_ValueError, "called with symbolic factor");

    n = L->n;
    if (L->minor<n) PY_ERR(PyExc_ArithmeticError, "singular matrix");

    if (sys < 0 || sys > 8)
         PY_ERR(PyExc_ValueError, "invalid value for sys");

    if (!Matrix_Check(B) || MAT_ID(B) == INT ||
        (MAT_ID(B) == DOUBLE && L->xtype == CHOLMOD_COMPLEX) ||
        (MAT_ID(B) == COMPLEX && L->xtype == CHOLMOD_REAL))
            PY_ERR_TYPE("B must a dense matrix of the same numerical "
                "type as F");

    if (nrhs < 0) nrhs = MAT_NCOLS(B);
    if (n == 0 || nrhs == 0) return Py_BuildValue("");
    if (ldB == 0) ldB = MAX(1,MAT_NROWS(B));
    if (ldB < MAX(1,n)) err_ld("ldB");
    if (oB < 0) err_nn_int("offsetB");
    if (oB + (nrhs-1)*ldB + n > MAT_LGT(B)) err_buf_len("B");

    cholmod_dense *x;
    cholmod_dense *b = CHOL(allocate_dense)(n, 1, n,
        (MAT_ID(B) == DOUBLE ? CHOLMOD_REAL : CHOLMOD_COMPLEX),
        &Common);
    if (Common.status == CHOLMOD_OUT_OF_MEMORY) return PyErr_NoMemory();

    void *b_old = b->x;
    for (i=0; i<nrhs; i++){
        b->x = MAT_BUF(B) + (i*ldB + oB)*E_SIZE[MAT_ID(B)];
        x = CHOL(solve) (sysvalues[sys], L, b, &Common);
        if (Common.status != CHOLMOD_OK){
            PyErr_SetString(PyExc_ValueError, "solve step failed");
            CHOL(free_dense)(&x, &Common);
            CHOL(free_dense)(&b, &Common);
	    return NULL;
	}
	memcpy(b->x, x->x, n*E_SIZE[MAT_ID(B)]);
        CHOL(free_dense)(&x, &Common);
    }
    b->x = b_old;
    CHOL(free_dense)(&b, &Common);

    return Py_BuildValue("");
}
Example #11
0
static PyObject* numeric(PyObject *self, PyObject *args)
{
    spmatrix *A;
    PyObject *F;
    cholmod_factor *Lc;
    cholmod_sparse *Ac = NULL;
    char uplo;
#if PY_MAJOR_VERSION >= 3
    const char *descr; 
#else
    char *descr; 
#endif

    if (!set_options()) return NULL;

    if (!PyArg_ParseTuple(args, "OO", &A, &F)) return NULL;

    if (!SpMatrix_Check(A) || SP_NROWS(A) != SP_NCOLS(A))
        PY_ERR_TYPE("A is not a sparse matrix");

#if PY_MAJOR_VERSION >= 3
    if (!PyCapsule_CheckExact(F) || !(descr = PyCapsule_GetName(F)))
        err_CO("F");
#else
    if (!PyCObject_Check(F)) err_CO("F");
    descr = PyCObject_GetDesc(F);
    if (!descr) PY_ERR_TYPE("F is not a CHOLMOD factor");
#endif
    if (SP_ID(A) == DOUBLE){
        if (!strcmp(descr, "CHOLMOD FACTOR D L"))
	    uplo = 'L';
	else if (!strcmp(descr, "CHOLMOD FACTOR D U"))
	    uplo = 'U';
        else
	    PY_ERR_TYPE("F is not the CHOLMOD factor of a 'd' matrix");
    } else {
        if (!strcmp(descr, "CHOLMOD FACTOR Z L"))
	    uplo = 'L';
	else if (!strcmp(descr, "CHOLMOD FACTOR Z U"))
	    uplo = 'U';
        else
	    PY_ERR_TYPE("F is not the CHOLMOD factor of a 'z' matrix");
    }
#if PY_MAJOR_VERSION >= 3
    Lc = (cholmod_factor *) PyCapsule_GetPointer(F, descr);
#else
    Lc = (cholmod_factor *) PyCObject_AsVoidPtr(F);
#endif
    if (!(Ac = pack(A, uplo))) return PyErr_NoMemory();
    CHOL(factorize) (Ac, Lc, &Common);
    CHOL(free_sparse)(&Ac, &Common);

    if (Common.status < 0) switch (Common.status) {
        case CHOLMOD_OUT_OF_MEMORY:
            return PyErr_NoMemory();

        default:
            PyErr_SetString(PyExc_ValueError, "factorization failed");
            return NULL;
    }

    if (Common.status > 0) switch (Common.status) {
        case CHOLMOD_NOT_POSDEF:
            PyErr_SetObject(PyExc_ArithmeticError, Py_BuildValue("i",
                Lc->minor));
            return NULL;
            break;

        case CHOLMOD_DSMALL:
            /* This never happens unless we change the default value
             * of Common.dbound (0.0).  */
            if (Lc->is_ll)
                PyErr_Warn(PyExc_RuntimeWarning, "tiny diagonal "\
                    "elements in L");
            else
                PyErr_Warn(PyExc_RuntimeWarning, "tiny diagonal "\
                    "elements in D");
            break;

        default:
            PyErr_Warn(PyExc_UserWarning, "");
    }

    return Py_BuildValue("");
}
Example #12
0
static int
CLazyLinker_init(CLazyLinker *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {
      (char*)"nodes",
      (char*)"thunks",
      (char*)"pre_call_clear",
      (char*)"allow_gc",
      (char*)"call_counts",
      (char*)"call_times",
      (char*)"compute_map_list",
      (char*)"storage_map_list",
      (char*)"base_input_output_list",
      (char*)"node_n_inputs",
      (char*)"node_n_outputs",
      (char*)"node_input_offset",
      (char*)"node_output_offset",
      (char*)"var_owner",
      (char*)"is_lazy_list",
      (char*)"output_vars",
      (char*)"node_prereqs",
      (char*)"node_output_size",
      (char*)"update_storage",
      (char*)"dependencies",
      NULL};

    PyObject *compute_map_list=NULL,
             *storage_map_list=NULL,
             *base_input_output_list=NULL,
             *node_n_inputs=NULL,
             *node_n_outputs=NULL,
             *node_input_offset=NULL,
             *node_output_offset=NULL,
             *var_owner=NULL,
             *is_lazy=NULL,
             *output_vars=NULL,
             *node_prereqs=NULL,
             *node_output_size=NULL,
             *update_storage=NULL,
             *dependencies=NULL;

    assert(!self->nodes);
    if (! PyArg_ParseTupleAndKeywords(args, kwds, "OOOiOOOOOOOOOOOOOOOO", kwlist,
                                      &self->nodes,
                                      &self->thunks,
                                      &self->pre_call_clear,
                                      &self->allow_gc,
                                      &self->call_counts,
                                      &self->call_times,
                                      &compute_map_list,
                                      &storage_map_list,
                                      &base_input_output_list,
                                      &node_n_inputs,
                                      &node_n_outputs,
                                      &node_input_offset,
                                      &node_output_offset,
                                      &var_owner,
                                      &is_lazy,
                                      &output_vars,
                                      &node_prereqs,
                                      &node_output_size,
                                      &update_storage,
                                      &dependencies
                                      ))
        return -1;
    Py_INCREF(self->nodes);
    Py_INCREF(self->thunks);
    Py_INCREF(self->pre_call_clear);
    Py_INCREF(self->call_counts);
    Py_INCREF(self->call_times);

    Py_ssize_t n_applies = PyList_Size(self->nodes);

    self->n_applies = n_applies;
    self->n_vars = PyList_Size(var_owner);

    if (PyList_Size(self->thunks) != n_applies) return -1;
    if (PyList_Size(self->call_counts) != n_applies) return -1;
    if (PyList_Size(self->call_times) != n_applies) return -1;

    // allocated and initialize thunk_cptr_data and thunk_cptr_fn
    if (n_applies)
      {
        self->thunk_cptr_data = (void**)calloc(n_applies, sizeof(void*));
        self->thunk_cptr_fn = (void**)calloc(n_applies, sizeof(void*));
        self->is_lazy = (int*)calloc(n_applies, sizeof(int));
        self->node_prereqs = (Py_ssize_t**)calloc(n_applies, sizeof(Py_ssize_t*));
        self->node_n_prereqs = (Py_ssize_t*)calloc(n_applies, sizeof(Py_ssize_t));
        assert(self->node_prereqs);
        assert(self->node_n_prereqs);
        assert(self->is_lazy);
        assert(self->thunk_cptr_fn);
        assert(self->thunk_cptr_data);

        for (int i = 0; i < n_applies; ++i)
          {
            PyObject * thunk = PyList_GetItem(self->thunks, i);
            //thunk is borrowed
            if (PyObject_HasAttrString(thunk, "cthunk"))
              {
                PyObject * cthunk = PyObject_GetAttrString(thunk, "cthunk");
                //new reference
                assert (cthunk && PyCObject_Check(cthunk));
                self->thunk_cptr_fn[i] = PyCObject_AsVoidPtr(cthunk);
                self->thunk_cptr_data[i] = PyCObject_GetDesc(cthunk);
                Py_DECREF(cthunk);
                // cthunk is kept alive by membership in self->thunks
              }

            PyObject * el_i = PyList_GetItem(is_lazy, i);
            self->is_lazy[i] = PyNumber_AsSsize_t(el_i, NULL);

            /* now get the prereqs */
            el_i = PyList_GetItem(node_prereqs, i);
            assert (PyList_Check(el_i));
            self->node_n_prereqs[i] = PyList_Size(el_i);
            if (self->node_n_prereqs[i])
              {
                self->node_prereqs[i] = (Py_ssize_t*)malloc(
                              PyList_Size(el_i)*sizeof(Py_ssize_t));
                for (int j = 0; j < PyList_Size(el_i); ++j)
                  {
                    PyObject * el_ij = PyList_GetItem(el_i, j);
                    Py_ssize_t N = PyNumber_AsSsize_t(el_ij, PyExc_IndexError);
                    if (PyErr_Occurred())
                      return -1;
                    // N < n. variables
                    assert(N < PyList_Size(var_owner));
                    self->node_prereqs[i][j] = N;
                  }
              }
          }
      }
    if (PyList_Check(base_input_output_list))
      {
        Py_ssize_t n_inputs_outputs_base = PyList_Size(base_input_output_list);
        self->node_inputs_outputs_base = (Py_ssize_t*)calloc(n_inputs_outputs_base,sizeof(Py_ssize_t));
        assert(self->node_inputs_outputs_base);
        for (int i = 0; i < n_inputs_outputs_base; ++i)
          {
            PyObject *el_i = PyList_GetItem(base_input_output_list, i);
            Py_ssize_t idx = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            self->node_inputs_outputs_base[i] = idx;
          }
        self->node_n_inputs = (Py_ssize_t*)calloc(n_applies,sizeof(Py_ssize_t));
        assert(self->node_n_inputs);
        self->node_n_outputs = (Py_ssize_t*)calloc(n_applies,sizeof(Py_ssize_t));
        assert(self->node_n_outputs);
        self->node_inputs = (Py_ssize_t**)calloc(n_applies,sizeof(Py_ssize_t*));
        assert(self->node_inputs);
        self->node_outputs = (Py_ssize_t**)calloc(n_applies,sizeof(Py_ssize_t*));
        assert(self->node_outputs);
        for (int i = 0; i < n_applies; ++i)
          {
            Py_ssize_t N;
            N = PyNumber_AsSsize_t(PyList_GetItem(node_n_inputs, i),PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            assert (N <= n_inputs_outputs_base);
            self->node_n_inputs[i] = N;
            N = PyNumber_AsSsize_t(PyList_GetItem(node_n_outputs, i),PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            assert (N <= n_inputs_outputs_base);
            self->node_n_outputs[i] = N;
            N = PyNumber_AsSsize_t(PyList_GetItem(node_input_offset, i),PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            assert (N <= n_inputs_outputs_base);
            self->node_inputs[i] = &self->node_inputs_outputs_base[N];
            N = PyNumber_AsSsize_t(PyList_GetItem(node_output_offset, i),PyExc_IndexError);
            if (PyErr_Occurred()) return -1;
            assert (N <= n_inputs_outputs_base);
            self->node_outputs[i] = &self->node_inputs_outputs_base[N];
          }
      }
    else
      {
        PyErr_SetString(PyExc_TypeError, "base_input_output_list must be list");
        return -1;
      }

    // allocation for var_owner
    if (PyList_Check(var_owner))
      {
        self->var_owner = (Py_ssize_t*)calloc(self->n_vars,sizeof(Py_ssize_t));
        self->var_has_owner = (int*)calloc(self->n_vars,sizeof(int));
        self->var_computed = (int*)calloc(self->n_vars,sizeof(int));
        self->var_computed_cells = (PyObject**)calloc(self->n_vars,sizeof(PyObject*));
        self->var_value_cells = (PyObject**)calloc(self->n_vars,sizeof(PyObject*));
        for (int i = 0; i < self->n_vars; ++i)
          {
            PyObject * el_i = PyList_GetItem(var_owner, i);
            if (el_i == Py_None)
              {
                self->var_has_owner[i] = 0;
              }
            else
              {
                Py_ssize_t N = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
                if (PyErr_Occurred()) return -1;
                assert (N <= n_applies);
                self->var_owner[i] = N;
                self->var_has_owner[i] = 1;
              }
            self->var_computed_cells[i] = PyList_GetItem(compute_map_list, i);
            Py_INCREF(self->var_computed_cells[i]);
            self->var_value_cells[i] = PyList_GetItem(storage_map_list, i);
            Py_INCREF(self->var_value_cells[i]);
          }
      }
    else
      {
        PyErr_SetString(PyExc_TypeError, "var_owner must be list");
        return -1;
      }

    if (dependencies != Py_None)
      {
        self->dependencies = (Py_ssize_t**)calloc(self->n_vars, sizeof(Py_ssize_t *));
        self->n_dependencies = (Py_ssize_t*)calloc(self->n_vars, sizeof(Py_ssize_t));
        assert(self->dependencies);
        assert(self->n_dependencies);

        for (int i = 0; i < self->n_vars; ++i)
          {
            PyObject *tmp = PyList_GetItem(dependencies, i);
            // refcounting - tmp is borrowed
            if (unpack_list_of_ssize_t(tmp, &self->dependencies[i], &self->n_dependencies[i],
                                       "dependencies"))
              return -1;
          }
      }

    if (unpack_list_of_ssize_t(output_vars, &self->output_vars, &self->n_output_vars,
                               "output_vars"))
      return -1;
    for (int i = 0; i < self->n_output_vars; ++i)
      {
        assert(self->output_vars[i] < self->n_vars);
      }
    if (unpack_list_of_ssize_t(update_storage, &self->update_storage, &self->n_updates,
                               "updates_storage"))
      return -1;
    return 0;
}
Example #13
0
static PyObject *Py_GeometricTransform(PyObject *obj, PyObject *args)
{
    PyArrayObject *input = NULL, *output = NULL;
    PyArrayObject *coordinates = NULL, *matrix = NULL, *shift = NULL;
    PyObject *fnc = NULL, *extra_arguments = NULL, *extra_keywords = NULL;
    int mode, order;
    double cval;
    void *func = NULL, *data = NULL;
    NI_PythonCallbackData cbdata;
    ccallback_t callback;
    static ccallback_signature_t callback_signatures[] = {
        {"int (intptr_t *, double *, int, int, void *)"},
        {"int (npy_intp *, double *, int, int, void *)"},
#if NPY_SIZEOF_INTP == NPY_SIZEOF_SHORT
        {"int (short *, double *, int, int, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_INT
        {"int (int *, double *, int, int, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_LONG
        {"int (long *, double *, int, int, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_LONGLONG
        {"int (long long *, double *, int, int, void *)"},
#endif
        {NULL}
    };

    callback.py_function = NULL;
    callback.c_function = NULL;

    if (!PyArg_ParseTuple(args, "O&OO&O&O&O&iidOO",
                          NI_ObjectToInputArray, &input,
                          &fnc,
                          NI_ObjectToOptionalInputArray, &coordinates,
                          NI_ObjectToOptionalInputArray, &matrix,
                          NI_ObjectToOptionalInputArray, &shift,
                          NI_ObjectToOutputArray, &output,
                          &order, &mode, &cval,
                          &extra_arguments, &extra_keywords))
        goto exit;

    if (fnc != Py_None) {
        if (!PyTuple_Check(extra_arguments)) {
            PyErr_SetString(PyExc_RuntimeError,
                                            "extra_arguments must be a tuple");
            goto exit;
        }
        if (!PyDict_Check(extra_keywords)) {
            PyErr_SetString(PyExc_RuntimeError,
                                            "extra_keywords must be a dictionary");
            goto exit;
        }
        if (PyCapsule_CheckExact(fnc) && PyCapsule_GetName(fnc) == NULL) {
            func = PyCapsule_GetPointer(fnc, NULL);
            data = PyCapsule_GetContext(fnc);
#if PY_VERSION_HEX < 0x03000000
        } else if (PyCObject_Check(fnc)) {
            /* 'Legacy' low-level callable on Py2 */
            func = PyCObject_AsVoidPtr(fnc);
            data = PyCObject_GetDesc(fnc);
#endif
        } else {
            int ret;

            ret = ccallback_prepare(&callback, callback_signatures, fnc, CCALLBACK_DEFAULTS);
            if (ret == -1) {
                goto exit;
            }

            if (callback.py_function != NULL) {
                cbdata.extra_arguments = extra_arguments;
                cbdata.extra_keywords = extra_keywords;
                callback.info_p = (void*)&cbdata;
                func = Py_Map;
                data = (void*)&callback;
            }
            else {
                func = callback.c_function;
                data = callback.user_data;
            }
        }
    }

    NI_GeometricTransform(input, func, data, matrix, shift, coordinates,
                          output, order, (NI_ExtendMode)mode, cval);
    #ifdef HAVE_WRITEBACKIFCOPY
        PyArray_ResolveWritebackIfCopy(output);
    #endif

exit:
    if (callback.py_function != NULL || callback.c_function != NULL) {
        ccallback_release(&callback);
    }
    Py_XDECREF(input);
    Py_XDECREF(output);
    Py_XDECREF(coordinates);
    Py_XDECREF(matrix);
    Py_XDECREF(shift);
    return PyErr_Occurred() ? NULL : Py_BuildValue("");
}
Example #14
0
static PyObject *Py_GenericFilter(PyObject *obj, PyObject *args)
{
    PyArrayObject *input = NULL, *output = NULL, *footprint = NULL;
    PyObject *fnc = NULL, *extra_arguments = NULL, *extra_keywords = NULL;
    void *func = NULL, *data = NULL;
    NI_PythonCallbackData cbdata;
    int mode;
    PyArray_Dims origin;
    double cval;
    ccallback_t callback;
    static ccallback_signature_t callback_signatures[] = {
        {"int (double *, intptr_t, double *, void *)"},
        {"int (double *, npy_intp, double *, void *)"},
#if NPY_SIZEOF_INTP == NPY_SIZEOF_SHORT
        {"int (double *, short, double *, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_INT
        {"int (double *, int, double *, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_LONG
        {"int (double *, long, double *, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_LONGLONG
        {"int (double *, long long, double *, void *)"},
#endif
        {NULL}
    };

    callback.py_function = NULL;
    callback.c_function = NULL;

    if (!PyArg_ParseTuple(args, "O&OO&O&idO&OO",
                          NI_ObjectToInputArray, &input,
                          &fnc,
                          NI_ObjectToInputArray, &footprint,
                          NI_ObjectToOutputArray, &output,
                          &mode, &cval,
                          PyArray_IntpConverter, &origin,
                          &extra_arguments, &extra_keywords)) {
        goto exit;
    }
    if (!_validate_origin(input, origin)) {
        goto exit;
    }
    if (!PyTuple_Check(extra_arguments)) {
        PyErr_SetString(PyExc_RuntimeError, "extra_arguments must be a tuple");
        goto exit;
    }
    if (!PyDict_Check(extra_keywords)) {
        PyErr_SetString(PyExc_RuntimeError,
                                        "extra_keywords must be a dictionary");
        goto exit;
    }
    if (PyCapsule_CheckExact(fnc) && PyCapsule_GetName(fnc) == NULL) {
        func = PyCapsule_GetPointer(fnc, NULL);
        data = PyCapsule_GetContext(fnc);
#if PY_VERSION_HEX < 0x03000000
    } else if (PyCObject_Check(fnc)) {
        /* 'Legacy' low-level callable on Py2 */
        func = PyCObject_AsVoidPtr(fnc);
        data = PyCObject_GetDesc(fnc);
#endif
    } else {
        int ret;

        ret = ccallback_prepare(&callback, callback_signatures, fnc, CCALLBACK_DEFAULTS);
        if (ret == -1) {
            goto exit;
        }

        if (callback.py_function != NULL) {
            cbdata.extra_arguments = extra_arguments;
            cbdata.extra_keywords = extra_keywords;
            callback.info_p = (void*)&cbdata;
            func = Py_FilterFunc;
            data = (void*)&callback;
        }
        else {
            func = callback.c_function;
            data = callback.user_data;
        }
    }

    NI_GenericFilter(input, func, data, footprint, output, (NI_ExtendMode)mode,
                     cval, origin.ptr);
    #ifdef HAVE_WRITEBACKIFCOPY
        PyArray_ResolveWritebackIfCopy(output);
    #endif

exit:
    if (callback.py_function != NULL || callback.c_function != NULL) {
        ccallback_release(&callback);
    }
    Py_XDECREF(input);
    Py_XDECREF(output);
    Py_XDECREF(footprint);
    PyDimMem_FREE(origin.ptr);
    return PyErr_Occurred() ? NULL : Py_BuildValue("");
}
/* Convert a pointer value */
static int
SWIG_Python_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) {
  swig_type_info *tc;
  char  *c = 0;
  static PyObject *SWIG_this = 0;
  int    newref = 0;
  PyObject  *pyobj = 0;
  void *vptr;
  
  if (!obj) return 0;
  if (obj == Py_None) {
    *ptr = 0;
    return 0;
  }

#ifdef SWIG_COBJECT_TYPES
  if (!(PyCObject_Check(obj))) {
    if (!SWIG_this)
      SWIG_this = PyString_FromString("this");
    pyobj = obj;
    obj = PyObject_GetAttr(obj,SWIG_this);
    newref = 1;
    if (!obj) goto type_error;
    if (!PyCObject_Check(obj)) {
      Py_DECREF(obj);
      goto type_error;
    }
  }  
  vptr = PyCObject_AsVoidPtr(obj);
  c = (char *) PyCObject_GetDesc(obj);
  if (newref) Py_DECREF(obj);
  goto type_check;
#else
  if (!(PyString_Check(obj))) {
    if (!SWIG_this)
      SWIG_this = PyString_FromString("this");
    pyobj = obj;
    obj = PyObject_GetAttr(obj,SWIG_this);
    newref = 1;
    if (!obj) goto type_error;
    if (!PyString_Check(obj)) {
      Py_DECREF(obj);
      goto type_error;
    }
  } 
  c = PyString_AS_STRING(obj);
  /* Pointer values must start with leading underscore */
  if (*c != '_') {
    if (strcmp(c,"NULL") == 0) {
      if (newref) { Py_DECREF(obj); }
      *ptr = (void *) 0;
      return 0;
    } else {
      if (newref) { Py_DECREF(obj); }
      goto type_error;
    }
  }
  c++;
  c = SWIG_UnpackData(c,&vptr,sizeof(void *));
  if (newref) { Py_DECREF(obj); }
#endif

type_check:

  if (ty) {
    tc = SWIG_TypeCheck(c,ty);
    if (!tc) goto type_error;
    *ptr = SWIG_TypeCast(tc,vptr);
  }

  if ((pyobj) && (flags & SWIG_POINTER_DISOWN)) {
    PyObject_SetAttrString(pyobj,(char*)"thisown",Py_False);
  }
  return 0;

type_error:
  PyErr_Clear();
  if (pyobj && !obj) {    
    obj = pyobj;
    if (PyCFunction_Check(obj)) {
      /* here we get the method pointer for callbacks */
      char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
      c = doc ? strstr(doc, "swig_ptr: ") : 0;
      if (c) {
	c += 10;
	if (*c == '_') {
	  c++;
	  c = SWIG_UnpackData(c,&vptr,sizeof(void *));
	  goto type_check;
	}
      }
    }
  }
  if (flags & SWIG_POINTER_EXCEPTION) {
    if (ty) {
      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
    } else {
      SWIG_Python_TypeError("C/C++ pointer", obj);
    }
  }
  return -1;
}
SWIG_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) {
  unsigned long p;
  register int d;
  swig_type_info *tc;
  char  *c;
  static PyObject *SWIG_this = 0;
  int    newref = 0;

  if (!obj || (obj == Py_None)) {
    *ptr = 0;
    return 0;
  }
#ifdef SWIG_COBJECT_TYPES
  if (!(PyCObject_Check(obj))) {
    if (!SWIG_this)
      SWIG_this = PyString_InternFromString("this");
    obj = PyObject_GetAttr(obj,SWIG_this);
    newref = 1;
    if (!obj) goto type_error;
    if (!PyCObject_Check(obj)) {
      Py_DECREF(obj);
      goto type_error;
    }
  } 
  *ptr = PyCObject_AsVoidPtr(obj);
  c = (char *) PyCObject_GetDesc(obj);
  if (newref) Py_DECREF(obj);
  goto cobject;
#else
  if (!(PyString_Check(obj))) {
    if (!SWIG_this)
      SWIG_this = PyString_InternFromString("this");
    obj = PyObject_GetAttr(obj,SWIG_this);
    newref = 1;
    if (!obj) goto type_error;
    if (!PyString_Check(obj)) {
      Py_DECREF(obj);
      goto type_error;
    }
  } 
  c = PyString_AsString(obj);
  p = 0;
  /* Pointer values must start with leading underscore */
  if (*c != '_') {
    *ptr = (void *) 0;
    if (strcmp(c,"NULL") == 0) {
      if (newref) Py_DECREF(obj);
      return 0;
    } else {
      if (newref) Py_DECREF(obj);
      goto type_error;
    }
  }
  c++;
  /* Extract hex value from pointer */
  while ((d = *c)) {
    if ((d >= '0') && (d <= '9'))
      p = (p << 4) + (d - '0');
    else if ((d >= 'a') && (d <= 'f'))
      p = (p << 4) + (d - ('a'-10));
    else
      break; 
    c++;
  }
  *ptr = (void *) p;
  if (newref) Py_DECREF(obj);
#endif

#ifdef SWIG_COBJECT_TYPES
cobject:
#endif

  if (ty) {
    tc = SWIG_TypeCheck(c,ty);
    if (!tc) goto type_error;
    *ptr = SWIG_TypeCast(tc,(void*)p);
  }
  return 0;

type_error:

  if (flags) {
    if (ty) {
      char *temp = (char *) malloc(64+strlen(ty->name));
      sprintf(temp,"Type error. Expected %s", ty->name);
      PyErr_SetString(PyExc_TypeError, temp);
      free((char *) temp);
    } else {
      PyErr_SetString(PyExc_TypeError,"Expected a pointer");
    }
  }
  return -1;
}
Example #17
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;
		}
	}