/*static*/ PyObject * ViewerClientInformationElement_SetRawData(PyObject *self, PyObject *args) { ViewerClientInformationElementObject *obj = (ViewerClientInformationElementObject *)self; unsignedCharVector &vec = obj->data->GetRawData(); PyObject *tuple; if(!PyArg_ParseTuple(args, "O", &tuple)) return NULL; if(PyTuple_Check(tuple)) { vec.resize(PyTuple_Size(tuple)); for(int i = 0; i < PyTuple_Size(tuple); ++i) { int c; PyObject *item = PyTuple_GET_ITEM(tuple, i); if(PyFloat_Check(item)) c = int(PyFloat_AS_DOUBLE(item)); else if(PyInt_Check(item)) c = int(PyInt_AS_LONG(item)); else if(PyLong_Check(item)) c = int(PyLong_AsDouble(item)); else c = 0; if(c < 0) c = 0; if(c > 255) c = 255; vec[i] = (unsigned char)(c); } } else if(PyFloat_Check(tuple)) { vec.resize(1); int c = int(PyFloat_AS_DOUBLE(tuple)); if(c < 0) c = 0; if(c > 255) c = 255; vec[0] = (unsigned char)(c); } else if(PyInt_Check(tuple)) { vec.resize(1); int c = int(PyInt_AS_LONG(tuple)); if(c < 0) c = 0; if(c > 255) c = 255; vec[0] = (unsigned char)(c); } else if(PyLong_Check(tuple)) { vec.resize(1); int c = PyLong_AsLong(tuple); if(c < 0) c = 0; if(c > 255) c = 255; vec[0] = (unsigned char)(c); } else return NULL; // Mark the rawData in the object as modified. obj->data->SelectRawData(); Py_INCREF(Py_None); return Py_None; }
static PyObject *Polygon_sample(Polygon *self, PyObject *args) { PyObject *rng, *val1, *val2, *val3, *res; double A; if (! PyArg_ParseTuple(args, "O", &rng)) return Polygon_Raise(ERR_ARG); if (!PyCallable_Check(rng)) return Polygon_Raise(ERR_ARG); res = NULL; Py_INCREF(rng); // Sampling requires three random values val1 = val2 = val3 = NULL; val1 = PyObject_CallObject(rng, NULL); val2 = PyObject_CallObject(rng, NULL); val3 = PyObject_CallObject(rng, NULL); Py_DECREF(rng); if ((! PyFloat_Check(val1)) || (! PyFloat_Check(val2)) || (! PyFloat_Check(val3))) { Polygon_Raise(PolyError, "rng returned something other than a float"); goto cleanup; } A = poly_p_area(self->gpc_p); if (A == 0.0) { Polygon_Raise(PolyError, "cannot sample from a zero-area polygon"); goto cleanup; } else { gpc_tristrip *t = (gpc_tristrip *)alloca(sizeof(gpc_tristrip)); gpc_vertex_list *vl; gpc_vertex_list one_tri; int i, j; gpc_vertex *tri_verts; double a, b, c, px, py; t->num_strips = 0; t->strip = NULL; gpc_polygon_to_tristrip(self->gpc_p, t); A *= PyFloat_AS_DOUBLE(val1); one_tri.num_vertices = 3; for (i=0; i < t->num_strips; i++) { vl = t->strip + i; for (j=0; j < vl->num_vertices - 2; j++) { one_tri.vertex = vl->vertex + j; A -= poly_c_area(& one_tri); if (A <= 0.0) goto tri_found; } } tri_found: // sample a point from this triangle a = PyFloat_AS_DOUBLE(val2); b = PyFloat_AS_DOUBLE(val3); if ((a + b) > 1.0) { a = 1 - a; b = 1 - b; } c = 1 - a - b; tri_verts = one_tri.vertex; px = a * tri_verts[0].x + b * tri_verts[1].x + c * tri_verts[2].x; py = a * tri_verts[0].y + b * tri_verts[1].y + c * tri_verts[2].y; res = PyTuple_New(2); PyTuple_SetItem(res, 0, PyFloat_FromDouble(px)); PyTuple_SetItem(res, 1, PyFloat_FromDouble(py)); gpc_free_tristrip(t); } cleanup: Py_XDECREF(val1); Py_XDECREF(val2); Py_XDECREF(val3); return res; }
//----------------------------------------------------------------------------- // NumberVar_GetValue() // Returns the value stored at the given array position. //----------------------------------------------------------------------------- static PyObject *NumberVar_GetValue( udt_NumberVar *var, // variable to determine value for unsigned pos) // array position { PyObject *result, *stringObj; char stringValue[200]; long integerValue; ub4 stringLength; sword status; #if PY_MAJOR_VERSION < 3 if (var->type == &vt_Integer || var->type == &vt_Boolean) { #else if (var->type == &vt_Boolean) { #endif status = OCINumberToInt(var->environment->errorHandle, &var->data[pos], sizeof(long), OCI_NUMBER_SIGNED, (dvoid*) &integerValue); if (Environment_CheckForError(var->environment, status, "NumberVar_GetValue(): as integer") < 0) return NULL; #if PY_MAJOR_VERSION < 3 if (var->type == &vt_Integer) return PyInt_FromLong(integerValue); #endif return PyBool_FromLong(integerValue); } if (var->type == &vt_NumberAsString || var->type == &vt_LongInteger) { stringLength = sizeof(stringValue); status = OCINumberToText(var->environment->errorHandle, &var->data[pos], (text*) var->environment->numberToStringFormatBuffer.ptr, var->environment->numberToStringFormatBuffer.size, NULL, 0, &stringLength, (unsigned char*) stringValue); if (Environment_CheckForError(var->environment, status, "NumberVar_GetValue(): as string") < 0) return NULL; stringObj = cxString_FromEncodedString(stringValue, stringLength, var->environment->encoding); if (!stringObj) return NULL; if (var->type == &vt_NumberAsString) return stringObj; #if PY_MAJOR_VERSION >= 3 result = PyNumber_Long(stringObj); #else result = PyNumber_Int(stringObj); #endif Py_DECREF(stringObj); if (result || !PyErr_ExceptionMatches(PyExc_ValueError)) return result; PyErr_Clear(); } return OracleNumberToPythonFloat(var->environment, &var->data[pos]); } #ifdef SQLT_BFLOAT //----------------------------------------------------------------------------- // NativeFloatVar_GetValue() // Returns the value stored at the given array position as a float. //----------------------------------------------------------------------------- static PyObject *NativeFloatVar_GetValue( udt_NativeFloatVar *var, // variable to determine value for unsigned pos) // array position { return PyFloat_FromDouble(var->data[pos]); } //----------------------------------------------------------------------------- // NativeFloatVar_SetValue() // Set the value of the variable which should be a native double. //----------------------------------------------------------------------------- static int NativeFloatVar_SetValue( udt_NativeFloatVar *var, // variable to set value for unsigned pos, // array position to set PyObject *value) // value to set { if (!PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "expecting float"); return -1; } var->data[pos] = PyFloat_AS_DOUBLE(value); return 0; }
// This dMList function creates a list of the dM values giving the probabilities of mutations static PyObject *dMList(PyObject *self, PyObject *args) { // Calling variables are (in order): uts, only_need, n_aa, length, grs, dmlist, residue_to_compute, iwt, brs PyObject *uts, *only_need, *grs, *r_grs_tuple, *gr_diag, *p, *p_inv, *dmlist, *brs, *brz; long n_aa, length, n_aa2, n_uts, residue_to_compute, i_ut, x, y, index, only_need_index, only_need_i, only_need_i_n_aa, index2, iwt, n_aa3, z; double *arr_dmlist, *cp_inv, *cp, *cgr_diag, *cexpd, *cbrz, *cvrz, *cvrz_p_inv; complex double *complex_cp_inv, *complex_cp, *complex_cgr_diag, *complex_cexpd, *complex_naa2_list, *complex_naa_list, *complex_cvrz, *complex_cvrz_p_inv, *complex_cbrz; double ut, exp_utdx, exp_utdy, dx, dy; complex double complex_exp_utdx, complex_exp_utdy, complex_dx, complex_dy; int array_type; #ifdef USE_ACCELERATE_CBLAS complex double complex_one = 1, complex_zero = 0; #else complex double complex_dmxy, complex_v_p_inv_xy; double dmxy, v_p_inv_xy; long yindex, irowcolumn; #endif // Parse the arguments. if (! PyArg_ParseTuple( args, "O!O!llO!O!llO!", &PyList_Type, &uts, &PyList_Type, &only_need, &n_aa, &length, &PyList_Type, &grs, &PyArray_Type, &dmlist, &residue_to_compute, &iwt, &PyList_Type, &brs)) { PyErr_SetString(PyExc_TypeError, "Invalid calling arguments to dMList."); return NULL; } // Error checking on arguments if (length < 1) { // length of the protein PyErr_SetString(PyExc_ValueError, "length is less than one."); return NULL; } if (n_aa < 1) { // number of amino acids. Normally will be 20. PyErr_SetString(PyExc_ValueError, "n_aa is less than one."); return NULL; } if (PyList_GET_SIZE(grs) != length) { // make sure grs is of the same size as length PyErr_SetString(PyExc_ValueError, "grs is not of the same size as length."); return NULL; } n_uts = PyList_GET_SIZE(uts); // number of entries in uts if (n_uts < 1) { // make sure there are entries in uts PyErr_SetString(PyExc_ValueError, "uts has no entries."); return NULL; } if (PyList_GET_SIZE(only_need) != n_uts * length) { // make sure only_need is of correct size PyErr_SetString(PyExc_ValueError, "only_need is of wrong size."); return NULL; } if (! ((residue_to_compute >= 0) && (residue_to_compute < length))) { PyErr_SetString(PyExc_ValueError, "Invalid value for residue_to_compute."); return NULL; } if (! ((iwt >= 0) && (iwt < n_aa))) { PyErr_SetString(PyExc_ValueError, "Invalid value for iwt."); return NULL; } if (PyList_GET_SIZE(brs) != n_aa) { // make sure brs has one entry for each amino acid PyErr_SetString(PyExc_ValueError, "brs is not of length equal to n_aa"); return NULL; } n_aa2 = n_aa * n_aa; // square of the number of amino acids n_aa3 = n_aa2 * n_aa; // cube of the number of amino acids // The results will be returned in a numpy ndarray 'float_' (C type double) array called dmlist. // This array will be of size length * n_uts * n_aa3. arr_dmlist = (double *) PyArray_DATA(dmlist); // this is the data array of dmlist long const sizeof_cexpd = n_aa2 * sizeof(double); long const complex_sizeof_cexpd = n_aa2 * sizeof(complex double); // gr_diag, p, and p_inv are the eigenvalues, left, and right diagonalizing matrices of gr r_grs_tuple = PyList_GET_ITEM(grs, residue_to_compute); gr_diag = PyTuple_GET_ITEM(r_grs_tuple, 0); p = PyTuple_GET_ITEM(r_grs_tuple, 1); p_inv = PyTuple_GET_ITEM(r_grs_tuple, 2); // Now begin filling arr_dmlist with the appropriate values index = 0; only_need_index = residue_to_compute * n_uts; // determine if these arrays are complex double or real doubles array_type = PyArray_TYPE(gr_diag); if (array_type == NPY_DOUBLE) { // array is of doubles, real not complex // Note that these next assignments assume that the arrays are C-style contiguous cp = PyArray_DATA(p); cp_inv = PyArray_DATA(p_inv); cgr_diag = PyArray_DATA(gr_diag); cexpd = (double *) malloc(sizeof_cexpd); // allocate memory cvrz = (double *) malloc(sizeof_cexpd); // allocate memory cvrz_p_inv = (double *) malloc(sizeof_cexpd); // allocate memory for (i_ut = 0; i_ut < n_uts; i_ut++) { // loop over ut values only_need_i = PyInt_AS_LONG(PyList_GET_ITEM(only_need, only_need_index)); // value of only_need only_need_index++; if (only_need_i == -1) { // we don't need to do anything for these entries in dmlist index += n_aa3; } else { // we need to compute at least some entries in dmlist ut = PyFloat_AS_DOUBLE(PyList_GET_ITEM(uts, i_ut)); // ut value // Entries of cexpd are defined by D_xy = (exp(ut d_x) - exp(ut d_y)) / (d_x - d_y) // for x != y, and D_yy = ut exp(d_x ut) index2 = 0; for (x = 0; x < n_aa; x++) { dx = cgr_diag[x]; exp_utdx = exp(ut * dx); for (y = 0; y < n_aa; y++) { if (y == x) { cexpd[index2] = ut * exp_utdx; } else { dy = cgr_diag[y]; exp_utdy = exp(ut * dy); cexpd[index2] = (exp_utdx - exp_utdy) / (dx - dy); } index2++; } } for (z = 0; z < n_aa; z++) { // compute derivative with respect to z if (z == iwt) { // don't compute values with respect to wildtype index += n_aa2; continue; } brz = PyList_GET_ITEM(brs, z); cbrz = PyArray_DATA(brz); // cvrz is the element-by-element product of cbrz and cexpd for (index2 = 0; index2 < n_aa2; index2++) { cvrz[index2] = cbrz[index2] * cexpd[index2]; } #ifdef USE_ACCELERATE_CBLAS // multiply the matrices using cblas_dgemm cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_aa, n_aa, n_aa, (double) 1.0, cvrz, n_aa, cp_inv, n_aa, (double) 0.0, cvrz_p_inv, n_aa); // multiply cvrz and cp_inv into cvrz_p_inv #else // multiply the matrices in pure C code // multiply cvrz and cp_inv into cvrz_p_inv index2 = 0; for (x = 0; x < n_aa2; x += n_aa) { for (y = 0; y < n_aa; y++) { v_p_inv_xy = 0.0; yindex = y; for (irowcolumn = x; irowcolumn < x + n_aa; irowcolumn++) { v_p_inv_xy += cvrz[irowcolumn] * cp_inv[yindex]; yindex += n_aa; } cvrz_p_inv[index2++] = v_p_inv_xy; } } #endif if (only_need_i == -2) { // we need to compute all of these entries in dmlist #ifdef USE_ACCELERATE_CBLAS cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_aa, n_aa, n_aa, (double) 1.0, cp, n_aa, cvrz_p_inv, n_aa, (double) 0.0, &arr_dmlist[index], n_aa); // multiply cp and cvrz_p_inv into arr_dmlist[index : index + n_aa2] index += n_aa2; #else // multiply the matrices in pure C code, and fill dmlist with the results // multiply cp and cvrz_p_inv into arr_dmlist[index : index + n_aa2] for (x = 0; x < n_aa2; x += n_aa) { for (y = 0; y < n_aa; y++) { dmxy = 0.0; yindex = y; for (irowcolumn = x; irowcolumn < x + n_aa; irowcolumn++) { dmxy += cp[irowcolumn] * cvrz_p_inv[yindex]; yindex += n_aa; } arr_dmlist[index++] = dmxy; } } #endif } else { // we need to compute entries in dmlist only for x = only_need_i only_need_i_n_aa = only_need_i * n_aa; index += only_need_i_n_aa; #ifdef USE_ACCELERATE_CBLAS // do the matrix vector multiplication using cblas, and put results in dmlist cblas_dgemv(CblasRowMajor, CblasTrans, n_aa, n_aa, (double) 1.0, cvrz_p_inv, n_aa, &cp[only_need_i_n_aa], 1, (double) 0.0, &arr_dmlist[index], 1); index += n_aa2 - only_need_i_n_aa; #else // do the matrix vector multiplication in pure C code, and put results in mlist for (y = 0; y < n_aa; y++) { dmxy = 0.0; yindex = y; for (irowcolumn = only_need_i_n_aa; irowcolumn < only_need_i_n_aa + n_aa; irowcolumn++) { dmxy += cp[irowcolumn] * cvrz_p_inv[yindex]; yindex += n_aa; } arr_dmlist[index++] = dmxy; } index += n_aa2 - only_need_i_n_aa - n_aa; #endif } } } } free(cexpd); free(cvrz); free(cvrz_p_inv); } else if (array_type == NPY_CDOUBLE) { // array is of complex doubles // Note that these next assignments assume that the arrays are C-style contiguous complex_cp = PyArray_DATA(p); complex_cp_inv = PyArray_DATA(p_inv); complex_cgr_diag = PyArray_DATA(gr_diag); complex_cexpd = (complex double *) malloc(complex_sizeof_cexpd); // allocate memory complex_cvrz = (complex double *) malloc(complex_sizeof_cexpd); // allocate memory complex_cvrz_p_inv = (complex double *) malloc(complex_sizeof_cexpd); // allocate memory complex_naa2_list = (complex double *) malloc(n_aa2 * sizeof(complex double)); // allocate memory complex_naa_list = (complex double *) malloc(n_aa * sizeof(complex double)); // allocate memory for (i_ut = 0; i_ut < n_uts; i_ut++) { // loop over ut values only_need_i = PyInt_AS_LONG(PyList_GET_ITEM(only_need, only_need_index)); // value of only_need only_need_index++; if (only_need_i == -1) { // we don't need to do anything for these entries in dmlist index += n_aa3; } else { // we need to compute at least some entries in dmlist ut = PyFloat_AS_DOUBLE(PyList_GET_ITEM(uts, i_ut)); // ut value // Entries of cexpd are defined by D_xy = (exp(ut d_x) - exp(ut d_y)) / (d_x - d_y) // for x != y, and D_yy = ut exp(d_x ut) index2 = 0; for (x = 0; x < n_aa; x++) { complex_dx = complex_cgr_diag[x]; complex_exp_utdx = cexp(ut * complex_dx); for (y = 0; y < n_aa; y++) { if (y == x) { complex_cexpd[index2] = ut * complex_exp_utdx; } else { complex_dy = complex_cgr_diag[y]; complex_exp_utdy = cexp(ut * complex_dy); complex_cexpd[index2] = (complex_exp_utdx - complex_exp_utdy) / (complex_dx - complex_dy); } index2++; } } for (z = 0; z < n_aa; z++) { // compute derivative with respect to z if (z == iwt) { // don't compute values with respect to wildtype index += n_aa2; continue; } brz = PyList_GET_ITEM(brs, z); complex_cbrz = PyArray_DATA(brz); // cvrz is the element-by-element product of cbrz and cexpd for (index2 = 0; index2 < n_aa2; index2++) { complex_cvrz[index2] = complex_cbrz[index2] * complex_cexpd[index2]; } #ifdef USE_ACCELERATE_CBLAS // multiply the matrices using cblas_zgemm cblas_zgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_aa, n_aa, n_aa, &complex_one, complex_cvrz, n_aa, complex_cp_inv, n_aa, &complex_zero, complex_cvrz_p_inv, n_aa); // multiply cvrz and cp_inv into cvrz_p_inv #else // multiply the matrices in pure C code // multiply cvrz and cp_inv into cvrz_p_inv index2 = 0; for (x = 0; x < n_aa2; x += n_aa) { for (y = 0; y < n_aa; y++) { complex_v_p_inv_xy = 0.0; yindex = y; for (irowcolumn = x; irowcolumn < x + n_aa; irowcolumn++) { complex_v_p_inv_xy += complex_cvrz[irowcolumn] * complex_cp_inv[yindex]; yindex += n_aa; } complex_cvrz_p_inv[index2++] = complex_v_p_inv_xy; } } #endif if (only_need_i == -2) { // we need to compute all of these entries in dmlist #ifdef USE_ACCELERATE_CBLAS cblas_zgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_aa, n_aa, n_aa, &complex_one, complex_cp, n_aa, complex_cvrz_p_inv, n_aa, &complex_zero, complex_naa2_list, n_aa); // multiply cp and cvrz_p_inv into arr_dmlist[index : index + n_aa2] for (index2 = 0; index2 < n_aa2; index2++) { arr_dmlist[index + index2] = creal(complex_naa2_list[index2]); } index += n_aa2; #else // multiply the matrices in pure C code, and fill dmlist with the results // multiply cp and cvrz_p_inv into arr_dmlist[index : index + n_aa2] for (x = 0; x < n_aa2; x += n_aa) { for (y = 0; y < n_aa; y++) { complex_dmxy = 0.0; yindex = y; for (irowcolumn = x; irowcolumn < x + n_aa; irowcolumn++) { complex_dmxy += complex_cp[irowcolumn] * complex_cvrz_p_inv[yindex]; yindex += n_aa; } arr_dmlist[index++] = creal(complex_dmxy); } } #endif } else { // we need to compute entries in dmlist only for x = only_need_i only_need_i_n_aa = only_need_i * n_aa; index += only_need_i_n_aa; #ifdef USE_ACCELERATE_CBLAS // do the matrix vector multiplication using cblas, and put results in dmlist cblas_zgemv(CblasRowMajor, CblasTrans, n_aa, n_aa, &complex_one, complex_cvrz_p_inv, n_aa, &complex_cp[only_need_i_n_aa], 1, &complex_zero, complex_naa_list, 1); for (index2 = 0; index2 < n_aa; index2++) { arr_dmlist[index + index2] = creal(complex_naa_list[index2]); } index += n_aa2 - only_need_i_n_aa; #else // do the matrix vector multiplication in pure C code, and put results in mlist for (y = 0; y < n_aa; y++) { complex_dmxy = 0.0; yindex = y; for (irowcolumn = only_need_i_n_aa; irowcolumn < only_need_i_n_aa + n_aa; irowcolumn++) { complex_dmxy += complex_cp[irowcolumn] * complex_cvrz_p_inv[yindex]; yindex += n_aa; } arr_dmlist[index++] = creal(complex_dmxy); } index += n_aa2 - only_need_i_n_aa - n_aa; #endif } } } } free(complex_cexpd); free(complex_cvrz); free(complex_cvrz_p_inv); free(complex_naa2_list); free(complex_naa_list); } else { // array is of neither real nor complex doubles PyErr_SetString(PyExc_ValueError, "matrices are neither double nor complex doubles."); return NULL; } return PyInt_FromLong((long) 1); }
static void LFO_generates_ii(LFO *self) { MYFLT val, inc, freq, sharp, pointer, numh; MYFLT v1, v2, inc2, fade; int i, maxHarms; freq = PyFloat_AS_DOUBLE(self->freq); if (freq <= 0) { return; } sharp = PyFloat_AS_DOUBLE(self->sharp); if (sharp < 0.0) sharp = 0.0; else if (sharp > 1.0) sharp = 1.0; inc = freq / self->sr; switch (self->wavetype) { case 0: /* Saw up */ maxHarms = (int)(self->srOverFour/freq); numh = sharp * 46.0 + 4.0; if (numh > maxHarms) numh = maxHarms; for (i=0; i<self->bufsize; i++) { pointer = self->pointerPos * 2.0 - 1.0; val = pointer - MYTANH(numh * pointer) / MYTANH(numh); self->data[i] = val; self->pointerPos += inc; if (self->pointerPos < 0) self->pointerPos += 1.0; else if (self->pointerPos >= 1) self->pointerPos -= 1.0; } break; case 1: /* Saw down */ maxHarms = (int)(self->srOverFour/freq); numh = sharp * 46.0 + 4.0; if (numh > maxHarms) numh = maxHarms; for (i=0; i<self->bufsize; i++) { pointer = self->pointerPos * 2.0 - 1.0; val = -(pointer - MYTANH(numh * pointer) / MYTANH(numh)); self->data[i] = val; self->pointerPos += inc; if (self->pointerPos < 0) self->pointerPos += 1.0; else if (self->pointerPos >= 1) self->pointerPos -= 1.0; } break; case 2: /* Square */ maxHarms = (int)(self->srOverEight/freq); numh = sharp * 46.0 + 4.0; if (numh > maxHarms) numh = maxHarms; for (i=0; i<self->bufsize; i++) { val = MYATAN(numh * MYSIN(TWOPI*self->pointerPos)); self->data[i] = val * self->oneOverPiOverTwo; self->pointerPos += inc; if (self->pointerPos < 0) self->pointerPos += 1.0; else if (self->pointerPos >= 1) self->pointerPos -= 1.0; } break; case 3: /* Triangle */ maxHarms = (int)(self->srOverFour/freq); if ((sharp * 36.0) > maxHarms) numh = (MYFLT)(maxHarms / 36.0); else numh = sharp; for (i=0; i<self->bufsize; i++) { v1 = MYTAN(MYSIN(TWOPI*self->pointerPos)); pointer = self->pointerPos + 0.25; if (pointer > 1.0) pointer -= 1.0; v2 = 4.0 * (0.5 - MYFABS(pointer - 0.5)) - 1.0; val = v1 * (1 - numh) + v2 * numh; self->data[i] = val; self->pointerPos += inc; if (self->pointerPos < 0) self->pointerPos += 1.0; else if (self->pointerPos >= 1) self->pointerPos -= 1.0; } break; case 4: /* Pulse */ maxHarms = (int)(self->srOverEight/freq); numh = MYFLOOR(sharp * 46.0 + 4.0); if (numh > maxHarms) numh = maxHarms; if (MYFMOD(numh, 2.0) == 0.0) numh += 1.0; for (i=0; i<self->bufsize; i++) { val = MYTAN(MYPOW(MYFABS(MYSIN(TWOPI*self->pointerPos)), numh)); self->data[i] = val * self->oneOverPiOverTwo; self->pointerPos += inc; if (self->pointerPos < 0) self->pointerPos += 1.0; else if (self->pointerPos >= 1) self->pointerPos -= 1.0; } break; case 5: /* Bi-Pulse */ maxHarms = (int)(self->srOverEight/freq); numh = MYFLOOR(sharp * 46.0 + 4.0); if (numh > maxHarms) numh = maxHarms; if (MYFMOD(numh, 2.0) == 0.0) numh += 1.0; for (i=0; i<self->bufsize; i++) { val = MYTAN(MYPOW(MYSIN(TWOPI*self->pointerPos), numh)); self->data[i] = val * self->oneOverPiOverTwo; self->pointerPos += inc; if (self->pointerPos < 0) self->pointerPos += 1.0; else if (self->pointerPos >= 1) self->pointerPos -= 1.0; } break; case 6: /* SAH */ numh = 1.0 - sharp; inc2 = 1.0 / (int)(1.0 / inc * numh); for (i=0; i<self->bufsize; i++) { self->pointerPos += inc; if (self->pointerPos < 0) self->pointerPos += 1.0; else if (self->pointerPos >= 1) { self->pointerPos -= 1.0; self->sahPointerPos = 0.0; self->sahLastValue = self->sahCurrentValue; self->sahCurrentValue = rand()/((MYFLT)(RAND_MAX)*0.5) - 1.0; } if (self->sahPointerPos < 1.0) { fade = 0.5 * MYSIN(PI * (self->sahPointerPos+0.5)) + 0.5; val = self->sahCurrentValue * (1.0 - fade) + self->sahLastValue * fade; self->sahPointerPos += inc2; } else { val = self->sahCurrentValue; } self->data[i] = val; } break; case 7: /* Sine-mod */ inc2 = inc * sharp; for (i=0; i<self->bufsize; i++) { self->modPointerPos += inc2; if (self->modPointerPos < 0) self->modPointerPos += 1.0; else if (self->modPointerPos >= 1) self->modPointerPos -= 1.0; val = (0.5 * MYCOS(TWOPI*self->modPointerPos) + 0.5) * MYSIN(TWOPI*self->pointerPos); self->data[i] = val; self->pointerPos += inc; if (self->pointerPos < 0) self->pointerPos += 1.0; else if (self->pointerPos >= 1) self->pointerPos -= 1.0; } break; default: break; } }
/*static*/ PyObject * MultiCurveAttributes_SetMultiColor(PyObject *self, PyObject *args) { MultiCurveAttributesObject *obj = (MultiCurveAttributesObject *)self; PyObject *pyobj = NULL; ColorAttributeList &cL = obj->data->GetMultiColor(); int index = 0; int c[4] = {0,0,0,255}; bool setTheColor = true; if(!PyArg_ParseTuple(args, "iiiii", &index, &c[0], &c[1], &c[2], &c[3])) { if(!PyArg_ParseTuple(args, "iiii", &index, &c[0], &c[1], &c[2])) { double dr, dg, db, da; if(PyArg_ParseTuple(args, "idddd", &index, &dr, &dg, &db, &da)) { c[0] = int(dr); c[1] = int(dg); c[2] = int(db); c[3] = int(da); } else if(PyArg_ParseTuple(args, "iddd", &index, &dr, &dg, &db)) { c[0] = int(dr); c[1] = int(dg); c[2] = int(db); c[3] = 255; } else { if(!PyArg_ParseTuple(args, "iO", &index, &pyobj)) { if(PyArg_ParseTuple(args, "O", &pyobj)) { setTheColor = false; if(PyTuple_Check(pyobj)) { // Make sure that the tuple is the right size. if(PyTuple_Size(pyobj) < cL.GetNumColors()) return NULL; // Make sure that the tuple is the right size. bool badInput = false; int *C = new int[4 * cL.GetNumColors()]; for(int i = 0; i < PyTuple_Size(pyobj) && !badInput; ++i) { PyObject *item = PyTuple_GET_ITEM(pyobj, i); if(PyTuple_Check(item) && PyTuple_Size(item) == 3 || PyTuple_Size(item) == 4) { C[i*4] = 0; C[i*4+1] = 0; C[i*4+2] = 0; C[i*4+3] = 255; for(int j = 0; j < PyTuple_Size(item) && !badInput; ++j) { PyObject *colorcomp = PyTuple_GET_ITEM(item, j); if(PyInt_Check(colorcomp)) C[i*4+j] = int(PyInt_AS_LONG(colorcomp)); else if(PyFloat_Check(colorcomp)) C[i*4+j] = int(PyFloat_AS_DOUBLE(colorcomp)); else badInput = true; } } else badInput = true; } if(badInput) { delete [] C; return NULL; } for(int i = 0; i < cL.GetNumColors(); ++i) cL[i].SetRgba(C[i*4], C[i*4+1], C[i*4+2], C[i*4+3]); delete [] C; } else if(PyList_Check(pyobj)) { // Make sure that the list is the right size. if(PyList_Size(pyobj) < cL.GetNumColors()) return NULL; // Make sure that the tuple is the right size. bool badInput = false; int *C = new int[4 * cL.GetNumColors()]; for(int i = 0; i < PyList_Size(pyobj) && !badInput; ++i) { PyObject *item = PyList_GET_ITEM(pyobj, i); if(PyTuple_Check(item) && PyTuple_Size(item) == 3 || PyTuple_Size(item) == 4) { C[i*4] = 0; C[i*4+1] = 0; C[i*4+2] = 0; C[i*4+3] = 255; for(int j = 0; j < PyTuple_Size(item) && !badInput; ++j) { PyObject *colorcomp = PyTuple_GET_ITEM(item, j); if(PyInt_Check(colorcomp)) C[i*4+j] = int(PyInt_AS_LONG(colorcomp)); else if(PyFloat_Check(colorcomp)) C[i*4+j] = int(PyFloat_AS_DOUBLE(colorcomp)); else badInput = true; } } else badInput = true; } if(badInput) { delete [] C; return NULL; } for(int i = 0; i < cL.GetNumColors(); ++i) cL[i].SetRgba(C[i*4], C[i*4+1], C[i*4+2], C[i*4+3]); delete [] C; } else return NULL; } } else { if(!PyTuple_Check(pyobj)) return NULL; // Make sure that the tuple is the right size. if(PyTuple_Size(pyobj) < 3 || PyTuple_Size(pyobj) > 4) return NULL; // Make sure that all elements in the tuple are ints. for(int i = 0; i < PyTuple_Size(pyobj); ++i) { PyObject *item = PyTuple_GET_ITEM(pyobj, i); if(PyInt_Check(item)) c[i] = int(PyInt_AS_LONG(PyTuple_GET_ITEM(pyobj, i))); else if(PyFloat_Check(item)) c[i] = int(PyFloat_AS_DOUBLE(PyTuple_GET_ITEM(pyobj, i))); else return NULL; } } } } PyErr_Clear(); } if(index < 0 || index >= cL.GetNumColors()) return NULL; // Set the color in the object. if(setTheColor) cL[index] = ColorAttribute(c[0], c[1], c[2], c[3]); cL.SelectColors(); obj->data->SelectMultiColor(); Py_INCREF(Py_None); return Py_None; }
static PyObject * GMPy_Real_Sub(PyObject *x, PyObject *y, CTXT_Object *context) { MPFR_Object *result; CHECK_CONTEXT(context); if (!(result = GMPy_MPFR_New(0, context))) return NULL; /* This only processes mpfr if the exponent is still in-bounds. Need * to handle the rare case at the end. */ if (MPFR_Check(x) && MPFR_Check(y)) { mpfr_clear_flags(); result->rc = mpfr_sub(result->f, MPFR(x), MPFR(y), GET_MPFR_ROUND(context)); goto done; } if (MPFR_Check(x)) { if (PyIntOrLong_Check(y)) { int error; long temp = GMPy_Integer_AsLongAndError(y, &error); if (!error) { mpfr_clear_flags(); result->rc = mpfr_sub_si(result->f, MPFR(x), temp, GET_MPFR_ROUND(context)); goto done; } else { mpz_t tempz; mpz_inoc(tempz); mpz_set_PyIntOrLong(tempz, y); mpfr_clear_flags(); result->rc = mpfr_sub_z(result->f, MPFR(x), tempz, GET_MPFR_ROUND(context)); mpz_cloc(tempz); goto done; } } if (CHECK_MPZANY(y)) { mpfr_clear_flags(); result->rc = mpfr_sub_z(result->f, MPFR(x), MPZ(y), GET_MPFR_ROUND(context)); goto done; } if (IS_RATIONAL(y)) { MPQ_Object *tempy; if (!(tempy = GMPy_MPQ_From_Number(y, context))) { Py_DECREF((PyObject*)result); return NULL; } mpfr_clear_flags(); result->rc = mpfr_sub_q(result->f, MPFR(x), tempy->q, GET_MPFR_ROUND(context)); Py_DECREF((PyObject*)tempy); goto done; } if (PyFloat_Check(y)) { mpfr_clear_flags(); result->rc = mpfr_sub_d(result->f, MPFR(x), PyFloat_AS_DOUBLE(y), GET_MPFR_ROUND(context)); goto done; } } if (MPFR_Check(y)) { if (PyIntOrLong_Check(x)) { int error; long temp = GMPy_Integer_AsLongAndError(x, &error); if (!error) { mpfr_clear_flags(); result->rc = mpfr_sub_si(result->f, MPFR(y), temp, GET_MPFR_ROUND(context)); mpfr_neg(result->f, result->f, GET_MPFR_ROUND(context)); goto done; } else { mpz_t tempz; mpz_inoc(tempz); mpz_set_PyIntOrLong(tempz, x); mpfr_clear_flags(); result->rc = mpfr_sub_z(result->f, MPFR(y), tempz, GET_MPFR_ROUND(context)); mpfr_neg(result->f, result->f, GET_MPFR_ROUND(context)); mpz_cloc(tempz); goto done; } } if (CHECK_MPZANY(x)) { mpfr_clear_flags(); result->rc = mpfr_sub_z(result->f, MPFR(y), MPZ(x), GET_MPFR_ROUND(context)); mpfr_neg(result->f, result->f, GET_MPFR_ROUND(context)); goto done; } if (IS_RATIONAL(x)) { MPQ_Object *tempx; if (!(tempx = GMPy_MPQ_From_Number(x, context))) { Py_DECREF((PyObject*)result); return NULL; } mpfr_clear_flags(); result->rc = mpfr_sub_q(result->f, MPFR(y), tempx->q, GET_MPFR_ROUND(context)); mpfr_neg(result->f, result->f, GET_MPFR_ROUND(context)); Py_DECREF((PyObject*)tempx); goto done; } if (PyFloat_Check(x)) { mpfr_clear_flags(); result->rc = mpfr_sub_d(result->f, MPFR(y), PyFloat_AS_DOUBLE(x), GET_MPFR_ROUND(context)); mpfr_neg(result->f, result->f, GET_MPFR_ROUND(context)); goto done; } } if (IS_REAL(x) && IS_REAL(y)) { MPFR_Object *tempx, *tempy; tempx = GMPy_MPFR_From_Real(x, 1, context); tempy = GMPy_MPFR_From_Real(y, 1, context); if (!tempx || !tempy) { Py_XDECREF((PyObject*)tempx); Py_XDECREF((PyObject*)tempy); Py_DECREF((PyObject*)result); return NULL; } mpfr_clear_flags(); result->rc = mpfr_sub(result->f, MPFR(tempx), MPFR(tempy), GET_MPFR_ROUND(context)); Py_DECREF((PyObject*)tempx); Py_DECREF((PyObject*)tempy); goto done; } Py_DECREF((PyObject*)result); Py_RETURN_NOTIMPLEMENTED; done: GMPY_MPFR_CLEANUP(result, context, "subtraction"); return (PyObject*)result; }
$FreeBSD$ --- src/rpcUtils.c.orig +++ src/rpcUtils.c @@ -276,7 +280,7 @@ double d; d = PyFloat_AS_DOUBLE(value); - snprintf(buff, 255, "%f", d); + snprintf(buff, 255, "%.17f", d); if ((buffConstant(sp, "<double>") == NULL) or (buffConcat(sp, buff) == NULL) or (buffConstant(sp, "</double>") == NULL))
/** Node Class methods Returns an error code. TRUE for success, FALSE for error... */ static int _Node_input_sum(Node *self, PyObject *inputs, double *sum) { // Iterate over the items in the weights dict PyObject *key, *pyweight; double weight, value = 0, recursive_val; Py_ssize_t pos = 0; int result = TRUE; *sum = 0; while (PyDict_Next(self->weights, &pos, &key, &pyweight)) { // First verify that the weight is a float if (!PyFloat_Check(pyweight)) { PyErr_Format(PyExc_ValueError, "The value of the weights dict was NOT a float!"); result = FALSE; } else { weight = PyFloat_AS_DOUBLE(pyweight); // If node is a Node, call its inputsum. Else, it's an input index. if (PyObject_IsInstance(key, (PyObject*) self->ob_type)) { if (_Node_output((Node*) key, inputs, &recursive_val)) *sum += weight * recursive_val; else result = FALSE; } else if (PyObject_IsInstance(key, (PyObject*) &BiasNodeType)) { *sum += weight * 1; } else if (PyInt_Check(key))// It's an input index { Py_ssize_t index = PyInt_AsSsize_t(key); // Two cases, python list or numpy list if (PyList_CheckExact(inputs)) // Python list { PyObject *pyval = PyList_GetItem(inputs, index); if (pyval == NULL) result = FALSE; else value = PyFloat_AS_DOUBLE(pyval); } else // Numpy list { double *ptr = (double *) PyArray_GETPTR1((PyArrayObject*) inputs, index); if (ptr == NULL) result = FALSE; else value = *ptr; } *sum += weight * value; } else // Someone f****d up the weight dict { PyErr_Format(PyExc_ValueError, "The key of the weights dict was neither a Node nor an Int!"); result = FALSE; } } //if float } //while return result; }
int convert_pyObj_prObj(PyObject *pyObj, prolog_term *prTerm) { if(pyObj == Py_None){ return 1;// todo: check this case for a list with a none in the list. how does prolog side react } if(PyInt_Check(pyObj)) { int result = PyInt_AS_LONG(pyObj); //extern_ctop_int(3, result); c2p_int(result, *prTerm); return 1; } else if(PyFloat_Check(pyObj)) { float result = PyFloat_AS_DOUBLE(pyObj); //extern_ctop_float(3, result); c2p_float(result, *prTerm); return 1; }else if(PyString_Check(pyObj)) { char *result = PyString_AS_STRING(pyObj); //extern_ctop_string(3, result); c2p_string(result, *prTerm); return 1; }else if(PyList_Check(pyObj)) { size_t size = PyList_Size(pyObj); size_t i = 0; prolog_term head, tail; prolog_term P = p2p_new(); tail = P; for(i = 0; i < size; i++) { c2p_list(CTXTc tail); head = p2p_car(CTXTc tail); PyObject *pyObjInner = PyList_GetItem(pyObj, i); //int temp = PyInt_AS_LONG(pyObj); //c2p_int(temp, head); convert_pyObj_prObj(pyObjInner, &head); tail = p2p_cdr(tail); } c2p_nil(CTXTc tail); //p2p_unify(P, reg_term(CTXTc 3)); return 1; }else { //returns an object refernce to prolog side. pyobj_ref_node *node = add_pyobj_ref_list(pyObj); //printf("node : %p", node); char str[30]; sprintf(str, "%p", node); //extern_ctop_string(3,str); prolog_term ref = p2p_new(); c2p_functor("pyObject", 1, ref); prolog_term ref_inner = p2p_arg(ref, 1); c2p_string(str, ref_inner); p2p_unify(ref, *prTerm); return 1; } }
static uint32_t pointless_export_py_rec(pointless_export_state_t* state, PyObject* py_object, uint32_t depth) { // don't go too deep if (depth >= POINTLESS_MAX_DEPTH) { PyErr_SetString(PyExc_ValueError, "structure is too deep"); state->is_error = 1; printf("line: %i\n", __LINE__); state->error_line = __LINE__; return POINTLESS_CREATE_VALUE_FAIL; } // check simple types first uint32_t handle = POINTLESS_CREATE_VALUE_FAIL; // return an error on failure #define RETURN_OOM(state) {PyErr_NoMemory(); (state)->is_error = 1; printf("line: %i\n", __LINE__); state->error_line = __LINE__; return POINTLESS_CREATE_VALUE_FAIL;} #define RETURN_OOM_IF_FAIL(handle, state) if ((handle) == POINTLESS_CREATE_VALUE_FAIL) RETURN_OOM(state); // booleans, need this above integer check, cause PyInt_Check return 1 for booleans if (PyBool_Check(py_object)) { if (py_object == Py_True) handle = pointless_create_boolean_true(&state->c); else handle = pointless_create_boolean_false(&state->c); RETURN_OOM_IF_FAIL(handle, state); // integer } else if (PyInt_Check(py_object)) { long v = PyInt_AS_LONG(py_object); // unsigned if (v >= 0) { if (v > UINT32_MAX) { PyErr_Format(PyExc_ValueError, "integer too large for mere 32 bits"); printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; return POINTLESS_CREATE_VALUE_FAIL; } handle = pointless_create_u32(&state->c, (uint32_t)v); // signed } else { if (!(INT32_MIN <= v && v <= INT32_MAX)) { PyErr_Format(PyExc_ValueError, "integer too large for mere 32 bits with a sign"); printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; return POINTLESS_CREATE_VALUE_FAIL; } handle = pointless_create_i32(&state->c, (int32_t)v); } RETURN_OOM_IF_FAIL(handle, state); // long } else if (PyLong_Check(py_object)) { // this will raise an overflow error if number is outside the legal range of PY_LONG_LONG PY_LONG_LONG v = PyLong_AsLongLong(py_object); // if there was an exception, clear it, and set our own if (PyErr_Occurred()) { PyErr_Clear(); PyErr_SetString(PyExc_ValueError, "value of long is way beyond what we can store right now"); printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; return POINTLESS_CREATE_VALUE_FAIL; } // unsigned if (v >= 0) { if (v > UINT32_MAX) { PyErr_Format(PyExc_ValueError, "long too large for mere 32 bits"); printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; return POINTLESS_CREATE_VALUE_FAIL; } handle = pointless_create_u32(&state->c, (uint32_t)v); // signed } else { if (!(INT32_MIN <= v && v <= INT32_MAX)) { PyErr_Format(PyExc_ValueError, "long too large for mere 32 bits with a sign"); printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; return POINTLESS_CREATE_VALUE_FAIL; } handle = pointless_create_i32(&state->c, (int32_t)v); } RETURN_OOM_IF_FAIL(handle, state); // None object } else if (py_object == Py_None) { handle = pointless_create_null(&state->c); RETURN_OOM_IF_FAIL(handle, state); } else if (PyFloat_Check(py_object)) { handle = pointless_create_float(&state->c, (float)PyFloat_AS_DOUBLE(py_object)); RETURN_OOM_IF_FAIL(handle, state); } if (handle != POINTLESS_CREATE_VALUE_FAIL) return handle; // remaining types are containers/big-values, which we track // either for space-savings or maintaining circular references // if object has been seen before, return its handle handle = pointless_export_get_seen(state, py_object); if (handle != POINTLESS_CREATE_VALUE_FAIL) return handle; // list/tuple object if (PyList_Check(py_object) || PyTuple_Check(py_object)) { // create and cache handle assert(is_container(py_object)); handle = pointless_create_vector_value(&state->c); RETURN_OOM_IF_FAIL(handle, state); if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } // populate vector Py_ssize_t i, n_items = PyList_Check(py_object) ? PyList_GET_SIZE(py_object) : PyTuple_GET_SIZE(py_object); for (i = 0; i < n_items; i++) { PyObject* child = PyList_Check(py_object) ? PyList_GET_ITEM(py_object, i) : PyTuple_GET_ITEM(py_object, i); uint32_t child_handle = pointless_export_py_rec(state, child, depth + 1); if (child_handle == POINTLESS_CREATE_VALUE_FAIL) return child_handle; if (pointless_create_vector_value_append(&state->c, handle, child_handle) == POINTLESS_CREATE_VALUE_FAIL) { RETURN_OOM(state); } } // pointless value vectors } else if (PyPointlessVector_Check(py_object)) { // currently, we only support value vectors, they are simple PyPointlessVector* v = (PyPointlessVector*)py_object; const char* error = 0; switch(v->v->type) { case POINTLESS_VECTOR_VALUE: case POINTLESS_VECTOR_VALUE_HASHABLE: handle = pointless_recreate_value(&v->pp->p, v->v, &state->c, &error); if (handle == POINTLESS_CREATE_VALUE_FAIL) { printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; PyErr_Format(PyExc_ValueError, "pointless_recreate_value(): %s", error); return POINTLESS_CREATE_VALUE_FAIL; } break; case POINTLESS_VECTOR_I8: handle = pointless_create_vector_i8_owner(&state->c, pointless_reader_vector_i8(&v->pp->p, v->v) + v->slice_i, v->slice_n); break; case POINTLESS_VECTOR_U8: handle = pointless_create_vector_u8_owner(&state->c, pointless_reader_vector_u8(&v->pp->p, v->v) + v->slice_i, v->slice_n); break; case POINTLESS_VECTOR_I16: handle = pointless_create_vector_i16_owner(&state->c, pointless_reader_vector_i16(&v->pp->p, v->v) + v->slice_i, v->slice_n); break; case POINTLESS_VECTOR_U16: handle = pointless_create_vector_u16_owner(&state->c, pointless_reader_vector_u16(&v->pp->p, v->v) + v->slice_i, v->slice_n); break; case POINTLESS_VECTOR_I32: handle = pointless_create_vector_i32_owner(&state->c, pointless_reader_vector_i32(&v->pp->p, v->v) + v->slice_i, v->slice_n); break; case POINTLESS_VECTOR_U32: handle = pointless_create_vector_u32_owner(&state->c, pointless_reader_vector_u32(&v->pp->p, v->v) + v->slice_i, v->slice_n); break; case POINTLESS_VECTOR_I64: handle = pointless_create_vector_i64_owner(&state->c, pointless_reader_vector_i64(&v->pp->p, v->v) + v->slice_i, v->slice_n); break; case POINTLESS_VECTOR_U64: handle = pointless_create_vector_u64_owner(&state->c, pointless_reader_vector_u64(&v->pp->p, v->v) + v->slice_i, v->slice_n); break; case POINTLESS_VECTOR_FLOAT: handle = pointless_create_vector_float_owner(&state->c, pointless_reader_vector_float(&v->pp->p, v->v) + v->slice_i, v->slice_n); break; case POINTLESS_VECTOR_EMPTY: handle = pointless_create_vector_value(&state->c); break; default: state->error_line = __LINE__; printf("line: %i\n", __LINE__); state->is_error = 1; PyErr_SetString(PyExc_ValueError, "internal error: illegal type for primitive vector"); return POINTLESS_CREATE_VALUE_FAIL; } RETURN_OOM_IF_FAIL(handle, state); if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } // python bytearray } else if (PyByteArray_Check(py_object)) { // create handle and hand over the memory Py_ssize_t n_items = PyByteArray_GET_SIZE(py_object); if (n_items > UINT32_MAX) { PyErr_SetString(PyExc_ValueError, "bytearray has too many items"); state->error_line = __LINE__; printf("line: %i\n", __LINE__); state->is_error = 1; return POINTLESS_CREATE_VALUE_FAIL; } handle = pointless_create_vector_u8_owner(&state->c, (uint8_t*)PyByteArray_AS_STRING(py_object), (uint32_t)n_items); RETURN_OOM_IF_FAIL(handle, state); if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } // primitive vectors } else if (PyPointlessPrimVector_Check(py_object)) { // we just hand over the memory PyPointlessPrimVector* prim_vector = (PyPointlessPrimVector*)py_object; uint32_t n_items = pointless_dynarray_n_items(&prim_vector->array); void* data = prim_vector->array._data; switch (prim_vector->type) { case POINTLESS_PRIM_VECTOR_TYPE_I8: handle = pointless_create_vector_i8_owner(&state->c, (int8_t*)data, n_items); break; case POINTLESS_PRIM_VECTOR_TYPE_U8: handle = pointless_create_vector_u8_owner(&state->c, (uint8_t*)data, n_items); break; case POINTLESS_PRIM_VECTOR_TYPE_I16: handle = pointless_create_vector_i16_owner(&state->c, (int16_t*)data, n_items); break; case POINTLESS_PRIM_VECTOR_TYPE_U16: handle = pointless_create_vector_u16_owner(&state->c, (uint16_t*)data, n_items); break; case POINTLESS_PRIM_VECTOR_TYPE_I32: handle = pointless_create_vector_i32_owner(&state->c, (int32_t*)data, n_items); break; case POINTLESS_PRIM_VECTOR_TYPE_U32: handle = pointless_create_vector_u32_owner(&state->c, (uint32_t*)data, n_items); break; case POINTLESS_PRIM_VECTOR_TYPE_I64: handle = pointless_create_vector_i64_owner(&state->c, (int64_t*)data, n_items); break; case POINTLESS_PRIM_VECTOR_TYPE_U64: handle = pointless_create_vector_u64_owner(&state->c, (uint64_t*)data, n_items); break; case POINTLESS_PRIM_VECTOR_TYPE_FLOAT: handle = pointless_create_vector_float_owner(&state->c, (float*)data, n_items); break; default: PyErr_SetString(PyExc_ValueError, "internal error: illegal type for primitive vector"); state->error_line = __LINE__; printf("line: %i\n", __LINE__); state->is_error = 1; return POINTLESS_CREATE_VALUE_FAIL; } RETURN_OOM_IF_FAIL(handle, state); if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } // unicode object } else if (PyUnicode_Check(py_object)) { // get it from python Py_UNICODE* python_buffer = PyUnicode_AS_UNICODE(py_object); // string must not contain zero's Py_ssize_t s_len_python = PyUnicode_GET_SIZE(py_object); #if Py_UNICODE_SIZE == 4 uint32_t s_len_pointless = pointless_ucs4_len(python_buffer); #else uint32_t s_len_pointless = pointless_ucs2_len(python_buffer); #endif if (s_len_python < 0 || (uint64_t)s_len_python != s_len_pointless) { PyErr_SetString(PyExc_ValueError, "unicode string contains a zero, where it shouldn't"); state->error_line = __LINE__; printf("line: %i\n", __LINE__); state->is_error = 1; return POINTLESS_CREATE_VALUE_FAIL; } #if Py_UNICODE_SIZE == 4 if (state->unwiden_strings && pointless_is_ucs4_ascii((uint32_t*)python_buffer)) handle = pointless_create_string_ucs4(&state->c, python_buffer); else handle = pointless_create_unicode_ucs4(&state->c, python_buffer); #else if (state->unwiden_strings && pointless_is_ucs2_ascii(python_buffer)) handle = pointless_create_string_ucs2(&state->c, python_buffer); else handle = pointless_create_unicode_ucs2(&state->c, python_buffer); #endif RETURN_OOM_IF_FAIL(handle, state); if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } // string object } else if (PyString_Check(py_object)) { // get it from python uint8_t* python_buffer = (uint8_t*)PyString_AS_STRING(py_object); // string must not contain zero's Py_ssize_t s_len_python = PyString_GET_SIZE(py_object); uint32_t s_len_pointless = pointless_ascii_len(python_buffer); if (s_len_python < 0 || (uint64_t)s_len_python != s_len_pointless) { PyErr_SetString(PyExc_ValueError, "string contains a zero, where it shouldn't"); state->error_line = __LINE__; printf("line: %i\n", __LINE__); state->is_error = 1; return POINTLESS_CREATE_VALUE_FAIL; } handle = pointless_create_string_ascii(&state->c, python_buffer); RETURN_OOM_IF_FAIL(handle, state); if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } // dict object } else if (PyDict_Check(py_object)) { handle = pointless_create_map(&state->c); RETURN_OOM_IF_FAIL(handle, state); if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } PyObject* key = 0; PyObject* value = 0; Py_ssize_t pos = 0; while (PyDict_Next(py_object, &pos, &key, &value)) { uint32_t key_handle = pointless_export_py_rec(state, key, depth + 1); uint32_t value_handle = pointless_export_py_rec(state, value, depth + 1); if (key_handle == POINTLESS_CREATE_VALUE_FAIL || value_handle == POINTLESS_CREATE_VALUE_FAIL) break; if (pointless_create_map_add(&state->c, handle, key_handle, value_handle) == POINTLESS_CREATE_VALUE_FAIL) { PyErr_SetString(PyExc_ValueError, "error adding key/value pair to map"); state->error_line = __LINE__; printf("line: %i\n", __LINE__); state->is_error = 1; break; } } if (state->is_error) { return POINTLESS_CREATE_VALUE_FAIL; } // set object } else if (PyAnySet_Check(py_object)) { PyObject* iterator = PyObject_GetIter(py_object); PyObject* item = 0; if (iterator == 0) { printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; return POINTLESS_CREATE_VALUE_FAIL; } // get a handle handle = pointless_create_set(&state->c); RETURN_OOM_IF_FAIL(handle, state); // cache object if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } // iterate over it while ((item = PyIter_Next(iterator)) != 0) { uint32_t item_handle = pointless_export_py_rec(state, item, depth + 1); if (item_handle == POINTLESS_CREATE_VALUE_FAIL) break; if (pointless_create_set_add(&state->c, handle, item_handle) == POINTLESS_CREATE_VALUE_FAIL) { PyErr_SetString(PyExc_ValueError, "error adding item to set"); printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; break; } } Py_DECREF(iterator); if (PyErr_Occurred()) { printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; return POINTLESS_CREATE_VALUE_FAIL; } // bitvector } else if (PyPointlessBitvector_Check(py_object)) { PyPointlessBitvector* bitvector = (PyPointlessBitvector*)py_object; if (bitvector->is_pointless) { uint32_t i, n_bits = pointless_reader_bitvector_n_bits(&bitvector->pointless_pp->p, bitvector->pointless_v); void* bits = pointless_calloc(ICEIL(n_bits, 8), 1); if (bits == 0) { RETURN_OOM(state); } for (i = 0; i < n_bits; i++) { if (pointless_reader_bitvector_is_set(&bitvector->pointless_pp->p, bitvector->pointless_v, i)) bm_set_(bits, i); } if (state->normalize_bitvector) handle = pointless_create_bitvector(&state->c, bits, n_bits); else handle = pointless_create_bitvector_no_normalize(&state->c, bits, n_bits); pointless_free(bits); bits = 0; } else { if (state->normalize_bitvector) handle = pointless_create_bitvector(&state->c, bitvector->primitive_bits, bitvector->primitive_n_bits); else handle = pointless_create_bitvector_no_normalize(&state->c, bitvector->primitive_bits, bitvector->primitive_n_bits); } RETURN_OOM_IF_FAIL(handle, state); if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } } else if (PyPointlessSet_Check(py_object)) { PyPointlessSet* set = (PyPointlessSet*)py_object; const char* error = 0; handle = pointless_recreate_value(&set->pp->p, set->v, &state->c, &error); if (handle == POINTLESS_CREATE_VALUE_FAIL) { printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; PyErr_Format(PyExc_ValueError, "pointless_recreate_value(): %s", error); return POINTLESS_CREATE_VALUE_FAIL; } if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } } else if (PyPointlessMap_Check(py_object)) { PyPointlessMap* map = (PyPointlessMap*)py_object; const char* error = 0; handle = pointless_recreate_value(&map->pp->p, map->v, &state->c, &error); if (handle == POINTLESS_CREATE_VALUE_FAIL) { printf("line: %i\n", __LINE__); state->is_error = 1; state->error_line = __LINE__; PyErr_Format(PyExc_ValueError, "pointless_recreate_value(): %s", error); return POINTLESS_CREATE_VALUE_FAIL; } if (!pointless_export_set_seen(state, py_object, handle)) { RETURN_OOM(state); } // type not supported } else { PyErr_Format(PyExc_ValueError, "type <%s> not supported", py_object->ob_type->tp_name); state->error_line = __LINE__; printf("line: %i\n", __LINE__); state->is_error = 1; } #undef RETURN_OOM #undef RETURN_IF_OOM return handle; }
int splat_signal_init(struct splat_signal *s, size_t length, size_t origin, PyObject **signals, size_t n_signals, unsigned rate) { size_t i; s->origin = origin; s->length = length + s->origin; s->n_vectors = n_signals; s->vectors = PyMem_Malloc(n_signals * sizeof(struct splat_vector)); s->rate = rate; if (s->vectors == NULL) { PyErr_NoMemory(); return -1; } s->py_float = PyFloat_FromDouble(0); if (s->py_float == NULL) { PyErr_SetString(PyExc_AssertionError, "Failed to create float object"); return -1; } s->py_args = PyTuple_New(1); if (s->py_args == NULL) { PyErr_NoMemory(); return -1; } PyTuple_SET_ITEM(s->py_args, 0, s->py_float); for (i = 0; i < n_signals; ++i) { struct splat_vector *v = &s->vectors[i]; PyObject *signal = signals[i]; struct splat_spline *spline = splat_spline_from_obj(signal); struct splat_fragment *frag = splat_frag_from_obj(signal); if (PyFloat_Check(signal)) { const sample_t value = PyFloat_AS_DOUBLE(signal); size_t j; for (j = 0; j < SPLAT_VECTOR_LEN; ++j) v->data[j] = value; v->signal = NULL; } else if (PyCallable_Check(signal)) { v->signal = splat_signal_func; } else if (frag != NULL) { if (frag->n_channels != 1) { PyErr_SetString(PyExc_ValueError, "Fragment signal must have only 1 channel"); return -1; } if (s->length > frag->length) { PyErr_SetString(PyExc_ValueError, "Fragment signal length too short"); return -1; } v->signal = splat_signal_frag; } else if (spline != NULL) { size_t spline_length = spline->end * rate; if (s->length > spline_length) { PyErr_SetString(PyExc_ValueError, "Spline signal length too short"); return -1; } v->signal = splat_signal_spline; } else { PyErr_SetString(PyExc_TypeError, "unsupported signal type"); return -1; } v->obj = signal; } s->cur = s->origin; s->end = 0; s->len = 0; s->stat = SPLAT_SIGNAL_CONTINUE; return 0; }
static int Params_parameter_set(ParamsObject *self, PyObject *value, struct param_getsets *pgs) { if (value == NULL) { // Maybe in future this should restore to default, but I can't be arsed. PyErr_Format(PyExc_TypeError,"cannot delete attribute '%s'", pgs->attr_name); return -1; } switch (pgs->type) { case 0: { // Boolean. int truth = PyObject_IsTrue(value); if (truth < 0) return -1; lpx_set_int_parm(LP, pgs->code, truth); return 0; } case 1: { // Integer. if (!PyInt_Check(value)) { PyErr_Format(PyExc_TypeError, "attribute '%s' requires an int", pgs->attr_name); return -1; } int val = PyInt_AS_LONG(value); // Do all that range checking. if (pgs->low < pgs->high) { if (pgs->low > val) { PyErr_Format(PyExc_ValueError,"attribute '%s' must be at least %d", pgs->attr_name, (int)pgs->low); return -1; } if (pgs->high < val) { PyErr_Format(PyExc_ValueError,"attribute '%s' must be at most %d", pgs->attr_name, (int)pgs->high); return -1; } } // It's in range. Set it. lpx_set_int_parm(LP, pgs->code, val); return 0; } case 2: { // Float. value = PyNumber_Float(value); if (value == NULL) { PyErr_Format(PyExc_TypeError, "attribute %s requires a float", pgs->attr_name); return -1; } double val = PyFloat_AS_DOUBLE(value); Py_DECREF(value); // Do the range checking. if (pgs->low < pgs->high) { if ((!pgs->include_low && pgs->low==val) || pgs->low>val) { char buffer[100]; snprintf(buffer, sizeof(buffer), "attribute '%s' must be %s %g", pgs->attr_name, pgs->include_low?"at least":"greater than", pgs->low); PyErr_SetString(PyExc_ValueError, buffer); return -1; } if ((!pgs->include_high && pgs->high==val) || pgs->high<val) { char buffer[100]; snprintf(buffer, sizeof(buffer), "attribute '%s' must be %s %g", pgs->attr_name, pgs->include_high?"at most":"less than", pgs->high); PyErr_SetString(PyExc_ValueError, buffer); return -1; } } // It's in range. Set it. lpx_set_real_parm(LP, pgs->code, val); return 0; } default: // Um, apparently I made a mistake in the PGS definition array. PyErr_Format(PyExc_RuntimeError, "parameter type code %d unrecognized", pgs->type); return -1; } }
double operator()(PyObject* obj) { if(PyFloat_Check(obj)) return PyFloat_AS_DOUBLE(obj); else return PyInt_AS_LONG(obj); }
static PyObject * GMPy_Real_Mul(PyObject *x, PyObject *y, CTXT_Object *context) { MPFR_Object *result = NULL; CHECK_CONTEXT(context); if (!(result = GMPy_MPFR_New(0, context))) { /* LCOV_EXCL_START */ return NULL; /* LCOV_EXCL_STOP */ } if (MPFR_Check(x) && MPFR_Check(y)) { mpfr_clear_flags(); result->rc = mpfr_mul(result->f, MPFR(x), MPFR(y), GET_MPFR_ROUND(context)); goto done; } if (MPFR_Check(x)) { if (PyIntOrLong_Check(y)) { int error; long temp = GMPy_Integer_AsLongAndError(y, &error); if (!error) { mpfr_clear_flags(); result->rc = mpfr_mul_si(result->f, MPFR(x), temp, GET_MPFR_ROUND(context)); goto done; } else { mpz_t tempz; mpz_inoc(tempz); mpz_set_PyIntOrLong(tempz, y); mpfr_clear_flags(); result->rc = mpfr_mul_z(result->f, MPFR(x), tempz, GET_MPFR_ROUND(context)); mpz_cloc(tempz); goto done; } } if (CHECK_MPZANY(y)) { mpfr_clear_flags(); result->rc = mpfr_mul_z(result->f, MPFR(x), MPZ(y), GET_MPFR_ROUND(context)); goto done; } if (IS_RATIONAL(y)) { MPQ_Object *tempy = NULL; if (!(tempy = GMPy_MPQ_From_Number(y, context))) { /* LCOV_EXCL_START */ Py_DECREF((PyObject*)result); return NULL; /* LCOV_EXCL_STOP */ } mpfr_clear_flags(); result->rc = mpfr_mul_q(result->f, MPFR(x), tempy->q, GET_MPFR_ROUND(context)); Py_DECREF((PyObject*)tempy); goto done; } if (PyFloat_Check(y)) { mpfr_clear_flags(); result->rc = mpfr_mul_d(result->f, MPFR(x), PyFloat_AS_DOUBLE(y), GET_MPFR_ROUND(context)); goto done; } } if (MPFR_Check(y)) { if (PyIntOrLong_Check(x)) { int error; long temp = GMPy_Integer_AsLongAndError(x, &error); if (!error) { mpfr_clear_flags(); result->rc = mpfr_mul_si(result->f, MPFR(y), temp, GET_MPFR_ROUND(context)); goto done; } else { mpz_t tempz; mpz_inoc(tempz); mpz_set_PyIntOrLong(tempz, x); mpfr_clear_flags(); result->rc = mpfr_mul_z(result->f, MPFR(y), tempz, GET_MPFR_ROUND(context)); mpz_cloc(tempz); goto done; } } if (CHECK_MPZANY(x)) { mpfr_clear_flags(); result->rc = mpfr_mul_z(result->f, MPFR(y), MPZ(x), GET_MPFR_ROUND(context)); goto done; } if (IS_RATIONAL(x)) { MPQ_Object *tempx = NULL; if (!(tempx = GMPy_MPQ_From_Number(x, context))) { /* LCOV_EXCL_START */ Py_DECREF((PyObject*)result); return NULL; /* LCOV_EXCL_STOP */ } mpfr_clear_flags(); result->rc = mpfr_mul_q(result->f, MPFR(y), tempx->q, GET_MPFR_ROUND(context)); Py_DECREF((PyObject*)tempx); goto done; } if (PyFloat_Check(x)) { mpfr_clear_flags(); result->rc = mpfr_mul_d(result->f, MPFR(y), PyFloat_AS_DOUBLE(x), GET_MPFR_ROUND(context)); goto done; } } if (IS_REAL(x) && IS_REAL(y)) { MPFR_Object *tempx = NULL, *tempy = NULL; if (!(tempx = GMPy_MPFR_From_Real(x, 1, context)) || !(tempy = GMPy_MPFR_From_Real(y, 1, context))) { /* LCOV_EXCL_START */ Py_XDECREF((PyObject*)tempx); Py_XDECREF((PyObject*)tempy); Py_DECREF((PyObject*)result); return NULL; /* LCOV_EXCL_STOP */ } mpfr_clear_flags(); result->rc = mpfr_mul(result->f, MPFR(tempx), MPFR(tempy), GET_MPFR_ROUND(context)); Py_DECREF((PyObject*)tempx); Py_DECREF((PyObject*)tempy); goto done; } /* LCOV_EXCL_START */ Py_DECREF((PyObject*)result); SYSTEM_ERROR("Internal error in GMPy_Real_Mul()."); return NULL; /* LCOV_EXCL_STOP */ done: _GMPy_MPFR_Cleanup(&result, context); return (PyObject*)result; }
static void OscBank_readframes(OscBank *self) { MYFLT freq, spread, slope, frndf, frnda, arndf, arnda, amp, modamp, pos, inc, x, y, fpart; int i, j, ipart; MYFLT *tablelist = TableStream_getData(self->table); int size = TableStream_getSize(self->table); MYFLT tabscl = size / self->sr; for (i=0; i<self->bufsize; i++) { self->data[i] = 0.0; } if (self->modebuffer[2] == 0) freq = PyFloat_AS_DOUBLE(self->freq); else freq = Stream_getData((Stream *)self->freq_stream)[0]; if (self->modebuffer[3] == 0) spread = PyFloat_AS_DOUBLE(self->spread); else spread = Stream_getData((Stream *)self->spread_stream)[0]; if (self->modebuffer[4] == 0) slope = PyFloat_AS_DOUBLE(self->slope); else slope = Stream_getData((Stream *)self->slope_stream)[0]; if (self->modebuffer[5] == 0) frndf = PyFloat_AS_DOUBLE(self->frndf); else frndf = Stream_getData((Stream *)self->frndf_stream)[0]; if (self->modebuffer[6] == 0) frnda = PyFloat_AS_DOUBLE(self->frnda); else frnda = Stream_getData((Stream *)self->frnda_stream)[0]; if (self->modebuffer[7] == 0) arndf = PyFloat_AS_DOUBLE(self->arndf); else arndf = Stream_getData((Stream *)self->arndf_stream)[0]; if (self->modebuffer[8] == 0) arnda = PyFloat_AS_DOUBLE(self->arnda); else arnda = Stream_getData((Stream *)self->arnda_stream)[0]; if (freq != self->lastFreq || spread != self->lastSpread) { self->lastFreq = freq; self->lastSpread = spread; OscBank_setFrequencies(self, freq, spread); } if (self->fjit != self->lastFjit) { self->lastFjit = self->fjit; OscBank_setFrequencies(self, freq, spread); if (self->fjit == 0) { for (i=0; i<self->stages; i++) { self->pointerPos[i] = 0.0; } } } if (frnda == 0.0 && arnda == 0.0) { amp = self->amplitude; for (j=0; j<self->stages; j++) { inc = self->frequencies[j] * tabscl; pos = self->pointerPos[j]; for (i=0; i<self->bufsize; i++) { pos = OscBank_clip(pos, size); ipart = (int)pos; fpart = pos - ipart; x = tablelist[ipart]; y = tablelist[ipart+1]; self->data[i] += (x + (y - x) * fpart) * amp; pos += inc; } self->pointerPos[j] = pos; amp *= slope; } } else if (frnda != 0.0 && arnda != 0.0) { if (self->ftime >= 1.0) { OscBank_pickNewFrnds(self, frndf, frnda); } if (self->atime >= 1.0) { OscBank_pickNewArnds(self, arndf, arnda); } amp = self->amplitude; for (j=0; j<self->stages; j++) { inc = (self->frequencies[j] + (self->fOldValues[j] + self->fDiffs[j] * self->ftime)) * tabscl; pos = self->pointerPos[j]; modamp = (1.0 - arnda) + (self->aOldValues[j] + self->aDiffs[j] * self->atime); for (i=0; i<self->bufsize; i++) { pos = OscBank_clip(pos, size); ipart = (int)pos; fpart = pos - ipart; x = tablelist[ipart]; y = tablelist[ipart+1]; self->data[i] += (x + (y - x) * fpart) * amp * modamp; pos += inc; } self->pointerPos[j] = pos; amp *= slope; } self->ftime += self->finc; self->atime += self->ainc; } else if (frnda != 0.0 && arnda == 0.0) { if (self->ftime >= 1.0) { OscBank_pickNewFrnds(self, frndf, frnda); } amp = self->amplitude; for (j=0; j<self->stages; j++) { inc = (self->frequencies[j] + (self->fOldValues[j] + self->fDiffs[j] * self->ftime)) * tabscl; pos = self->pointerPos[j]; for (i=0; i<self->bufsize; i++) { pos = OscBank_clip(pos, size); ipart = (int)pos; fpart = pos - ipart; x = tablelist[ipart]; y = tablelist[ipart+1]; self->data[i] += (x + (y - x) * fpart) * amp; pos += inc; } self->pointerPos[j] = pos; amp *= slope; } self->ftime += self->finc; } else if (frnda == 0.0 && arnda != 0.0) { if (self->atime >= 1.0) { OscBank_pickNewArnds(self, arndf, arnda); } amp = self->amplitude; for (j=0; j<self->stages; j++) { inc = self->frequencies[j] * tabscl; pos = self->pointerPos[j]; modamp = (1.0 - arnda) + (self->aOldValues[j] + self->aDiffs[j] * self->atime); for (i=0; i<self->bufsize; i++) { pos = OscBank_clip(pos, size); ipart = (int)pos; fpart = pos - ipart; x = tablelist[ipart]; y = tablelist[ipart+1]; self->data[i] += (x + (y - x) * fpart) * amp * modamp; pos += inc; } self->pointerPos[j] = pos; amp *= slope; } self->atime += self->ainc; } }
/*static*/ PyObject * MultiCurveAttributes_SetChangedColors(PyObject *self, PyObject *args) { MultiCurveAttributesObject *obj = (MultiCurveAttributesObject *)self; unsignedCharVector &vec = obj->data->GetChangedColors(); PyObject *tuple; if(!PyArg_ParseTuple(args, "O", &tuple)) return NULL; if(PyTuple_Check(tuple)) { vec.resize(PyTuple_Size(tuple)); for(int i = 0; i < PyTuple_Size(tuple); ++i) { int c; PyObject *item = PyTuple_GET_ITEM(tuple, i); if(PyFloat_Check(item)) c = int(PyFloat_AS_DOUBLE(item)); else if(PyInt_Check(item)) c = int(PyInt_AS_LONG(item)); else if(PyLong_Check(item)) c = int(PyLong_AsDouble(item)); else c = 0; if(c < 0) c = 0; if(c > 255) c = 255; vec[i] = (unsigned char)(c); } } else if(PyFloat_Check(tuple)) { vec.resize(1); int c = int(PyFloat_AS_DOUBLE(tuple)); if(c < 0) c = 0; if(c > 255) c = 255; vec[0] = (unsigned char)(c); } else if(PyInt_Check(tuple)) { vec.resize(1); int c = int(PyInt_AS_LONG(tuple)); if(c < 0) c = 0; if(c > 255) c = 255; vec[0] = (unsigned char)(c); } else if(PyLong_Check(tuple)) { vec.resize(1); int c = PyLong_AsLong(tuple); if(c < 0) c = 0; if(c > 255) c = 255; vec[0] = (unsigned char)(c); } else return NULL; // Mark the changedColors in the object as modified. obj->data->SelectChangedColors(); Py_INCREF(Py_None); return Py_None; }
static void FourBandMain_filters(FourBandMain *self) { double val, inval, tmp, f1, f2, f3; int i, j, j1, ind, ind1; MYFLT *in = Stream_getData((Stream *)self->input_stream); if (self->modebuffer[0] == 0) f1 = PyFloat_AS_DOUBLE(self->freq1); else f1 = (double)Stream_getData((Stream *)self->freq1_stream)[0]; if (self->modebuffer[1] == 0) f2 = PyFloat_AS_DOUBLE(self->freq2); else f2 = (double)Stream_getData((Stream *)self->freq2_stream)[0]; if (self->modebuffer[2] == 0) f3 = PyFloat_AS_DOUBLE(self->freq3); else f3 = (double)Stream_getData((Stream *)self->freq3_stream)[0]; if (f1 != self->last_freq1) { self->last_freq1 = f1; FourBandMain_compute_variables(self, f1, 0); } if (f2 != self->last_freq2) { self->last_freq2 = f2; FourBandMain_compute_variables(self, f2, 1); } if (f3 != self->last_freq3) { self->last_freq3 = f3; FourBandMain_compute_variables(self, f3, 2); } for (i=0; i<self->bufsize; i++) { inval = (double)in[i]; /* First band */ val = self->la0[0] * inval + self->la1[0] * self->x1[0] + self->la2[0] * self->x2[0] + self->la1[0] * self->x3[0] + self->la0[0] * self->x4[0] - self->b1[0] * self->y1[0] - self->b2[0] * self->y2[0] - self->b3[0] * self->y3[0] - self->b4[0] * self->y4[0]; self->y4[0] = self->y3[0]; self->y3[0] = self->y2[0]; self->y2[0] = self->y1[0]; self->y1[0] = val; self->x4[0] = self->x3[0]; self->x3[0] = self->x2[0]; self->x2[0] = self->x1[0]; self->x1[0] = inval; self->buffer_streams[i] = (MYFLT)val; /* Second and third bands */ for (j=0; j<2; j++) { j1 = j + 1; ind = j * 2 + 1; ind1 = ind + 1; tmp = self->ha0[j] * inval + self->ha1[j] * self->x1[ind] + self->ha2[j] * self->x2[ind] + self->ha1[j] * self->x3[ind] + self->ha0[j] * self->x4[ind] - self->b1[j] * self->y1[ind] - self->b2[j] * self->y2[ind] - self->b3[j] * self->y3[ind] - self->b4[j] * self->y4[ind]; self->y4[ind] = self->y3[ind]; self->y3[ind] = self->y2[ind]; self->y2[ind] = self->y1[ind]; self->y1[ind] = tmp; self->x4[ind] = self->x3[ind]; self->x3[ind] = self->x2[ind]; self->x2[ind] = self->x1[ind]; self->x1[ind] = inval; val = self->la0[j1] * tmp + self->la1[j1] * self->x1[ind1] + self->la2[j1] * self->x2[ind1] + self->la1[j1] * self->x3[ind1] + self->la0[j1] * self->x4[ind1] - self->b1[j1] * self->y1[ind1] - self->b2[j1] * self->y2[ind1] - self->b3[j1] * self->y3[ind1] - self->b4[j1] * self->y4[ind1]; self->y4[ind1] = self->y3[ind1]; self->y3[ind1] = self->y2[ind1]; self->y2[ind1] = self->y1[ind1]; self->y1[ind1] = val; self->x4[ind1] = self->x3[ind1]; self->x3[ind1] = self->x2[ind1]; self->x2[ind1] = self->x1[ind1]; self->x1[ind1] = tmp; self->buffer_streams[i + j1 * self->bufsize] = (MYFLT)val; } val = self->ha0[2] * inval + self->ha1[2] * self->x1[5] + self->ha2[2] * self->x2[5] + self->ha1[2] * self->x3[5] + self->ha0[2] * self->x4[5] - self->b1[2] * self->y1[5] - self->b2[2] * self->y2[5] - self->b3[2] * self->y3[5] - self->b4[2] * self->y4[5]; self->y4[5] = self->y3[5]; self->y3[5] = self->y2[5]; self->y2[5] = self->y1[5]; self->y1[5] = val; self->x4[5] = self->x3[5]; self->x3[5] = self->x2[5]; self->x2[5] = self->x1[5]; self->x1[5] = inval; self->buffer_streams[i + 3 * self->bufsize] = (MYFLT)val; } }
/** * Evaluate the code and return the value * @return */ QVariant PythonScript::evaluateImpl() { ScopedPythonGIL lock; PyObject *compiledCode = this->compileToByteCode(true); if (!compiledCode) { return QVariant(""); } PyObject *pyret; beginStdoutRedirect(); if (PyCallable_Check(compiledCode)) { PyObject *empty_tuple = PyTuple_New(0); pyret = PyObject_Call(compiledCode, empty_tuple, localDict); Py_DECREF(empty_tuple); } else { pyret = PyEval_EvalCode(CODE_OBJECT(compiledCode), localDict, localDict); } endStdoutRedirect(); if (!pyret) { if (PyErr_ExceptionMatches(PyExc_ValueError) || PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) { PyErr_Clear(); // silently ignore errors return QVariant(""); } else { emit_error(); return QVariant(); } } QVariant qret = QVariant(); /* None */ if (pyret == Py_None) { qret = QVariant(""); } /* numeric types */ else if (PyFloat_Check(pyret)) { qret = QVariant(PyFloat_AS_DOUBLE(pyret)); } else if (INT_CHECK(pyret)) { qret = QVariant((qlonglong)TO_LONG(pyret)); } #if !defined(IS_PY3K) else if (PyLong_Check(pyret)) { qret = QVariant((qlonglong)PyLong_AsLongLong(pyret)); } #endif else if (PyNumber_Check(pyret)) { PyObject *number = PyNumber_Float(pyret); if (number) { qret = QVariant(PyFloat_AS_DOUBLE(number)); Py_DECREF(number); } } /* bool */ else if (PyBool_Check(pyret)) { qret = QVariant(pyret == Py_True); } // could handle advanced types (such as PyList->QValueList) here if needed /* fallback: try to convert to (unicode) string */ if (!qret.isValid()) { #if defined(IS_PY3K) // In 3 everything is unicode PyObject *pystring = PyObject_Str(pyret); if (pystring) { qret = QVariant(QString::fromUtf8(_PyUnicode_AsString(pystring))); } #else PyObject *pystring = PyObject_Unicode(pyret); if (pystring) { PyObject *asUTF8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(pystring), (int)PyUnicode_GET_DATA_SIZE(pystring), nullptr); Py_DECREF(pystring); if (asUTF8) { qret = QVariant(QString::fromUtf8(PyString_AS_STRING(asUTF8))); Py_DECREF(asUTF8); } else if ((pystring = PyObject_Str(pyret))) { qret = QVariant(QString(PyString_AS_STRING(pystring))); Py_DECREF(pystring); } } #endif } Py_DECREF(pyret); if (PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_ValueError) || PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) { PyErr_Clear(); // silently ignore errors return QVariant(""); } else { emit_error(); } return QVariant(); } return qret; }
int PyPath_Flatten(PyObject* data, double **pxy) { int i, j, n; double *xy; if (PyPath_Check(data)) { /* This was another path object. */ PyPathObject *path = (PyPathObject*) data; xy = alloc_array(path->count); if (!xy) return -1; memcpy(xy, path->xy, 2 * path->count * sizeof(double)); *pxy = xy; return path->count; } if (PyImaging_CheckBuffer(data)) { /* Assume the buffer contains floats */ float* ptr; int n = PyImaging_ReadBuffer(data, (const void**) &ptr); n /= 2 * sizeof(float); xy = alloc_array(n); if (!xy) return -1; for (i = 0; i < n+n; i++) xy[i] = ptr[i]; *pxy = xy; return n; } if (!PySequence_Check(data)) { PyErr_SetString(PyExc_TypeError, "argument must be sequence"); return -1; } j = 0; n = PyObject_Length(data); /* Just in case __len__ breaks (or doesn't exist) */ if (PyErr_Occurred()) return -1; /* Allocate for worst case */ xy = alloc_array(n); if (!xy) return -1; /* Copy table to path array */ if (PyList_Check(data)) { for (i = 0; i < n; i++) { double x, y; PyObject *op = PyList_GET_ITEM(data, i); if (PyFloat_Check(op)) xy[j++] = PyFloat_AS_DOUBLE(op); else if (PyInt_Check(op)) xy[j++] = (float) PyInt_AS_LONG(op); else if (PyNumber_Check(op)) xy[j++] = PyFloat_AsDouble(op); else if (PyArg_ParseTuple(op, "dd", &x, &y)) { xy[j++] = x; xy[j++] = y; } else { free(xy); return -1; } } } else if (PyTuple_Check(data)) { for (i = 0; i < n; i++) { double x, y; PyObject *op = PyTuple_GET_ITEM(data, i); if (PyFloat_Check(op)) xy[j++] = PyFloat_AS_DOUBLE(op); else if (PyInt_Check(op)) xy[j++] = (float) PyInt_AS_LONG(op); else if (PyNumber_Check(op)) xy[j++] = PyFloat_AsDouble(op); else if (PyArg_ParseTuple(op, "dd", &x, &y)) { xy[j++] = x; xy[j++] = y; } else { free(xy); return -1; } } } else { for (i = 0; i < n; i++) { double x, y; PyObject *op = PySequence_GetItem(data, i); if (!op) { /* treat IndexError as end of sequence */ if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_IndexError)) { PyErr_Clear(); break; } else { free(xy); return -1; } } if (PyFloat_Check(op)) xy[j++] = PyFloat_AS_DOUBLE(op); else if (PyInt_Check(op)) xy[j++] = (float) PyInt_AS_LONG(op); else if (PyNumber_Check(op)) xy[j++] = PyFloat_AsDouble(op); else if (PyArg_ParseTuple(op, "dd", &x, &y)) { xy[j++] = x; xy[j++] = y; } else { Py_DECREF(op); free(xy); return -1; } Py_DECREF(op); } } if (j & 1) { PyErr_SetString(PyExc_ValueError, "wrong number of coordinates"); free(xy); return -1; } *pxy = xy; return j/2; }
// This MList function creates a list of the M values giving the probabilities of mutations static PyObject *MList(PyObject *self, PyObject *args) { // Calling variables are (in order): uts, only_need, n_aa, length, grs, mlist, residue_to_compute PyObject *uts, *only_need, *grs, *r_grs_tuple, *gr_diag, *p, *p_inv, *mlist; long n_aa, length, n_aa2, n_uts, residue_to_compute, i_ut, y, index, irowcolumn, only_need_index, only_need_i, only_need_i_n_aa; double *arr_mlist, *cp_inv, *cp, *cgr_diag, *cp_inv_exp; complex double *complex_cp_inv, *complex_cp, *complex_cgr_diag, *complex_cp_inv_exp, *complex_naa2_list, *complex_naa_list; double ut, exp_ut; complex double complex_exp_ut; int array_type; #ifdef USE_ACCELERATE_CBLAS complex double complex_one = 1, complex_zero = 0; long index2; #else complex double complex_mxy; double mxy; long x, yindex; #endif // Parse the arguments. if (! PyArg_ParseTuple( args, "O!O!llO!O!l", &PyList_Type, &uts, &PyList_Type, &only_need, &n_aa, &length, &PyList_Type, &grs, &PyArray_Type, &mlist, &residue_to_compute)) { PyErr_SetString(PyExc_TypeError, "Invalid calling arguments to MList."); return NULL; } // Error checking on arguments if (length < 1) { // length of the protein PyErr_SetString(PyExc_ValueError, "length is less than one."); return NULL; } if (n_aa < 1) { // number of amino acids. Normally will be 20. PyErr_SetString(PyExc_ValueError, "n_aa is less than one."); return NULL; } if (PyList_GET_SIZE(grs) != length) { // make sure grs is of the same size as length // PyErr_SetString(PyExc_ValueError, "grs is not of the same size as length."); char errstring[200]; sprintf(errstring, "grs is not of the same size as length: %ld, %ld", PyList_GET_SIZE(grs), length); PyErr_SetString(PyExc_ValueError, errstring); return NULL; } n_uts = PyList_GET_SIZE(uts); // number of entries in uts if (n_uts < 1) { // make sure there are entries in uts PyErr_SetString(PyExc_ValueError, "uts has no entries."); return NULL; } if (PyList_GET_SIZE(only_need) != n_uts * length) { // make sure only_need is of correct size PyErr_SetString(PyExc_ValueError, "only_need is of wrong size."); return NULL; } if (! ((residue_to_compute >= 0) && (residue_to_compute < length))) { char errstring[200]; sprintf(errstring, "Invalid value for residue_to_compute: %ld, %ld", residue_to_compute, length); PyErr_SetString(PyExc_ValueError, errstring); return NULL; } n_aa2 = n_aa * n_aa; // square of the number of amino acids // The results will be returned in a numpy ndarray 'float_' (C type double) array called mlist. // This array will be of size length * n_uts * n_aa2. arr_mlist = (double *) PyArray_DATA(mlist); // this is the data array of mlist long const sizeof_cp_inv = n_aa2 * sizeof(double); long const complex_sizeof_cp_inv = n_aa2 * sizeof(complex double); // Now begin filling arr_mlist with the appropriate values index = 0; only_need_index = residue_to_compute * n_uts; r_grs_tuple = PyList_GET_ITEM(grs, residue_to_compute); // gr_diag, p, and p_inv are the eigenvalues, left, and right diagonalizing matrices of gr gr_diag = PyTuple_GET_ITEM(r_grs_tuple, 0); p = PyTuple_GET_ITEM(r_grs_tuple, 1); p_inv = PyTuple_GET_ITEM(r_grs_tuple, 2); // determine if these arrays are complex double or real doubles array_type = PyArray_TYPE(gr_diag); if (array_type == NPY_DOUBLE) { // array is of doubles, real not complex cp_inv_exp = (double *) malloc(sizeof_cp_inv); // allocate memory // Note that these next assignments assume that the arrays are C-style contiguous cp = PyArray_DATA(p); cp_inv = PyArray_DATA(p_inv); cgr_diag = PyArray_DATA(gr_diag); for (i_ut = 0; i_ut < n_uts; i_ut++) { // loop over ut values only_need_i = PyInt_AS_LONG(PyList_GET_ITEM(only_need, only_need_index)); // value of only_need only_need_index++; if (only_need_i == -1) { // we don't need to do anything for these entries in mlist index += n_aa2; } else { // we need to compute at least some entries in mlist ut = PyFloat_AS_DOUBLE(PyList_GET_ITEM(uts, i_ut)); // ut value for (irowcolumn = 0; irowcolumn < n_aa; irowcolumn++) { exp_ut = exp(ut * cgr_diag[irowcolumn]); for (y = irowcolumn * n_aa; y < (irowcolumn + 1) * n_aa; y++) { cp_inv_exp[y] = cp_inv[y] * exp_ut; } } if (only_need_i == -2) { // we need to compute all of these entries in mlist #ifdef USE_ACCELERATE_CBLAS // multiply the matrices using cblas_dgemm, and fill mlist with the results cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_aa, n_aa, n_aa, (double) 1.0, cp, n_aa, cp_inv_exp, n_aa, (double) 0.0, &arr_mlist[index], n_aa); for (index2 = index; index2 < index + n_aa2; index2++) { arr_mlist[index2] = fabs(arr_mlist[index2]); } index += n_aa2; #else // multiply the matrices in pure C code, and fill mlist with the results for (x = 0; x < n_aa2; x += n_aa) { for (y = 0; y < n_aa; y++) { mxy = 0.0; yindex = y; for (irowcolumn = x; irowcolumn < x + n_aa; irowcolumn++) { mxy += cp[irowcolumn] * cp_inv_exp[yindex]; yindex += n_aa; } arr_mlist[index++] = fabs(mxy); } } #endif } else { // we need to compute entries in mlist only for x = only_need_i only_need_i_n_aa = only_need_i * n_aa; index += only_need_i_n_aa; #ifdef USE_ACCELERATE_CBLAS // do the matrix vector multiplication using cblas, and put results in mlist cblas_dgemv(CblasRowMajor, CblasTrans, n_aa, n_aa, (double) 1.0, cp_inv_exp, n_aa, &cp[only_need_i_n_aa], 1, (double) 0.0, &arr_mlist[index], 1); for (index2 = index; index2 < index + n_aa2 - only_need_i_n_aa; index2++) { arr_mlist[index2] = fabs(arr_mlist[index2]); } index += n_aa2 - only_need_i_n_aa; #else // do the matrix vector multiplication in pure C code, and put results in mlist for (y = 0; y < n_aa; y++) { mxy = 0.0; yindex = y; for (irowcolumn = only_need_i_n_aa; irowcolumn < only_need_i_n_aa + n_aa; irowcolumn++) { mxy += cp[irowcolumn] * cp_inv_exp[yindex]; yindex += n_aa; } arr_mlist[index++] = fabs(mxy); } index += n_aa2 - only_need_i_n_aa - n_aa; #endif } } } free(cp_inv_exp); } else if (array_type == NPY_CDOUBLE) { // array is complex doubles complex_cp_inv_exp = (complex double *) malloc(complex_sizeof_cp_inv); // allocate memory complex_naa2_list = (complex double *) malloc(n_aa2 * sizeof(complex double)); // allocate memory complex_naa_list = (complex double *) malloc(n_aa * sizeof(complex double)); // allocate memory // Note that these next assignments assume that the arrays are C-style contiguous complex_cp = PyArray_DATA(p); complex_cp_inv = PyArray_DATA(p_inv); complex_cgr_diag = PyArray_DATA(gr_diag); for (i_ut = 0; i_ut < n_uts; i_ut++) { // loop over ut values only_need_i = PyInt_AS_LONG(PyList_GET_ITEM(only_need, only_need_index)); // value of only_need only_need_index++; if (only_need_i == -1) { // we don't need to do anything for these entries in mlist index += n_aa2; } else { // we need to compute at least some entries in mlist ut = PyFloat_AS_DOUBLE(PyList_GET_ITEM(uts, i_ut)); // ut value for (irowcolumn = 0; irowcolumn < n_aa; irowcolumn++) { complex_exp_ut = cexp(ut * complex_cgr_diag[irowcolumn]); for (y = irowcolumn * n_aa; y < (irowcolumn + 1) * n_aa; y++) { complex_cp_inv_exp[y] = complex_cp_inv[y] * complex_exp_ut; } } if (only_need_i == -2) { // we need to compute all of these entries in mlist #ifdef USE_ACCELERATE_CBLAS // multiply the matrices using cblas_zgemm, and fill mlist with the results cblas_zgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_aa, n_aa, n_aa, &complex_one, complex_cp, n_aa, complex_cp_inv_exp, n_aa, &complex_zero, complex_naa2_list, n_aa); for (index2 = 0; index2 < n_aa2; index2++) { arr_mlist[index + index2] = cabs(complex_naa2_list[index2]); } index += n_aa2; #else // multiply the matrices in pure C code, and fill mlist with the results for (x = 0; x < n_aa2; x += n_aa) { for (y = 0; y < n_aa; y++) { complex_mxy = (complex double) 0.0; yindex = y; for (irowcolumn = x; irowcolumn < x + n_aa; irowcolumn++) { complex_mxy += complex_cp[irowcolumn] * complex_cp_inv_exp[yindex]; yindex += n_aa; } arr_mlist[index++] = cabs(complex_mxy); } } #endif } else { // we need to compute entries in mlist only for x = only_need_i only_need_i_n_aa = only_need_i * n_aa; index += only_need_i_n_aa; #ifdef USE_ACCELERATE_CBLAS // do the matrix vector multiplication using cblas, and put results in mlist cblas_zgemv(CblasRowMajor, CblasTrans, n_aa, n_aa, &complex_one, complex_cp_inv_exp, n_aa, &complex_cp[only_need_i_n_aa], 1, &complex_zero, complex_naa_list, 1); for (index2 = 0; index2 < n_aa; index2++) { arr_mlist[index + index2] = cabs(complex_naa_list[index2]); } index += n_aa2 - only_need_i_n_aa; #else // do the matrix vector multiplication in pure C code, and put results in mlist for (y = 0; y < n_aa; y++) { complex_mxy = (complex double) 0.0; yindex = y; for (irowcolumn = only_need_i_n_aa; irowcolumn < only_need_i_n_aa + n_aa; irowcolumn++) { complex_mxy += complex_cp[irowcolumn] * complex_cp_inv_exp[yindex]; yindex += n_aa; } arr_mlist[index++] = cabs(complex_mxy); } index += n_aa2 - only_need_i_n_aa - n_aa; #endif } } } free(complex_cp_inv_exp); free(complex_naa2_list); free(complex_naa_list); } else { // array is of neither real nor complex doubles PyErr_SetString(PyExc_ValueError, "gr entries are neither double nor complex doubles."); return NULL; } return PyInt_FromLong((long) 1); }
LLBC_PacketHeaderParts *pyllbc_Service::BuildCLayerParts(PyObject *pyLayerParts) { // Python layer parts(dict type) convert rules describe: // python type c++ type // -------------------------- // int/long/bool --> sint64 // float4/8 --> float/double // str/bytearray --> LLBC_String if (!PyDict_Check(pyLayerParts)) { pyllbc_SetError("parts instance not dict type"); return NULL; } LLBC_PacketHeaderParts *cLayerParts = LLBC_New(LLBC_PacketHeaderParts); Py_ssize_t pos = 0; PyObject *key, *value; while (PyDict_Next(pyLayerParts, &pos, &key, &value)) // key & value are borrowed. { const int serialNo = static_cast<int>(PyInt_AsLong(key)); if (UNLIKELY(serialNo == -1 && PyErr_Occurred())) { pyllbc_TransferPyError("When fetch header part serial no"); LLBC_Delete(cLayerParts); return NULL; } // Value type check order: // int-> // str-> // float-> // long-> // bool-> // bytearray-> // other objects if (PyInt_CheckExact(value)) { const sint64 cValue = PyInt_AS_LONG(value); cLayerParts->SetPart<sint64>(serialNo, cValue); } else if (PyString_CheckExact(value)) { char *strBeg; Py_ssize_t strLen; if (UNLIKELY(PyString_AsStringAndSize(value, &strBeg, &strLen) == -1)) { pyllbc_TransferPyError("When fetch header part value"); LLBC_Delete(cLayerParts); return NULL; } cLayerParts->SetPart(serialNo, strBeg, strLen); } else if (PyFloat_CheckExact(value)) { const double cValue = PyFloat_AS_DOUBLE(value); cLayerParts->SetPart<double>(serialNo, cValue); } else if (PyLong_CheckExact(value)) { const sint64 cValue = PyLong_AsLongLong(value); cLayerParts->SetPart<sint64>(serialNo, cValue); } else if (PyBool_Check(value)) { const int pyBoolCheck = PyObject_IsTrue(value); if (UNLIKELY(pyBoolCheck == -1)) { pyllbc_TransferPyError("when fetch header part value"); LLBC_Delete(cLayerParts); return NULL; } cLayerParts->SetPart<uint8>(serialNo, pyBoolCheck); } else if (PyByteArray_CheckExact(value)) { char *bytesBeg = PyByteArray_AS_STRING(value); Py_ssize_t bytesLen = PyByteArray_GET_SIZE(value); cLayerParts->SetPart(serialNo, bytesBeg, bytesLen); } else // Other types, we simple get the object string representations. { LLBC_String strRepr = pyllbc_ObjUtil::GetObjStr(value); if (UNLIKELY(strRepr.empty() && PyErr_Occurred())) { LLBC_Delete(cLayerParts); return NULL; } cLayerParts->SetPart(serialNo, strRepr.data(), strRepr.size()); } } return cLayerParts; }
/*static*/ PyObject * MoleculeAttributes_SetBondSingleColor(PyObject *self, PyObject *args) { MoleculeAttributesObject *obj = (MoleculeAttributesObject *)self; int c[4]; if(!PyArg_ParseTuple(args, "iiii", &c[0], &c[1], &c[2], &c[3])) { c[3] = 255; if(!PyArg_ParseTuple(args, "iii", &c[0], &c[1], &c[2])) { double dr, dg, db, da; if(PyArg_ParseTuple(args, "dddd", &dr, &dg, &db, &da)) { c[0] = int(dr); c[1] = int(dg); c[2] = int(db); c[3] = int(da); } else if(PyArg_ParseTuple(args, "ddd", &dr, &dg, &db)) { c[0] = int(dr); c[1] = int(dg); c[2] = int(db); c[3] = 255; } else { PyObject *tuple = NULL; if(!PyArg_ParseTuple(args, "O", &tuple)) return NULL; if(!PyTuple_Check(tuple)) return NULL; // Make sure that the tuple is the right size. if(PyTuple_Size(tuple) < 3 || PyTuple_Size(tuple) > 4) return NULL; // Make sure that all elements in the tuple are ints. for(int i = 0; i < PyTuple_Size(tuple); ++i) { PyObject *item = PyTuple_GET_ITEM(tuple, i); if(PyInt_Check(item)) c[i] = int(PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, i))); else if(PyFloat_Check(item)) c[i] = int(PyFloat_AS_DOUBLE(PyTuple_GET_ITEM(tuple, i))); else return NULL; } } } PyErr_Clear(); } // Set the bondSingleColor in the object. ColorAttribute ca(c[0], c[1], c[2], c[3]); obj->data->SetBondSingleColor(ca); Py_INCREF(Py_None); return Py_None; }
static PyObject * MidiIn_getMessage(MidiIn *self, PyObject *args) { PyObject *timeout = NULL; PyObject *result = NULL; if(!PyArg_ParseTuple(args, "|O:getMessage", &timeout)) return NULL; long ms = -1; if(timeout) { if(PyFloat_CheckExact(timeout)) ms = (long) PyFloat_AS_DOUBLE(timeout); #if ! PK_PYTHON3 else if(PyInt_CheckExact(timeout)) ms = PyInt_AS_LONG(timeout); #endif else if(PyLong_CheckExact(timeout)) ms = PyLong_AsLong(timeout); else { PyErr_Format(RtMidiError, "timeout value must be a number, not %s", timeout->ob_type->tp_name); return NULL; } if(ms < 0) { PyErr_SetString(RtMidiError, "timeout value must be a positive number"); return NULL; } } #if PK_WINDOWS WaitForSingleObject(self->mutex); #else pthread_mutex_lock(&self->mutex); #endif if(ms > -1 && self->triggered == false) { PyThreadState *_save = PyEval_SaveThread(); #if PK_WINDOWS WaitForSingleObject(self->cond, ms < 0 ? INFINITE : ms); #else if(ms < 0) { pthread_cond_wait(&self->cond, &self->mutex); } else { struct timeval now; gettimeofday(&now, 0); struct timespec time; TIMEVAL_TO_TIMESPEC(&now, &time); unsigned long sec = ms / 1000; unsigned long nsec = (ms % 1000) * 1000000; time.tv_sec += sec; time.tv_nsec += nsec; while(time.tv_nsec >= 1000000000) { time.tv_sec++; time.tv_nsec -= 1000000000; } pthread_cond_timedwait(&self->cond, &self->mutex, &time); } #endif PyEval_RestoreThread(_save); } if(self->m_q->size() > 0) { result = (PyObject *) PyMidiMessage_new(); MidiMessage *inMidi = self->m_q->front(); (*((PyMidiMessage *)result)->m) = (*inMidi); self->m_q->pop(); self->triggered = false; delete inMidi; } #if PK_WINDOWS ReleaseMutex(self->mutex); #else pthread_mutex_unlock(&self->mutex); #endif if(result) return result; Py_RETURN_NONE; }
PyObject* _PyCode_ConstantKey(PyObject *op) { PyObject *key; /* Py_None and Py_Ellipsis are singleton */ if (op == Py_None || op == Py_Ellipsis || PyLong_CheckExact(op) || PyBool_Check(op) || PyBytes_CheckExact(op) || PyUnicode_CheckExact(op) /* code_richcompare() uses _PyCode_ConstantKey() internally */ || PyCode_Check(op)) { key = PyTuple_Pack(2, Py_TYPE(op), op); } else if (PyFloat_CheckExact(op)) { double d = PyFloat_AS_DOUBLE(op); /* all we need is to make the tuple different in either the 0.0 * or -0.0 case from all others, just to avoid the "coercion". */ if (d == 0.0 && copysign(1.0, d) < 0.0) key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None); else key = PyTuple_Pack(2, Py_TYPE(op), op); } else if (PyComplex_CheckExact(op)) { Py_complex z; int real_negzero, imag_negzero; /* For the complex case we must make complex(x, 0.) different from complex(x, -0.) and complex(0., y) different from complex(-0., y), for any x and y. All four complex zeros must be distinguished.*/ z = PyComplex_AsCComplex(op); real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; /* use True, False and None singleton as tags for the real and imag * sign, to make tuples different */ if (real_negzero && imag_negzero) { key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True); } else if (imag_negzero) { key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False); } else if (real_negzero) { key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None); } else { key = PyTuple_Pack(2, Py_TYPE(op), op); } } else if (PyTuple_CheckExact(op)) { Py_ssize_t i, len; PyObject *tuple; len = PyTuple_GET_SIZE(op); tuple = PyTuple_New(len); if (tuple == NULL) return NULL; for (i=0; i < len; i++) { PyObject *item, *item_key; item = PyTuple_GET_ITEM(op, i); item_key = _PyCode_ConstantKey(item); if (item_key == NULL) { Py_DECREF(tuple); return NULL; } PyTuple_SET_ITEM(tuple, i, item_key); } key = PyTuple_Pack(2, tuple, op); Py_DECREF(tuple); } else if (PyFrozenSet_CheckExact(op)) { Py_ssize_t pos = 0; PyObject *item; Py_hash_t hash; Py_ssize_t i, len; PyObject *tuple, *set; len = PySet_GET_SIZE(op); tuple = PyTuple_New(len); if (tuple == NULL) return NULL; i = 0; while (_PySet_NextEntry(op, &pos, &item, &hash)) { PyObject *item_key; item_key = _PyCode_ConstantKey(item); if (item_key == NULL) { Py_DECREF(tuple); return NULL; } assert(i < len); PyTuple_SET_ITEM(tuple, i, item_key); i++; } set = PyFrozenSet_New(tuple); Py_DECREF(tuple); if (set == NULL) return NULL; key = PyTuple_Pack(2, set, op); Py_DECREF(set); return key; } else { /* for other types, use the object identifier as a unique identifier * to ensure that they are seen as unequal. */ PyObject *obj_id = PyLong_FromVoidPtr(op); if (obj_id == NULL) return NULL; key = PyTuple_Pack(2, obj_id, op); Py_DECREF(obj_id); } return key; }
QVariant PythonScript::eval() { if (!isFunction) compiled = notCompiled; if (compiled != isCompiled && !compile(true)) return QVariant(); PyObject *pyret; beginStdoutRedirect(); if (PyCallable_Check(PyCode)) { PyObject *empty_tuple = PyTuple_New(0); pyret = PyObject_Call(PyCode, empty_tuple, localDict); Py_DECREF(empty_tuple); } else pyret = PyEval_EvalCode((PyCodeObject*)PyCode, env()->globalDict(), localDict); endStdoutRedirect(); if (!pyret) { if (PyErr_ExceptionMatches(PyExc_ValueError) || PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) { PyErr_Clear(); // silently ignore errors return QVariant(""); } else { emit_error(env()->errorMsg(), 0); return QVariant(); } } QVariant qret = QVariant(); /* None */ if (pyret == Py_None) qret = QVariant(""); /* numeric types */ else if (PyFloat_Check(pyret)) qret = QVariant(PyFloat_AS_DOUBLE(pyret)); else if (PyInt_Check(pyret)) qret = QVariant((qlonglong)PyInt_AS_LONG(pyret)); else if (PyLong_Check(pyret)) qret = QVariant((qlonglong)PyLong_AsLongLong(pyret)); else if (PyNumber_Check(pyret)) { PyObject *number = PyNumber_Float(pyret); if (number) { qret = QVariant(PyFloat_AS_DOUBLE(number)); Py_DECREF(number); } /* bool */ } else if (PyBool_Check(pyret)) qret = QVariant(pyret==Py_True, 0); // could handle advanced types (such as PyList->QValueList) here if needed /* fallback: try to convert to (unicode) string */ if(!qret.isValid()) { PyObject *pystring = PyObject_Unicode(pyret); if (pystring) { PyObject *asUTF8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(pystring), PyUnicode_GET_DATA_SIZE(pystring), 0); Py_DECREF(pystring); if (asUTF8) { qret = QVariant(QString::fromUtf8(PyString_AS_STRING(asUTF8))); Py_DECREF(asUTF8); } else if (pystring = PyObject_Str(pyret)) { qret = QVariant(QString(PyString_AS_STRING(pystring))); Py_DECREF(pystring); } } } Py_DECREF(pyret); if (PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_ValueError) || PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) { PyErr_Clear(); // silently ignore errors return QVariant(""); } else { emit_error(env()->errorMsg(), 0); return QVariant(); } } else return qret; }
static PyObject *phoebeSetPar(PyObject *self, PyObject *args) { int index, status; char *parname; PyObject *parval; PHOEBE_parameter *par; PyArg_ParseTuple(args, "sO|i", &parname, &parval, &index); par = phoebe_parameter_lookup(parname); switch (par->type) { case TYPE_INT: { #ifdef PY3K long val; if (!PyLong_Check(parval)) { printf("error: integer value expected for %s.\n", parname); return NULL; } val = PyLong_AsLong(parval); #else int val; if (!PyInt_Check(parval)) { printf("error: integer value expected for %s.\n", parname); return NULL; } val = PyInt_AS_LONG(parval); #endif status = phoebe_parameter_set_value(par, (int) val); break; } case TYPE_BOOL: { int val; #ifdef PY3K if (!PyLong_Check(parval)) { printf("error: boolean value expected for %s.\n", parname); return NULL; } val = PyLong_AsLong(parval); #else if (!PyInt_Check(parval)) { printf("error: boolean value expected for %s.\n", parname); return NULL; } val = PyInt_AS_LONG(parval); #endif status = phoebe_parameter_set_value(par, (int) val); break; } case TYPE_DOUBLE: { double val; if (!PyFloat_Check(parval)) { printf("error: float value expected for %s.\n", parname); return NULL; } val = PyFloat_AS_DOUBLE(parval); status = phoebe_parameter_set_value(par, val); break; } case TYPE_STRING: { char *val; #ifdef PY3K if (!PyUnicode_Check(parval)) { printf("error: string value expected for %s.\n", parname); return NULL; } val = PyUnicode_AsUTF8(parval); #else if (!PyString_Check(parval)) { printf("error: string value expected for %s.\n", parname); return NULL; } val = PyString_AS_STRING(parval); #endif status = phoebe_parameter_set_value(par, val); break; } case TYPE_INT_ARRAY: { int val; #ifdef PY3K if (!PyLong_Check(parval)) { printf("error: float value expected for %s.\n", parname); return NULL; } val = PyLong_AsLong(parval); #else if (!PyInt_Check(parval)) { printf("error: float value expected for %s.\n", parname); return NULL; } val = PyInt_AS_LONG(parval); #endif status = phoebe_parameter_set_value(par, index, (int) val); break; } case TYPE_BOOL_ARRAY: { int val; #ifdef PY3K if (!PyLong_Check(parval)) { printf("error: float value expected for %s.\n", parname); return NULL; } val = PyLong_AsLong(parval); #else if (!PyInt_Check(parval)) { printf("error: float value expected for %s.\n", parname); return NULL; } val = PyInt_AS_LONG(parval); #endif status = phoebe_parameter_set_value(par, index, (int) val); break; } case TYPE_DOUBLE_ARRAY: { double val; if (!PyFloat_Check(parval)) { printf("error: float value expected for %s.\n", parname); return NULL; } val = PyFloat_AS_DOUBLE(parval); status = phoebe_parameter_set_value(par, index, val); break; } case TYPE_STRING_ARRAY: { char *val; #ifdef PY3K if (!PyUnicode_Check(parval)) { printf("error: string value expected for %s.\n", parname); return NULL; } val = PyUnicode_AsUTF8(parval); #else if (!PyString_Check(parval)) { printf("error: string value expected for %s.\n", parname); return NULL; } val = PyString_AS_STRING(parval); #endif status = phoebe_parameter_set_value(par, index, val); break; } default: status = 0; printf("not yet implemented, sorry.\n"); break; } if (status != SUCCESS) { printf ("%s", phoebe_error (status)); return NULL; } return Py_BuildValue ("i", status); }
static void *PyFloatToDOUBLE(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen) { PyObject *obj = (PyObject *) _obj; *((double *) outValue) = PyFloat_AS_DOUBLE (obj); return NULL; }
// Convert a Python object to a QJSValue. int qpyqml_convertTo_QJSValue(PyObject *py, PyObject *transferObj, QJSValue **cpp, int *isErr) { if (PyObject_TypeCheck(py, sipTypeAsPyTypeObject(sipType_QJSValue_SpecialValue))) { *cpp = new QJSValue((QJSValue::SpecialValue)SIPLong_AsLong(py)); return sipGetState(transferObj); } if (PyBool_Check(py)) { *cpp = new QJSValue(py == Py_True); return sipGetState(transferObj); } #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(py)) { *cpp = new QJSValue((int)PyLong_AS_LONG(py)); return sipGetState(transferObj); } #else if (PyInt_Check(py)) { *cpp = new QJSValue((int)PyInt_AS_LONG(py)); return sipGetState(transferObj); } #endif if (PyFloat_Check(py)) { *cpp = new QJSValue((double)PyFloat_AS_DOUBLE(py)); return sipGetState(transferObj); } if (sipCanConvertToType(py, sipType_QString, 0)) { int state; QString *qs = reinterpret_cast<QString *>(sipConvertToType(py, sipType_QString, 0, 0, &state, isErr)); if (*isErr) { sipReleaseType(qs, sipType_QString, state); return 0; } *cpp = new QJSValue(*qs); sipReleaseType(qs, sipType_QString, state); return sipGetState(transferObj); } *cpp = reinterpret_cast<QJSValue *>(sipConvertToType(py, sipType_QJSValue, transferObj, SIP_NO_CONVERTORS, 0, isErr)); return 0; }
bool PyDict_To_MapNode(PyObject *obj, MapNode &mn) { if (!PyDict_Check(obj)) return false; Py_ssize_t pos = 0; PyObject *key = NULL; PyObject *value = NULL; while(PyDict_Next(obj, &pos, &key, &value)) { std::string mkey; if (PyString_Check(key)) mkey = PyString_AS_STRING(key); else { return false; } if (PyTuple_Check(value) || PyList_Check(value)) { PyObject *item = PySequence_GetItem(value, 0); if (PyFloat_Check(item)) { doubleVector mval; mval.push_back(PyFloat_AS_DOUBLE(item)); for (Py_ssize_t i = 1; i < PySequence_Size(value); ++i) { item = PySequence_GetItem(value, i); if (PyFloat_Check(item)) mval.push_back(PyFloat_AS_DOUBLE(item)); else if (PyInt_Check(item)) mval.push_back((double)PyInt_AS_LONG(item)); else { debug3 << "PyDict_To_MapNode: tuples/lists must " << "contain same type." << endl; return false; } } mn[mkey] = mval; } else if (PyInt_Check(item)) { int ni = 1, nd = 0, no = 0; for (Py_ssize_t i = 1; i < PySequence_Size(value); ++i) { item = PySequence_GetItem(value, i); if (PyFloat_Check(item)) nd++; else if (PyInt_Check(item)) ni++; else no++; } if (no != 0) { debug3 << "PyDict_To_MapNode: tuples/lists must " << "contain same type." << endl; return false; } else if (nd != 0) { // process as doubleVector doubleVector mval; for (Py_ssize_t i = 0; i < PySequence_Size(value); ++i) { item = PySequence_GetItem(value, i); if (PyFloat_Check(item)) mval.push_back(PyFloat_AS_DOUBLE(item)); else if (PyInt_Check(item)) mval.push_back((double)PyInt_AS_LONG(item)); } mn[mkey] = mval; } else { intVector mval; for (Py_ssize_t i = 0; i < PySequence_Size(value); ++i) { item = PySequence_GetItem(value, i); mval.push_back(PyInt_AS_LONG(item)); } mn[mkey] = mval; } } else if (PyString_Check(item)) { stringVector mval; mval.push_back(PyString_AS_STRING(item)); for (Py_ssize_t i = 1; i < PySequence_Size(value); ++i) { item = PySequence_GetItem(value, i); if (!PyString_Check(item)) { debug3 << "PyDict_To_MapNode: tuples/lists must " << "contain same type." << endl; return false; } mval.push_back(PyString_AS_STRING(item)); } mn[mkey] = mval; } else { debug3 << "PyDict_To_MapNode: type " << item->ob_type->tp_name << " not currently implemented." << endl; return false; } } else if (PyFloat_Check(value)) { mn[mkey] = (double) PyFloat_AS_DOUBLE(value); } else if (PyInt_Check(value)) { mn[mkey] = (int) PyInt_AS_LONG(value); } else if (PyString_Check(value)) { mn[mkey] = (std::string) PyString_AS_STRING(value); } else if (PyDict_Check(value)) { MapNode tmp; if (PyDict_To_MapNode(value, tmp)) mn[mkey] = tmp; } else { debug3 << "PyDict_To_MapNode: type " << value->ob_type->tp_name << " not currently implemented." << endl; return false; } } return true; }