text
stringlengths 1.18k
92.5k
| lang
stringclasses 39
values |
---|---|
cimport numpy as np
cimport cython
cimport set_ops as so
from libc.stdlib cimport malloc, free
from dealloc cimport dealloc_matrix_2
from dealloc cimport dealloc_matrix
from dealloc cimport dealloc_vector
from dealloc cimport dealloc_vec_int
from libc.stdlib cimport malloc, free, realloc
from libc.math cimport sqrt
ctypedef np.int32_t INT_t
ctypedef unsigned int unint
ctypedef double FLOAT
cpdef double bcubed_rec(object wordsAndClusters, object clusters_lengths,
object wordsAndClasses, object classes_lengths,
int numClusters, int numClasses)
cpdef double bcubed_prec(object wordsAndClusters, object clusters_lengths,
object wordsAndClasses, object classes_lengths,
int numClusters, int numClasses)
<|end_of_text|>cdef extern from "hello.h":
int hello()
cdef extern from "echo.h":
int echo(int)
cpdef int addone(int)<|end_of_text|>from khash cimport *
# prototypes for sharing
# cdef class StringHashTable:
# cdef kh_str_t *table
# cdef inline int check_type(self, object)
# cpdef get_item(self, object)
# cpdef set_item(self, object, Py_ssize_t)
# cdef class Int32HashTable:
# cdef kh_int32_t *table
# cdef inline int check_type(self, object)
# cpdef get_item(self, int32_t)
# cpdef set_item(self, int32_t, Py_ssize_t)
# cdef class Int64HashTable:
# cdef kh_int64_t *table
# cdef inline bint has_key(self, int64_t)
# cpdef get_item(self, int64_t)
# cpdef set_item(self, int64_t, Py_ssize_t)
# cdef class Float64HashTable:
# cdef kh_float64_t *table
# cpdef get_labels(self, ndarray, list, Py_ssize_t, int32_t)
# cdef class PyObjectHashTable:
# cdef kh_pymap_t *table
# cdef destroy(self)
# cpdef get_item(self, object)
# cpdef set_item(self, object, Py_ssize_t)
# cpdef get_labels(self, ndarray, list, Py_ssize_t, int32_t)
# cdef class Factorizer:
# cdef public PyObjectHashTable table
# cdef public uniques
# cdef public Py_ssize_t count
# cdef class Int64Factorizer:
# cdef public Int64HashTable table
# cdef public list uniques
# cdef public Py_ssize_t count
<|end_of_text|># cython: infer_types=True
cimport cython
from libc.math cimport exp, fabs, sqrt, fmin, fmax
import numpy as np
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef void scalar_square_add_constant(float[:, :] field, float[:] x, float[:] y, float[:] width, float[:] v) nogil:
cdef long minx, miny, maxx, maxy
cdef Py_ssize_t i, xx, yy
cdef float cx, cy, cv, cwidth
for i in range(x.shape[0]):
cx = x[i]
cy = y[i]
cv = v[i]
cwidth = width[i]
minx = (<long>clip(cx - cwidth, 0, field.shape[1] - 1))
maxx = (<long>clip(cx + cwidth, minx + 1, field.shape[1]))
miny = (<long>clip(cy - cwidth, 0, field.shape[0] - 1))
maxy = (<long>clip(cy + cwidth, miny + 1, field.shape[0]))
for xx in range(minx, maxx):
for yy in range(miny, maxy):
field[yy, xx] += cv
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
cpdef void cumulative_average(float[:, :] cuma, float[:, :] cumw, float[:] x, float[:] y, float[:] width, float[:] v, float[:] w) nogil:
cdef long minx, miny, maxx, maxy
cdef float cv, cw, cx, cy, cwidth
cdef Py_ssize_t i, xx, yy
for i in range(x.shape[0]):
cw = w[i]
if cw <= 0.0:
continue
cv = v[i]
cx = x[i]
cy = y[i]
cwidth = width[i]
minx = (<long>clip(cx - cwidth, 0, cuma.shape[1] - 1))
maxx = (<long>clip(cx + cwidth, minx + 1, cuma.shape[1]))
miny = (<long>clip(cy - cwidth, 0, cuma.shape[0] - 1))
maxy = (<long>clip(cy + cwidth, miny + 1, cuma.shape[0]))
for xx in range(minx, maxx):
for yy in range(miny, maxy):
cuma[yy, xx] = (cw * cv + cumw[yy, xx] * cuma[yy, xx]) / (cumw[yy, xx] + cw)
cumw[yy, xx] += cw
cdef inline float approx_exp(float x) nogil:
if x > 2.0 or x < -2.0:
return 0.0
x = 1.0 + x / 8.0
x *= x
x *= x
x *= x
return x
cdef inline float clip(float v, float minv, float maxv) nogil:
return fmax(minv, fmin(maxv, v))
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
cpdef void scalar_square_add_gauss(float[:, :] field, float[:] x, float[:] y, float[:] sigma, float[:] v, float truncate=2.0) nogil:
cdef Py_ssize_t i, xx, yy
cdef float vv, deltax2, deltay2
cdef float cv, cx, cy, csigma, csigma2
cdef long minx, miny, maxx, maxy
for i in range(x.shape[0]):
csigma = sigma[i]
csigma2 = csigma * csigma
cx = x[i]
cy = y[i]
cv = v[i]
minx = (<long>clip(cx - truncate * csigma, 0, field.shape[1] - 1))
maxx = (<long>clip(cx + truncate * csigma, minx + 1, field.shape[1]))
miny = (<long>clip(cy - truncate * csigma, 0, field.shape[0] - 1))
maxy = (<long>clip(cy + truncate * csigma, miny + 1, field.shape[0]))
for xx in range(minx, maxx):
deltax2 = (xx - cx)**2
for yy in range(miny, maxy):
deltay2 = (yy - cy)**2
vv = cv * approx_exp(-0.5 * (deltax2 + deltay2) / csigma2)
field[yy, xx] += vv
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
def weiszfeld_nd(x_np, y_np, float[:] weights=None, float epsilon=1e-8, Py_ssize_t max_steps=20):
"""Weighted Weiszfeld algorithm."""
if weights is None:
weights = np.ones(x_np.shape[0])
cdef float[:, :] x = x_np
cdef float[:] y = y_np
cdef float[:, :] weights_x = np.zeros_like(x)
for i in range(weights_x.shape[0]):
for j in range(weights_x.shape[1]):
weights_x[i, j] = weights[i] * x[i, j]
cdef float[:] prev_y = np.zeros_like(y)
cdef float[:] y_top = np.zeros_like(y)
cdef float y_bottom
denom_np = np.zeros_like(weights)
cdef float[:] denom = denom_np
for s in range(max_steps):
prev_y[:] = y
for i in range(denom.shape[0]):
denom[i] = sqrt((x[i][0] - prev_y[0])**2 + (x[i][1] - prev_y[1])**2) + epsilon
y_top[:] = 0.0
y_bottom = 0.0
for j in range(denom.shape[0]):
y_top[0] += weights_x[j, 0] / denom[j]
y_top[1] += weights_x[j, 1] / denom[j]
y_bottom += weights[j] / denom[j]
y[0] = y_top[0] / y_bottom
y[1] = y_top[1] / y_bottom
if fabs(y[0] - prev_y[0 | Cython |
]) + fabs(y[1] - prev_y[1]) < 1e-2:
return y_np, denom_np
return y_np, denom_np
@cython.boundscheck(False)
@cython.wraparound(False)
def paf_mask_center(float[:, :] paf_field, float x, float y, float sigma=1.0):
mask_np = np.zeros((paf_field.shape[1],), dtype=np.uint8)
cdef unsigned char[:] mask = mask_np
for i in range(mask.shape[0]):
mask[i] = (
paf_field[1, i] > x - sigma * paf_field[3, i] and
paf_field[1, i] < x + sigma * paf_field[3, i] and
paf_field[2, i] > y - sigma * paf_field[3, i] and
paf_field[2, i] < y + sigma * paf_field[3, i]
)
return mask_np!= 0
@cython.boundscheck(False)
@cython.wraparound(False)
def scalar_values(float[:, :] field, float[:] x, float[:] y, float default=-1):
values_np = np.full((x.shape[0],), default, dtype=np.float32)
cdef float[:] values = values_np
cdef float maxx = <float>field.shape[1] - 1, maxy = <float>field.shape[0] - 1
for i in range(values.shape[0]):
if x[i] < 0.0 or y[i] < 0.0 or x[i] > maxx or y[i] > maxy:
continue
values[i] = field[<Py_ssize_t>y[i], <Py_ssize_t>x[i]]
return values_np
@cython.boundscheck(False)
@cython.wraparound(False)
def scalar_value(float[:, :] field, float x, float y, float default=-1):
if x < 0.0 or y < 0.0 or x > field.shape[1] - 1 or y > field.shape[0] - 1:
return default
return field[<Py_ssize_t>y, <Py_ssize_t>x]
@cython.boundscheck(False)
@cython.wraparound(False)
def scalar_value_clipped(float[:, :] field, float x, float y):
x = clip(x, 0.0, field.shape[1] - 1)
y = clip(y, 0.0, field.shape[0] - 1)
return field[<Py_ssize_t>y, <Py_ssize_t>x]
@cython.boundscheck(False)
@cython.wraparound(False)
def scalar_nonzero(unsigned char[:, :] field, float x, float y, unsigned char default=0):
if x < 0.0 or y < 0.0 or x > field.shape[1] - 1 or y > field.shape[0] - 1:
return default
return field[<Py_ssize_t>y, <Py_ssize_t>x]
@cython.boundscheck(False)
@cython.wraparound(False)
def scalar_nonzero_clipped(unsigned char[:, :] field, float x, float y):
x = clip(x, 0.0, field.shape[1] - 1)
y = clip(y, 0.0, field.shape[0] - 1)
return field[<Py_ssize_t>y, <Py_ssize_t>x]
@cython.boundscheck(False)
@cython.wraparound(False)
def paf_center(float[:, :] paf_field, float x, float y, float sigma=1.0):
result_np = np.empty_like(paf_field)
cdef float[:, :] result = result_np
cdef unsigned int result_i = 0
cdef bint take
for i in range(paf_field.shape[1]):
take = (
paf_field[1, i] > x - sigma * paf_field[3, i] and
paf_field[1, i] < x + sigma * paf_field[3, i] and
paf_field[2, i] > y - sigma * paf_field[3, i] and
paf_field[2, i] < y + sigma * paf_field[3, i]
)
if not take:
continue
result[:, result_i] = paf_field[:, i]
result_i += 1
return result_np[:, :result_i]
<|end_of_text|>import numpy as np
cimport numpy as np
#from scipy.special import gammaln
ctypedef np.float64_t DTYPE_t
cdef extern from "quad_utils.h":
void _quad1d "_quad1d" (int N, double* mu, double* var, double* Y, int Ngh, double* gh_x, double* gh_w, double* F, double* dF_dm, double* dF_dv)
cdef extern from "quad_utils.h":
void _quad2d_stut "_quad2d_stut" (int N, double* muf, double* varf, double* mug, double* varg, double* Y, int Ngh, double v, double* gh_x, double* gh_w, double* F, double* dF_dmf, double* dF_dvf, double* dF_dmg, double* dF_dvg, double* dF_ddf)
cdef extern from "math.h":
double exp(double x)
cdef extern from "math.h":
double sqrt(double x)
def quad2d_stut(int N, np.ndarray[DTYPE_t, ndim=1] _muf,
np.ndarray[DTYPE_t, ndim=1] _varf,
np.ndarray[DTYPE_t, ndim=1] _mug,
np.ndarray[DTYPE_t, ndim=1] _varg,
np.ndarray[DTYPE_t, ndim=1] _Y,
int Ngh,
double df,
np.ndarray[DTYPE_t, ndim=1] _gh_x,
np.ndarray[DTYPE_t, ndim=1] _gh_w,
np.ndarray[DTYPE_t, ndim=1] _F,
np.ndarray[DTYPE_t, ndim=1] _dF_dmf,
np.ndarray[DTYPE_t, ndim=1] _dF_dvf,
np.ndarray[DTYPE_t, ndim=1] _dF_dmg,
np.ndarray[DTYPE_t, ndim=1] _dF_dvg,
np.ndarray[DTYPE_t, ndim=1] _dF_ddf
):
cdef double *muf = <double*> _muf.data
cdef double *varf = <double*> _varf.data
cdef double *mug = <double*> _mug.data
cdef double *varg = <double*> _varg.data
cdef double *Y = <double*> _Y.data
cdef double *gh_x = <double*> _gh_x.data
cdef double *gh_w = <double*> _gh_w.data
cdef double *F = <double*> _F.data
cdef double *dF_dmf = <double*> _dF_dmf.data
cdef double *dF_dvf = <double*> _dF_dvf.data
cdef double *dF_dmg = <double*> _dF_dmg.data
cdef double *dF_dvg = <double*> _dF_dvg.data
cdef double *dF_ddf = <double*> _dF_ddf.data
_quad2d_stut(N, muf, varf, mug, varg, Y, Ngh, df, gh_x, gh_w, F, dF_dmf, dF_dvf, dF_dmg, dF_dvg, dF_ddf)
def quad2d_beta(double[:, :] muf,
double[:, :] varf,
double[:, :] mug,
double[:, :] varg,
double[:, :] Y,
double[:] gh_x,
double[:] gh_w,
double[:, :] F,
double[:, :] dF_dmf,
double[:, :] dF_dvf,
double[:, :] dF_dmg,
double[:, :] dF_dvg,
):
cdef int N = Y.shape[0]
cdef int D = Y.shape[1]
cdef int Ngh = gh_x.shape[0]
cdef int n, i, j
for d in range(D):
for n in range(N):
stdfi = sqrt(2.0*varf[n, d])
stdgi = sqrt(2.0*varg[n, d])
mugi = mug[n, d]
mufi = muf[n, d]
Yi = Y[n, d]
for i in range(Ngh):
#Use c sqrt instead of numpy
gi = mugi + stdgi*gh_x[i]
e_gi = exp(gi)
for j in range(Ngh):
fj = mufi + stdfi*gh_x[j] #Get the location in f scale
e_fj = exp(fj)
#logpdf = -lgam(e_fj) -lgam(e_gi) + lg | Cython |
am(e_fj + e_gi)
raise NotImplementedError
logpdf = Gamma(Yi)
dlogpdf_df = polygamma(0, Yi)
d2logpdf_df2 = 0.0
dlogpdf_dg = 0.0
d2logpdf_dg2 = 0.0
F[n, d] += gh_w[i]*gh_w[j]*logpdf
dF_dmf[n, d] += gh_w[i]*gh_w[j]*dlogpdf_df
dF_dvf[n, d] += gh_w[i]*gh_w[j]*d2logpdf_df2
dF_dmg[n, d] += gh_w[i]*gh_w[j]*dlogpdf_dg
dF_dvg[n, d] += gh_w[i]*gh_w[j]*d2logpdf_dg2
return F, dF_dmf, dF_dvf, dF_dmg, dF_dvg
<|end_of_text|>from godot_headers.gdnative_api cimport GODOT_PROPERTY_HINT_NONE, GODOT_PROPERTY_USAGE_DEFAULT
from.defs cimport *
cdef class SignalArgument:
def __init__(self, str name, godot_property_hint hint=GODOT_PROPERTY_HINT_NONE, str hint_string='',
godot_property_usage_flags usage=GODOT_PROPERTY_USAGE_DEFAULT, object default_value=None):
self.name = name
self.hint = hint
self.hint_string = hint_string
self.usage = usage
self.default_value = default_value
def as_dict(self):
return {self.name: self.type}
cdef class SignalArgumentNil(SignalArgument):
def __cinit__(self, str name):
self.name = name
self.type = <godot_int>VARIANT_NIL
cdef class SignalArgumentBool(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_BOOL
cdef class SignalArgumentInt(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_INT
cdef class SignalArgumentReal(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_REAL
cdef class SignalArgumentString(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_STRING
cdef class SignalArgumentVector2(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_VECTOR2
cdef class SignalArgumentRect2(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_RECT3
cdef class SignalArgumentVector3(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_VECTOR3
cdef class SignalArgumentTransform2D(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_TRANSFORM2D
cdef class SignalArgumentPlane(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_PLANE
cdef class SignalArgumentQuat(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_QUAT
cdef class SignalArgumentRect3(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_RECT3
cdef class SignalArgumentBasis(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_BASIS
cdef class SignalArgumentTransform(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_TRANSFORM
cdef class SignalArgumentColor(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_COLOR
cdef class SignalArgumentNodePath(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_NODE_PATH
cdef class SignalArgumentRID(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT__RID
cdef class SignalArgumentObject(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_OBJECT
def __init__(self, str name, godot_property_hint hint=GODOT_PROPERTY_HINT_NONE, str hint_string='',
godot_property_usage_flags usage=GODOT_PROPERTY_USAGE_DEFAULT, object default_value=-1):
self.name = name
self.hint = hint
self.hint_string = hint_string
self.usage = usage
self.default_value = default_value
cdef class SignalArgumentDictionary(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_DICTIONARY
cdef class SignalArgumentArray(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_ARRAY
cdef class SignalArgumentPoolByteArray(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_POOL_BYTE_ARRAY
cdef class SignalArgumentPoolIntArray(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_POOL_INT_ARRAY
cdef class SignalArgumentPoolRealArray(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_POOL_REAL_ARRAY
cdef class SignalArgumentPoolStringArray(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_POOL_STRING_ARRAY
cdef class SignalArgumentPoolVector2Array(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_POOL_VECTOR2_ARRAY
cdef class SignalArgumentPoolVector3Array(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_POOL_VECTOR3_ARRAY
cdef class SignalArgumentPoolColorArray(SignalArgument):
def __cinit__(self, name):
self.name = name
self.type = <godot_int>VARIANT_POOL_COLOR_ARRAY
<|end_of_text|>cimport openmp
from cython.parallel import prange
import numpy as np
from scipy.linalg.cython_blas cimport dgemm
from threadpoolctl import threadpool_info
def check_nested_prange_blas(double[:, ::1] A, double[:, ::1] B, int nthreads):
"""Run multithreaded BLAS calls within OpenMP parallel loop"""
cdef:
int m = A.shape[0]
int n = B.shape[0]
int k = A.shape[1]
double[:, ::1] C = np.empty((m, n))
int n_chunks = 100
int chunk_size = A.shape[0] // n_chunks
char* trans = 't'
char* no_trans = 'n'
double alpha = 1.0
double beta = 0.0
int i
int prange_num_threads
threadpool_infos = None
for i in prange(n_chunks, num_threads=nthreads, nogil=True):
dgemm(trans, no_trans, &n, &chunk_size, &k,
&alpha, &B[0, 0], &k, &A[i * chunk_size, 0], &k,
&beta, &C[i * chunk_size, 0], &n)
prange_num_threads = openmp.omp_get_num_threads()
if i == 0:
with gil:
threadpool_infos = threadpool_info()
return np.asarray(C), prange_num_threads, threadpool_infos
<|end_of_text|># Copyright (c) 2019, NVIDIA CORPORATION.
# cython: profile=False
# distutils: language = c++
# cython: embedsignature = True
# cython: language_level = 3
from cudf.bindings.cudf_cpp cimport *
from cudf.bindings.cudf_cpp import *
from cudf.bindings.unaryops cimport *
from libc.stdlib cimport free
from librmm_cffi import librmm as rmm
_MATH_OP = {
'sin' : GDF_SIN,
'cos' : GDF_COS,
'tan' : GDF_TAN,
'asin' : GDF_ARCSIN,
'acos' : GDF_ARCCOS,
'atan' : GDF_ARCTAN,
'exp' : GDF_EXP,
'log' : GDF_LOG,
'sqrt' : GDF_SQRT,
| Cython |
'ceil' : GDF_CEIL,
'floor' : GDF_FLOOR,
'abs' : GDF_ABS,
'not' : GDF_BIT_INVERT,
}
def apply_math_op(incol, outcol, op):
"""
Call Unary math ops.
"""
check_gdf_compatibility(incol)
check_gdf_compatibility(outcol)
cdef gdf_column* c_incol = column_view_from_column(incol)
cdef gdf_column* c_outcol = column_view_from_column(outcol)
cdef gdf_error result
cdef gdf_unary_math_op c_op = _MATH_OP[op]
with nogil:
result = gdf_unary_math(
<gdf_column*>c_incol,
<gdf_column*>c_outcol,
c_op)
free(c_incol)
free(c_outcol)
check_gdf_error(result)
def apply_dt_extract_op(incol, outcol, op):
"""
Call a datetime extraction op
"""
check_gdf_compatibility(incol)
check_gdf_compatibility(outcol)
cdef gdf_column* c_incol = column_view_from_column(incol)
cdef gdf_column* c_outcol = column_view_from_column(outcol)
cdef gdf_error result = GDF_CUDA_ERROR
with nogil:
if op == 'year':
result = gdf_extract_datetime_year(
<gdf_column*>c_incol,
<gdf_column*>c_outcol
)
elif op =='month':
result = gdf_extract_datetime_month(
<gdf_column*>c_incol,
<gdf_column*>c_outcol
)
elif op == 'day':
result = gdf_extract_datetime_day(
<gdf_column*>c_incol,
<gdf_column*>c_outcol
)
elif op == 'hour':
result = gdf_extract_datetime_hour(
<gdf_column*>c_incol,
<gdf_column*>c_outcol
)
elif op =='minute':
result = gdf_extract_datetime_minute(
<gdf_column*>c_incol,
<gdf_column*>c_outcol
)
elif op =='second':
result = gdf_extract_datetime_second(
<gdf_column*>c_incol,
<gdf_column*>c_outcol
)
free(c_incol)
free(c_outcol)
check_gdf_error(result)
<|end_of_text|># -*- coding: utf-8 -*-
"""
Cython linker with C solver
"""
# Author: Remi Flamary <[email protected]>
#
# License: MIT License
import numpy as np
cimport numpy as np
from..utils import dist
cimport cython
cimport libc.math as math
from libc.stdint cimport uint64_t
import warnings
cdef extern from "EMD.h":
int EMD_wrap(int n1,int n2, double *X, double *Y,double *D, double *G, double* alpha, double* beta, double *cost, uint64_t maxIter) nogil
int EMD_wrap_omp(int n1,int n2, double *X, double *Y,double *D, double *G, double* alpha, double* beta, double *cost, uint64_t maxIter, int numThreads) nogil
cdef enum ProblemType: INFEASIBLE, OPTIMAL, UNBOUNDED, MAX_ITER_REACHED
def check_result(result_code):
if result_code == OPTIMAL:
return None
if result_code == INFEASIBLE:
message = "Problem infeasible. Check that a and b are in the simplex"
elif result_code == UNBOUNDED:
message = "Problem unbounded"
elif result_code == MAX_ITER_REACHED:
message = "numItermax reached before optimality. Try to increase numItermax."
warnings.warn(message)
return message
@cython.boundscheck(False)
@cython.wraparound(False)
def emd_c(np.ndarray[double, ndim=1, mode="c"] a, np.ndarray[double, ndim=1, mode="c"] b, np.ndarray[double, ndim=2, mode="c"] M, uint64_t max_iter, int numThreads):
"""
Solves the Earth Movers distance problem and returns the optimal transport matrix
gamm=emd(a,b,M)
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the metric cost matrix
- a and b are the sample weights
.. warning::
Note that the M matrix needs to be a C-order :py.cls:`numpy.array`
.. warning::
The C++ solver discards all samples in the distributions with
zeros weights. This means that while the primal variable (transport
matrix) is exact, the solver only returns feasible dual potentials
on the samples with weights different from zero.
Parameters
----------
a : (ns,) numpy.ndarray, float64
source histogram
b : (nt,) numpy.ndarray, float64
target histogram
M : (ns,nt) numpy.ndarray, float64
loss matrix
max_iter : uint64_t
The maximum number of iterations before stopping the optimization
algorithm if it has not converged.
Returns
-------
gamma: (ns x nt) numpy.ndarray
Optimal transportation matrix for the given parameters
"""
cdef int n1= M.shape[0]
cdef int n2= M.shape[1]
cdef int nmax=n1+n2-1
cdef int result_code = 0
cdef int nG=0
cdef double cost=0
cdef np.ndarray[double, ndim=1, mode="c"] alpha=np.zeros(n1)
cdef np.ndarray[double, ndim=1, mode="c"] beta=np.zeros(n2)
cdef np.ndarray[double, ndim=2, mode="c"] G=np.zeros([0, 0])
cdef np.ndarray[double, ndim=1, mode="c"] Gv=np.zeros(0)
if not len(a):
a=np.ones((n1,))/n1
if not len(b):
b=np.ones((n2,))/n2
# init OT matrix
G=np.zeros([n1, n2])
# calling the function
with nogil:
if numThreads == 1:
result_code = EMD_wrap(n1, n2, <double*> a.data, <double*> b.data, <double*> M.data, <double*> G.data, <double*> alpha.data, <double*> beta.data, <double*> &cost, max_iter)
else:
result_code = EMD_wrap_omp(n1, n2, <double*> a.data, <double*> b.data, <double*> M.data, <double*> G.data, <double*> alpha.data, <double*> beta.data, <double*> &cost, max_iter, numThreads)
return G, cost, alpha, beta, result_code
@cython.boundscheck(False)
@cython.wraparound(False)
def emd_1d_sorted(np.ndarray[double, ndim=1, mode="c"] u_weights,
np.ndarray[double, ndim=1, mode="c"] v_weights,
np.ndarray[double, ndim=1, mode="c"] u,
np.ndarray[double, ndim=1, mode="c"] v,
str metric='sqeuclidean',
double p=1.):
r"""
Solves the Earth Movers distance problem between sorted 1d measures and
returns the OT matrix and the associated cost
Parameters
----------
u_weights : (ns,) ndarray, float64
Source histogram
v_weights : (nt,) ndarray, float64
Target histogram
u : (ns,) ndarray, float64
Source dirac locations (on the real line)
v : (nt,) ndarray, float64
Target dirac locations (on the real line)
metric: str, optional (default='sqeuclidean')
Metric to be used. Only strings listed in :func:`ot.dist` are accepted.
Due to implementation details, this function runs faster when
`'sqeuclidean'`, `'minkowski'`, `'cityblock'`, or `'euclidean'` metrics
are used.
p: float, optional (default=1.0)
The p-norm to apply for if metric='minkowski'
Returns
-------
gamma: (n, ) ndarray, float64
Values in the Optimal transportation matrix
indices: (n, 2) ndarray, int64
Indices of the values stored in gamma for the Optimal transportation
matrix
cost
cost associated to the optimal transportation
"""
cdef double cost = 0.
cdef Py_ssize_t n = u_weights.shape[0]
cdef Py_ssize_t m = v_weights.shape[0]
cdef Py_ssize_t i = 0
| Cython |
cdef double w_i = u_weights[0]
cdef Py_ssize_t j = 0
cdef double w_j = v_weights[0]
cdef double m_ij = 0.
cdef np.ndarray[double, ndim=1, mode="c"] G = np.zeros((n + m - 1, ),
dtype=np.float64)
cdef np.ndarray[long long, ndim=2, mode="c"] indices = np.zeros((n + m - 1, 2),
dtype=np.int64)
cdef Py_ssize_t cur_idx = 0
while True:
if metric =='sqeuclidean':
m_ij = (u[i] - v[j]) * (u[i] - v[j])
elif metric == 'cityblock' or metric == 'euclidean':
m_ij = math.fabs(u[i] - v[j])
elif metric =='minkowski':
m_ij = math.pow(math.fabs(u[i] - v[j]), p)
else:
m_ij = dist(u[i].reshape((1, 1)), v[j].reshape((1, 1)),
metric=metric)[0, 0]
if w_i < w_j or j == m - 1:
cost += m_ij * w_i
G[cur_idx] = w_i
indices[cur_idx, 0] = i
indices[cur_idx, 1] = j
i += 1
if i == n:
break
w_j -= w_i
w_i = u_weights[i]
else:
cost += m_ij * w_j
G[cur_idx] = w_j
indices[cur_idx, 0] = i
indices[cur_idx, 1] = j
j += 1
if j == m:
break
w_i -= w_j
w_j = v_weights[j]
cur_idx += 1
cur_idx += 1
return G[:cur_idx], indices[:cur_idx], cost
<|end_of_text|>cpdef int recip(int n)
<|end_of_text|>from _shared cimport SharedArray, SharedItem
cdef extern from "lb.h":
enum: DQ_d
enum: DQ_q
cdef cppclass LBParams:
double cs2
double w[DQ_q]
double xi[DQ_q][DQ_d]
int ci[DQ_q][DQ_d]
double Q[DQ_q][DQ_d][DQ_d]
int complement[DQ_q]
double norms[DQ_q]
double mm[DQ_q][DQ_q]
double mmi[DQ_q][DQ_q]
double tau_s
double tau_b
cdef cppclass LatticeAddressing:
int size[DQ_d]
int strides[DQ_d]
int n
# cdef cppclass LDView:
# double* rho
# double* u
# double* force
# double* fOld
# double* fNew
cdef cppclass LatticeData:
SharedArray[double] rho
SharedArray[double] u
SharedArray[double] force
SharedArray[double] fOld
SharedArray[double] fNew
cdef cppclass Lattice:
Lattice(int, int, int, double, double)
void Step()
void CalcHydro()
void InitFromHydro()
void ZeroForce()
LatticeData* data
SharedItem[LBParams] params
SharedItem[LatticeAddressing] addr
int time_step
<|end_of_text|># cython: language_level=3, boundscheck=False, wraparound=False
import cython
cimport numpy as np
ctypedef fused T_INPUT:
np.uint16_t
np.uint8_t
ctypedef np.uint8_t T_OUTPUT
cdef int index_4d(int dim, int r, int g, int b, int c):
return c + 3 * (b + dim * (g + dim * r))
@cython.cdivision(True)
cpdef void lut_apply(T_INPUT[::1] pixels,
T_OUTPUT[:, :, :, ::1] lut, float binsize,
T_OUTPUT[::1] output) nogil:
cdef:
int pxcount = pixels.shape[0] // 3
int px, plane
T_INPUT r, g, b
float rf, gf, bf
int r_id, g_id, b_id
float r_d, g_d, b_d
T_OUTPUT[:] lutid000, lutid100, lutid010, lutid110, lutid001, lutid101, lutid011, lutid111
float w000, w100, w010, w110, w001, w101, w011, w111
double tmp
for px in range(pxcount):
# get pixels in lut-float
rf = pixels[3 * px] / binsize
gf = pixels[3 * px + 1] / binsize
bf = pixels[3 * px + 2] / binsize
# integer bin
r_id = int(rf)
g_id = int(gf)
b_id = int(bf)
# fraction to neighbor
r_d = rf - r_id
g_d = gf - g_id
b_d = bf - b_id
# trilinear interpolation
for plane in range(3):
tmp = 0
tmp += (1 - r_d) * (1 - g_d) * (1 - b_d) * lut[r_id, g_id, b_id, plane]
tmp += r_d * (1 - g_d) * (1 - b_d) * lut[r_id + 1, g_id, b_id, plane]
tmp += (1 - r_d) * g_d * (1 - b_d) * lut[r_id, g_id + 1, b_id, plane]
tmp += r_d * g_d * (1 - b_d) * lut[r_id + 1, g_id + 1, b_id, plane]
tmp += (1 - r_d) * (1 - g_d) * b_d * lut[r_id, g_id, b_id + 1, plane]
tmp += r_d * (1 - g_d) * b_d * lut[r_id + 1, g_id, b_id + 1, plane]
tmp += (1 - r_d) * g_d * b_d * lut[r_id, g_id + 1, b_id + 1, plane]
tmp += r_d * g_d * b_d * lut[r_id + 1, g_id + 1, b_id + 1, plane]
output[3 * px + plane] = int(tmp)
<|end_of_text|>from mpi4py import MPI
from data_handler import *
def scrub(configs):
logger = get_logger()
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
num_process = comm.Get_size()
data_file = configs['data_file']
noise_file = configs['noise_file']
size_notation = configs['size_notation']
verbose = configs['verbose']
ticks_per_iteration = configs['ticks_per_iteration']
memory_per_iteration = configs['memory_per_iteration']
ret_threshold = configs['ret_threshold']
time_drift_threshold = configs['time_drift_threshold']
size_mult = configs['size_mult']
size_per_process = int(float(memory_per_iteration)/num_process)
buffer_per_process = bytearray(size_per_process)
if rank == 0:
logger.info('Configs|memoryPerIteration=%i M|ticksPeriteration=%i|sizeNotation=%s|inputFile=%s|verbose=%i'
%(memory_per_iteration>>size_mult, ticks_per_iteration, size_notation, data_file, verbose))
if verbose:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
comm.Barrier()
file_ = MPI.File.Open(comm, data_file, MPI.MODE_RDONLY)
noise_file = MPI.File.Open(comm, noise_file, MPI.MODE_WRONLY|MPI.MODE_CREATE)
size = file_.Get_size()
load_iterations = int(float(size) / memory_per_iteration)
if rank == 0:
logger.info('Initializing|fileSize=%i %s|totalLoadIterations=%i|numberOfProcesses=%i|bufferSize=%i %s'
%(size>>size_mult, size_notation, load_iterations, num_process, len(buffer_per_process)>>size_mult, size_notation))
total_time = 0
load_file_time = 0
process_file_time = 0
write_file_time = 0
bad_data_records = ''
total_start_time = MPI.Wtime()
for i in range(load_iterations):
file_offset = i * memory_per_iteration
offset_per_process = rank * size_per_process + file_offset
load_file_start_time = MPI.Wtime()
raw_data = read_data(file_, offset_per_process, buffer_per_process)
data = format_data(raw_data)
load_file_time += MPI.Wtime() - load_file_start_time
if rank == 0:
| Cython |
logger.info('Processing file|iteration=%i|totalIterations=%i|numLines=%i' % (i, load_iterations, len(data)))
process_file_start_time = MPI.Wtime()
bad_data_records += scrub_data(rank, data, ticks_per_iteration, ret_threshold)
process_file_time += MPI.Wtime() - process_file_start_time
write_file_start_time = MPI.Wtime()
if rank == 0:
logger.info("Writing data start")
write_data(noise_file, bad_data_records)
if rank == 0:
logger.info("Writing data done")
total_time += MPI.Wtime() - total_start_time
write_file_time += MPI.Wtime() - write_file_start_time
total_time = np.array([total_time])
load_file_time = np.array([load_file_time])
process_file_time = np.array([process_file_time])
write_file_time = np.array([write_file_time])
num_bad_ticks = np.array([float(len(bad_data_records.split('\n')))])
max_execution_time = np.zeros(1)
min_execution_time = np.zeros(1)
max_write_file_time = np.zeros(1)
min_write_file_time = np.zeros(1)
max_process_file_time = np.zeros(1)
min_process_file_time = np.zeros(1)
max_load_file_time = np.zeros(1)
min_load_file_time = np.zeros(1)
sum_num_bad_ticks = np.zeros(1)
comm.Barrier()
file_.Close()
noise_file.Close()
comm.Reduce([total_time, MPI.DOUBLE], [max_execution_time, MPI.DOUBLE], op=MPI.MAX, root=0)
comm.Reduce([total_time, MPI.DOUBLE], [min_execution_time, MPI.DOUBLE], op=MPI.MIN, root=0)
comm.Reduce([process_file_time, MPI.DOUBLE], [max_process_file_time, MPI.DOUBLE], op=MPI.MAX, root=0)
comm.Reduce([process_file_time, MPI.DOUBLE], [min_process_file_time, MPI.DOUBLE], op=MPI.MIN, root=0)
comm.Reduce([load_file_time, MPI.DOUBLE], [max_load_file_time, MPI.DOUBLE], op=MPI.MAX, root=0)
comm.Reduce([load_file_time, MPI.DOUBLE], [min_load_file_time, MPI.DOUBLE], op=MPI.MIN, root=0)
comm.Reduce([write_file_time, MPI.DOUBLE], [max_write_file_time, MPI.DOUBLE], op=MPI.MAX, root=0)
comm.Reduce([write_file_time, MPI.DOUBLE], [min_write_file_time, MPI.DOUBLE], op=MPI.MIN, root=0)
comm.Reduce([num_bad_ticks, MPI.DOUBLE], [sum_num_bad_ticks, MPI.DOUBLE], op=MPI.SUM, root=0)
if rank == 0:
logger.info("Timer: total max - %f, min - %f" % (max_execution_time, min_execution_time))
logger.info("Timer: load file max - %f, min - %f" % (max_load_file_time, min_load_file_time))
logger.info("Timer: process file max - %f, min - %f" % (max_process_file_time, min_process_file_time))
logger.info("Timer: write file max - %f, min - %f" % (max_write_file_time, min_write_file_time))
logger.info("Counter: bad ticks sum - %i" % (sum_num_bad_ticks))
<|end_of_text|># --------------------------------------------------------------------
cdef extern from * nogil:
ctypedef enum PetscDMPlexReorderDefaultFlag "DMPlexReorderDefaultFlag":
DMPLEX_REORDER_DEFAULT_NOTSET
DMPLEX_REORDER_DEFAULT_FALSE
DMPLEX_REORDER_DEFAULT_TRUE
ctypedef const char* PetscDMPlexTransformType "DMPlexTransformType"
PetscDMPlexTransformType DMPLEXREFINEREGULAR
PetscDMPlexTransformType DMPLEXREFINEALFELD
PetscDMPlexTransformType DMPLEXREFINEPOWELLSABIN
PetscDMPlexTransformType DMPLEXREFINEBOUNDARYLAYER
PetscDMPlexTransformType DMPLEXREFINESBR
PetscDMPlexTransformType DMPLEXREFINETOBOX
PetscDMPlexTransformType DMPLEXREFINETOSIMPLEX
PetscDMPlexTransformType DMPLEXREFINE1D
PetscDMPlexTransformType DMPLEXEXTRUDE
PetscDMPlexTransformType DMPLEXTRANSFORMFILTER
PetscErrorCode DMPlexCreate(MPI_Comm,PetscDM*)
PetscErrorCode DMPlexCreateCohesiveSubmesh(PetscDM,PetscBool,const char[],PetscInt,PetscDM*)
PetscErrorCode DMPlexCreateFromCellListPetsc(MPI_Comm,PetscInt,PetscInt,PetscInt,PetscInt,PetscBool,PetscInt[],PetscInt,PetscReal[],PetscDM*)
#int DMPlexCreateFromDAG(PetscDM,PetscInt,const PetscInt[],const PetscInt[],const PetscInt[],const PetscInt[],const PetscScalar[])
PetscErrorCode DMPlexGetChart(PetscDM,PetscInt*,PetscInt*)
PetscErrorCode DMPlexSetChart(PetscDM,PetscInt,PetscInt)
PetscErrorCode DMPlexGetConeSize(PetscDM,PetscInt,PetscInt*)
PetscErrorCode DMPlexSetConeSize(PetscDM,PetscInt,PetscInt)
PetscErrorCode DMPlexGetCone(PetscDM,PetscInt,const PetscInt*[])
PetscErrorCode DMPlexSetCone(PetscDM,PetscInt,const PetscInt[])
PetscErrorCode DMPlexInsertCone(PetscDM,PetscInt,PetscInt,PetscInt)
PetscErrorCode DMPlexInsertConeOrientation(PetscDM,PetscInt,PetscInt,PetscInt)
PetscErrorCode DMPlexGetConeOrientation(PetscDM,PetscInt,const PetscInt*[])
PetscErrorCode DMPlexSetConeOrientation(PetscDM,PetscInt,const PetscInt[])
PetscErrorCode DMPlexSetCellType(PetscDM,PetscInt,PetscDMPolytopeType)
PetscErrorCode DMPlexGetCellType(PetscDM,PetscInt,PetscDMPolytopeType*)
PetscErrorCode DMPlexGetCellTypeLabel(PetscDM,PetscDMLabel*)
PetscErrorCode DMPlexGetSupportSize(PetscDM,PetscInt,PetscInt*)
PetscErrorCode DMPlexSetSupportSize(PetscDM,PetscInt,PetscInt)
PetscErrorCode DMPlexGetSupport(PetscDM,PetscInt,const PetscInt*[])
PetscErrorCode DMPlexSetSupport(PetscDM,PetscInt,const PetscInt[])
#int DMPlexInsertSupport(PetscDM,PetscInt,PetscInt,PetscInt)
#int DMPlexGetConeSection(PetscDM,PetscSection*)
#int DMPlexGetSupportSection(PetscDM,PetscSection*)
#int DMPlexGetCones(PetscDM,PetscInt*[])
#int DMPlexGetConeOrientations(PetscDM,PetscInt*[])
PetscErrorCode DMPlexGetMaxSizes(PetscDM,PetscInt*,PetscInt*)
PetscErrorCode DMPlexSymmetrize(PetscDM)
PetscErrorCode DMPlexStratify(PetscDM)
#int DMPlexEqual(PetscDM,PetscDM,PetscBool*)
PetscErrorCode DMPlexOrient(PetscDM)
PetscErrorCode DMPlexInterpolate(PetscDM,PetscDM*)
PetscErrorCode DMPlexUninterpolate(PetscDM,PetscDM*)
#int DMPlexLoad(PetscViewer,PetscDM)
#int DMPlexSetPreallocationCenterDimension(PetscDM,PetscInt)
#int DMPlexGetPreallocationCenterDimension(PetscDM,PetscInt*)
#int DMPlexPreallocateOperator(PetscDM,PetscInt,PetscSection,PetscSection,PetscInt[],PetscInt[],PetscInt[],PetscInt[],Mat,PetscBool)
PetscErrorCode DMPlexGetPointLocal(PetscDM,PetscInt,PetscInt*,PetscInt*)
#int DMPlexPointLocalRef(PetscDM,PetscInt,PetscScalar*,void*)
#int DMPlexPointLocalRead(PetscDM,PetscInt,const PetscScalar*,const void*)
PetscErrorCode DMPlexGetPointGlobal(PetscDM,PetscInt,PetscInt*,PetscInt*)
#int DMPlexPointGlobalRef(PetscDM,PetscInt,PetscScalar*,void*)
#int DMPlexPointGlobalRead(PetscDM,PetscInt,const PetscScalar*,const void*)
PetscErrorCode DMPlexGetPointLocalField(PetscDM,PetscInt,PetscInt,P | Cython |
etscInt*,PetscInt*)
PetscErrorCode DMPlexGetPointGlobalField(PetscDM,PetscInt,PetscInt,PetscInt*,PetscInt*)
PetscErrorCode DMPlexCreateClosureIndex(PetscDM,PetscSection)
#int PetscSectionCreateGlobalSectionLabel(PetscSection,PetscSF,PetscBool,PetscDMLabel,PetscInt,PetscSection*)
PetscErrorCode DMPlexGetCellNumbering(PetscDM,PetscIS*)
PetscErrorCode DMPlexGetVertexNumbering(PetscDM,PetscIS*)
PetscErrorCode DMPlexCreatePointNumbering(PetscDM,PetscIS*)
PetscErrorCode DMPlexGetDepth(PetscDM,PetscInt*)
#int DMPlexGetDepthLabel(PetscDM,PetscDMLabel*)
PetscErrorCode DMPlexGetDepthStratum(PetscDM,PetscInt,PetscInt*,PetscInt*)
PetscErrorCode DMPlexGetHeightStratum(PetscDM,PetscInt,PetscInt*,PetscInt*)
PetscErrorCode DMPlexGetPointDepth(PetscDM,PetscInt,PetscInt*)
PetscErrorCode DMPlexGetPointHeight(PetscDM,PetscInt,PetscInt*)
PetscErrorCode DMPlexGetMeet(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**)
#int DMPlexGetFullMeet(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**)
PetscErrorCode DMPlexRestoreMeet(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**)
PetscErrorCode DMPlexGetJoin(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**)
PetscErrorCode DMPlexGetFullJoin(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**)
PetscErrorCode DMPlexRestoreJoin(PetscDM,PetscInt,const PetscInt[],PetscInt*,const PetscInt**)
PetscErrorCode DMPlexGetTransitiveClosure(PetscDM,PetscInt,PetscBool,PetscInt*,PetscInt*[])
PetscErrorCode DMPlexRestoreTransitiveClosure(PetscDM,PetscInt,PetscBool,PetscInt*,PetscInt*[])
PetscErrorCode DMPlexVecGetClosure(PetscDM,PetscSection,PetscVec,PetscInt,PetscInt*,PetscScalar*[])
PetscErrorCode DMPlexVecRestoreClosure(PetscDM,PetscSection,PetscVec,PetscInt,PetscInt*,PetscScalar*[])
PetscErrorCode DMPlexVecSetClosure(PetscDM,PetscSection,PetscVec,PetscInt,PetscScalar[],PetscInsertMode)
PetscErrorCode DMPlexMatSetClosure(PetscDM,PetscSection,PetscSection,PetscMat,PetscInt,PetscScalar[],PetscInsertMode)
PetscErrorCode DMPlexGenerate(PetscDM,const char[],PetscBool,PetscDM*)
PetscErrorCode DMPlexTriangleSetOptions(PetscDM,const char*)
PetscErrorCode DMPlexTetgenSetOptions(PetscDM,const char*)
#int DMPlexCopyCoordinates(PetscDM,PetscDM)
#int DMPlexCreateDoublet(MPI_Comm,PetscInt,PetscBool,PetscBool,PetscBool,PetscReal,PetscDM*)
PetscErrorCode DMPlexCreateBoxMesh(MPI_Comm,PetscInt,PetscBool,PetscInt[],PetscReal[],PetscReal[],PetscDMBoundaryType[],PetscBool,PetscDM*)
PetscErrorCode DMPlexCreateBoxSurfaceMesh(MPI_Comm,PetscInt,PetscInt[],PetscReal[],PetscReal[],PetscBool,PetscDM*)
PetscErrorCode DMPlexCreateFromFile(MPI_Comm,const char[],const char[],PetscBool,PetscDM*)
PetscErrorCode DMPlexCreateCGNS(MPI_Comm,PetscInt,PetscBool,PetscDM*)
PetscErrorCode DMPlexCreateCGNSFromFile(MPI_Comm,const char[],PetscBool,PetscDM*)
PetscErrorCode DMPlexCreateExodus(MPI_Comm,PetscInt,PetscBool,PetscDM*)
PetscErrorCode DMPlexCreateExodusFromFile(MPI_Comm,const char[],PetscBool,PetscDM*)
PetscErrorCode DMPlexCreateGmsh(MPI_Comm,PetscViewer,PetscBool,PetscDM*)
#int DMPlexInvertCell(PetscInt,PetscInt,int[])
#int DMPlexCheckSymmetry(PetscDM)
#int DMPlexCheckSkeleton(PetscDM,PetscBool,PetscInt)
#int DMPlexCheckFaces(PetscDM,PetscBool,PetscInt)
PetscErrorCode DMPlexSetAdjacencyUseAnchors(PetscDM,PetscBool)
PetscErrorCode DMPlexGetAdjacencyUseAnchors(PetscDM,PetscBool*)
PetscErrorCode DMPlexGetAdjacency(PetscDM,PetscInt,PetscInt*,PetscInt*[])
#int DMPlexCreateNeighborCSR(PetscDM,PetscInt,PetscInt*,PetscInt**,PetscInt**)
PetscErrorCode DMPlexRebalanceSharedPoints(PetscDM,PetscInt,PetscBool,PetscBool,PetscBool*)
PetscErrorCode DMPlexDistribute(PetscDM,PetscInt,PetscSF*,PetscDM*)
PetscErrorCode DMPlexDistributeOverlap(PetscDM,PetscInt,PetscSF*,PetscDM*)
PetscErrorCode DMPlexDistributeGetDefault(PetscDM,PetscBool*)
PetscErrorCode DMPlexDistributeSetDefault(PetscDM,PetscBool)
PetscErrorCode DMPlexSetPartitioner(PetscDM,PetscPartitioner)
PetscErrorCode DMPlexGetPartitioner(PetscDM,PetscPartitioner*)
PetscErrorCode DMPlexDistributeField(PetscDM,PetscSF,PetscSection,PetscVec,PetscSection,PetscVec)
#int DMPlexDistributeData(PetscDM,PetscSF,PetscSection,MPI_Datatype,void*,PetscSection,void**)
PetscErrorCode DMPlexIsDistributed(PetscDM,PetscBool*)
PetscErrorCode DMPlexIsSimplex(PetscDM,PetscBool*)
PetscErrorCode DMPlexDistributionSetName(PetscDM,const char[])
PetscErrorCode DMPlexDistributionGetName(PetscDM,const char*[])
PetscErrorCode DMPlexGetOrdering(PetscDM,PetscMatOrderingType,PetscDMLabel,PetscIS*)
PetscErrorCode DMPlexPermute(PetscDM,PetscIS,PetscDM*)
PetscErrorCode DMPlexReorderGetDefault(PetscDM,PetscDMPlexReorderDefaultFlag*)
PetscErrorCode DMPlexReorderSetDefault(PetscDM,PetscDMPlexReorderDefaultFlag)
#int DMPlexCreateSubmesh(PetscDM,PetscDMLabel,PetscInt,PetscDM*)
#int DMPlexCreateHybridMesh(PetscDM,PetscDMLabel,PetscDMLabel,PetscInt,PetscDMLabel*,PetscDMLabel*,PetscDM *,PetscDM *)
#int DMPlexGetSubpointMap(PetscDM,PetscDMLabel*)
#int DMPlexSetSubpointMap(PetscDM,PetscDMLabel)
#int DMPlexCreateSubpointIS(PetscDM,PetscIS*)
PetscErrorCode DMPlexCreateCoarsePointIS(PetscDM,PetscIS*)
PetscErrorCode DMPlexMarkBoundaryFaces(PetscDM,PetscInt,PetscDMLabel)
PetscErrorCode DMPlexLabelComplete(PetscDM,PetscDMLabel)
PetscErrorCode DMPlexLabelCohesiveComplete(PetscDM,PetscDMLabel,PetscDMLabel,PetscInt,PetscBool,PetscDM)
PetscErrorCode DMPlexGetRefinementLimit(PetscDM,PetscReal*)
PetscErrorCode DMPlexSetRefinementLimit(PetscDM,PetscReal)
PetscErrorCode DMPlexGetRefinementUniform(PetscDM,PetscBool*)
PetscErrorCode DMPlexSetRefinementUniform(PetscDM,PetscBool)
PetscErrorCode DMPlexGetMinRadius(PetscDM, PetscReal*)
#int DMPlexGetNumFaceVertices(PetscDM,PetscInt,PetscInt,PetscInt*)
#int DMPlexGetOrientedFace(PetscDM,PetscInt,PetscInt,const PetscInt[],PetscInt,PetscInt[],PetscInt[],PetscInt[],PetscBool*)
PetscErrorCode DMPlexCreateSection(PetscDM,PetscDMLabel[],const PetscInt[],const PetscInt[],PetscInt,const PetscInt[],const PetscIS[],const PetscIS[],PetscIS,PetscSection*)
PetscErrorCode DMPlexComputeCellGeometryFVM(PetscDM,PetscInt,PetscReal*,Petsc | Cython |
Real[],PetscReal[])
PetscErrorCode DMPlexConstructGhostCells(PetscDM,const char[],PetscInt*,PetscDM*)
PetscErrorCode DMPlexMetricSetFromOptions(PetscDM)
PetscErrorCode DMPlexMetricSetUniform(PetscDM,PetscBool)
PetscErrorCode DMPlexMetricIsUniform(PetscDM,PetscBool*)
PetscErrorCode DMPlexMetricSetIsotropic(PetscDM,PetscBool)
PetscErrorCode DMPlexMetricIsIsotropic(PetscDM,PetscBool*)
PetscErrorCode DMPlexMetricSetRestrictAnisotropyFirst(PetscDM,PetscBool)
PetscErrorCode DMPlexMetricRestrictAnisotropyFirst(PetscDM,PetscBool*)
PetscErrorCode DMPlexMetricSetNoInsertion(PetscDM,PetscBool)
PetscErrorCode DMPlexMetricNoInsertion(PetscDM,PetscBool*)
PetscErrorCode DMPlexMetricSetNoSwapping(PetscDM,PetscBool)
PetscErrorCode DMPlexMetricNoSwapping(PetscDM,PetscBool*)
PetscErrorCode DMPlexMetricSetNoMovement(PetscDM,PetscBool)
PetscErrorCode DMPlexMetricNoMovement(PetscDM,PetscBool*)
PetscErrorCode DMPlexMetricSetNoSurf(PetscDM,PetscBool)
PetscErrorCode DMPlexMetricNoSurf(PetscDM,PetscBool*)
PetscErrorCode DMPlexMetricSetVerbosity(PetscDM,PetscInt)
PetscErrorCode DMPlexMetricGetVerbosity(PetscDM,PetscInt*)
PetscErrorCode DMPlexMetricSetNumIterations(PetscDM,PetscInt)
PetscErrorCode DMPlexMetricGetNumIterations(PetscDM,PetscInt*)
PetscErrorCode DMPlexMetricSetMinimumMagnitude(PetscDM,PetscReal)
PetscErrorCode DMPlexMetricGetMinimumMagnitude(PetscDM,PetscReal*)
PetscErrorCode DMPlexMetricSetMaximumMagnitude(PetscDM,PetscReal)
PetscErrorCode DMPlexMetricGetMaximumMagnitude(PetscDM,PetscReal*)
PetscErrorCode DMPlexMetricSetMaximumAnisotropy(PetscDM,PetscReal)
PetscErrorCode DMPlexMetricGetMaximumAnisotropy(PetscDM,PetscReal*)
PetscErrorCode DMPlexMetricSetTargetComplexity(PetscDM,PetscReal)
PetscErrorCode DMPlexMetricGetTargetComplexity(PetscDM,PetscReal*)
PetscErrorCode DMPlexMetricSetNormalizationOrder(PetscDM,PetscReal)
PetscErrorCode DMPlexMetricGetNormalizationOrder(PetscDM,PetscReal*)
PetscErrorCode DMPlexMetricSetGradationFactor(PetscDM,PetscReal)
PetscErrorCode DMPlexMetricGetGradationFactor(PetscDM,PetscReal*)
PetscErrorCode DMPlexMetricSetHausdorffNumber(PetscDM,PetscReal)
PetscErrorCode DMPlexMetricGetHausdorffNumber(PetscDM,PetscReal*)
PetscErrorCode DMPlexMetricCreate(PetscDM,PetscInt,PetscVec*)
PetscErrorCode DMPlexMetricCreateUniform(PetscDM,PetscInt,PetscReal,PetscVec*)
PetscErrorCode DMPlexMetricCreateIsotropic(PetscDM,PetscInt,PetscVec,PetscVec*)
PetscErrorCode DMPlexMetricDeterminantCreate(PetscDM,PetscInt,PetscVec*,PetscDM*)
PetscErrorCode DMPlexMetricEnforceSPD(PetscDM,PetscVec,PetscBool,PetscBool,PetscVec,PetscVec)
PetscErrorCode DMPlexMetricNormalize(PetscDM,PetscVec,PetscBool,PetscBool,PetscVec,PetscVec)
PetscErrorCode DMPlexMetricAverage2(PetscDM,PetscVec,PetscVec,PetscVec)
PetscErrorCode DMPlexMetricAverage3(PetscDM,PetscVec,PetscVec,PetscVec,PetscVec)
PetscErrorCode DMPlexMetricIntersection2(PetscDM,PetscVec,PetscVec,PetscVec)
PetscErrorCode DMPlexMetricIntersection3(PetscDM,PetscVec,PetscVec,PetscVec,PetscVec)
PetscErrorCode DMPlexComputeGradientClementInterpolant(PetscDM,PetscVec,PetscVec)
PetscErrorCode DMPlexTopologyView(PetscDM,PetscViewer)
PetscErrorCode DMPlexCoordinatesView(PetscDM,PetscViewer)
PetscErrorCode DMPlexLabelsView(PetscDM,PetscViewer)
PetscErrorCode DMPlexSectionView(PetscDM,PetscViewer,PetscDM)
PetscErrorCode DMPlexGlobalVectorView(PetscDM,PetscViewer,PetscDM,PetscVec)
PetscErrorCode DMPlexLocalVectorView(PetscDM,PetscViewer,PetscDM,PetscVec)
PetscErrorCode DMPlexTopologyLoad(PetscDM,PetscViewer,PetscSF*)
PetscErrorCode DMPlexCoordinatesLoad(PetscDM,PetscViewer,PetscSF)
PetscErrorCode DMPlexLabelsLoad(PetscDM,PetscViewer,PetscSF)
PetscErrorCode DMPlexSectionLoad(PetscDM,PetscViewer,PetscDM,PetscSF,PetscSF*,PetscSF*)
PetscErrorCode DMPlexGlobalVectorLoad(PetscDM,PetscViewer,PetscDM,PetscSF,PetscVec)
PetscErrorCode DMPlexLocalVectorLoad(PetscDM,PetscViewer,PetscDM,PetscSF,PetscVec)
PetscErrorCode DMPlexTransformApply(PetscDMPlexTransform, PetscDM, PetscDM *);
PetscErrorCode DMPlexTransformCreate(MPI_Comm, PetscDMPlexTransform *);
PetscErrorCode DMPlexTransformDestroy(PetscDMPlexTransform*);
PetscErrorCode DMPlexTransformGetType(PetscDMPlexTransform, PetscDMPlexTransformType *);
PetscErrorCode DMPlexTransformSetType(PetscDMPlexTransform tr, PetscDMPlexTransformType method);
PetscErrorCode DMPlexTransformSetFromOptions(PetscDMPlexTransform);
PetscErrorCode DMPlexTransformSetDM(PetscDMPlexTransform, PetscDM);
PetscErrorCode DMPlexTransformSetUp(PetscDMPlexTransform);
PetscErrorCode DMPlexTransformView(PetscDMPlexTransform tr, PetscViewer v);
<|end_of_text|>#'Test generation'
from tempmin import *
from math import *
import numpy
def test_test_snow1():
params= tempmin(
P_prof = 10.0,
P_tminseuil = -0.5,
P_tmaxseuil = 0.0,
Sdepth_cm = 91.2,
tmin = 0.279,
)
tminrec_estimated = round(params, 2)
tminrec_computed = 45.6
assert (tminrec_estimated == tminrec_computed)<|end_of_text|>#distutils: language = c++
from libcpp cimport bool
cdef extern from "../sucpp/api.hpp":
struct mat:
double* condensed_form
unsigned int n_samples
unsigned int cf_size
char** sample_ids
struct results_vec:
unsigned int n_samples
double* values
char** sample_ids
enum compute_status:
okay,
tree_missing,
table_missing,
table_empty,
unknown_method,
table_and_tree_do_not_overlap,
output_error
compute_status one_off(const char* biom_filename, const char* tree_filename,
const char* unifrac_method, bool variance_adjust, double alpha,
bool bypass_tips, unsigned int threads, mat** result)
compute_status faith_pd_one_off(const char* biom_filename, const char* tree_filename,
results_vec** result)
void destroy_mat(mat** result)
void destroy_results_vec(results_vec** result)
compute_status unifrac_to_file(const char* biom_filename, const char* tree_filename, const char* out_filename,
const char* unifrac_method, bool variance_adjust, double alpha,
bool bypass_tips, unsigned int threads, const char* format,
unsigned int pcoa_dims, const char *mmap_dir)
<|end_of_text|>
import os
from libc cimport stdint
cdef extern from "ext/batch_jaro_winkler.h":
ctypedef struct bjw_result:
void *candidate
float score
stdint.uint32_t candidate_length
void *bjw_build_exportable_model(void **candidates, stdint.uint32_t char_width, stdint.uint32_t *candidates_lengths, stdint.uint32_t nb_candidates, float *min_scores, stdint.uint32_t nb_runtime_threads, stdint.uint32_t *res_model_size);
void *bjw_build_runtime_model(void *exportable_model);
void bjw_free_runtime_model(void *runtime_model);
bjw_result *bjw_jaro_winkler_distance(void *runtime_model, void *input, stdint.uint32_t input_length, float min_score, float weight, float threshold, stdint.uint32_t n_best_results, stdint.uint32_t *nb_results) nog | Cython |
il;<|end_of_text|># distutils: extra_compile_args = -O3 -w
# distutils: include_dirs = pylds/
# cython: boundscheck = False, nonecheck = False, wraparound = False, cdivision = True
import scipy.linalg.blas
import scipy.linalg.lapack
cdef extern from "f2pyptr.h":
void *f2py_pointer(object) except NULL
cdef:
# BLAS
dcopy_t *dcopy = <dcopy_t*>f2py_pointer(scipy.linalg.blas.dcopy._cpointer)
dnrm2_t *dnrm2 = <dnrm2_t*>f2py_pointer(scipy.linalg.blas.dnrm2._cpointer)
daxpy_t *daxpy = <daxpy_t*>f2py_pointer(scipy.linalg.blas.daxpy._cpointer)
srotg_t *srotg = <srotg_t*>f2py_pointer(scipy.linalg.blas.srotg._cpointer)
srot_t *srot = <srot_t*>f2py_pointer(scipy.linalg.blas.srot._cpointer)
drotg_t *drotg = <drotg_t*>f2py_pointer(scipy.linalg.blas.drotg._cpointer)
drot_t *drot = <drot_t*>f2py_pointer(scipy.linalg.blas.drot._cpointer)
ddot_t *ddot = <ddot_t*>f2py_pointer(scipy.linalg.blas.ddot._cpointer)
dsymv_t *dsymv = <dsymv_t*>f2py_pointer(scipy.linalg.blas.dsymv._cpointer)
dgemv_t *dgemv = <dgemv_t*>f2py_pointer(scipy.linalg.blas.dgemv._cpointer)
dger_t *dger = <dger_t*>f2py_pointer(scipy.linalg.blas.dger._cpointer)
dtrmv_t *dtrmv = <dtrmv_t*>f2py_pointer(scipy.linalg.blas.dtrmv._cpointer)
dgemm_t *dgemm = <dgemm_t*>f2py_pointer(scipy.linalg.blas.dgemm._cpointer)
dsymm_t *dsymm = <dsymm_t*>f2py_pointer(scipy.linalg.blas.dsymm._cpointer)
dsyrk_t *dsyrk = <dsyrk_t*>f2py_pointer(scipy.linalg.blas.dsyrk._cpointer)
# LAPACK
dposv_t *dposv = <dposv_t*>f2py_pointer(scipy.linalg.lapack.dposv._cpointer)
dpotrf_t *dpotrf = <dpotrf_t*>f2py_pointer(scipy.linalg.lapack.dpotrf._cpointer)
dpotrs_t *dpotrs = <dpotrs_t*>f2py_pointer(scipy.linalg.lapack.dpotrs._cpointer)
dtrtrs_t *dtrtrs = <dtrtrs_t*>f2py_pointer(scipy.linalg.lapack.dtrtrs._cpointer)
dpotri_t *dpotri = <dpotri_t*>f2py_pointer(scipy.linalg.lapack.dpotri._cpointer)
<|end_of_text|># This source code is part of the
# PyQuante quantum chemistry suite
#
# Written by Gabriele Lanaro, 2009-2010
# Copyright (c) 2009-2010, Gabriele Lanaro
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
cimport contracted_gto
import contracted_gto
from primitive_gto cimport PrimitiveGTO, cPrimitiveGTO
#from primitive_gto import PrimitiveGTO
from stdlib cimport *
cdef class ContractedGTO:
'''
Class that represents a linear combination of PrimitiveGTOs
'''
def __cinit__(self, origin, powers, atid=0):
self.this = contracted_gto.contracted_gto_new()
def __init__(self,origin, powers, atid=0):
x,y,z = origin
l,m,n = powers
contracted_gto.contracted_gto_init(self.this, x, y, z, l, m, n, atid)
@classmethod
def from_primitives(cls, pgtos, coefs, atid=0):
raise NotImplementedError()
cdef cPrimitiveGTO **pgto_array
cdef int n,i
cdef PrimitiveGTO cy_pgto
n = <int>len(pgtos)
# this array will be free in the cgto destructor
pgto_array = <cPrimitiveGTO **>malloc(n * sizeof(cPrimitiveGTO*))
# Constructing the PrimitiveGTO** array...
for i in range(n):
cy_pgto = <PrimitiveGTO> pgtos[i]
cy_pgto.this.coef = <double>coefs[i] # set the coef
pgto_array[i] = <cPrimitiveGTO *> cy_pgto.this
#obj = ContractedGTO(x,y,z,l,m,n,atid)
#contracted_gto.contracted_gto_from_primitives(obj.this, pgto_array, n)
#return obj
def __dealloc__(self):
contracted_gto.contracted_gto_free(self.this)
def add_primitive(self, primitive_gto.PrimitiveGTO pgto, double coeff):
contracted_gto.contracted_gto_add_primitive(self.this, pgto.this, coeff)
def amp(self,double x,double y,double z):
'''
given a point in the space it returns the amplitude of the
GTO
'''
return contracted_gto.contracted_gto_amp(self.this,x,y,z)
def normalize(self):
contracted_gto.contracted_gto_normalize(self.this)
property norm:
def __get__(self):
return self.this.norm
def __set__(self, double value):
self.this.norm = value
property primitives:
def __get__(self):
cdef cPrimitiveGTO* prim
ret = []
for i in range(self.this.nprims):
prim = <cPrimitiveGTO *>self.this.primitives[i]
ret.append(PrimitiveGTO(prim.alpha,
(prim.x0,prim.y0,prim.z0),
(prim.l,prim.m,prim.n),
prim.coef))
return ret
'''
cpdef double coulomb( ContractedGTO a,
ContractedGTO b,
ContractedGTO c,
ContractedGTO d ):
return contracted_gto.contracted_gto_coulomb(a.this,
b.this,
c.this,
d.this)
'''
<|end_of_text|>from quantlib.handle cimport shared_ptr
from quantlib.indexes.interest_rate_index cimport InterestRateIndex
cdef class SwapIndex(InterestRateIndex):
pass
<|end_of_text|>
ctypedef unsigned char uint8_t
cdef extern from "embed/usart.h":
void usart_puts(const char *data)
int usart_gets(char *data)
void isr_USART_UDRE_vect()
void isr_USART_RX_vect()
ctypedef struct buffer_t:
char data[64]
uint8_t head, tail
buffer_t _buffer_debug(char buf, char debug)
cdef extern from "avr/io.h":
uint8_t UBRR0H
uint8_t UBRR0L
uint8_t RXCIE0
uint8_t UCSR0B
uint8_t UDRIE0
uint8_t RXC0
uint8_t UCSR0A
uint8_t UDRE0
uint8_t UDR0
<|end_of_text|>cimport cython
# This file must not cimport anything from gevent.
cdef get_objects
cdef wref
cdef BlockingSwitchOutError
cdef extern from "greenlet/greenlet.h":
ctypedef class greenlet.greenlet [object PyGreenlet]:
pass
# These are actually macros and so much be included
# (defined) in each.pxd, as are the two functions
# that call them.
greenlet PyGreenlet_GetCurrent()
object PyGreenlet_Switch(greenlet self, void* args, void* kwargs)
void PyGreenlet_Import()
@cython.final
cdef inline greenlet getcurrent():
return PyGreenlet_GetCurrent()
cdef bint _greenlet_imported
cdef inline void greenlet_init():
global _greenlet_imported
if not _greenlet_imported:
PyGreenlet_Import()
_greenlet_imported = True
cdef inline object _greenlet_switch(greenlet self):
return PyGreenlet_Switch(self, NULL, NULL)
cdef class TrackedRawGreenlet(greenlet):
pass
cdef class SwitchOutGreenletWithLoop(TrackedRawGreenlet):
cdef public loop
cpdef switch(self)
cpdef switch_out(self)
cpdef list get_reachable_greenlets()
<|end_of_text|># POSIX additions to <stdlib | Cython |
.h>
# https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stdlib.h.html
cdef extern from "<stdlib.h>" nogil:
void _Exit(int)
double drand48()
double erand48(unsigned short *)
int getsubopt(char **, char *const *, char **)
void lcong48(unsigned short *)
long lrand()
char *mkdtemp(char *)
int mkstemp(char *)
long mrand()
long nrand48(unsigned short *)
int posix_memalign(void **, size_t, size_t)
int posix_openpt(int)
char *ptsname(int)
int putenv(char *)
int rand_r(unsigned *)
long random()
char *realpath(const char *, char *)
unsigned short *seed48(unsigned short *)
int setenv(const char *, const char *, int)
void setkey(const char *)
char *setstate(char *)
void srand48(long)
void srandom(unsigned)
int unlockpt(int)
int unsetenv(const char *)
<|end_of_text|>import numpy as np
cimport numpy as np
ctypedef np.double_t DTYPE_t
cdef extern from "stdlib.h":
ctypedef void const_void "const void"
void qsort(void *base, int nmemb, int size,
int(*compar)(const_void *, const_void *)) nogil
cdef int mycmp(const_void * pa, const_void * pb):
cdef double a = (<double *>pa)[0]
cdef double b = (<double *>pb)[0]
if a < b:
return -1
elif a > b:
return 1
else:
return 0
cdef void myfunc(double * y, ssize_t l) nogil:
qsort(y, l, sizeof(double), mycmp)
def sortArray(np.ndarray[DTYPE_t,ndim=1] inpArray):
cdef int lengthArr=inpArray.shape[0]
cdef double* ArrPtr=&inpArray[0]
myfunc(ArrPtr,lengthArr)
# Usage
#import numpy as np
#inpArray=np.array([1.,2.,3.,7.,4.])
#cythonSort.sortArray(inpArray)
#print(inpArray)
# [1. 2. 3. 4. 7.]
<|end_of_text|>#cython: boundscheck=False
#cython: wraparound=False
#cython: cdivision=True
#cython: embedsignature=True
# cython: profile=False
# ==============================================================
import numpy as np
#
from libc.math cimport floor
#
cimport cython
from cython.parallel cimport prange
# ==============================================================
def translate_2D(double[:,:] in_arr, double dX, double dY):
"""
dX, dY --> Amount of translation
"""
# ==========================================================
cdef:
ssize_t x, nX=in_arr.shape[0]
ssize_t y, nY=in_arr.shape[1]
ssize_t x_lo, y_lo #
ssize_t x_hi, y_hi #
double x_est, y_est # Estimates of where (x,y) in
# the out-array corresponds to
# in the input array
double Wx_lo, Wy_lo, Wx_hi, Wy_hi
double W_LL, W_LH, W_HL, W_HH
double eps = 1E-6
double[:,:] arr = np.zeros((nX,nY), dtype=np.float64)
# ==========================================================
with nogil:
for x in prange(nX):
for y in range(nY):
# translate (x,y) by (dX,dY)
x_est = <double> x - dX
y_est = <double> y - dY
# interpolate
x_lo = <int> floor(x_est)
y_lo = <int> floor(y_est)
x_hi = x_lo + 1 #ceil(x_est)
y_hi = y_lo + 1 #ceil(y_est)
# 1D interpolation weights
Wx_lo = - x_est + <double> x_hi + eps
Wy_lo = - y_est + <double> y_hi + eps
Wx_hi = + x_est - <double> x_lo + eps
Wy_hi = + y_est - <double> y_lo + eps
# 2D interpolation weights
W_LL = Wx_lo * Wy_lo
W_LH = Wx_lo * Wy_hi
W_HL = Wx_hi * Wy_lo
W_HH = Wx_hi * Wy_hi
#
if ((x_lo >= 0) and (x_hi < nX) and
(y_lo >= 0) and (y_hi < nY)):
arr[x,y] = W_LL * in_arr[x_lo, y_lo] + \
W_LH * in_arr[x_lo, y_hi] + \
W_HL * in_arr[x_hi, y_lo] + \
W_HH * in_arr[x_hi, y_hi]
# end for y loop
# end for x loop
return np.asarray(arr)
# ==============================================================
<|end_of_text|>class java_method(object):
def __init__(self, signature, name=None):
super(java_method, self).__init__()
self.signature = signature
self.name = name
def __get__(self, instance, instancetype):
return partial(self.__call__, instance)
def __call__(self, f):
f.__javasignature__ = self.signature
f.__javaname__ = self.name
return f
cdef class PythonJavaClass(object):
'''
Base class to create a java class from python
'''
cdef jclass j_cls
cdef public object j_self
def __cinit__(self, *args):
self.j_cls = NULL
self.j_self = None
def __init__(self, *args, **kwargs):
self._init_j_self_ptr()
def _init_j_self_ptr(self):
javacontext ='system'
if hasattr(self, '__javacontext__'):
javacontext = self.__javacontext__
self.j_self = create_proxy_instance(get_jnienv(), self,
self.__javainterfaces__, javacontext)
# discover all the java method implemented
self.__javamethods__ = {}
for x in dir(self):
attr = getattr(self, x)
if not callable(attr):
continue
if not hasattr(attr, '__javasignature__'):
continue
signature = parse_definition(attr.__javasignature__)
self.__javamethods__[(attr.__javaname__ or x, signature)] = attr
def invoke(self, method, *args):
try:
ret = self._invoke(method, *args)
return ret
except Exception:
traceback.print_exc()
return None
def _invoke(self, method, *args):
from.reflect import get_signature
# search the java method
ret_signature = get_signature(method.getReturnType())
args_signature = tuple([get_signature(x) for x in method.getParameterTypes()])
method_name = method.getName()
key = (method_name, (ret_signature, args_signature))
py_method = self.__javamethods__.get(key, None)
if not py_method:
print(''.join([
'\n===== Python/java method missing ======',
'\nPython class:', repr(self),
'\nJava method name:', method_name,
'\nSignature: ({}){}'.format(''.join(args_signature), ret_signature),
'\n=======================================\n']))
raise NotImplementedError('The method {} is not implemented'.format(key))
return py_method(*args)
cdef jobject py_invoke0(JNIEnv *j_env, jobject j_this, jobject j_proxy, jobject
j_method, jobjectArray args) except * with gil:
from.reflect import get_signature, Method
cdef jfieldID ptrField
cdef jlong jptr
cdef object py_obj
cdef JavaClass method
cdef jobject j_arg
# get the python object
ptrField = j_env[0].GetFieldID(j_env,
j_env[0].GetObjectClass(j_env, j_this), "ptr", "J")
jptr = j_env[0].GetLongField(j_env, j_this, ptrField)
py_obj = <object><void *>jptr
# extract the method information
method = Method(noinstance=True)
method.instanciate_from(create_local_ref(j_env, j_method))
ret_signature = get_signature(method.getReturnType())
args_signature = [get_signature(x) for x in method.getParameterTypes()]
# convert java argument to python object
# native java type are given with java.lang.*, even if the signature say
# it's a native type.
py_args = []
convert_signature = {
'Z': 'Ljava/lang/Boolean;',
'B': 'Ljava/lang/Byte;',
'C': 'Ljava/lang/Character;',
'S': 'Ljava/lang/Short;',
'I': 'Ljava/lang/Integer;',
'J': 'Ljava/lang/Long;',
'F': 'Ljava/lang/Float;',
| Cython |
'D': 'Ljava/lang/Double;'}
for index, arg_signature in enumerate(args_signature):
arg_signature = convert_signature.get(arg_signature, arg_signature)
j_arg = j_env[0].GetObjectArrayElement(j_env, args, index)
py_arg = convert_jobject_to_python(j_env, arg_signature, j_arg)
j_env[0].DeleteLocalRef(j_env, j_arg)
py_args.append(py_arg)
# really invoke the python method
name = method.getName()
ret = py_obj.invoke(method, *py_args)
# convert back to the return type
# use the populate_args(), but in the reverse way :)
t = ret_signature[:1]
# did python returned a "native" type?
jtype = None
if ret_signature == 'Ljava/lang/Object;':
# generic object, try to manually convert it
tp = type(ret)
if tp == int:
jtype = 'J'
elif tp == float:
jtype = 'D'
elif tp == bool:
jtype = 'Z'
elif len(ret_signature) == 1:
jtype = ret_signature
try:
return convert_python_to_jobject(j_env, jtype or ret_signature, ret)
except Exception:
traceback.print_exc()
cdef jobject invoke0(JNIEnv *j_env, jobject j_this, jobject j_proxy, jobject
j_method, jobjectArray args) with gil:
try:
return py_invoke0(j_env, j_this, j_proxy, j_method, args)
except Exception:
traceback.print_exc()
return NULL
# now we need to create a proxy and pass it an invocation handler
cdef create_proxy_instance(JNIEnv *j_env, py_obj, j_interfaces, javacontext):
from.reflect import autoclass
Proxy = autoclass('java.lang.reflect.Proxy')
NativeInvocationHandler = autoclass('org.jnius.NativeInvocationHandler')
# convert strings to Class
j_interfaces = [find_javaclass(x) for x in j_interfaces]
cdef JavaClass nih = NativeInvocationHandler(<long long><void *>py_obj)
cdef JNINativeMethod invoke_methods[1]
invoke_methods[0].name = 'invoke0'
invoke_methods[0].signature = '(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;'
invoke_methods[0].fnPtr = <void *>&invoke0
j_env[0].RegisterNatives(j_env, nih.j_cls, <JNINativeMethod *>invoke_methods, 1)
# create the proxy and pass it the invocation handler
cdef JavaClass j_obj
if javacontext == 'app':
Thread = autoclass('java.lang.Thread')
classLoader = Thread.currentThread().getContextClassLoader()
j_obj = Proxy.newProxyInstance(
classLoader, j_interfaces, nih)
elif javacontext =='system':
ClassLoader = autoclass('java.lang.ClassLoader')
classLoader = ClassLoader.getSystemClassLoader()
j_obj = Proxy.newProxyInstance(
classLoader, j_interfaces, nih)
else:
raise Exception(
'Invalid __javacontext__ {}, must be app or system.'.format(
javacontext))
return j_obj
<|end_of_text|>"""
Symbolic matrices
Matrices with symbolic entries. The underlying representation is a
pointer to a Maxima object.
EXAMPLES::
sage: matrix(SR, 2, 2, range(4))
[0 1]
[2 3]
sage: matrix(SR, 2, 2, var('t'))
[t 0]
[0 t]
Arithmetic::
sage: -matrix(SR, 2, range(4))
[ 0 -1]
[-2 -3]
sage: m = matrix(SR, 2, [1..4]); sqrt(2)*m
[ sqrt(2) 2*sqrt(2)]
[3*sqrt(2) 4*sqrt(2)]
sage: m = matrix(SR, 4, [1..4^2])
sage: m * m
[ 90 100 110 120]
[202 228 254 280]
[314 356 398 440]
[426 484 542 600]
sage: m = matrix(SR, 3, [1, 2, 3]); m
[1]
[2]
[3]
sage: m.transpose() * m
[14]
Computing inverses::
sage: M = matrix(SR, 2, var('a,b,c,d'))
sage: ~M
[1/a - b*c/(a^2*(b*c/a - d)) b/(a*(b*c/a - d))]
[ c/(a*(b*c/a - d)) -1/(b*c/a - d)]
sage: (~M*M).simplify_rational()
[1 0]
[0 1]
sage: M = matrix(SR, 3, 3, range(9)) - var('t')
sage: (~M * M).simplify_rational()
[1 0 0]
[0 1 0]
[0 0 1]
sage: matrix(SR, 1, 1, 1).inverse()
[1]
sage: matrix(SR, 0, 0).inverse()
[]
sage: matrix(SR, 3, 0).inverse()
Traceback (most recent call last):
...
ArithmeticError: self must be a square matrix
Transposition::
sage: m = matrix(SR, 2, [sqrt(2), -1, pi, e^2])
sage: m.transpose()
[sqrt(2) pi]
[ -1 e^2]
``.T`` is a convenient shortcut for the transpose::
sage: m.T
[sqrt(2) pi]
[ -1 e^2]
Test pickling::
sage: m = matrix(SR, 2, [sqrt(2), 3, pi, e]); m
[sqrt(2) 3]
[ pi e]
sage: TestSuite(m).run()
Comparison::
sage: m = matrix(SR, 2, [sqrt(2), 3, pi, e])
sage: cmp(m,m)
0
sage: cmp(m,3)!= 0
True
sage: m = matrix(SR,2,[1..4]); n = m^2
sage: (exp(m+n) - exp(m)*exp(n)).simplify_rational() == 0 # indirect test
True
Determinant::
sage: M = matrix(SR, 2, 2, [x,2,3,4])
sage: M.determinant()
4*x - 6
sage: M = matrix(SR, 3,3,range(9))
sage: M.det()
0
sage: t = var('t')
sage: M = matrix(SR, 2, 2, [cos(t), sin(t), -sin(t), cos(t)])
sage: M.det()
cos(t)^2 + sin(t)^2
sage: M = matrix([[sqrt(x),0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]])
sage: det(M)
sqrt(x)
Permanents::
sage: M = matrix(SR, 2, 2, [x,2,3,4])
sage: M.permanent()
4*x + 6
Rank::
sage: M = matrix(SR, 5, 5, range(25))
sage: M.rank()
2
sage: M = matrix(SR, 5, 5, range(25)) - var('t')
sage: M.rank()
5
.. warning::
:meth:`rank` may return the wrong answer if it cannot determine that a
matrix element that is equivalent to zero is indeed so.
Copying symbolic matrices::
sage: m = matrix(SR, 2, [sqrt(2), 3, pi, e])
sage: n = copy(m)
sage: n[0,0] = sin(1)
sage: m
[sqrt(2) 3]
[ pi e]
sage: n
[sin(1) 3]
[ pi e]
Conversion to Maxima::
sage: m = matrix(SR, 2, [sqrt(2), 3, pi, e])
sage: m._maxima_()
matrix([sqrt(2),3],[%pi,%e])
"""
from sage.rings.polynomial.all import PolynomialRing
from sage.structure.element cimport ModuleElement, RingElement, Element
from sage.structure.factorization import Factorization
from matrix_generic_dense cimport Matrix_generic_dense
cimport matrix
cdef maxima
from sage.calculus.calculus import symbolic_expression_from_maxima_string, maxima
cdef class Matrix_symbolic_dense(Matrix_generic_dense):
def eigenvalues(self):
"""
Compute the eigenvalues | Cython |
by solving the characteristic
polynomial in maxima
EXAMPLES::
sage: a=matrix(SR,[[1,2],[3,4]])
sage: a.eigenvalues()
[-1/2*sqrt(33) + 5/2, 1/2*sqrt(33) + 5/2]
"""
maxima_evals = self._maxima_(maxima).eigenvalues()._sage_()
if len(maxima_evals)==0:
raise ArithmeticError("could not determine eigenvalues exactly using symbolic matrices; try using a different type of matrix via self.change_ring(), if possible")
return sum([[eval]*int(mult) for eval,mult in zip(*maxima_evals)],[])
def eigenvectors_left(self):
r"""
Compute the left eigenvectors of a matrix.
For each distinct eigenvalue, returns a list of the form (e,V,n)
where e is the eigenvalue, V is a list of eigenvectors forming a
basis for the corresponding left eigenspace, and n is the
algebraic multiplicity of the eigenvalue.
EXAMPLES::
sage: A = matrix(SR,3,3,range(9)); A
[0 1 2]
[3 4 5]
[6 7 8]
sage: es = A.eigenvectors_left(); es
[(-3*sqrt(6) + 6, [(1, -1/5*sqrt(6) + 4/5, -2/5*sqrt(3)*sqrt(2) + 3/5)], 1), (3*sqrt(6) + 6, [(1, 1/5*sqrt(6) + 4/5, 2/5*sqrt(3)*sqrt(2) + 3/5)], 1), (0, [(1, -2, 1)], 1)]
sage: eval, [evec], mult = es[0]
sage: delta = eval*evec - evec*A
sage: abs(abs(delta)) < 1e-10
sqrt(abs(1/25*(3*(2*sqrt(3)*sqrt(2) - 3)*(sqrt(6) - 2) + 16*sqrt(3)*sqrt(2) + 5*sqrt(6) - 54)^2 + 1/25*(3*(sqrt(6) - 2)*(sqrt(6) - 4) + 14*sqrt(3)*sqrt(2) + 4*sqrt(6) - 42)^2 + 144/25*(sqrt(3)*sqrt(2) - sqrt(6))^2)) < (1.00000000000000e-10)
sage: abs(abs(delta)).n() < 1e-10
True
::
sage: A = matrix(SR, 2, 2, var('a,b,c,d'))
sage: A.eigenvectors_left()
[(1/2*a + 1/2*d - 1/2*sqrt(a^2 + 4*b*c - 2*a*d + d^2), [(1, -1/2*(a - d + sqrt(a^2 + 4*b*c - 2*a*d + d^2))/c)], 1), (1/2*a + 1/2*d + 1/2*sqrt(a^2 + 4*b*c - 2*a*d + d^2), [(1, -1/2*(a - d - sqrt(a^2 + 4*b*c - 2*a*d + d^2))/c)], 1)]
sage: es = A.eigenvectors_left(); es
[(1/2*a + 1/2*d - 1/2*sqrt(a^2 + 4*b*c - 2*a*d + d^2), [(1, -1/2*(a - d + sqrt(a^2 + 4*b*c - 2*a*d + d^2))/c)], 1), (1/2*a + 1/2*d + 1/2*sqrt(a^2 + 4*b*c - 2*a*d + d^2), [(1, -1/2*(a - d - sqrt(a^2 + 4*b*c - 2*a*d + d^2))/c)], 1)]
sage: eval, [evec], mult = es[0]
sage: delta = eval*evec - evec*A
sage: delta.apply_map(lambda x: x.full_simplify())
(0, 0)
This routine calls Maxima and can struggle with even small matrices
with a few variables, such as a `3\times 3` matrix with three variables.
However, if the entries are integers or rationals it can produce exact
values in a reasonable time. These examples create 0-1 matrices from
the adjacency matrices of graphs and illustrate how the format and type
of the results differ when the base ring changes. First for matrices
over the rational numbers, then the same matrix but viewed as a symbolic
matrix. ::
sage: G=graphs.CycleGraph(5)
sage: am = G.adjacency_matrix()
sage: spectrum = am.eigenvectors_left()
sage: qqbar_evalue = spectrum[2][0]
sage: type(qqbar_evalue)
<class'sage.rings.qqbar.AlgebraicNumber'>
sage: qqbar_evalue
0.618033988749895?
sage: am = G.adjacency_matrix().change_ring(SR)
sage: spectrum = am.eigenvectors_left()
sage: symbolic_evalue = spectrum[2][0]
sage: type(symbolic_evalue)
<type'sage.symbolic.expression.Expression'>
sage: symbolic_evalue
1/2*sqrt(5) - 1/2
sage: bool(qqbar_evalue == symbolic_evalue)
True
A slightly larger matrix with a "nice" spectrum. ::
sage: G=graphs.CycleGraph(6)
sage: am = G.adjacency_matrix().change_ring(SR)
sage: am.eigenvectors_left()
[(-1, [(1, 0, -1, 1, 0, -1), (0, 1, -1, 0, 1, -1)], 2), (1, [(1, 0, -1, -1, 0, 1), (0, 1, 1, 0, -1, -1)], 2), (-2, [(1, -1, 1, -1, 1, -1)], 1), (2, [(1, 1, 1, 1, 1, 1)], 1)]
"""
from sage.modules.free_module_element import vector
from sage.all import ZZ
[evals,mults],evecs=self.transpose()._maxima_(maxima).eigenvectors()._sage_()
result=[]
for e,evec,m in zip(evals,evecs,mults):
result.append((e,[vector(v) for v in evec], ZZ(m)))
return result
def eigenvectors_right(self):
r"""
Compute the right eigenvectors of a matrix.
For each distinct eigenvalue, returns a list of the form (e,V,n)
where e is the eigenvalue, V is a list of eigenvectors forming a
basis for the corresponding right eigenspace, and n is the
algebraic multiplicity of the eigenvalue.
EXAMPLES::
sage: A = matrix(SR,2,2,range(4)); A
[0 1]
[2 3]
sage: right = A.eigenvectors_right(); right
[(-1/2*sqrt(17) + 3/2, [(1, -1/2*sqrt(17) + 3/2)], 1), (1/2*sqrt(17) + 3/2, [(1, 1/2*sqrt(17) + 3/2)], 1)]
The right eigenvectors are nothing but the left eigenvectors of the
transpose matrix::
sage: left = A.transpose().eigenvectors_left(); left
[(-1/2*sqrt(17) + 3/2, [(1, -1/2*sqrt(17) + 3/2)], 1), (1/2*sqrt(17) + 3/2, [(1, 1/2*sqrt(17) + 3/2)], 1)]
sage: right[0][1] == left[0][1]
True
"""
return self.transpose().eigenvectors_left()
def exp(self):
r"""
Return the matrix exponential of this matrix $X$, which is the matrix
.. math::
e^X = \sum_{k=0}^{\infty} \frac{X^k}{k!}.
This function depends on maxima's matrix exponentiation
function, which does not deal well with floating point
numbers. If the matrix has floating point numbers, they will
be rounded automatically to rational numbers during the
computation.
| Cython |
EXAMPLES::
sage: m = matrix(SR,2, [0,x,x,0]); m
[0 x]
[x 0]
sage: m.exp()
[1/2*(e^(2*x) + 1)*e^(-x) 1/2*(e^(2*x) - 1)*e^(-x)]
[1/2*(e^(2*x) - 1)*e^(-x) 1/2*(e^(2*x) + 1)*e^(-x)]
sage: exp(m)
[1/2*(e^(2*x) + 1)*e^(-x) 1/2*(e^(2*x) - 1)*e^(-x)]
[1/2*(e^(2*x) - 1)*e^(-x) 1/2*(e^(2*x) + 1)*e^(-x)]
Exp works on 0x0 and 1x1 matrices::
sage: m = matrix(SR,0,[]); m
[]
sage: m.exp()
[]
sage: m = matrix(SR,1,[2]); m
[2]
sage: m.exp()
[e^2]
Commuting matrices $m, n$ have the property that
`e^{m+n} = e^m e^n` (but non-commuting matrices need not)::
sage: m = matrix(SR,2,[1..4]); n = m^2
sage: m*n
[ 37 54]
[ 81 118]
sage: n*m
[ 37 54]
[ 81 118]
sage: a = exp(m+n) - exp(m)*exp(n)
sage: a.simplify_rational() == 0
True
The input matrix must be square::
sage: m = matrix(SR,2,3,[1..6]); exp(m)
Traceback (most recent call last):
...
ValueError: exp only defined on square matrices
In this example we take the symbolic answer and make it
numerical at the end::
sage: exp(matrix(SR, [[1.2, 5.6], [3,4]])).change_ring(RDF) # rel tol 1e-15
[ 346.5574872980695 661.7345909344504]
[354.50067371488416 677.4247827652946]
Another example involving the reversed identity matrix, which
we clumsily create::
sage: m = identity_matrix(SR,4); m = matrix(list(reversed(m.rows()))) * x
sage: exp(m)
[1/2*(e^(2*x) + 1)*e^(-x) 0 0 1/2*(e^(2*x) - 1)*e^(-x)]
[ 0 1/2*(e^(2*x) + 1)*e^(-x) 1/2*(e^(2*x) - 1)*e^(-x) 0]
[ 0 1/2*(e^(2*x) - 1)*e^(-x) 1/2*(e^(2*x) + 1)*e^(-x) 0]
[1/2*(e^(2*x) - 1)*e^(-x) 0 0 1/2*(e^(2*x) + 1)*e^(-x)]
"""
if not self.is_square():
raise ValueError("exp only defined on square matrices")
if self.nrows() == 0:
return self
# Maxima's matrixexp function chokes on floating point numbers
# so we automatically convert floats to rationals by passing
# keepfloat: false
m = self._maxima_(maxima)
z = maxima('matrixexp(%s), keepfloat: false'%m.name())
if self.nrows() == 1:
# We do the following, because Maxima stupidly exp's 1x1
# matrices into non-matrices!
z = maxima('matrix([%s])'%z.name())
return z._sage_()
def charpoly(self, var='x', algorithm=None):
"""
Compute the characteristic polynomial of self, using maxima.
EXAMPLES::
sage: M = matrix(SR, 2, 2, var('a,b,c,d'))
sage: M.charpoly('t')
t^2 + (-a - d)*t - b*c + a*d
sage: matrix(SR, 5, [1..5^2]).charpoly()
x^5 - 65*x^4 - 250*x^3
TESTS:
The cached polynomial should be independent of the ``var``
argument (:trac:`12292`). We check (indirectly) that the
second call uses the cached value by noting that its result is
not cached::
sage: M = MatrixSpace(SR, 2)
sage: A = M(range(0, 2^2))
sage: type(A)
<type'sage.matrix.matrix_symbolic_dense.Matrix_symbolic_dense'>
sage: A.charpoly('x')
x^2 - 3*x - 2
sage: A.charpoly('y')
y^2 - 3*y - 2
sage: A._cache['charpoly']
x^2 - 3*x - 2
Ensure the variable name of the polynomial does not conflict
with variables used within the matrix (:trac:`14403`)::
sage: Matrix(SR, [[sqrt(x), x],[1,x]]).charpoly().list()
[x^(3/2) - x, -x - sqrt(x), 1]
Test that :trac:`13711` is fixed::
sage: matrix([[sqrt(2), -1], [pi, e^2]]).charpoly()
x^2 + (-sqrt(2) - e^2)*x + pi + sqrt(2)*e^2
"""
cache_key = 'charpoly'
cp = self.fetch(cache_key)
if cp is not None:
return cp.change_variable_name(var)
from sage.symbolic.ring import SR
# We must not use a variable name already present in the matrix
vname = 'do_not_use_this_name_in_a_matrix_youll_compute_a_charpoly_of'
vsym = SR(vname)
cp = self._maxima_(maxima).charpoly(vname)._sage_().expand()
cp = [cp.coefficient(vsym, i) for i in range(self.nrows() + 1)]
cp = SR[var](cp)
# Maxima has the definition det(matrix-xI) instead of
# det(xI-matrix), which is what Sage uses elsewhere. We
# correct for the discrepancy.
if self.nrows() % 2 == 1:
cp = -cp
self.cache(cache_key, cp)
return cp
def minpoly(self, var='x'):
"""
Return the minimal polynomial of ``self``.
EXAMPLES::
sage: M = Matrix.identity(SR, 2)
sage: M.minpoly()
x - 1
sage: t = var('t')
sage: m = matrix(2, [1, 2, 4, t])
sage: m.minimal_polynomial()
x^2 + (-t - 1)*x + t - 8
TESTS:
Check that the variable `x` can occur in the matrix::
sage: m = matrix([[x]])
sage: m.minimal_polynomial('y')
y - x
"""
mp = self.fetch('minpoly')
if mp is None:
mp = self._maxima_lib_().jordan().minimalPoly().expand()
d = mp.hipow('x')
mp = [mp.coeff('x', i) for i in xrange(0, d + 1)]
mp = PolynomialRing(self.base_ring(), 'x')(mp)
self.cache('minpoly', mp)
return mp.change_variable_name(var)
def fcp(self, var='x'):
"""
Return the factorization of the characteristic polynomial of self.
INPUT:
- ``var`` - (default: 'x') name of variable of charpoly
EXAMPLES::
sage: a = matrix(SR,[[1,2],[3,4]])
sage: a.fcp()
x^2 - 5*x - 2
sage: [i for i in a.fcp()]
[(x^2 - 5*x - 2, 1)]
sage: a = matrix(SR,[[1,0],[0,2]])
sage: a.fcp()
(x - 2) * (x - 1)
sage: [i for i in a.fcp()]
[(x - 2, 1), (x - 1, 1)]
sage: a = matrix(SR, 5, [1..5^2])
sage: a.fcp()
(x^2 - 65*x - 250) * x^3
| Cython |
sage: list(a.fcp())
[(x^2 - 65*x - 250, 1), (x, 3)]
"""
from sage.symbolic.ring import SR
sub_dict = {var: SR.var(var)}
return Factorization(self.charpoly(var).subs(**sub_dict).factor_list())
def jordan_form(self, subdivide=True, transformation=False):
"""
Return a Jordan normal form of ``self``.
INPUT:
- ``self`` -- a square matrix
- ``subdivide`` -- boolean (default: ``True``)
- ``transformation`` -- boolean (default: ``False``)
OUTPUT:
If ``transformation`` is ``False``, only a Jordan normal form
(unique up to the ordering of the Jordan blocks) is returned.
Otherwise, a pair ``(J, P)`` is returned, where ``J`` is a
Jordan normal form and ``P`` is an invertible matrix such that
``self`` equals ``P * J * P^(-1)``.
If ``subdivide`` is ``True``, the Jordan blocks in the
returned matrix ``J`` are indicated by a subdivision in
the sense of :meth:`~sage.matrix.matrix2.subdivide`.
EXAMPLES:
We start with some examples of diagonalisable matrices::
sage: a,b,c,d = var('a,b,c,d')
sage: matrix([a]).jordan_form()
[a]
sage: matrix([[a, 0], [1, d]]).jordan_form(subdivide=True)
[d|0]
[-+-]
[0|a]
sage: matrix([[a, 0], [1, d]]).jordan_form(subdivide=False)
[d 0]
[0 a]
sage: matrix([[a, x, x], [0, b, x], [0, 0, c]]).jordan_form()
[c|0|0]
[-+-+-]
[0|b|0]
[-+-+-]
[0|0|a]
In the following examples, we compute Jordan forms of some
non-diagonalisable matrices::
sage: matrix([[a, a], [0, a]]).jordan_form()
[a 1]
[0 a]
sage: matrix([[a, 0, b], [0, c, 0], [0, 0, a]]).jordan_form()
[c|0 0]
[-+---]
[0|a 1]
[0|0 a]
The following examples illustrate the ``transformation`` flag.
Note that symbolic expressions may need to be simplified to
make consistency checks succeed::
sage: A = matrix([[x - a*c, a^2], [-c^2, x + a*c]])
sage: J, P = A.jordan_form(transformation=True)
sage: J, P
(
[x 1] [-a*c 1]
[0 x], [-c^2 0]
)
sage: A1 = P * J * ~P; A1
[ -a*c + x (a*c - x)*a/c + a*x/c]
[ -c^2 a*c + x]
sage: A1.simplify_rational() == A
True
sage: B = matrix([[a, b, c], [0, a, d], [0, 0, a]])
sage: J, T = B.jordan_form(transformation=True)
sage: J, T
(
[a 1 0] [b*d c 0]
[0 a 1] [ 0 d 0]
[0 0 a], [ 0 0 1]
)
sage: (B * T).simplify_rational() == T * J
True
Finally, some examples involving square roots::
sage: matrix([[a, -b], [b, a]]).jordan_form()
[a - I*b| 0]
[-------+-------]
[ 0|a + I*b]
sage: matrix([[a, b], [c, d]]).jordan_form(subdivide=False)
[1/2*a + 1/2*d - 1/2*sqrt(a^2 + 4*b*c - 2*a*d + d^2) 0]
[ 0 1/2*a + 1/2*d + 1/2*sqrt(a^2 + 4*b*c - 2*a*d + d^2)]
"""
A = self._maxima_lib_()
jordan_info = A.jordan()
J = jordan_info.dispJordan()._sage_()
if subdivide:
v = [x[1] for x in jordan_info]
w = [sum(v[0:i]) for i in xrange(1, len(v))]
J.subdivide(w, w)
if transformation:
P = A.diag_mode_matrix(jordan_info)._sage_()
return J, P
else:
return J
def simplify(self):
"""
Simplifies self.
EXAMPLES::
sage: var('x,y,z')
(x, y, z)
sage: m = matrix([[z, (x+y)/(x+y)], [x^2, y^2+2]]); m
[ z 1]
[ x^2 y^2 + 2]
sage: m.simplify()
[ z 1]
[ x^2 y^2 + 2]
"""
return self.parent()([x.simplify() for x in self.list()])
def simplify_trig(self):
"""
EXAMPLES::
sage: theta = var('theta')
sage: M = matrix(SR, 2, 2, [cos(theta), sin(theta), -sin(theta), cos(theta)])
sage: ~M
[1/cos(theta) - sin(theta)^2/((sin(theta)^2/cos(theta) + cos(theta))*cos(theta)^2) -sin(theta)/((sin(theta)^2/cos(theta) + cos(theta))*cos(theta))]
[ sin(theta)/((sin(theta)^2/cos(theta) + cos(theta))*cos(theta)) 1/(sin(theta)^2/cos(theta) + cos(theta))]
sage: (~M).simplify_trig()
[ cos(theta) -sin(theta)]
[ sin(theta) cos(theta)]
"""
return self._maxima_(maxima).trigexpand().trigsimp()._sage_()
def simplify_rational(self):
"""
EXAMPLES::
sage: M = matrix(SR, 3, 3, range(9)) - var('t')
sage: (~M*M)[0,0]
t*(3*(2/t + (6/t + 7)/((t - 3/t - 4)*t))*(2/t + (6/t + 5)/((t - 3/t
- 4)*t))/(t - (6/t + 7)*(6/t + 5)/(t - 3/t - 4) - 12/t - 8) + 1/t +
3/((t - 3/t - 4)*t^2)) - 6*(2/t + (6/t + 5)/((t - 3/t - 4)*t))/(t -
(6/t + 7)*(6/t + 5)/(t - 3/t - 4) - 12/t - 8) - 3*(6/t + 7)*(2/t +
(6/t + 5)/((t - 3/t - 4)*t))/((t - (6/t + 7)*(6/t + 5)/(t - 3/t -
4) - 12/t - 8)*(t - 3/t - 4)) - 3/((t - 3/t - 4)*t)
sage: expand((~M*M)[0,0])
1
sage: (~M * M).simplify_rational()
[1 0 0]
[0 1 0]
[0 0 1]
"""
return self._maxima_(maxima).fullratsimp()._sage_()
def simplify_full(self):
"""
Simplify a symbolic matrix by calling
:meth:`Expression.simplify_full()` componentwise.
INPUT:
- ``self`` - The matrix whose entries we should simplify.
OUTPUT:
A copy of ``self`` with all of its entries simplified.
EXAMPLES:
Symbolic matrices will have their entries simplified::
sage: a,n,k = SR.var('a,n,k')
sage: f1 = sin(x)^2 + cos(x)^2
sage: f2 = sin(x/(x^2 + x))
sage: f3 = binomial(n,k)*factorial(k)*factorial(n-k)
sage: f4 = x*sin(2)/(x^a)
sage: A = matrix(SR, [[f1,f2],[f3,f4]])
sage: A.simplify_full()
[ 1 sin(1/(x + 1))]
[ | Cython |
factorial(n) x^(-a + 1)*sin(2)]
"""
M = self.parent()
return M([expr.simplify_full() for expr in self])
def canonicalize_radical(self):
r"""
Choose a canonical branch of each entrie of ``self`` by calling
:meth:`Expression.canonicalize_radical()` componentwise.
EXAMPLES::
sage: var('x','y')
(x, y)
sage: l1 = [sqrt(2)*sqrt(3)*sqrt(6), log(x*y)]
sage: l2 = [sin(x/(x^2 + x)), 1]
sage: m = matrix([l1, l2])
sage: m
[sqrt(6)*sqrt(3)*sqrt(2) log(x*y)]
[ sin(x/(x^2 + x)) 1]
sage: m.canonicalize_radical()
[ 6 log(x) + log(y)]
[ sin(1/(x + 1)) 1]
"""
M = self.parent()
return M([expr.canonicalize_radical() for expr in self])
def factor(self):
"""
Operates point-wise on each element.
EXAMPLES::
sage: M = matrix(SR, 2, 2, x^2 - 2*x + 1); M
[x^2 - 2*x + 1 0]
[ 0 x^2 - 2*x + 1]
sage: M.factor()
[(x - 1)^2 0]
[ 0 (x - 1)^2]
"""
return self._maxima_(maxima).factor()._sage_()
def expand(self):
"""
Operates point-wise on each element.
EXAMPLES::
sage: M = matrix(2, 2, range(4)) - var('x')
sage: M*M
[ x^2 + 2 -2*x + 3]
[ -4*x + 6 (x - 3)^2 + 2]
sage: (M*M).expand()
[ x^2 + 2 -2*x + 3]
[ -4*x + 6 x^2 - 6*x + 11]
"""
from sage.misc.misc import attrcall
return self.apply_map(attrcall('expand'))
def variables(self):
"""
Returns the variables of self.
EXAMPLES::
sage: var('a,b,c,x,y')
(a, b, c, x, y)
sage: m = matrix([[x, x+2], [x^2, x^2+2]]); m
[ x x + 2]
[ x^2 x^2 + 2]
sage: m.variables()
(x,)
sage: m = matrix([[a, b+c], [x^2, y^2+2]]); m
[ a b + c]
[ x^2 y^2 + 2]
sage: m.variables()
(a, b, c, x, y)
"""
vars = set(sum([op.variables() for op in self.list()], ()))
return tuple(sorted(vars, key=repr))
def arguments(self):
"""
Returns a tuple of the arguments that self can take.
EXAMPLES::
sage: var('x,y,z')
(x, y, z)
sage: M = MatrixSpace(SR,2,2)
sage: M(x).arguments()
(x,)
sage: M(x+sin(x)).arguments()
(x,)
"""
return self.variables()
def number_of_arguments(self):
"""
Returns the number of arguments that self can take.
EXAMPLES::
sage: var('a,b,c,x,y')
(a, b, c, x, y)
sage: m = matrix([[a, (x+y)/(x+y)], [x^2, y^2+2]]); m
[ a 1]
[ x^2 y^2 + 2]
sage: m.number_of_arguments()
3
"""
return len(self.variables())
def __call__(self, *args, **kwargs):
"""
EXAMPLES::
sage: var('x,y,z')
(x, y, z)
sage: M = MatrixSpace(SR,2,2)
sage: h = M(sin(x)+cos(x))
sage: h
[cos(x) + sin(x) 0]
[ 0 cos(x) + sin(x)]
sage: h(x=1)
[cos(1) + sin(1) 0]
[ 0 cos(1) + sin(1)]
sage: h(x=x)
[cos(x) + sin(x) 0]
[ 0 cos(x) + sin(x)]
sage: h = M((sin(x)+cos(x)).function(x))
sage: h
[cos(x) + sin(x) 0]
[ 0 cos(x) + sin(x)]
sage: h(1)
doctest:...: DeprecationWarning: Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...)
See http://trac.sagemath.org/4513 for details.
doctest:...: DeprecationWarning: Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...)
See http://trac.sagemath.org/5930 for details.
[cos(1) + sin(1) 0]
[ 0 cos(1) + sin(1)]
sage: h(x)
[cos(x) + sin(x) 0]
[ 0 cos(x) + sin(x)]
sage: f = M([0,x,y,z]); f
[0 x]
[y z]
sage: f.arguments()
(x, y, z)
sage: f()
[0 x]
[y z]
sage: f(1)
[0 1]
[y z]
sage: f(1,2)
[0 1]
[2 z]
sage: f(1,2,3)
[0 1]
[2 3]
sage: f(x=1)
[0 1]
[y z]
sage: f(x=1,y=2)
[0 1]
[2 z]
sage: f(x=1,y=2,z=3)
[0 1]
[2 3]
sage: f({x:1,y:2,z:3})
[0 1]
[2 3]
sage: f(1, x=2)
Traceback (most recent call last):
...
ValueError: args and kwargs cannot both be specified
sage: f(1,2,3,4)
Traceback (most recent call last):
...
ValueError: the number of arguments must be less than or equal to 3
"""
if kwargs and args:
raise ValueError("args and kwargs cannot both be specified")
if len(args) == 1 and isinstance(args[0], dict):
kwargs = dict([(repr(x[0]), x[1]) for x in args[0].iteritems()])
if kwargs:
#Handle the case where kwargs are specified
new_entries = []
for entry in self.list():
try:
new_entries.append( entry(**kwargs) )
except ValueError:
new_entries.append(entry)
else:
#Handle the case where args are specified
if args:
from sage.misc.superseded import deprecation
deprecation(4513, "Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...)")
#Get all the variables
variables = list( self.arguments() )
if len(args) > self.number_of_arguments():
raise ValueError("the number of arguments must be less than or equal to %s" % self.number_of_arguments())
new_entries = []
for entry in self.list():
try:
entry_vars = entry.variables()
if len(entry_vars) == 0:
if len(args)!= 0:
new_entries.append( entry(args[0]) )
else:
new_entries.append( entry )
continue
else:
indices = [i for i in map(variables.index, entry_vars) if i < len(args)]
if len(indices) == 0:
new_entries.append( entry )
else:
new_entries.append( entry(*[args[i] for i in indices]) )
except ValueError:
new_entries.append( entry )
return self.parent(new_entries)
<|end_of_text|>
ctypes_struct_cache = []
def partition_array(array, dim):
chunks = lambda l, n: [l[i:i + n] for i in range(0, len(l), n)]
sol | Cython |
= chunks(array, dim[len(dim) - 1])
dim.pop()
while dim:
sol = chunks(sol, dim[len(dim) - 1])
dim.pop()
return sol[0]
def dereference(py_ptr, **kwargs):
''' Function for casting python object of one type, to another (supported type)
Args:
obj_to_cast: Python object which will be casted into some other type
type: type in which object will be casted
return_count: if it's a pointer with multiple values, indicate the size of the array
Returns:
Casted Python object
Note:
All types aren't implemented!
'''
if py_ptr is None:
return None
cdef unsigned long long *c_addr
cdef void *struct_res_ptr = NULL
if isinstance(py_ptr, ObjcReferenceToType):
c_addr = <unsigned long long*><unsigned long long>py_ptr.arg_ref
else:
c_addr = <unsigned long long*><unsigned long long>py_ptr
if 'of_type' in kwargs:
of_type = kwargs['of_type']
if issubclass(of_type, ctypes.Structure) or issubclass(of_type, ctypes.Union):
return ctypes.cast(<unsigned long long>c_addr, ctypes.POINTER(of_type)).contents
elif issubclass(of_type, ObjcClassInstance):
return convert_to_cy_cls_instance(<id>c_addr)
elif issubclass(of_type, CArray) and "return_count" in kwargs:
dprint("Returning CArray from c_addr, size={0}, type={1}".format(kwargs['return_count'], py_ptr.of_type))
dprint("{}".format(str(py_ptr.of_type)))
return_count = kwargs["return_count"]
if isinstance(return_count, ctypes._SimpleCData):
return_count = return_count.value
return CArray().get_from_ptr(py_ptr.arg_ref, py_ptr.of_type, return_count)
elif issubclass(of_type, CArray) and "partition" in kwargs:
partitions = kwargs["partition"]
total_count = partitions[0]
for i in xrange(1, len(partitions)):
total_count *= int(partitions[i])
dprint("Total count for {} is {}".format(partitions, total_count))
array = CArray().get_from_ptr(py_ptr.arg_ref, py_ptr.of_type, total_count)
return partition_array(array, partitions)
elif issubclass(of_type, CArray):
# search for return count in ObjcReferenceToType object
dprint("Returning CArray, calculating returned value by'reference'")
for item in py_ptr.reference_return_values:
if type(item) == CArrayCount:
dprint("CArray().get_from_ptr({0}, {1}, {2})".format(py_ptr.arg_ref, py_ptr.of_type, item.value))
return CArray().get_from_ptr(py_ptr.arg_ref, py_ptr.of_type, item.value)
py_ptr.of_type = of_type.enc
# TODO: other types
# elif issubclass(type, MissingTypes....):
# pass
return convert_cy_ret_to_py(<id*>c_addr, py_ptr.of_type, py_ptr.size)
cdef void* cast_to_cy_data_type(id *py_obj, size_t size, char* of_type, by_value=True, py_val=None):
''' Function for casting Python data type (struct, union) to some Cython type
Args:
py_obj: address of Python data type which need to be converted to Cython data type
size: size in bypes of data type
type: string containing name of data type
by_value: boolean value, indicate wheather we need pass data type by value or by reference
Returns:
void* to eqvivalent Cython data type
'''
cdef void *val_ptr = malloc(size)
cdef CGRect rect
cdef CGRect *rect_ptr
cdef CGSize sz
cdef CGPoint point
cdef bytes b_of_type = <bytes>of_type
dprint("of_type={!r} {!r}".format(str(of_type), of_type))
if b_of_type == b'_NSRange':
if by_value:
(<CFRange*>val_ptr)[0] = (<CFRange*>py_obj)[0]
else:
(<CFRange**>val_ptr)[0] = <CFRange*>py_obj
elif b_of_type == b'CGPoint':
if by_value:
(<CGPoint*>val_ptr)[0] = (<CGPoint*>py_obj)[0]
else:
(<CGPoint**>val_ptr)[0] = <CGPoint*>py_obj
elif b_of_type == b'CGSize':
if by_value:
(<CGSize*>val_ptr)[0] = (<CGSize*>py_obj)[0]
else:
(<CGSize**>val_ptr)[0] = <CGSize*>py_obj
elif b_of_type == b'CGRect':
IF PLATFORM == 'darwin':
if by_value:
(<CGRect*>val_ptr)[0] = (<CGRect*>py_obj)[0]
else:
(<CGRect**>val_ptr)[0] = <CGRect*>py_obj
ELIF PLATFORM == 'ios':
if py_val:
point.x = py_val.origin.x
point.y = py_val.origin.y
sz.width = py_val.size.width
sz.height = py_val.size.height
if by_value and py_val:
rect.origin = point
rect.size = sz
(<CGRect*>val_ptr)[0] = rect
# TODO: find appropriate method and test these cases on iOS
elif not by_value and py_val:
rect_ptr = <CGRect*>malloc(sizeof(CGRect))
rect_ptr.origin = point
rect_ptr.size = sz
(<CGRect**>val_ptr)[0] = rect_ptr
elif not by_value and not py_val:
(<CGRect**>val_ptr)[0] = <CGRect*>py_obj
else:
if by_value:
(<id*>val_ptr)[0] = (<id*>py_obj)[0]
else:
(<id**>val_ptr)[0] = (<id*>py_obj)
dprint("Possible problems with casting, in pyobjus_conversionx.pxi", of_type='w')
return val_ptr
cdef convert_to_cy_cls_instance(id ret_id, main_cls_name=None):
''' Function for converting C pointer into Cython ObjcClassInstance type
Args:
ret_id: C pointer
Returns:
ObjcClassInstance type
'''
dprint("convert_to_cy_cls_instance: {0}".format(pr(ret_id)))
cdef ObjcClassInstance cret
bret = <bytes><char *>object_getClassName(ret_id)
dprint(' - object_getClassName(f_result) =', bret)
if bret == b'nil':
dprint('<-- returned pointer value:', pr(ret_id), of_type="w")
return None
load_instance_methods = None
if bret in omethod_partial_register:
key = bret
else:
key = main_cls_name
if key in omethod_partial_register:
load_instance_methods = omethod_partial_register[key]
omethod_partial_register[bret] = load_instance_methods
cret = autoclass(bret, new_instance=True, load_instance_methods=load_instance_methods)(noinstance=True)
cret.instanciate_from(ret_id)
dprint('<-- return object', cret)
return cret
cdef object convert_cy_ret_to_py(id *f_result, sig, size_t size, members=None, objc_prop=False, main_cls_name=None):
cdef CGRect rect
if f_result is NULL:
dprint('null pointer in convert_cy_ret_to_py function', of_type='w')
return None
if sig.startswith((b'(', b'{')):
return_type = sig[1:-1].split(b'=', 1)
elif sig == b'c':
# this should be a char. Most of the time, a BOOL is also
# implemented as a char. So it's not a string, but just the numeric
# value of the char.
if <int>f_result[0] in [1, 0]:
return ctypes.c_bool(<int>f_result[0]).value
return chr(<int><char>f_result[0])
elif sig == b'i':
return (<int>f_result[0])
elif sig == b's':
return (<short>f_result[0])
elif sig == b'l':
return (<long>f_result[0])
elif sig == b'q':
return (<long long>f_result[0])
elif sig == b'C':
return (<unsigned char>f_result[0])
elif sig == b'I':
return (<unsigned int>f_result[0])
elif sig == b'S':
return (<unsigned short>f_result[0])
elif sig == b'L':
return (<unsigned long>f_result[0])
elif sig == b'Q':
return (<unsigned long long>f_result[0])
elif sig == b'f':
return (<float>ctypes.cast(<unsigned long long>f_result, ctypes.POINTER(ctypes.c_float)).contents.value)
elif sig == b'd':
return (<double>ctypes.cast(<unsigned long long>f_result, ctypes.POINTER(ctypes.c_double)).contents.value)
elif sig == b'B':
if <int | Cython |
>f_result[0]:
return True
return False
elif sig == b'v':
return None
elif sig == b'*':
if f_result[0] is not NULL:
return <bytes>(<char*>f_result[0])
else:
return None
# return type -> id
if sig == b'@':
return convert_to_cy_cls_instance(<id>f_result[0], main_cls_name)
# return type -> class
elif sig == b'#':
ocls = ObjcClass()
ocls.o_cls = <Class>object_getClass(<id>f_result[0])
return ocls
# return type -> selector
elif sig == b':':
osel = ObjcSelector()
osel.selector = <SEL>f_result[0]
return osel
elif sig.startswith(b'['):
# array
pass
# return type -> struct OR union
elif sig.startswith((b'(', b'{')):
#NOTE: This need to be tested more! Does this way work in all cases? TODO: Find better solution for this!
if <unsigned long long>f_result[0] in ctypes_struct_cache:
val = ctypes.cast(<unsigned long long>f_result[0], ctypes.POINTER(factory.find_object(return_type, members=members))).contents
else:
if return_type[0]!= b'CGRect' or dev_platform == 'darwin':
val = ctypes.cast(<unsigned long long>f_result, ctypes.POINTER(factory.find_object(return_type, members=members))).contents
else:
# NOTE: this is hardcoded case for CGRect on iOS
# For some reason CGRect with ctypes don't work as it should work on arm
rect = (<CGRect*>f_result)[0]
val = NSRect()
val.size = NSSize(rect.size.width, rect.size.height)
val.origin = NSPoint(rect.origin.x, rect.origin.y)
factory.empty_cache()
return val
# TODO: return type -> bit field
elif sig == b'b':
raise ObjcException("Bit fields aren't supported in pyobjus!")
# return type --> pointer to type
elif sig.startswith(b'^'):
if objc_prop:
c_addr = <unsigned long long>f_result
else:
c_addr = <unsigned long long>f_result[0]
return ObjcReferenceToType(c_addr, sig[1:], size)
# return type --> unknown type
elif sig == b'?':
# TODO: Check is this possible at all?
dprint('Returning unknown type by value...')
assert(0)
else:
assert(0)
cdef char convert_py_bool_to_objc(arg):
''' Function for converting python bool value (True, False, 0, 1) to objc BOOL type (YES, NO)
Args:
arg: argument to convert to objc equivalent bool value
Returns:
Returns objective c boolean value (YES or NO)
'''
if arg == True or arg == 1:
return YES
return NO
def remove_dimensions(array):
""" Function for flattening multidimensional list to one dimensional """
result = list()
if isinstance(array, list):
for item in array:
result.extend(remove_dimensions(item))
else:
result.append(array)
return result
cdef void *parse_array(sig, arg, size, multidimension=False):
cdef void *val_ptr = malloc(size)
sig = sig[1:len(sig) - 1]
sig_split = re.split(b'(\d+)', sig)
array_size = int(sig_split[1])
array_type = sig_split[2]
dprint("..[+] parse_array(array_type={}, array_size={}, {}, {})".format(
array_type, array_size, arg, size))
if array_size!= len(arg) and not multidimension:
dprint("DyLib is accepting array of size {0}, but you are forwarding {1} args.".format(
array_size, len(arg)))
raise TypeError()
elif array_type == b"i":
dprint(" [+]...array is integer!")
(<int **>val_ptr)[0] = CArray(arg).as_int()
elif array_type == b"c":
dprint(" [+]...array is char!")
(<char **>val_ptr)[0] = CArray(arg).as_char()
elif array_type == b"s":
dprint(" [+]...array is short")
(<short **>val_ptr)[0] = CArray(arg).as_short()
elif array_type == b"l":
dprint(" [+]...array is long")
(<long **>val_ptr)[0] = CArray(arg).as_long()
elif array_type == b"q":
dprint(" [+]...array is long long")
(<long long**>val_ptr)[0] = CArray(arg).as_longlong()
elif array_type == b"f":
dprint(" [+]...array is float")
(<float**>val_ptr)[0] = CArray(arg).as_float()
elif array_type == b"d":
dprint(" [+]...array is double")
(<double**>val_ptr)[0] = CArray(arg).as_double()
elif array_type == b"I":
dprint(" [+]...array is unsigned int")
(<unsigned int**>val_ptr)[0] = CArray(arg).as_uint()
elif array_type == b"S":
dprint(" [+]...array is unsigned short")
(<unsigned short**>val_ptr)[0] = CArray(arg).as_ushort()
elif array_type == b"L":
dprint(" [+]...array is unsigned long")
(<unsigned long**>val_ptr)[0] = CArray(arg).as_ulong()
elif array_type == b"Q":
dprint(" [+]...array is unsigned long long")
(<unsigned long long**>val_ptr)[0] = CArray(arg).as_ulonglong()
elif array_type == b"C":
dprint(" [+]...array is unsigned char")
(<unsigned char**>val_ptr)[0] = CArray(arg).as_uchar()
elif array_type == b"B":
dprint(" [+]...array is bool")
(<bool**>val_ptr)[0] = CArray(arg).as_bool()
elif array_type == b"*":
dprint(" [+]...array is char*")
(<char***>val_ptr)[0] = CArray(arg).as_char_ptr()
elif array_type == b"@":
dprint(" [+]...array is object(@)")
(<id**>val_ptr)[0] = CArray(arg).as_object_array()
elif array_type == b"#":
dprint(" [+]...array is class(#)")
(<Class**>val_ptr)[0] = CArray(arg).as_class_array()
elif array_type == b":":
dprint(" [+]...array is sel(:)")
(<SEL**>val_ptr)[0] = CArray(arg).as_sel_array()
elif array_type.startswith(b"["):
dprint(" [+]...array is array({})".format(sig))
parse_position = sig.find(b"[")
depth = int(sig[0:parse_position])
sig = sig[parse_position:]
dprint("Entering recursion for signature {}".format(sig))
return parse_array(sig, remove_dimensions(arg), size, multidimension=True)
elif array_type.startswith((b"{", b"(")):
arg_type = array_type[1:-1].split(b'=', 1)
dprint(" [+]...array is struct: {}".format(arg_type))
(<id**>val_ptr)[0] = CArray(arg).as_struct_array(size, arg_type)
elif array_type == b"b":
pass
elif array_type == b"^":
pass
elif array_type == b"?":
pass
return val_ptr
cdef extern from "objc/objc.h":
cdef id *nil
cpdef object convert_py_to_nsobject(arg):
if arg is None or isinstance(arg, ObjcClassInstance):
return arg
elif arg in (True, False):
return autoclass('NSNumber').alloc().initWithBool_(int(arg))
elif isinstance(arg, (str, unicode)):
return autoclass('NSString').alloc().initWithUTF8String_(arg)
elif isinstance(arg, long):
return autoclass('NSNumber').alloc().initWithInt_(arg)
elif isinstance(arg, int):
return autoclass('NSNumber').alloc().initWithLong_(arg)
elif isinstance(arg, float):
return autoclass('NSNumber').alloc().initWithFloat_(arg)
elif isinstance(arg, list):
args = arg + [None]
return autoclass('NSArray').alloc().initWithObjects_(*args)
elif isinstance(arg, dict):
items = []
for key, value in arg.items():
items.append(key)
items.append(value)
items.append(None)
return autoclass('NSDictionary').alloc().initWithObjectsAndKeys_(*items)
# maybe it's a delegate?
dprint('construct a delegate!')
d = objc_create_delegate(arg)
dprint('delegate is', d)
return d
cdef void* convert_py_arg_to_cy(arg, sig, by_value, size_t size) except *:
''' Function for converting Python argument to | Cython |
Cython, by given method signature
Args:
arg: argument to convert
sig: method signature
by_value: True or False, are we passing argument by value or by reference
size: size of argument in memory
Returns:
Pointer (void*) to converted Cython object
'''
cdef void *val_ptr = malloc(size)
cdef void *arg_val_ptr = NULL
cdef object del_arg_val_ptr = False
cdef object objc_ref = False
dprint(
"convert_py_arg_to_cy arg={!r} sig={!r} by_value={!r} size={!r}".format(
arg, sig, by_value, size))
if by_value:
bytype = 'value'
else:
if type(arg) is ObjcReferenceToType:
arg_val_ptr = <unsigned long long*><unsigned long long>arg.arg_ref
objc_ref = True
elif isinstance(arg, ctypes._SimpleCData):
arg_val_ptr = <unsigned long long*><unsigned long long>(
ctypes.addressof(arg))
objc_ref = True
elif not isinstance(arg, ctypes.Structure):
arg_val_ptr = malloc(size)
del_arg_val_ptr = True
bytype ='reference'
dprint("passing argument {} by {} (sig={})".format(
arg, bytype, sig), of_type='i')
# method is accepting char (or BOOL, which is also interpreted as char)
if sig == b'c':
if by_value:
if arg in [True, False, 1, 0]:
(<char*>val_ptr)[0] = convert_py_bool_to_objc(arg)
else:
(<char*>val_ptr)[0] = <char>ord(arg)
else:
if not objc_ref:
if arg in [True, False, 1, 0]:
(<char*>arg_val_ptr)[0] = convert_py_bool_to_objc(arg)
else:
(<char*>arg_val_ptr)[0] = <char>bytes(arg)
(<char**>val_ptr)[0] = <char*>arg_val_ptr
# method is accepting int
elif sig == b'i':
if by_value:
(<int*>val_ptr)[0] = <int> int(arg)
else:
if not objc_ref:
(<int*>arg_val_ptr)[0] = <int>int(arg)
(<int**>val_ptr)[0] = <int*>arg_val_ptr
# method is accepting short
elif sig == b's':
if by_value:
(<short*>val_ptr)[0] = <short> int(arg)
else:
if not objc_ref:
(<short*>arg_val_ptr)[0] = <short>int(arg)
(<short**>val_ptr)[0] = <short*>arg_val_ptr
# method is accepting long
elif sig == b'l':
if by_value:
(<long*>val_ptr)[0] = <long>long(arg)
else:
if not objc_ref:
(<long*>arg_val_ptr)[0] = <long>long(arg)
(<long**>val_ptr)[0] = <long*>arg_val_ptr
# method is accepting long long
elif sig == b'q':
if by_value:
(<long long*>val_ptr)[0] = <long long>ctypes.c_longlong(arg).value
else:
if not objc_ref:
(<long long*>arg_val_ptr)[0] = <long long>ctypes.c_ulonglong(arg).value
(<long long**>val_ptr)[0] = <long long*>arg_val_ptr
# method is accepting unsigned char
elif sig == b'C':
(<unsigned char*>val_ptr)[0] = <unsigned char>arg
# method is accepting unsigned integer
elif sig == b'I':
if by_value:
(<unsigned int*>val_ptr)[0] = <unsigned int>ctypes.c_uint32(arg).value
else:
if not objc_ref:
(<unsigned int*>arg_val_ptr)[0] = <unsigned int>ctypes.c_uint32(arg).value
(<unsigned int**>val_ptr)[0] = <unsigned int*>arg_val_ptr
# method is accepting unsigned short
elif sig == b'S':
if by_value:
(<unsigned short*>val_ptr)[0] = <unsigned short>ctypes.c_ushort(arg).value
else:
if not objc_ref:
(<unsigned short*>arg_val_ptr)[0] = <unsigned short>ctypes.c_ushort(arg).value
(<unsigned short**>val_ptr)[0] = <unsigned short*>arg_val_ptr
# method is accepting unsigned long
elif sig == b'L':
if by_value:
(<unsigned long*>val_ptr)[0] = <unsigned long>ctypes.c_ulong(arg).value
else:
if not objc_ref:
(<unsigned long*>arg_val_ptr)[0] = <unsigned long>ctypes.c_ulong(arg).value
(<unsigned long**>val_ptr)[0] = <unsigned long*>arg_val_ptr
# method is accepting unsigned long long
elif sig == b'Q':
if by_value:
(<unsigned long long*>val_ptr)[0] = <unsigned long long>ctypes.c_ulonglong(arg).value
else:
if not objc_ref:
(<unsigned long long*>arg_val_ptr)[0] = <unsigned long long>ctypes.c_ulonglong(arg).value
(<unsigned long long**>val_ptr)[0] = <unsigned long long*>arg_val_ptr
# method is accepting float
elif sig == b'f':
if by_value:
(<float*>val_ptr)[0] = <float>float(arg)
else:
if not objc_ref:
(<float*>arg_val_ptr)[0] = <float>float(arg)
(<float**>val_ptr)[0] = <float*>arg_val_ptr
# method is accepting double
elif sig == b'd':
if by_value:
(<double*>val_ptr)[0] = <double>ctypes.c_double(arg).value
else:
if not objc_ref:
(<double*>arg_val_ptr)[0] = <double>ctypes.c_double(arg).value
(<double**>val_ptr)[0] = <double*>arg_val_ptr
# method is accepting bool
elif sig == b'B':
if by_value:
(<bool*>val_ptr)[0] = <bool>ctypes.c_bool(arg).value
else:
if not objc_ref:
(<bool*>arg_val_ptr)[0] = <bool>ctypes.c_bool(arg).value
(<bool**>val_ptr)[0] = <bool*>arg_val_ptr
# method is accepting character string (char *)
elif sig == b'*':
if isinstance(arg, bytes):
b_arg = arg
else:
b_arg = <bytes>arg.encode("utf8")
# FIXME clear leaks here, must found a way to fix it.
Py_INCREF(b_arg)
(<char **>val_ptr)[0] = <char *>b_arg
# method is accepting an object
elif sig == b'@':
dprint('====> ARG', <ObjcClassInstance>arg)
arg = convert_py_to_nsobject(arg)
if arg == None:
(<id*>val_ptr)[0] = <id>NULL
else:
ocl = <ObjcClassInstance>arg
(<id*>val_ptr)[0] = <id>ocl.o_instance
# method is accepting class
elif sig == b'#':
if by_value:
dprint('==> Class arg', <ObjcClass>arg)
ocls = <ObjcClass>arg
(<Class*>val_ptr)[0] = <Class>ocls.o_cls
else:
if not objc_ref:
ocls = <ObjcClass>arg
(<Class*>arg_val_ptr)[0] = <Class>ocls.o_cls
(<Class**>val_ptr)[0] = <Class*>arg_val_ptr
# method is accepting selector
elif sig == b":":
if by_value:
dprint("==> Selector arg", <ObjcSelector>arg)
osel = <ObjcSelector>arg
(<SEL*>val_ptr)[0] = <SEL>osel.selector
else:
if not objc_ref:
osel = <ObjcSelector>arg
(<SEL*>arg_val_ptr)[0] = <SEL>osel.selector
(<SEL**>val_ptr)[0] = <SEL*>arg_val_ptr
# TODO: array
elif sig.startswith(b'['):
dprint("==> Array signature for: {0}".format(list(arg)))
val_ptr = parse_array(sig, arg, size)
# method is accepting structure OR union
# NOTE: Support for passing union as arguments by value wasn't supported with libffi,
# in time of writing this version of pyobjus.
# However we can pass union as argument if function accepts pointer to union type
# Return types for union are working (both, returned union is value, or returned union is pointer)
# NOTE: There are no problems with structs, only unions, reason -> libffi
| Cython |
# TODO: ADD SUPPORT FOR PASSING UNIONS AS ARGUMENTS BY VALUE
elif sig.startswith((b'(', b'{')):
dprint("==> Structure arg", arg, sig)
arg_type = sig[1:-1].split(b'=', 1)[0]
if arg is None:
(<void**>val_ptr)[0] = nil
elif by_value:
str_long_ptr = <unsigned long long*><unsigned long long>ctypes.addressof(arg)
ctypes_struct_cache.append(<unsigned long long>str_long_ptr)
val_ptr = cast_to_cy_data_type(<id*>str_long_ptr, size, arg_type, by_value=True, py_val=arg)
else:
if not objc_ref:
str_long_ptr = <unsigned long long*><unsigned long long>ctypes.addressof(arg)
val_ptr = cast_to_cy_data_type(<id*>str_long_ptr, size, arg_type, by_value=False, py_val=arg)
else:
val_ptr = cast_to_cy_data_type(<id*>arg_val_ptr, size, arg_type, by_value=False)
# method is accepting void pointer (void*)
# XXX is the signature changed or never works?
elif sig == b'v':
if isinstance(arg, ctypes.Structure) or isinstance(arg, ctypes.Union):
(<void**>val_ptr)[0] = <void*><unsigned long long>ctypes.addressof(arg)
elif isinstance(arg, ObjcReferenceToType):
(<unsigned long long**>val_ptr)[0] = <unsigned long long*>arg_val_ptr
elif isinstance(arg, ObjcClassInstance):
ocl = <ObjcClassInstance>arg
(<void**>val_ptr)[0] = <void*>ocl.o_instance
elif isinstance(arg, ObjcClass):
ocls = <ObjcClass>arg
(<void**>val_ptr)[0] = <void*>ocls.o_cls
elif isinstance(arg, ObjcSelector):
osel = <ObjcSelector>arg
(<void**>val_ptr)[0] = <void*>osel.selector
# TODO: Add other types..
# elif:
# ARRAY, ETC.
else:
# TODO: Add better conversion between primitive types!
if type(arg) is long:
(<void**>val_ptr)[0] = <void*><unsigned long long>arg
elif type(arg) is str:
# passing bytes as void* is the same as for char*
b_arg = <bytes>arg.encode("utf8")
Py_INCREF(b_arg)
(<char **>val_ptr)[0] = <char *>b_arg
else:
if type(arg) is float:
(<float*>arg_val_ptr)[0] = <float>arg
elif type(arg) is int:
(<int*>arg_val_ptr)[0] = <int>arg
(<void**>val_ptr)[0] = <void*>arg_val_ptr
# TODO: method is accepting bit field
elif sig.startswith(b'b'):
raise ObjcException("Bit fields aren't supported in pyobjus!")
# method is accepting unknown type (^?)
elif sig.startswith(b'?'):
if by_value:
assert(0)
else:
(<void**>val_ptr)[0] = arg_val_ptr
else:
dprint("WARNING: Unknown signature component, passing nil")
(<int*>val_ptr)[0] = 0
# TODO: Find best time to dealloc memory used by this pointer
# if arg_val_ptr!= NULL and del_arg_val_ptr:
# free(arg_val_ptr)
# arg_val_ptr = NULL
return val_ptr
<|end_of_text|># distutils: language = c++
# distutils: sources = mt19937.cpp
from cython.operator cimport dereference as deref
from cpython.array cimport array
cdef extern from "mt19937.h" namespace "mtrandom":
unsigned int N
cdef cppclass MT_RNG:
MT_RNG()
MT_RNG(unsigned long s)
MT_RNG(unsigned long init_key[], int key_length)
void init_genrand(unsigned long s)
unsigned long genrand_int32()
double genrand_real1()
double operator()()
def make_random_list(unsigned long seed, unsigned int len):
cdef list randlist = [0] * len
cdef MT_RNG rng # calls default ctor.
cdef unsigned int i
rng.init_genrand(seed)
for i in range(len):
randlist[i] = rng.genrand_int32()
return randlist
<|end_of_text|># cython: language_level=3
import numpy as np
import torch
import torch.multiprocessing as mp
from MCTS import MCTS
class SelfPlayAgent(mp.Process):
def __init__(self, id, game, ready_queue, batch_ready, batch_tensor, policy_tensor, value_tensor, output_queue,
result_queue, complete_count, games_played, args):
super().__init__()
self.id = id
self.game = game
self.ready_queue = ready_queue
self.batch_ready = batch_ready
self.batch_tensor = batch_tensor
self.batch_size = self.batch_tensor.shape[0]
self.policy_tensor = policy_tensor
self.value_tensor = value_tensor
self.output_queue = output_queue
self.result_queue = result_queue
self.games = []
self.canonical = []
self.histories = []
self.player = []
self.turn = []
self.mcts = []
self.games_played = games_played
self.complete_count = complete_count
self.args = args
self.valid = torch.zeros_like(self.policy_tensor)
self.fast = False
for _ in range(self.batch_size):
self.games.append(self.game.getInitBoard())
self.histories.append([])
self.player.append(1)
self.turn.append(1)
self.mcts.append(MCTS(self.game, None, self.args))
self.canonical.append(None)
def run(self):
np.random.seed()
while self.games_played.value < self.args.gamesPerIteration:
self.generateCanonical()
self.fast = np.random.random_sample() < self.args.probFastSim
if self.fast:
for i in range(self.args.numFastSims):
self.generateBatch()
self.processBatch()
else:
for i in range(self.args.numMCTSSims):
self.generateBatch()
self.processBatch()
self.playMoves()
with self.complete_count.get_lock():
self.complete_count.value += 1
self.output_queue.close()
self.output_queue.join_thread()
def generateBatch(self):
for i in range(self.batch_size):
board = self.mcts[i].findLeafToProcess(self.canonical[i], True)
if board is not None:
self.batch_tensor[i] = torch.from_numpy(board)
self.ready_queue.put(self.id)
def processBatch(self):
self.batch_ready.wait()
self.batch_ready.clear()
for i in range(self.batch_size):
self.mcts[i].processResults(
self.policy_tensor[i].data.numpy(), self.value_tensor[i][0])
def playMoves(self):
for i in range(self.batch_size):
temp = int(self.turn[i] < self.args.tempThreshold)
policy = self.mcts[i].getExpertProb(
self.canonical[i], temp, not self.fast)
action = np.random.choice(len(policy), p=policy)
if not self.fast:
self.histories[i].append((self.canonical[i], self.mcts[i].getExpertProb(self.canonical[i], prune=True),
self.mcts[i].getExpertValue(self.canonical[i]), self.player[i]))
self.games[i], self.player[i] = self.game.getNextState(
self.games[i], self.player[i], action)
self.turn[i] += 1
winner = self.game.getGameEnded(self.games[i], 1)
if winner!= 0:
self.result_queue.put(winner)
lock = self.games_played.get_lock()
lock.acquire()
if self.games_played.value < self.args.gamesPerIteration:
self.games_played.value += 1
lock.release()
for hist in self.histories[i]:
if self.args.symmetricSamples:
sym = self.game.getSymmetries(hist[0], hist[1])
for b, p in sym:
self.output_queue.put((b, p,
winner *
hist[3] *
(1 - self.args.expertValueWeight.current)
+ self.args.expertValueWeight.current * hist[2]))
else:
self.output_queue.put((hist[0], hist[1],
winner *
hist[3] *
(1 - self.args.expertValueWeight.current)
+ self.args.expertValueWeight.current * hist[2]))
self.games[i] = self.game.getInitBoard()
self.histories[i] = []
self.player[i] = 1
self.turn[i] = 1
self.mcts[i] = MCTS(self.game, None, self.args)
else:
lock.release()
def generateCanonical(self):
for i in range(self.batch_size):
self.canonical[i] = self.game.getCanonicalForm(
self.games[i], self.player[i])
<|end_of_text|>cimport cython
cimport numpy as np
import numpy as np
import ctypes
from ibex.transforms import distance, seg2 | Cython |
seg
from cremi_python.cremi.evaluation.voi import voi
from cremi_python.cremi.evaluation import border_mask
import scipy.sparse as sparse
cdef extern from 'cpp-comparestacks.h':
void CppEvaluate(long *segmentation, long *gold, long resolution[3], unsigned char mask_ground_truth)
def adapted_rand(seg, gt, all_stats=False, dilate_ground_truth=1, filtersize=0):
"""Compute Adapted Rand error as defined by the SNEMI3D contest [1]
Formula is given as 1 - the maximal F-score of the Rand index
(excluding the zero component of the original labels). Adapted
from the SNEMI3D MATLAB script, hence the strange style.
Parameters
----------
seg : np.ndarray
the segmentation to score, where each value is the label at that point
gt : np.ndarray, same shape as seg
the groundtruth to score against, where each value is a label
all_stats : boolean, optional
whether to also return precision and recall as a 3-tuple with rand_error
Returns
-------
are : float
The adapted Rand error; equal to $1 - \frac{2pr}{p + r}$,
where $p$ and $r$ are the precision and recall described below.
prec : float, optional
The adapted Rand precision. (Only returned when `all_stats` is ``True``.)
rec : float, optional
The adapted Rand recall. (Only returned when `all_stats` is ``True``.)
References
----------
[1]: http://brainiac2.mit.edu/SNEMI3D/evaluation
"""
# remove all small connected components
if filtersize > 0:
seg = seg2seg.RemoveSmallConnectedComponents(seg, filtersize)
gt = seg2seg.RemoveSmallConnectedComponents(gt, filtersize)
if dilate_ground_truth > 0:
gt = distance.DilateData(gt, dilate_ground_truth)
# segA is truth, segB is query
segA = np.ravel(gt)
segB = np.ravel(seg)
n = segA.size
n_labels_A = np.amax(segA) + 1
n_labels_B = np.amax(segB) + 1
ones_data = np.ones(n)
p_ij = sparse.csr_matrix((ones_data, (segA[:], segB[:])), shape=(n_labels_A, n_labels_B))
a = p_ij[1:n_labels_A,:]
b = p_ij[1:n_labels_A,1:n_labels_B]
c = p_ij[1:n_labels_A,0].todense()
d = b.multiply(b)
a_i = np.array(a.sum(1))
b_i = np.array(b.sum(0))
sumA = np.sum(a_i * a_i)
sumB = np.sum(b_i * b_i) + (np.sum(c) / n)
sumAB = np.sum(d) + (np.sum(c) / n)
precision = sumAB / sumB
recall = sumAB / sumA
fScore = 2.0 * precision * recall / (precision + recall)
are = 1.0 - fScore
if all_stats:
return (are, precision, recall)
else:
return are
def PrincetonEvaluate(segmentation, gold, dilate_ground_truth=1, mask_ground_truth=True, filtersize=0):
# make sure these elements are the same size
assert (segmentation.shape == gold.shape)
assert (np.amin(segmentation) >= 0 and np.amin(gold) >= 0)
# remove all small connected components
if filtersize > 0:
segmentation = seg2seg.RemoveSmallConnectedComponents(segmentation, filtersize)
gold = seg2seg.RemoveSmallConnectedComponents(gold, filtersize)
if dilate_ground_truth > 0:
gold = distance.DilateData(gold, dilate_ground_truth)
# convert to c++ arrays
cdef np.ndarray[long, ndim=3, mode='c'] cpp_segmentation
cpp_segmentation = np.ascontiguousarray(segmentation, dtype=ctypes.c_int64)
cdef np.ndarray[long, ndim=3, mode='c'] cpp_gold
cpp_gold = np.ascontiguousarray(gold, dtype=ctypes.c_int64)
zres, yres, xres = segmentation.shape
CppEvaluate(&(cpp_segmentation[0,0,0]), &(cpp_gold[0,0,0]), [zres, yres, xres], mask_ground_truth)
def CremiEvaluate(segmentation, gold, dilate_ground_truth=1, mask_ground_truth=True, mask_segmentation=False, filtersize=0):
# make sure these elements are the same size
assert (segmentation.shape == gold.shape)
assert (np.amin(segmentation) >= 0 and np.amin(gold) >= 0)
# remove all small connected components
if filtersize > 0:
segmentation = seg2seg.RemoveSmallConnectedComponents(segmentation, filtersize)
gold = seg2seg.RemoveSmallConnectedComponents(gold, filtersize)
if dilate_ground_truth > 0:
gold = distance.DilateData(gold, 1)
vi_split, vi_merge = voi(segmentation, gold)
print 'Variation of Information Full: {}'.format(vi_split + vi_merge)
print 'Variation of Information Merge: {}'.format(vi_merge)
print 'Variation of Information Split: {}'.format(vi_split)<|end_of_text|>cimport numpy as np
import numpy as np
cdef extern from "opencv2/opencv.hpp":
cdef int CV_WINDOW_AUTOSIZE
cdef int CV_8UC3
cdef int CV_8UC1
cdef int CV_32FC1
cdef int CV_16UC1
cdef int CV_8U
cdef int CV_32F
cdef extern from "opencv2/opencv.hpp" namespace "cv":
cdef cppclass Mat:
Mat() except +
void create(int, int, int)
void* data
int rows
int cols
int channels()
int depth()
size_t elemSize()
# For Buffer usage
cdef extern from "Python.h":
ctypedef struct PyObject
object PyMemoryView_FromBuffer(Py_buffer *view)
int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int infoflags)
enum:
PyBUF_FULL_RO
PyBUF_CONTIG
cdef Mat np2Mat(np.ndarray ary)
cdef object Mat2np(Mat mat)<|end_of_text|>from kivy.properties import (NumericProperty, BooleanProperty, ListProperty,
StringProperty, ObjectProperty, BoundedNumericProperty)
from kivy.graphics import (Color, Callback, Rotate, PushMatrix,
PopMatrix, Translate, Quad, Scale, Point)
from libc.math cimport pow as power
from libc.math cimport sqrt, sin, cos, fmax, fmin
from random import random
from kivy.event import EventDispatcher
EMITTER_TYPE_GRAVITY = 0
EMITTER_TYPE_RADIAL = 1
cdef inline double calc_distance(tuple point_1, tuple point_2):
cdef double x_dist2 = power(point_2[0] - point_1[0], 2)
cdef double y_dist2 = power(point_2[1] - point_1[1], 2)
return sqrt(x_dist2 + y_dist2)
cdef inline double random_variance(double base, double variance):
return base + variance * (random() * 2.0 - 1.0)
cdef inline list random_color_variance(list base, list variance):
return [fmin(fmax(0.0, (random_variance(base[i], variance[i]))), 1.0)
for i in range(4)]
class ParticleEmitter(EventDispatcher):
max_num_particles = NumericProperty(200)
adjusted_num_particles = NumericProperty(200)
life_span = NumericProperty(2)
texture = ObjectProperty(None)
texture_path = StringProperty(None)
life_span_variance = NumericProperty(0)
start_size = NumericProperty(16)
start_size_variance = NumericProperty(0)
end_size = NumericProperty(16)
end_size_variance = NumericProperty(0)
emit_angle = NumericProperty(0)
emit_angle_variance = NumericProperty(0)
start_rotation = NumericProperty(0)
start_rotation_variance = NumericProperty(0)
end_rotation = NumericProperty(0)
end_rotation_variance = NumericProperty(0)
emitter_x_variance = NumericProperty(100)
emitter_y_variance = NumericProperty(100)
gameworld = ObjectProperty(None)
particle_manager = ObjectProperty(None)
fbo = ObjectProperty(None)
gravity_x = NumericProperty(0)
gravity_y = NumericProperty(0)
speed = NumericProperty(0)
speed_variance = NumericProperty(0)
radial_acceleration = NumericProperty(100)
radial_acceleration_variance = NumericProperty(0)
tangential_acceleration = NumericProperty(0)
tangential_acceleration_variance = NumericProperty(0)
max_radius = NumericProperty(100)
max_radius_variance = NumericProperty( | Cython |
0)
min_radius = NumericProperty(50)
rotate_per_second = NumericProperty(0)
rotate_per_second_variance = NumericProperty(0)
start_color = ListProperty([1.,1.,1.,1.])
start_color_variance = ListProperty([1.,1.,1.,1.])
end_color = ListProperty([1.,1.,1.,1.])
end_color_variance = ListProperty([1.,1.,1.,1.])
emitter_type = NumericProperty(0)
current_scroll = ListProperty((0, 0))
friction = NumericProperty(0.0)
_is_paused = BooleanProperty(False)
def __init__(self, fbo, **kwargs):
self.particles = list()
self.fbo = fbo
self.frame_time = 0
super(ParticleEmitter, self).__init__(**kwargs)
def on_adjusted_num_particles(self, instance, value):
self.emission_rate = value / self.life_span
def on_max_number_particles(self, instance, value):
self.emission_rate = value / self.life_span
def receive_particle(self, int entity_id):
cdef dict entity = self.gameworld.entities[entity_id]
cdef list particles = self.particles
particles.append(entity_id)
cdef dict particle_manager = entity['particle_manager']
cdef Particle particle = particle_manager['particle']
particle_manager['color'] = None
particle_manager['translate'] = None
particle_manager['scale'] = None
particle_manager['rotate'] = None
particle_manager['point'] = None
self.init_particle(particle)
self.draw_particle(entity)
def draw_particle(self, dict entity):
cdef dict particle_manager = entity['particle_manager']
cdef Particle particle = particle_manager['particle']
group_id = str(entity['id'])
current_scroll = self.current_scroll
cdef list color = particle.color[:]
with self.particle_manager.canvas:
#with self.fbo:
PushMatrix(group=group_id)
particle_manager['color'] = Color(color[0], color[1],
color[2], color[3], group=group_id)
particle_manager['translate'] = Translate(group=group_id)
particle_manager['scale'] = Scale(x=particle.scale,
y=particle.scale, group=group_id)
particle_manager['rotate'] = Rotate(group=group_id)
particle_manager['rotate'].set(particle.rotation, 0, 0, 1)
particle_manager['rect'] = Point(texture=self.texture,
points=(0,0), group=group_id)
particle_manager['translate'].xy = (particle.x +
current_scroll[0],
particle.y + current_scroll[1])
PopMatrix(group=group_id)
def render_particle(self, dict entity):
cdef dict particle_manager = entity['particle_manager']
cdef Particle particle = particle_manager['particle']
current_scroll = self.current_scroll
particle_manager['rotate'].angle = particle.rotation
particle_manager['scale'].x = particle.scale
particle_manager['scale'].y = particle.scale
particle_manager['translate'].xy = (particle.x +
current_scroll[0],
particle.y + current_scroll[1])
particle_manager['color'].rgba = particle.color
def free_all_particles(self):
cdef list particles_to_free = [particle for particle in self.particles]
cdef int entity_id
for entity_id in particles_to_free:
self.free_particle(entity_id)
def free_particle(self, int entity_id):
cdef list particles = self.particles
self.particle_manager.canvas.remove_group(str(entity_id))
self.particle_manager.free_particle(particles.pop(particles.index(entity_id)))
def on_life_span(self,instance,value):
self.emission_rate = self.max_num_particles/value
def init_particle(self, Particle particle):
cdef double life_span = random_variance(self.life_span,
self.life_span_variance)
if life_span <= 0.0:
return
pos = self.pos
particle.current_time = 0.0
particle.total_time = life_span
particle.x = random_variance(pos[0], self.emitter_x_variance)
particle.y = random_variance(pos[1], self.emitter_y_variance)
particle.start_x = pos[0]
particle.start_y = pos[1]
cdef double angle = random_variance(self.emit_angle,
self.emit_angle_variance)
cdef double speed = random_variance(self.speed, self.speed_variance)
particle.velocity_x = speed * cos(angle)
particle.velocity_y = speed * sin(angle)
particle.emit_radius = random_variance(self.max_radius,
self.max_radius_variance)
particle.emit_radius_delta = (self.max_radius -
self.min_radius) / life_span
particle.emit_rotation = random_variance(self.emit_angle,
self.emit_angle_variance)
particle.emit_rotation_delta = random_variance(self.rotate_per_second,
self.rotate_per_second_variance)
particle.radial_acceleration = random_variance(
self.radial_acceleration,
self.radial_acceleration_variance)
particle.tangent_acceleration = random_variance(
self.tangential_acceleration,
self.tangential_acceleration_variance)
cdef double start_size = random_variance(self.start_size,
self.start_size_variance)
cdef double end_size = random_variance(self.end_size,
self.end_size_variance)
start_size = max(0.1, start_size)
end_size = max(0.1, end_size)
particle.scale = start_size / 2.
particle.scale_delta = ((end_size - start_size) / life_span) / 2.
# colors
cdef list start_color = random_color_variance(self.start_color[:],
self.start_color_variance[:])
cdef list end_color = random_color_variance(self.end_color[:],
self.end_color_variance[:])
particle.color_delta = [(end_color[i] -
start_color[i]) / life_span for i in range(4)]
particle.color = start_color
# rotation
cdef double start_rotation = random_variance(self.start_rotation,
self.start_rotation_variance)
cdef double end_rotation = random_variance(self.end_rotation,
self.end_rotation_variance)
particle.rotation = start_rotation
particle.rotation_delta = (end_rotation - start_rotation) / life_span
def advance_particle_gravity(self, Particle particle, float passed_time):
cdef double distance_x = particle.x - particle.start_x
cdef double distance_y = particle.y - particle.start_y
cdef tuple start_pos = (particle.start_x, particle.start_y)
cdef tuple current_pos = (particle.x, particle.y)
cdef double distance_scalar = calc_distance(start_pos, current_pos)
if distance_scalar < 0.01:
distance_scalar = 0.01
cdef double radial_x = distance_x / distance_scalar
cdef double radial_y = distance_y / distance_scalar
cdef double tangential_x = radial_x
cdef double tangential_y = radial_y
radial_x *= particle.radial_acceleration
radial_y *= particle.radial_acceleration
cdef double new_y = tangential_x
tangential_x = -tangential_y * particle.tangent_acceleration
tangential_y = new_y * particle.tangent_acceleration
particle.velocity_x += passed_time * (self.gravity_x +
radial_x + tangential_x)
particle.velocity_y += passed_time * (self.gravity_y +
radial_y + tangential_y)
particle.velocity_x -= particle.velocity_x * self.friction
particle.velocity_y -= particle.velocity_y * self.friction
particle.x += particle.velocity_x * passed_time
particle.y += particle.velocity_y * passed_time
def advance_particle(self, Particle particle, float passed_time):
passed_time = min(passed_time, particle.total_time -
particle.current_time)
particle.current_time += passed_time
if self.emitter_type == EMITTER_TYPE_RADIAL:
pos = self.pos
particle.emit_rotation += (particle.emit_rotation_delta *
passed_time)
particle.emit_radius -= particle.emit_radius_delta * passed_time
particle.x = (pos[0] -
cos(particle.emit_rotation) * particle.emit_radius)
particle.y = (pos[1] -
sin(particle.emit_rotation) * particle.emit_radius)
if particle.emit_radius < self.min_radius:
particle.current_time = particle.total_time
else:
self.advance_particle_gravity(particle, passed_time)
particle.scale += particle.scale_delta * passed_time
particle.rotation += particle.rotation_delta * passed_time
particle.color = [particle.color[i] + particle.color_delta[i] *
passed_time for i in range(4)]
def update(self, float dt):
'''
loop through particles
if total_time < current_time:
free particle
else:
advance_particle
'''
gameworld = self.gameworld
cdef list entities = gameworld.entities
cdef Particle particle
cdef dict entity
cdef list particles = self.particles
for entity_id in particles:
entity = entities[entity_id]
particle = entity['particle_manager']['particle']
if particle.total_time <= particle.current_time:
self.free_particle(entity_id)
else:
self.advance_particle(particle, dt)
self.render_particle(entity)
| Cython |
<|end_of_text|># -*- coding: utf-8 -*-
# distutils: language = c++
# distutils: sources = dtw.cpp
import numpy as np
cimport numpy as np
cimport cython
from libc.math cimport fabs, sqrt, INFINITY
from libcpp.vector cimport vector
import warnings
ctypedef double (*metric_ptr)(double[::1] a, double[::1])
cdef inline double d_min(double a, double b, double c):
if a < b and a < c:
return a
elif b < c:
return b
else:
return c
cdef inline int d_argmin(double a, double b, double c):
if a <= b and a <= c:
return 0
elif b <= c:
return 1
else:
return 2
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double euclidean_distance(double[::1] a, double[::1] b):
cdef int i
cdef double tmp, d
d = 0
for i in range(a.shape[0]):
tmp = a[i] - b[i]
d += tmp * tmp
return sqrt(d)
@cython.boundscheck(False)
@cython.wraparound(False)
def check_constraint(a_shape, b_shape, constraint=0, warn=True):
cdef int min_size = abs(a_shape - b_shape) + 1
if constraint < min_size:
if warn:
warnings.warn("Constraint {} too small for sequences length {} and {}; using {}".format(constraint, a_shape, b_shape, min_size))
constraint = min_size
return constraint
@cython.boundscheck(False)
@cython.wraparound(False)
def dtw1d(np.ndarray[np.float64_t, ndim=1, mode="c"] a, np.ndarray[np.float64_t, ndim=1, mode="c"] b, penalty):
cdef int constraint = abs(a.shape[0] - b.shape[0]) + 1
cost_mat, cost, align_a, align_b = __dtw1d(a, b, constraint, penalty)
return cost_mat, cost, align_a, align_b
@cython.boundscheck(False)
@cython.wraparound(False)
def constrained_dtw1d(np.ndarray[np.float64_t, ndim=1, mode="c"] a, np.ndarray[np.float64_t, ndim=1, mode="c"] b,
double penalty, constraint=0):
constraint = check_constraint(a.shape[0],b.shape[0],constraint)
cost_mat, cost, align_a, align_b = __dtw1d(a, b, constraint, penalty)
return cost_mat, cost, align_a, align_b
@cython.boundscheck(False)
@cython.wraparound(False)
cdef __dtw1d(np.ndarray[np.float64_t, ndim=1, mode="c"] a, np.ndarray[np.float64_t, ndim=1, mode="c"] b,
int constraint, double penalty):
cdef double[:, ::1] cost_mat = create_cost_mat_1d(a, b, constraint)
align_a, align_b, cost = traceback(cost_mat, a.shape[0], b.shape[0], penalty)
align_a.reverse()
align_b.reverse()
return cost_mat, cost, align_a, align_b
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double[:, ::1] create_cost_mat_1d(double[::1] a, double[::1]b, int constraint):
cdef double[:, ::1] cost_mat = np.empty((a.shape[0] + 1, b.shape[0] + 1), dtype=np.float64)
cost_mat[:] = INFINITY
cost_mat[0, 0] = 0
cdef int i, j
for i in range(1, cost_mat.shape[0]):
for j in range(max(1, i-constraint), min(cost_mat.shape[1], i+constraint+1)):
cost_mat[i, j] = fabs(a[i - 1] - b[j - 1]) +\
d_min(cost_mat[i - 1, j], cost_mat[i, j - 1], cost_mat[i - 1, j - 1])
return cost_mat[1:, 1:]
@cython.boundscheck(False)
@cython.wraparound(False)
def dtw2d(np.ndarray[np.float64_t, ndim=2, mode="c"] a,
np.ndarray[np.float64_t, ndim=2, mode="c"] b, double penalty, metric="euclidean"):
cdef int constraint = abs(a.shape[0] - b.shape[0]) + 1
cost_mat, cost, align_a, align_b = __dtw2d(a, b, constraint, metric,penalty)
return cost_mat, cost, align_a, align_b
@cython.boundscheck(False)
@cython.wraparound(False)
def constrained_dtw2d(np.ndarray[np.float64_t, ndim=2, mode="c"] a,
np.ndarray[np.float64_t, ndim=2, mode="c"] b, double penalty,
constraint=0, metric="euclidean"):
constraint = check_constraint(a.shape[0],b.shape[0],constraint)
cost_mat, cost, align_a, align_b = __dtw2d(a, b, constraint, metric, penalty)
return cost_mat, cost, align_a, align_b
@cython.boundscheck(False)
@cython.wraparound(False)
cdef __dtw2d(np.ndarray[np.float64_t, ndim=2, mode="c"] a,
np.ndarray[np.float64_t, ndim=2, mode="c"] b, int constraint, metric, double penalty):
assert a.shape[1] == b.shape[1], 'Matrices must have same dimention. a={}, b={}'.format(a.shape[1], b.shape[1])
cdef metric_ptr dist_func
if metric == 'euclidean':
dist_func = &euclidean_distance
else:
raise ValueError("unrecognized metric")
cdef double[:, ::1] cost_mat = create_cost_mat_2d(a, b, constraint, dist_func)
align_a, align_b, cost = traceback(cost_mat, a.shape[0], b.shape[0], penalty)
align_a.reverse()
align_b.reverse()
return cost_mat, cost, align_a, align_b
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double[:, ::1] create_cost_mat_2d(double[:, ::1] a, double[:, ::1] b, int constraint, metric_ptr dist_func):
cdef double[:, ::1] cost_mat = np.empty((a.shape[0] + 1, b.shape[0] + 1), dtype=np.float64)
cost_mat[:] = INFINITY
cost_mat[0, 0] = 0
cdef int i, j
for i in range(1, cost_mat.shape[0]):
for j in range(max(1, i-constraint), min(cost_mat.shape[1], i+constraint+1)):
cost_mat[i, j] = dist_func(a[i - 1], b[j - 1]) +\
d_min(cost_mat[i - 1, j], cost_mat[i, j - 1], cost_mat[i - 1, j - 1])
return cost_mat[1:, 1:]
@cython.boundscheck(False)
@cython.wraparound(False)
cdef traceback(double[:, ::1] cost_mat, int ilen, int jlen, double penalty):
cdef int i, j
i = ilen - 1
j = jlen - 1
cdef double cost = cost_mat[i, j]
cdef vector[int] a
cdef vector[int] b
a.push_back(i)
b.push_back(j)
cdef int match
while (i > 0 or j > 0):
match = d_argmin(cost_mat[i - 1, j - 1], cost_mat[i - 1, j], cost_mat[i, j - 1])
if match == 0:
i -= 1
j -= 1
elif match == 1:
i -= 1
cost_mat[i,j] = cost_mat[i,j] * penalty
penalty = penalty * penalty
else:
j -= 1
cost_mat[i, j] = cost_mat[i, j] * penalty
penalty = penalty * penalty
a.push_back(i)
b.push_back(j)
return a, b, cost
<|end_of_text|>from collections import defaultdict
from bisect import bisect_left
from blist import blist
cdef class Node(object):
cpdef public object value
cpdef public object key
cpdef public float order
def __init__(self, key, value):
self.key = key
self.value = value
def __repr__(self):
return f"<{self.key}>{self.value}"
cdef class Nearset(object):
cpdef public object cmp
cpdef public set keys
cpdef public Node start_value
cpdef public object nodes
cpdef public object index_node_order
cp | Cython |
def public int max_size
def __init__(self, cmp, max_size=-1):
self.cmp = cmp
self.keys = set()
self.nodes = blist()
self.index_node_order = blist()
self.max_size = max_size
def __len__(self):
return len(self.keys)
def __setitem__(self, key, value):
self.add(key, value)
cpdef add(self, object key, object value=None):
cpdef Node node
# if no key is provided, key is the value
if value is None:
value = key
# if element already exists, ignore
if key in self.keys:
return
# create Node element and compute sort value
node = Node(key, value)
node.order = self.cmp(node.value)
if self.max_size > 0 \
and len(self.keys) >= self.max_size \
and node.order > self.nodes[self.max_size - 1].order:
return
# if the node is the first element to be inserted, insert immediately
if len(self.keys) == 0:
# add the key for later references
self.keys.add(key)
# add the node index to list
self.nodes.append(node)
self.index_node_order.append(node.order)
else:
# insert node using the standard method
self.insert(node)
cpdef insert(self, Node node):
idx = bisect_left(self.index_node_order, node.order)
self.nodes.insert(idx, node)
self.index_node_order.insert(idx, node.order)
self.keys.add(node.key)
if self.max_size > 0:
self.index_node_order = self.index_node_order[:self.max_size]
self.nodes = self.nodes[:self.max_size]
cpdef pop(self):
self.index_node_order.pop()
node = self.nodes.pop()
self.keys.remove(node.key)
return node
cpdef items(self):
return [(item.key, item.value) for item in self.nodes]
def __iter__(self):
for node in self.nodes:
yield node.key, node.value, node.order
def __repr__(self):
return str([item.value for item in self.nodes])
def __getitem__(self, key):
if isinstance(key, int):
return self.nodes[key].value
elif isinstance(key, slice):
return [item.value for item in self.nodes[key]]
raise KeyError(key)
<|end_of_text|>from cupy._core._carray cimport shape_t
from cupy._core.core cimport _ndarray_base
cpdef compute_type_to_str(compute_type)
cpdef get_compute_type(dtype)
cpdef _ndarray_base dot(_ndarray_base a, _ndarray_base b, _ndarray_base out=*)
cpdef _ndarray_base tensordot_core(
_ndarray_base a, _ndarray_base b, _ndarray_base out, Py_ssize_t n,
Py_ssize_t m, Py_ssize_t k, const shape_t& ret_shape)
cpdef _ndarray_base matmul(
_ndarray_base a, _ndarray_base b, _ndarray_base out=*)
cpdef enum:
COMPUTE_TYPE_TBD = 0
COMPUTE_TYPE_DEFAULT = 1 # default
COMPUTE_TYPE_PEDANTIC = 2 # disable algorithmic optimizations
COMPUTE_TYPE_FP16 = 3 # allow converting inputs to FP16
COMPUTE_TYPE_FP32 = 4 # allow converting inputs to FP32
COMPUTE_TYPE_FP64 = 5 # allow converting inputs to FP64
COMPUTE_TYPE_BF16 = 6 # allow converting inputs to BF16
COMPUTE_TYPE_TF32 = 7 # allow converting inputs to TF32
<|end_of_text|># -*- coding: utf-8 -*-
from _pcl cimport PointCloud
from _pcl cimport PointCloud_PointWithViewpoint
cimport pcl_defs as cpp
cimport pcl_range_image_180 as pcl_rim
cimport eigen as eigen3
from boost_shared_ptr cimport sp_assign
from cython.operator cimport dereference as deref, preincrement as inc
cimport pcl_common_180 as common
def copyPointCloud (PCLPointCloud2 cloud_in, PCLPointCloud2 cloud_out):
common.copyPointCloud (deref(cloud_in.thisptr()), deref(cloud_out.thisptr()))
def copyPointCloud (PCLPointCloud2 cloud_in, object indices, PCLPointCloud2 cloud_out):
cdef vector[int] vect
for i in indices:
vect.push_back(i)
common.copyPointCloud (deref(cloud_in.thisptr()), vect, deref(cloud_out.thisptr()))
<|end_of_text|># Copyright (c) 2010 Jean-Pascal Mercier
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
cdef extern from *:
ctypedef char * const_char_ptr "const char *"
cdef extern from "CL/cl.h":
ctypedef signed char cl_char
ctypedef unsigned char cl_uchar
ctypedef signed short cl_short
ctypedef unsigned short cl_ushort
ctypedef signed int cl_int
ctypedef unsigned int cl_uint
ctypedef signed long long cl_long
ctypedef unsigned long long cl_ulong
ctypedef unsigned short cl_half
ctypedef float cl_float
ctypedef double cl_double
ctypedef cl_uint cl_bool
ctypedef cl_int * cl_context_properties
ctypedef void *cl_platform_id
ctypedef void *cl_device_id
ctypedef void *cl_context
ctypedef void *cl_command_queue
ctypedef void *cl_mem
ctypedef void *cl_program
ctypedef void *cl_kernel
ctypedef void *cl_event
ctypedef void *cl_sampler
ctypedef cl_ulong cl_bitfield
ctypedef cl_bitfield cl_device_type
ctypedef cl_uint cl_platform_info
ctypedef cl_uint cl_device_info
ctypedef cl_bitfield cl_device_address_info
ctypedef cl_bitfield cl_device_fp_config
ctypedef cl_uint cl_device_mem_cache_type
ctypedef cl_uint cl_device_local_mem_type
ctypedef cl_bitfield cl_device_exec_capabilities
ctypedef cl_bitfield cl_command_queue_properties
ctypedef cl_uint cl_filter_mode
ctypedef cl_uint cl_addressing_mode
ctypedef cl_uint cl_profiling_info
ctypedef cl_uint cl_kernel_work_group_info
ctypedef enum cl_device_info_enum:
CL_DEVICE_TYPE = 0x1000
CL_DEVICE_VENDOR_ID = 0x1001
CL_DEVICE_MAX_COMPUTE_UNITS = 0x1002
CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS = 0x1003
CL_DEVICE_MAX_WORK_GROUP_SIZE = 0x1004
CL_DEVICE_MAX_WORK_ITEM_SIZES = 0x1005
CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR = 0x1006
CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT = 0x1007
CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT = 0x1008
CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG = 0x1009
CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT = 0x100A
CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE = 0x100B
CL_DEVICE_MAX_CLOCK_FREQUENCY = 0x100C
CL_DEVICE_ADDRESS_BITS = 0x100D
CL_DEVICE_MAX_READ_IMAGE_ARGS = 0x100E
CL_DEVICE_MAX_WRITE_IMAGE_ARGS = 0x100F
CL_DEVICE_MAX_MEM_ALLOC_SIZE = 0x1010
CL_DEVICE_IMAGE2D_MAX_WIDTH = 0x1011
CL_DEVICE_IMAGE2D_MAX_HEIGHT = 0x1012
CL_DEVICE_IMAGE3D_MAX_WIDTH = 0x1013
CL_DEVICE_IMAGE3D_MAX_HEIGHT = 0x1014
CL_DEVICE_IMAGE3D_MAX_DEPTH = 0x1015
CL_DEVICE_IMAGE_SUPPORT = 0x1016
CL_DEVICE_MAX_PARAMETER_SIZE = 0x1017
CL_DEVICE_MAX_SAMPLERS = 0x1018
CL_DEVICE_MEM_BASE_ADDR_ALIGN = 0x1019
CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE = 0 | Cython |
x101A
CL_DEVICE_SINGLE_FP_CONFIG = 0x101B
CL_DEVICE_GLOBAL_MEM_CACHE_TYPE = 0x101C
CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE = 0x101D
CL_DEVICE_GLOBAL_MEM_CACHE_SIZE = 0x101E
CL_DEVICE_GLOBAL_MEM_SIZE = 0x101F
CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE = 0x1020
CL_DEVICE_MAX_CONSTANT_ARGS = 0x1021
CL_DEVICE_LOCAL_MEM_TYPE = 0x1022
CL_DEVICE_LOCAL_MEM_SIZE = 0x1023
CL_DEVICE_ERROR_CORRECTION_SUPPORT = 0x1024
CL_DEVICE_PROFILING_TIMER_RESOLUTION = 0x1025
CL_DEVICE_ENDIAN_LITTLE = 0x1026
CL_DEVICE_AVAILABLE = 0x1027
CL_DEVICE_COMPILER_AVAILABLE = 0x1028
CL_DEVICE_EXECUTION_CAPABILITIES = 0x1029
CL_DEVICE_QUEUE_PROPERTIES = 0x102A
CL_DEVICE_NAME = 0x102B
CL_DEVICE_VENDOR = 0x102C
CL_DRIVER_VERSION = 0x102D
CL_DEVICE_PROFILE = 0x102E
CL_DEVICE_VERSION = 0x102F
CL_DEVICE_EXTENSIONS = 0x1030
CL_DEVICE_PLATFORM = 0x1031
ctypedef enum cl_platform_info_enum:
CL_PLATFORM_PROFILE = 0x0900
CL_PLATFORM_VERSION = 0x0901
CL_PLATFORM_NAME = 0x0902
CL_PLATFORM_VENDOR = 0x0903
CL_PLATFORM_EXTENSIONS = 0x0904
ctypedef enum cl_device_type_enum:
CL_DEVICE_TYPE_DEFAULT = (1 << 0)
CL_DEVICE_TYPE_CPU = (1 << 1)
CL_DEVICE_TYPE_GPU = (1 << 2)
CL_DEVICE_TYPE_ACCELERATOR = (1 << 3)
CL_DEVICE_TYPE_ALL = 0xFFFFFFFF
ctypedef enum cl_error_codes_enum:
CL_SUCCESS = 0
CL_DEVICE_NOT_FOUND = -1
CL_DEVICE_NOT_AVAILABLE = -2
CL_COMPILER_NOT_AVAILABLE = -3
CL_MEM_OBJECT_ALLOCATION_FAILURE = -4
CL_OUT_OF_RESOURCES = -5
CL_OUT_OF_HOST_MEMORY = -6
CL_PROFILING_INFO_NOT_AVAILABLE = -7
CL_MEM_COPY_OVERLAP = -8
CL_IMAGE_FORMAT_MISMATCH = -9
CL_IMAGE_FORMAT_NOT_SUPPORTED = -10
CL_BUILD_PROGRAM_FAILURE = -11
CL_MAP_FAILURE = -12
CL_INVALID_VALUE = -30
CL_INVALID_DEVICE_TYPE = -31
CL_INVALID_PLATFORM = -32
CL_INVALID_DEVICE = -33
CL_INVALID_CONTEXT = -34
CL_INVALID_QUEUE_PROPERTIES = -35
CL_INVALID_COMMAND_QUEUE = -36
CL_INVALID_HOST_PTR = -37
CL_INVALID_MEM_OBJECT = -38
CL_INVALID_IMAGE_FORMAT_DESCRIPTOR = -39
CL_INVALID_IMAGE_SIZE = -40
CL_INVALID_SAMPLER = -41
CL_INVALID_BINARY = -42
CL_INVALID_BUILD_OPTIONS = -43
CL_INVALID_PROGRAM = -44
CL_INVALID_PROGRAM_EXECUTABLE = -45
CL_INVALID_KERNEL_NAME = -46
CL_INVALID_KERNEL_DEFINITION = -47
CL_INVALID_KERNEL = -48
CL_INVALID_ARG_INDEX = -49
CL_INVALID_ARG_VALUE = -50
CL_INVALID_ARG_SIZE = -51
CL_INVALID_KERNEL_ARGS = -52
CL_INVALID_WORK_DIMENSION = -53
CL_INVALID_WORK_GROUP_SIZE = -54
CL_INVALID_WORK_ITEM_SIZE = -55
CL_INVALID_GLOBAL_OFFSET = -56
CL_INVALID_EVENT_WAIT_LIST = -57
CL_INVALID_EVENT = -58
CL_INVALID_OPERATION = -59
CL_INVALID_GL_OBJECT = -60
CL_INVALID_BUFFER_SIZE = -61
CL_INVALID_MIP_LEVEL = -62
CL_INVALID_GLOBAL_WORK_SIZE = -63
ctypedef enum cl_mem_flags:
CL_MEM_READ_WRITE = (1 << 0)
CL_MEM_WRITE_ONLY = (1 << 1)
CL_MEM_READ_ONLY = (1 << 2)
CL_MEM_USE_HOST_PTR = (1 << 3)
CL_MEM_ALLOC_HOST_PTR = (1 << 4)
CL_MEM_COPY_HOST_PTR = (1 << 5)
ctypedef enum cl_channel_order:
CL_R = 0x10B0
CL_A = 0x10B1
CL_RG = 0x10B2
CL_RA = 0x10B3
CL_RGB = 0x10B4
CL_RGBA = 0x10B5
CL_BGRA = 0x10B6
CL_ARGB = 0x10B7
CL_INTENSITY = 0x10B8
CL_LUMINANCE = 0x10B9
ctypedef enum cl_channel_type:
CL_SNORM_INT8 = 0x10D0
CL_SNORM_INT16 = 0x10D1
CL_UNORM_INT8 = 0x10D2
CL_UNORM_INT16 = 0x10D3
CL_UNORM_SHORT_565 = 0x10D4
CL_UNORM_SHORT_555 = 0x10D5
CL_UNORM_INT_101010 = 0x10D6
CL_SIGNED_INT8 = 0x10D7
CL_SIGNED_INT16 = 0x10D8
CL_SIGNED_INT32 = 0x10D9
CL_UNSIGNED_INT8 = 0x10DA
CL_UNSIGNED_INT16 = 0x10DB
CL_UNSIGNED_INT32 = 0x10DC
CL_HALF_FLOAT = 0x10DD
CL_FLOAT = 0x10DE
ctypedef enum cl_image_info:
CL_IMAGE_FORMAT = 0x1110
CL_IMAGE_ELEMENT_SIZE = 0x1111
CL_IMAGE_ROW_PITCH = 0x1112
CL_IMAGE_SLICE_PITCH = 0x1113
CL_IMAGE_WIDTH = 0x1114
CL_IMAGE_HEIGHT = 0x1115
CL_IMAGE_DEPTH = 0x1116
ctypedef enum cl_mem_info:
CL_MEM_TYPE = 0x1100
CL_MEM_FLAGS = 0x1101
CL_MEM_SIZE = 0x1102
CL_MEM_HOST_PTR = 0x1103
CL_MEM_MAP_COUNT = 0x1104
CL_MEM_REFERENCE_COUNT = 0x1105
CL_MEM_CONTEXT = 0x1106
ctypedef enum cl_program_build_info:
CL_PROGRAM_BUILD_STATUS = 0x1181
CL_PROGRAM_BUILD_OPTIONS = 0x1182
CL_PROGRAM_BUILD_LOG = 0x1183
ctypedef enum cl_program_info:
CL_PROGRAM_REFERENCE_COUNT = 0x1160
CL_PROGRAM_CONTEXT = 0x1161
CL_PROGRAM_NUM_DEVICES = 0x1162
CL_PROGRAM_DEVICES = 0x1163
CL_PROGRAM_SOURCE = 0x1164
CL_PROGRAM_BINARY_SIZES = 0x1165
CL_PROGRAM_BINARIES = 0x1166
ctypedef enum cl_kernel_info:
CL_KERNEL_FUNCTION_NAME = 0x1190
CL_KERNEL_NUM_ARGS = 0x1191
CL_KERNEL_REFERENCE_COUNT = 0x1192
CL_KERNEL_CONTEXT = 0x1193
CL_KERNEL_PROGRAM = 0x1194
ctypedef enum cl_command_type:
CL_COMMAND_NDRANGE_KERNEL = 0x11F0
CL_COMMAND_TASK = 0x11F1
CL_COMMAND_NATIVE_KERNEL = 0x11F2
CL_COMMAND_READ_BUFFER = 0x11F3
CL_COMMAND_WRITE_BUFFER = 0x11F4
CL_COMMAND_COPY_BUFFER = 0x11F5
CL_COMMAND_READ_IMAGE = 0x11F6
CL_COMMAND_WRITE_IMAGE = 0x11F7
CL_COMMAND_COPY_IMAGE = 0x11F8
CL_COMMAND_COPY_IMAGE_TO_BUFFER = 0x11F9
CL_COMMAND_COPY_BUFFER_TO_IMAGE = 0x11FA
CL_COMMAND_MAP_BUFFER = 0x11FB
CL_COMMAND_MAP_IMAGE = 0x11FC
CL_COMMAND_UNMAP_MEM_OBJECT = 0x11FD
CL_COMMAND_MARKER = 0x11FE
CL_COMMAND_ACQUIRE_GL_OBJECTS = 0x11FF
CL_COMMAND_RELEASE_GL_OBJECTS = | Cython |
0x1200
ctypedef enum cl_addressing_mode:
CL_ADDRESS_NONE = 0x1130
CL_ADDRESS_CLAMP_TO_EDGE = 0x1131
CL_ADDRESS_CLAMP = 0x1132
CL_ADDRESS_REPEAT = 0x1133
ctypedef enum cl_command_queue_properties:
CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE = (1 << 0)
CL_QUEUE_PROFILING_ENABLE = (1 << 1)
ctypedef enum cl_filter_mode:
CL_FILTER_NEAREST = 0x1140
CL_FILTER_LINEAR = 0x1141
ctypedef enum cl_sampler_info:
CL_SAMPLER_REFERENCE_COUNT = 0x1150
CL_SAMPLER_CONTEXT = 0x1151
CL_SAMPLER_NORMALIZED_COORDS = 0x1152
CL_SAMPLER_ADDRESSING_MODE = 0x1153
CL_SAMPLER_FILTER_MODE = 0x1154
ctypedef enum cl_event_info:
CL_EVENT_COMMAND_QUEUE = 0x11D0
CL_EVENT_COMMAND_TYPE = 0x11D1
CL_EVENT_REFERENCE_COUNT = 0x11D2
CL_EVENT_COMMAND_EXECUTION_STATUS = 0x11D3
ctypedef enum cl_kernel_work_group_info:
CL_KERNEL_WORK_GROUP_SIZE = 0x11B0
CL_KERNEL_COMPILE_WORK_GROUP_SIZE = 0x11B1
CL_KERNEL_LOCAL_MEM_SIZE = 0x11B2
ctypedef enum cl_profiling_info:
CL_PROFILING_COMMAND_QUEUED = 0x1280
CL_PROFILING_COMMAND_SUBMIT = 0x1281
CL_PROFILING_COMMAND_START = 0x1282
CL_PROFILING_COMMAND_END = 0x1283
ctypedef enum cl_execution_status:
CL_COMPLETE = 0x0
CL_RUNNING = 0x1
CL_SUBMITTED = 0x2
CL_QUEUED = 0x3
ctypedef enum cl_map_flags:
CL_MAP_READ = (1 << 0)
CL_MAP_WRITE = (1 << 1)
ctypedef enum cl_context_properties:
CL_CONTEXT_PLATFORM = 0x1084
ctypedef enum cl_kernel_work_group_info:
CL_KERNEL_WORK_GROUP_SIZE = 0x11B0
CL_KERNEL_COMPILE_WORK_GROUP_SIZE = 0x11B1
CL_KERNEL_LOCAL_MEM_SIZE = 0x11B2
ctypedef struct cl_image_format:
cl_channel_order image_channel_order
cl_channel_type image_channel_data_type
# Device API
cdef cl_int clGetDeviceInfo(cl_device_id,
cl_device_info,
size_t,
void *,
size_t *) nogil
# Platform API
cdef cl_int clGetPlatformIDs(cl_uint,
cl_platform_id *,
cl_uint *) nogil
cdef cl_int clGetDeviceIDs(cl_platform_id,
cl_device_type,
cl_uint,
cl_device_id *,
cl_uint *) nogil
cdef cl_int clGetPlatformInfo(cl_platform_id,
cl_platform_info,
size_t,
void *,
size_t *) nogil
cdef cl_context clCreateContext(cl_context_properties *,
cl_uint,
cl_device_id *,
void (*pfn_notify) (char *, void *, size_t, void *),
void *,
cl_int *)
cdef cl_int clGetContextInfo(cl_context,
cl_context_info,
size_t,
void *,
size_t *)
# Context API
#cdef cl_context clCreateContext(cl_context_properties *,
#cl_uint,
#cl_device_id *,
#void *,
#void *,
#cl_int *) nogil
cdef cl_int clReleaseContext(cl_context) nogil
# Memory API
cdef cl_mem clCreateBuffer(cl_context context,
cl_mem_flags,
size_t,
void *,
cl_int *) nogil
cdef cl_mem clCreateImage2D(cl_context,
cl_mem_flags,
cl_image_format *,
size_t,
size_t,
size_t,
void *,
cl_int *) nogil
cdef cl_mem clCreateImage3D(cl_context,
cl_mem_flags,
cl_image_format *,
size_t,
size_t,
size_t,
size_t,
size_t,
void *,
cl_int *) nogil
cdef cl_int clReleaseMemObject(cl_mem) nogil
cdef cl_int clGetImageInfo(cl_mem,
cl_image_info,
size_t,
void *,
size_t *) nogil
cdef cl_int clGetMemObjectInfo(cl_mem,
cl_mem_info,
size_t,
void *,
size_t *) nogil
# Program API
cdef cl_program clCreateProgramWithSource(cl_context,
cl_uint,
char **,
size_t *,
cl_int *) nogil
cdef cl_int clReleaseProgram(cl_program) nogil
cdef cl_int clBuildProgram(cl_program,
cl_uint,
cl_device_id *,
char *,
void (*pfn_notify)(cl_program, void *user_data),
void *) nogil
cdef cl_int clCreateKernelsInProgram(cl_program,
cl_uint,
cl_kernel *,
cl_uint *) nogil
# Kernel API
cdef cl_int clReleaseKernel(cl_kernel) nogil
cdef cl_kernel clCreateKernel(cl_program,
char *,
cl_int *) nogil
cdef cl_int clGetProgramBuildInfo(cl_program,
cl_device_id,
cl_program_build_info,
size_t,
void *,
size_t *) nogil
cdef cl_int clGetProgramInfo(cl_program program,
cl_program_info,
size_t,
void *,
size_t *) nogil
cdef cl_int clGetKernelInfo(cl_kernel,
cl_kernel_info,
size_t,
void *,
size_t *) nogil
cdef cl_int clGetKernelWorkGroupInfo(cl_kernel,
cl_device_id,
cl_kernel_work_group_info,
size_t,
void *,
size_t *) nogil
cdef cl_int clSetKernelArg(cl_kernel,
cl_uint,
size_t,
void *) nogil
# Command Queue API
cdef cl_command_queue clCreateCommandQueue(cl_context,
cl_device_id,
cl_command_queue_properties,
cl_int *) nogil
cdef cl_int clReleaseCommandQueue(cl_command_queue) nogil
cdef cl_int clFinish(cl_command_queue) nogil
cdef cl_int clFlush(cl_command_queue) nogil
cdef cl_int clEnqueueNDRangeKernel(cl_command_queue,
cl_kernel,
cl_uint,
size_t *,
size_t *,
size_t *,
cl_uint,
cl_event *,
cl_event *) nogil
cdef cl_int clEnqueueCopyImageToBuffer(cl_command_queue,
cl_mem,
cl_mem,
size_t *,
size_t *,
size_t,
cl_uint,
cl_event *,
cl_event *) nogil
cdef cl_int clEnqueueCopyBufferToImage(cl_command_queue,
cl_mem,
cl_mem,
size_t,
size_t *,
size_t *,
cl_uint,
cl_event *,
cl_event *) nogil
cdef cl_int clEnqueueWriteBuffer(cl_command_queue,
cl_mem,
cl_bool,
size_t,
size_t,
void *,
cl_uint,
cl_event *,
cl_event *) nogil
cdef cl_int clEnqueueReadBuffer(cl_command_queue,
cl_mem,
cl_bool,
size_t,
size_t,
void *,
cl_uint,
cl_event *,
cl_event *) nogil
cdef cl_int clEnqueueCopyBuffer(cl_command_queue,
cl_mem,
cl_mem,
size_t,
size_t,
size_t,
cl_uint,
cl_event *,
cl_event *) nogil
cdef void * clEnqueueMapBuffer (cl_command_queue command_queue,
cl_mem buffer,
cl_bool blocking_map,
cl_map_flags map_flags,
size_t offset,
size_t cb,
cl_uint num_events_in_wait_list,
cl_event *event_wait_list,
cl_event *event,
cl_int *errcode_ret)
cdef cl_int clEnqueueBarrier(cl_command_queue) nogil
cdef cl_int clEnqueueMarker(cl_command_queue, cl_event *) nogil
cdef cl_int clEnqueueWaitForEvents(cl_command_queue,
cl_uint,
cl_event *) nogil
# Sampler API
cdef cl_int clReleaseSampler(cl_sampler) nogil
cdef cl_sampler clCreateSampler(cl_context,
cl_bool,
cl_addressing_mode,
cl_filter_mode,
cl_int *) nogil
cdef cl_int clGetSamplerInfo(cl_sampler,
cl_sampler_info,
size_t,
void *,
size_t *) nogil
# Event API
cdef cl_int clReleaseEvent(cl_event) nogil
cdef cl_int clGetEventInfo(cl_event,
cl_event_info,
size_t,
void *,
size_t *) nogil
c | Cython |
def cl_int clWaitForEvents(cl_uint,
cl_event *) nogil
cdef cl_int clGetEventProfilingInfo(cl_event,
cl_profiling_info,
size_t,
void *,
size_t *) nogil
cdef cl_int clEnqueueUnmapMemObject(cl_command_queue,
cl_mem,
void *,
cl_uint,
cl_event *,
cl_event *) nogil
cdef cl_int clEnqueueReadImage (cl_command_queue queue,
cl_mem image,
cl_bool blocking,
size_t origin[3],
size_t region[3],
size_t row_pitch,
size_t slice_pitch,
void *ptr,
cl_uint num_events_in_wait_list,
cl_event *event_wait_list,
cl_event *event) nogil
cdef cl_int clEnqueueWriteImage (cl_command_queue command_queue,
cl_mem image,
cl_bool blocking_write,
size_t origin[3],
size_t region[3],
size_t input_row_pitch,
size_t input_slice_pitch,
void *ptr,
cl_uint num_events_in_wait_list,
cl_event *event_wait_list,
cl_event *event) nogil
<|end_of_text|>#Libraries
from __future__ import division
cimport cython
cimport numpy as np
import numpy as np
from libcpp.vector cimport vector
from sklearn.linear_model import RANSACRegressor
from operator import itemgetter
import time
np.import_array()
#Defining functions
#Ransac function
def ransac_polyfit(np.ndarray[np.npy_int64, ndim=1] x,
np.ndarray[np.npy_int64, ndim=1] y,
np.npy_intp order,
np.npy_float32 t,
np.npy_float32 n=0.8,
np.npy_intp k=100,
np.npy_float32 f=0.9):
cdef np.npy_intp kk, i, ransac_control
cdef np.npy_float64 thiserr, besterr = -1.0
cdef np.ndarray[np.npy_int64, ndim=1] maybeinliers
cdef np.ndarray[np.npy_bool, ndim=1] alsoinliers
cdef np.ndarray[np.npy_float64, ndim=1] bestfit = np.array([0.0]), bestfitderi = np.array([0.0]), maybemodel, res_th, bettermodel
cdef list polyderi
for kk in range(k):
maybeinliers = np.random.randint(len(x), size=int(n*len(x)))
maybemodel = np.polyfit(x[maybeinliers], y[maybeinliers], order)
polyderi = []
for i in range(order):
polyderi.append(maybemodel[i]*(order-i))
res_th = t / np.cos(np.arctan(np.polyval(np.array(polyderi),x)))
alsoinliers = np.abs(np.polyval(maybemodel, x)-y) < res_th
if sum(alsoinliers) > len(x)*f:
bettermodel = np.polyfit(x[alsoinliers], y[alsoinliers], order)
polyderi = []
for i in range(order):
polyderi.append(maybemodel[i]*(order-i))
thiserr = np.sum(np.abs(np.polyval(bettermodel, x[alsoinliers])-y[alsoinliers]))
if (thiserr < besterr) or (besterr == -1.0):
bestfit = bettermodel
besterr = thiserr
bestfitderi = np.array(polyderi)
if (besterr == -1.0):
ransac_control = 0
return ransac_control, bestfit, bestfitderi
else:
ransac_control = 1
return ransac_control, bestfit, bestfitderi
#ddbscan_inner function
def ddbscaninner(np.ndarray[np.npy_intp, ndim=2] data,
np.ndarray[np.uint8_t, ndim=1] is_core,
np.ndarray[object, ndim=1] neighborhoods,
np.ndarray[object, ndim=1] neighborhoods2,
np.ndarray[np.npy_intp, ndim=1] labels):
#Parameters of the ddbscan_inner
cdef np.npy_float32 acc_th = 0.80 #Accuracy of the RANSAC to save one point of the cluster for the directional search
cdef np.npy_int32 points_th = 70 #Minimum number of points to test the ransac
cdef np.npy_float32 t = 5 #The thickness of the track
cdef np.npy_float32 time_threshold = 600 #Maximum ammount of time that the directional search is enabled for each cluster (marked as infinite to see the results)
#Beginning of the algorithm - DBSCAN check part
cdef np.npy_intp i, label_num = 0, v, l1, ransac_control, control, j
cdef np.npy_int64 pts0, pts1
cdef np.npy_float32 accuracy, t1, t2
cdef np.ndarray[np.npy_intp, ndim=1] neighb, moment_lab, inliers
cdef np.ndarray[np.npy_intp, ndim=2] la_aux = np.zeros([labels.shape[0], 2], dtype = np.intp)
cdef list acc = [], clu_stra = [], length = [], auxiliar_points = [], clu_coordinates, stack = []
cdef np.ndarray[np.npy_int64, ndim=2] uniques
cdef np.ndarray[np.npy_int64, ndim=1] x, y
cdef np.ndarray[np.npy_float64, ndim = 2] vet_aux
cdef np.ndarray[np.npy_float64, ndim = 1] fit_model, fit_deri, res_th
cdef np.ndarray[np.npy_bool, ndim=1] lt, inliers_bool
cdef object ransac
for i in range(labels.shape[0]):
if labels[i]!= -1 or not is_core[i]:
continue
# Depth-first search starting from i, ending at the non-core points.
# This is very similar to the classic algorithm for computing connected
# components, the difference being that we label non-core points as
# part of a cluster (component), but don't expand their neighborhoods.
while True:
if labels[i] == -1:
labels[i] = label_num
if is_core[i]:
neighb = neighborhoods[i]
for i in range(neighb.shape[0]):
v = neighb[i]
if labels[v] == -1:
stack.append(v)
if len(stack) == 0:
break
i = stack[len(stack)-1]
del(stack[len(stack)-1])
#Ransac part
if sum(labels==label_num) > points_th:
x = data[labels==label_num][:,0]
y = data[labels==label_num][:,1]
if (np.median(np.abs(y - np.median(y))) == 0):
ransac = RANSACRegressor(min_samples=0.8, residual_threshold = 0.1)
ransac.fit(np.expand_dims(x, axis=1), y)
else:
ransac = RANSACRegressor(min_samples=0.8)
ransac.fit(np.expand_dims(x, axis=1), y)
accuracy = sum(ransac.inlier_mask_)/len(y)
if accuracy > acc_th:
clu_stra.append(label_num)
acc.append(accuracy)
length.append(sum(labels==label_num))
label_num += 1
#End of DBSCAN loop - check if directional part is viable
print("Clusters found in DBSCAN: %d" %(len(set(labels)) - (1 if -1 in labels else 0)))
if (len(clu_stra) == 0):
#If no cluster has a good fit model, the output will be the same of the DBSCAN
la_aux[:,0] = np.copy(labels)
return la_aux
else:
#If any cluster has a good fit model, it'll be marked from the worst fitted cluster to the best, each of them respecting the accuracy threshold
vet_aux = np.zeros([len(clu_stra),3])
vet_aux[:,0] = np.asarray(clu_stra)
vet_aux[:,1] = np.asarray(acc)
vet_aux[:,2] = np.asarray(length)
vet_aux = np.asarray(sorted(vet_aux,key=itemgetter(1),reverse=1))
if (sum(vet_aux[:,1]==1) > 1):
l1 = sum(vet_aux[:,1]==1)
vet_aux[0:l1,:] = np.asarray(sorted(vet_aux[0:l1,:],key=itemgetter(2),reverse=1))
for u in range(len(clu_stra)):
lt = (labels==vet_aux[u][0])*is_core
auxiliar_points.append(np.where(lt)[0][0])
print("The point %d has been assigned as part of a good fit" %(np.where(lt)[0][0]))
#Now the clusterization will begin from zero with directionality enabled for the | Cython |
clusters that have a good fit model
label_num = 0
labels = np.full(data.shape[0], -1, dtype=np.intp)
stack = []
for i in auxiliar_points:
if labels[i]!= -1 or not is_core[i]:
continue
while True:
if labels[i] == -1:
labels[i] = label_num
if is_core[i]:
neighb = neighborhoods[i]
for i in range(neighb.shape[0]):
v = neighb[i]
if labels[v] == -1:
stack.append(v)
if len(stack) == 0:
break
i = stack[len(stack)-1]
del(stack[len(stack)-1])
#Now that the provisional cluster has been found, directional search begins
if sum(labels==label_num) > points_th:
#Taking unique points to use on the ransac
clu_coordinates = [tuple(row) for row in data[labels==label_num]]
uniques = np.unique(clu_coordinates,axis=0)
x = uniques[:,0]
y = uniques[:,1]
#RANSAC fit
ransac_control, fit_model, fit_deri = ransac_polyfit(x,y,order=1, t = t)
counter = 1
#Adding new points to the cluster (If the fit_model output is None, then no model was found)
if ransac_control == 1:
control = 1
pts1 = 0
t1 = time.time()
while True:
#Filling stack list with possible new points to be added (start point)
pts0 = pts1
moment_lab = np.where(labels==label_num)[0]
stack = []
for j in moment_lab:
#if is_core[j]:
neig2 = neighborhoods2[j]
for k in neig2:
if labels[k]!= label_num:
#if (labels[k]!= label_num) or 1:
stack.append(k)
stack = np.unique(stack).tolist()
if len(stack) == 0:
break
res_th = t / np.cos(np.arctan(np.polyval(fit_deri,data[:,0])))
inliers_bool = np.abs(np.polyval(fit_model, data[:,0])-data[:,1]) < res_th
inliers = np.where(inliers_bool)[0]
i = stack[len(stack)-1]
#Adding the inliers points from stack list and filling stack with more possible points
while True:
if i in inliers and (labels[i]!= label_num):
#if i in inliers:
labels[i] = label_num
#if is_core[i]:
neig2 = neighborhoods2[i]
for i in range(neig2.shape[0]):
v = neig2[i]
if labels[v]!= label_num:
stack.append(v)
if len(stack) == 0:
break
i = stack[len(stack)-1]
del(stack[len(stack)-1])
#Checking current cluster for possible fit model update
clu_coordinates = [tuple(row) for row in data[labels==label_num]]
uniques = np.unique(clu_coordinates,axis=0)
x = uniques[:,0]
y = uniques[:,1]
#Updating the ransac model
if control == 1:
ransac_control, fit_model, fit_deri = ransac_polyfit(x,y,order=1, t = t)
else:
ransac_control, fit_model, fit_deri = ransac_polyfit(x,y,order=3, t = t)
pts1 = sum(labels==label_num)
#Stop criteria - time
t2 = time.time()
if (t2 - t1) > time_threshold:
break
#Stop criteria - When there is no more point to be added or if the fit is not good anymore
counter = counter + 1
if (pts1 == pts0) or (ransac_control!= 1):
if control == 0:
print('The cluster %d' %(label_num) +'needed %d attempts' %(counter))
break
else:
ransac_control, fit_model, fit_deri = ransac_polyfit(x,y,order=3, t = t)
control = 0
if ransac_control!= 1:
break
#label_num += 1
if sum(labels==label_num) > 29:
label_num += 1
else:
labels[labels==label_num] = len(data)
#Now that the clusters with good fit models were found, the rest of the data will be clustered with the standard DBSCAN logic
for i in range(labels.shape[0]):
if labels[i]!= -1 or not is_core[i]:
continue
while True:
if labels[i] == -1:
labels[i] = label_num
if is_core[i]: #Only core points are expanded
neighb = neighborhoods[i]
for i in range(neighb.shape[0]):
v = neighb[i]
if labels[v] == -1:
stack.append(v)
if len(stack) == 0:
break
i = stack[len(stack)-1]
del(stack[len(stack)-1])
if sum(labels==label_num) > 29:
label_num += 1
else:
labels[labels==label_num] = len(data)
#False clusters remotion
labels[labels==len(data)] = -1
#Clusterization has finished, now the clusters found with ransac fit model will be marked
la_aux[:,0] = np.copy(labels)
la_aux[auxiliar_points,1] = 1
return la_aux
<|end_of_text|># cython: language_level=3, boundscheck=False, wraparound=False, cdivision=True, embedsignature=True
cimport cython
from cython.operator cimport dereference as deref
import numpy as np
cimport numpy as np
import scipy.stats as sps
from enum import Enum
from addict import Dict as edict
from numpy.math cimport NAN, isnan, PI, isinf, INFINITY
from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t
from libc.math cimport atan2, sqrt, fabs
from libcpp.vector cimport vector
from libcpp.unordered_map cimport unordered_map
from libcpp.unordered_set cimport unordered_set
from libcpp.pair cimport pair
from d3d.abstraction cimport Target3DArray, TransformSet, ObjectTarget3D
from d3d.tracking.matcher cimport ScoreMatcher, DistanceTypes
from d3d.math cimport wmean, diffnorm3, cross3
cdef inline int bisect(vector[float] &arr, float x) nogil:
'''Cython version of bisect.bisect_left'''
cdef int lo=0, hi=arr.size(), mid
while lo < hi:
mid = (lo+hi)//2
if arr[mid] < x: lo = mid+1
else: hi = mid
return lo
cdef inline float calc_precision(int tp, int fp) nogil:
if fp == 0: return 1
else: return <float>tp / (tp + fp)
cdef inline float calc_recall(int tp, int fn) nogil:
if fn == 0: return 1
else: return <float>tp / (tp + fn)
cdef inline float calc_fscore(int tp, int fp, int fn, float b2) nogil:
return (1+b2) * tp / ((1+b2)*tp + b2*fn + fp)
@cython.boundscheck(False)
@cython.wraparound(False)
cdef inline float quatdiff( # calculate |inv(p) * q|
const float[:] p, const float[:] q
) nogil:
cdef float cx, cy, cz
cx, cy, cz = cross3(p, q)
cdef float rx, ry, rz, rw
rx = p[3]*q[0] - q[3]*p[0] + cx
ry = p[3]*q[1] - q[3]*p[1] + cy
rz = p[3]*q[2] - q[3]*p[2] + cz
rw = -p[3]*q[3] - p[0]*q[0] - p[1]*q[1] - p[2]*q[2]
cdef float angle
angle = 2 * atan2(sqrt(rx*rx + ry*ry + rz*rz), fabs(rw))
return angle
@cython.auto_pickle(True)
cdef class DetectionEvalStats:
''' Detection stats summary of a evaluation step '''
cdef public unordered_map[int, int] ngt
cdef public unordered_map[int, vector[int]] tp, fp, fn, ndt
cdef public unordered_map[int, vector[float]] acc_iou, acc_angular, acc_dist, acc_box, acc_var
cdef void initialize(self, unordered_set[int] &classes, int nsamples):
| Cython |
for k in classes:
self.ngt[k] = 0
self.ndt[k] = vector[int](nsamples, 0)
self.tp[k] = vector[int](nsamples, 0)
self.fp[k] = vector[int](nsamples, 0)
self.fn[k] = vector[int](nsamples, 0)
self.acc_angular[k] = vector[float](nsamples, NAN)
self.acc_iou[k] = vector[float](nsamples, NAN)
self.acc_box[k] = vector[float](nsamples, NAN)
self.acc_dist[k] = vector[float](nsamples, NAN)
self.acc_var[k] = vector[float](nsamples, NAN)
def as_object(self):
return dict(ngt=self.ngt, tp=self.tp, fp=self.fp, fn=self.fn, ndt=self.ndt,
acc_iou=self.acc_iou, acc_angular=self.acc_angular, acc_dist=self.acc_dist,
acc_box=self.acc_box, acc_var=self.acc_var
)
@cython.auto_pickle(True)
cdef class DetectionEvaluator:
'''Benchmark for object detection'''
# member declarations
cdef int _pr_nsamples
cdef float _min_score
cdef unordered_set[int] _classes
cdef object _class_type
cdef unordered_map[int, float] _max_distance
cdef vector[float] _pr_thresholds
cdef DetectionEvalStats _stats # aggregated statistics declarations
def __init__(self, classes, min_overlaps, int pr_sample_count=40, float min_score=0, str pr_sample_scale="log10"):
'''
Object detection benchmark. Targets association is done by score sorting.
:param classes: Object classes to consider
:param min_overlaps: Min overlaps per class for two boxes being considered as overlap.
If single value is provided, all class will use the same overlap threshold
:param min_score: Min score for precision-recall samples
:param pr_sample_count: Number of precision-recall sample points (expect for p=1,r=0 and p=0,r=1)
:param pr_sample_scale: PR sample type, {lin: linspace, log: logspace 1~10, logX: logspace 1~X}
'''
# parse parameters
if isinstance(classes, (list, tuple)):
assert len(classes) > 0
self._class_type = type(classes[0])
for c in classes:
self._classes.insert(c.value)
else:
self._class_type = type(classes)
self._classes.insert(classes.value)
if isinstance(min_overlaps, (list, tuple)):
self._max_distance = {classes[i].value: 1 - v for i, v in enumerate(min_overlaps)}
elif isinstance(min_overlaps, (int, float)):
self._max_distance = {c: 1 - min_overlaps for c in self._classes}
else:
raise ValueError("min_overlaps should be a list or a single value")
self._pr_nsamples = pr_sample_count
self._min_score = min_score
# generate score thresholds
cdef np.ndarray thresholds
if pr_sample_scale == "lin":
thresholds = np.linspace(min_score, 1, pr_sample_count, endpoint=False, dtype=np.float32)
elif pr_sample_scale.startswith("log"):
logstart, logend = 1, int(pr_sample_scale[3:] or "10")
thresholds = np.geomspace(logstart, logend, pr_sample_count+1, dtype=np.float32)
thresholds = (thresholds - logstart) * (1 - min_score) / (logend - logstart)
thresholds = (1 - thresholds)[:0:-1]
else:
raise ValueError("Unrecognized PR sample type")
self._pr_thresholds = thresholds
# initialize maps
self._stats = DetectionEvalStats()
self._stats.initialize(self._classes, self._pr_nsamples)
cpdef void reset(self):
self._stats.initialize(self._classes, self._pr_nsamples)
cdef inline unordered_map[int, vector[float]] _aggregate_stats(self,
vector[unordered_map[int, float]]& acc, vector[int]& gt_tags) nogil:
'''Help put accuracy values into categories'''
# init intermediate vars
cdef unordered_map[int, vector[float]] sorted_sum, aggregated
cdef unordered_map[int, vector[int]] sorted_count
for k in self._classes:
sorted_sum[k] = vector[float](self._pr_nsamples, 0)
sorted_count[k] = vector[int](self._pr_nsamples, 0)
aggregated[k] = vector[float](self._pr_nsamples, 0)
# sort accuracies into categories
for score_idx in range(self._pr_nsamples):
for diter in acc[score_idx]:
sorted_sum[gt_tags[diter.first]][score_idx] += diter.second
sorted_count[gt_tags[diter.first]][score_idx] += 1
# aggregate
for k in self._classes:
for score_idx in range(self._pr_nsamples):
# assert sorted_count[k][score_idx] == tp[k][score_idx]
if sorted_count[k][score_idx] > 0:
aggregated[k][score_idx] = sorted_sum[k][score_idx] / sorted_count[k][score_idx]
else:
aggregated[k][score_idx] = NAN
return aggregated
cpdef DetectionEvalStats calc_stats(self, Target3DArray gt_boxes, Target3DArray dt_boxes, TransformSet calib=None):
# convert boxes to the same frame
if gt_boxes.frame!= dt_boxes.frame:
if calib is None:
raise ValueError("Calibration is not provided when dt_boxes and gt_boxes are in different frames!")
gt_boxes = calib.transform_objects(gt_boxes, frame_to=dt_boxes.frame)
# forward definitions
cdef int gt_idx, gt_tag, dt_idx, dt_tag
cdef float score_thres, angular_acc_cur, var_acc_cur
# initialize matcher
cdef ScoreMatcher matcher = ScoreMatcher()
matcher.prepare_boxes(dt_boxes, gt_boxes, DistanceTypes.RIoU)
# initialize statistics
cdef DetectionEvalStats summary = DetectionEvalStats()
cdef vector[unordered_map[int, float]] iou_acc, angular_acc, dist_acc, box_acc, var_acc
for k in self._classes:
summary.ngt[k] = 0
summary.ndt[k] = vector[int](self._pr_nsamples, 0)
summary.tp[k] = vector[int](self._pr_nsamples, 0)
summary.fp[k] = vector[int](self._pr_nsamples, 0)
summary.fn[k] = vector[int](self._pr_nsamples, 0)
iou_acc.resize(self._pr_nsamples)
angular_acc.resize(self._pr_nsamples)
dist_acc.resize(self._pr_nsamples)
box_acc.resize(self._pr_nsamples)
var_acc.resize(self._pr_nsamples)
# select ground-truth boxes to match
cdef vector[int] gt_indices, dt_indices
for gt_idx in range(gt_boxes.size()):
gt_tag = gt_boxes.get(gt_idx).tag.labels[0]
if self._classes.find(gt_tag) == self._classes.end():
continue # skip objects within ignored category
summary.ngt[gt_tag] += 1
gt_indices.push_back(gt_idx)
# loop over score thres
cdef ObjectTarget3D gt_box, dt_box
for score_idx in range(self._pr_nsamples):
score_thres = self._pr_thresholds[score_idx]
# select detection boxes to match
dt_indices.clear()
for dt_idx in range(dt_boxes.size()):
dt_box = dt_boxes.get(dt_idx)
dt_tag = dt_box.tag.labels[0]
if self._classes.find(dt_tag) == self._classes.end():
continue # skip objects within ignored category
if dt_boxes.get(dt_idx).tag.scores[0] < score_thres:
continue # skip objects with lower scores
summary.ndt[dt_tag][score_idx] += 1
dt_indices.push_back(dt_idx)
# match boxes
matcher.clear_match()
matcher.match(dt_indices, gt_indices, self._max_distance)
# process ground-truth match results
for gt_idx in gt_indices:
gt_box = gt_boxes.get(gt_idx)
gt_tag = gt_box.tag.labels[0]
dt_idx = matcher.query_dst_match(gt_idx)
if dt_idx < 0:
summary.fn[gt_tag][score_idx] += 1
continue
summary.tp[gt_tag][score_idx] += 1
dt_box = dt_boxes.get(dt_idx)
# caculate accuracy values for various criteria
iou_acc[score_idx][gt_idx] = 1 - matcher._distance_cache[dt_idx, gt_idx] # FIXME: not elegant here
dist_acc[score_idx][gt_idx] = diffnorm3(gt_box.position_, dt_box.position_)
box_acc[score_idx][gt_idx] = diffnorm3(gt_box.dimension_, dt_box.dimension_)
angular_acc_cur = quatdiff(gt_box.orientation_, dt_box.orientation_)
angular_acc[score_idx][gt_idx] = angular_acc_cur / PI
if dt_boxes[dt_idx].orientation | Cython |
_var > 0: # FIXME: these operations slow down the evaluator
var_acc_cur = sps.multivariate_normal.logpdf(gt_boxes[gt_idx].position,
dt_boxes[dt_idx].position, cov=dt_boxes[dt_idx].position_var)
var_acc_cur += sps.multivariate_normal.logpdf(gt_boxes[gt_idx].dimension,
dt_boxes[dt_idx].dimension, cov=dt_boxes[dt_idx].dimension_var)
var_acc_cur += sps.vonmises.logpdf(angular_acc_cur, kappa=1/dt_boxes[dt_idx].orientation_var)
var_acc[score_idx][gt_idx] = var_acc_cur
else:
var_acc[score_idx][gt_idx] = -INFINITY
# process detection match results
for dt_idx in dt_indices:
dt_tag = dt_boxes.get(dt_idx).tag.labels[0]
if matcher.query_src_match(dt_idx) < 0:
summary.fp[dt_tag][score_idx] += 1
# aggregate accuracy metrics
cdef vector[int] gt_tags
gt_tags.reserve(gt_boxes.size())
for gt_idx in range(gt_boxes.size()):
gt_tags.push_back(gt_boxes.get(gt_idx).tag.labels[0])
summary.acc_iou = self._aggregate_stats(iou_acc, gt_tags)
summary.acc_angular = self._aggregate_stats(angular_acc, gt_tags)
summary.acc_dist = self._aggregate_stats(dist_acc, gt_tags)
summary.acc_box = self._aggregate_stats(box_acc, gt_tags)
summary.acc_var = self._aggregate_stats(var_acc, gt_tags)
return summary
cpdef void add_stats(self, DetectionEvalStats stats) except*:
'''
Add statistics from calc_stats into database
'''
cdef int otp, ntp
for k in self._classes:
self._stats.ngt[k] += stats.ngt[k]
for i in range(self._pr_nsamples):
# aggregate accuracies
otp, ntp = self._stats.tp[k][i], stats.tp[k][i]
self._stats.acc_angular[k][i] = wmean(
self._stats.acc_angular[k][i], otp, stats.acc_angular[k][i], ntp)
self._stats.acc_box[k][i] = wmean(
self._stats.acc_box[k][i], otp, stats.acc_box[k][i], ntp)
self._stats.acc_iou[k][i] = wmean(
self._stats.acc_iou[k][i], otp, stats.acc_iou[k][i], ntp)
self._stats.acc_dist[k][i] = wmean(
self._stats.acc_dist[k][i], otp, stats.acc_dist[k][i], ntp)
self._stats.acc_var[k][i] = wmean(
self._stats.acc_var[k][i], otp, stats.acc_var[k][i], ntp)
# aggregate common stats
self._stats.ndt[k][i] = self._stats.ndt[k][i] + stats.ndt[k][i]
self._stats.tp[k][i] = self._stats.tp[k][i] + stats.tp[k][i]
self._stats.fp[k][i] = self._stats.fp[k][i] + stats.fp[k][i]
self._stats.fn[k][i] = self._stats.fn[k][i] + stats.fn[k][i]
cpdef DetectionEvalStats get_stats(self):
'''
Summarize current state of the benchmark counters
'''
return self._stats
cdef inline int _get_score_idx(self, float score) nogil:
if isnan(score):
return self._pr_nsamples // 2
else:
return bisect(self._pr_thresholds, score)
@property
def score_thresholds(self):
return np.asarray(self._pr_thresholds)
def gt_count(self):
return self._stats.ngt
def dt_count(self, float score=NAN):
cdef int score_idx = self._get_score_idx(score)
return {self._class_type(diter.first): diter.second[score_idx] for diter in self._stats.ndt}
def tp(self, float score=NAN):
'''Return true positive count. If score is not specified, return the median value'''
cdef int score_idx = self._get_score_idx(score)
return {self._class_type(diter.first): diter.second[score_idx] for diter in self._stats.tp}
def fp(self, float score=NAN):
'''Return false positive count. If score is not specified, return the median value'''
cdef int score_idx = self._get_score_idx(score)
return {self._class_type(diter.first): diter.second[score_idx] for diter in self._stats.fp}
def fn(self, float score=NAN):
'''Return false negative count. If score is not specified, return the median value'''
cdef int score_idx = self._get_score_idx(score)
return {self._class_type(diter.first): diter.second[score_idx] for diter in self._stats.fn}
def precision(self, float score=NAN, bint return_all=False):
cdef int score_idx
if return_all:
p = {self._class_type(k): [None] * self._pr_nsamples for k in self._classes}
for k in self._classes:
for i in range(self._pr_nsamples):
p[self._class_type(k)][i] = calc_precision(self._stats.tp[k][i], self._stats.fp[k][i])
else:
score_idx = self._get_score_idx(score)
p = {self._class_type(k): calc_precision(self._stats.tp[k][score_idx], self._stats.fp[k][score_idx])
for k in self._classes}
return p
def recall(self, float score=NAN, bint return_all=False):
cdef int score_idx
if return_all:
r = {self._class_type(k): [None] * self._pr_nsamples for k in self._classes}
for k in self._classes:
for i in range(self._pr_nsamples):
r[self._class_type(k)][i] = calc_recall(self._stats.tp[k][i], self._stats.fn[k][i])
else:
score_idx = self._get_score_idx(score)
r = {self._class_type(k): calc_recall(self._stats.tp[k][score_idx], self._stats.fn[k][score_idx])
for k in self._classes}
return r
def fscore(self, float score=NAN, float beta=1, bint return_all=False):
cdef float b2 = beta * beta
cdef int score_idx
if return_all:
fs = {self._class_type(k): [None] * self._pr_nsamples for k in self._classes}
for k in self._classes:
for i in range(self._pr_nsamples):
fs[self._class_type(k)][i] = calc_fscore(self._stats.tp[k][i], self._stats.fp[k][i], self._stats.fn[k][i], b2)
else:
score_idx = self._get_score_idx(score)
fs = {self._class_type(k): calc_fscore(self._stats.tp[k][score_idx], self._stats.fp[k][score_idx], self._stats.fn[k][score_idx], b2)
for k in self._classes}
return fs
def ap(self):
'''Calculate (mean) average precision'''
p, r = self.precision(return_all=True), self.recall(return_all=True)
# usually pr curve grows from bottom right to top left as score threshold
# increases, so the area can be negative
typed_classes = (self._class_type(k) for k in self._classes)
area = {k: -np.trapz(p[k], r[k]) for k in typed_classes}
return area
def acc_iou(self, float score=NAN):
cdef int score_idx = self._get_score_idx(score)
return {self._class_type(diter.first): diter.second[score_idx] for diter in self._stats.acc_iou}
def acc_box(self, float score=NAN):
cdef int score_idx = self._get_score_idx(score)
return {self._class_type(diter.first): diter.second[score_idx] for diter in self._stats.acc_box}
def acc_dist(self, float score=NAN):
cdef int score_idx = self._get_score_idx(score)
return {self._class_type(diter.first): diter.second[score_idx] for diter in self._stats.acc_dist}
def acc_angular(self, float score=NAN):
cdef int score_idx = self._get_score_idx(score)
return {self._class_type(diter.first): diter.second[score_idx] for diter in self._stats.acc_angular}
def summary(self, float score_thres = 0.8, bint verbose = False):
'''
Print default summary (into returned string)
'''
cdef int score_idx = self._get_score_idx(score_thres)
cdef list lines = [''] # prepend an empty line
precision, recall = self.precision(score_thres), self.recall(score_thres)
fscore, ap = self.fscore(return_all=True), self | Cython |
.ap()
lines.append("========== Benchmark Summary ==========")
for k in self._classes:
typed_k = self._class_type(k)
if verbose:
lines.append("Results for %s:" % typed_k.name)
lines.append("\tTotal processed targets:\t%d gt boxes, %d dt boxes" % (
self._stats.ngt[k], max(self._stats.ndt[k])
))
lines.append("\tPrecision (score > %.2f):\t%.3f" % (score_thres, precision[typed_k]))
lines.append("\tRecall (score > %.2f):\t\t%.3f" % (score_thres, recall[typed_k]))
lines.append("\tMax F1:\t\t\t\t%.3f" % max(fscore[typed_k]))
lines.append("\tAP:\t\t\t\t%.3f" % ap[typed_k])
lines.append("")
lines.append("\tMean IoU (score > %.2f):\t\t%.3f" % (score_thres, self._stats.acc_iou[k][score_idx]))
lines.append("\tMean angular error (score > %.2f):\t%.3f" % (score_thres, self._stats.acc_angular[k][score_idx]))
lines.append("\tMean distance (score > %.2f):\t\t%.3f" % (score_thres, self._stats.acc_dist[k][score_idx]))
lines.append("\tMean box error (score > %.2f):\t\t%.3f" % (score_thres, self._stats.acc_box[k][score_idx]))
if not isinf(self._stats.acc_var[k][score_idx]):
lines.append("\tMean variance error (score > %.2f):\t%.3f" % (score_thres, self._stats.acc_var[k][score_idx]))
else:
lines.append("\tResults for %s: AP=%.3f" % (typed_k.name, ap[typed_k]))
lines.append("mAP: %.3f" % np.mean(list(ap.values())))
lines.append("========== Summary End ==========")
return '\n'.join(lines)
@cython.auto_pickle(True)
cdef class TrackingEvalStats(DetectionEvalStats):
''' Tracking stats summary of a evaluation step '''
cdef public unordered_map[int, vector[int]] id_switches
''' Number of tracked trajectory matched to different ground-truth trajectories '''
cdef public unordered_map[int, vector[int]] fragments
''' Number of ground-truth trajectory matched to different tracked tracjetories '''
cdef public unordered_map[int, unordered_map[uint64_t, int]] ngt_ids
''' Frame count of all ground-truth targets (represented by their IDs) '''
cdef public unordered_map[int, vector[unordered_map[uint64_t, int]]] ngt_tracked
''' Frame count of ground-truth targets being tracked '''
cdef public unordered_map[int, vector[unordered_map[uint64_t, int]]] ndt_ids
''' Frame count of all proposal targets (represented by their IDs) '''
cdef void initialize(self, unordered_set[int] &classes, int nsamples):
DetectionEvalStats.initialize(self, classes, nsamples)
for k in classes:
self.id_switches[k] = vector[int](nsamples, 0)
self.fragments[k] = vector[int](nsamples, 0)
self.ngt_ids[k] = unordered_map[uint64_t, int]()
self.ngt_tracked[k] = vector[unordered_map[uint64_t, int]](nsamples)
self.ndt_ids[k] = vector[unordered_map[uint64_t, int]](nsamples)
def as_object(self):
ret = dict(ngt=self.ngt, tp=self.tp, fp=self.fp, fn=self.fn, ndt=self.ndt,
acc_iou=self.acc_iou, acc_angular=self.acc_angular, acc_dist=self.acc_dist,
acc_box=self.acc_box, acc_var=self.acc_var,
id_switches=self.id_switches, fragments=self.fragments,
ngt_ids={i.first: list(i.second) for i in self.ngt_ids},
ngt_tracked={i.first: [list(s) for s in i.second] for i in self.ngt_tracked},
ndt_ids={i.first: [list(s) for s in i.second] for i in self.ndt_ids}
)
@cython.auto_pickle(True)
cdef class TrackingEvaluator(DetectionEvaluator):
'''Benchmark for object tracking'''
cdef TrackingEvalStats _tstats
# temporary variables for tracking
cdef vector[unordered_map[uint64_t, uint64_t]] _last_gt_assignment, _last_dt_assignment
cdef vector[unordered_map[uint64_t, int]] _last_gt_tags, _last_dt_tags
def __init__(self, classes, min_overlaps, int pr_sample_count=40, float min_score=0, str pr_sample_scale="log10"):
'''
Object tracking benchmark. Targets association is done by score sorting.
:param classes: Object classes to consider
:param min_overlaps: Min overlaps per class for two boxes being considered as overlap.
If single value is provided, all class will use the same overlap threshold
:param min_score: Min score for precision-recall samples
:param pr_sample_count: Number of precision-recall sample points (expect for p=1,r=0 and p=0,r=1)
:param pr_sample_scale: PR sample type, {lin: linspace, log: logspace 1~10, logX: logspace 1~X}
'''
super().__init__(classes, min_overlaps, min_score=min_score,
pr_sample_count=pr_sample_count, pr_sample_scale=pr_sample_scale)
self._last_gt_assignment.resize(self._pr_nsamples)
self._last_dt_assignment.resize(self._pr_nsamples)
self._last_gt_tags.resize(self._pr_nsamples)
self._last_dt_tags.resize(self._pr_nsamples)
self._tstats = TrackingEvalStats()
self._tstats.initialize(self._classes, self._pr_nsamples)
self._stats = self._tstats
cpdef void reset(self):
DetectionEvaluator.reset(self)
for k in self._classes:
self._tstats.id_switches[k].assign(self._pr_nsamples, 0)
self._tstats.fragments[k].assign(self._pr_nsamples, 0)
self._tstats.ngt_ids[k].clear()
for i in range(self._pr_nsamples):
self._tstats.ngt_tracked[k][i].clear()
for i in range(self._pr_nsamples):
self._last_gt_assignment[i].clear()
self._last_dt_assignment[i].clear()
self._last_gt_tags[i].clear()
self._last_dt_tags[i].clear()
cpdef TrackingEvalStats calc_stats(self, Target3DArray gt_boxes, Target3DArray dt_boxes, TransformSet calib=None):
# convert boxes to the same frame
if gt_boxes.frame!= dt_boxes.frame:
if calib is None:
raise ValueError("Calibration is not provided when dt_boxes and gt_boxes are in different frames!")
dt_boxes = calib.transform_objects(dt_boxes, frame_to=gt_boxes.frame)
# forward definitions
cdef int gt_idx, gt_tag, dt_idx, dt_tag
cdef uint64_t dt_tid, gt_tid
cdef float score_thres, angular_acc_cur, var_acc_cur
cdef unordered_map[uint64_t, int] gt_assignment_idx, dt_assignment_idx # store tid -> matched idx mapping
cdef unordered_set[uint64_t] gt_tid_set, dt_tid_set
# initialize matcher
cdef ScoreMatcher matcher = ScoreMatcher()
matcher.prepare_boxes(dt_boxes, gt_boxes, DistanceTypes.RIoU)
# initialize statistics
cdef TrackingEvalStats summary = TrackingEvalStats()
summary.initialize(self._classes, self._pr_nsamples)
cdef vector[unordered_map[int, float]] iou_acc, angular_acc, dist_acc, box_acc, var_acc
for k in self._classes:
iou_acc.resize(self._pr_nsamples)
angular_acc.resize(self._pr_nsamples)
dist_acc.resize(self._pr_nsamples)
box_acc.resize(self._pr_nsamples)
var_acc.resize(self._pr_nsamples)
# select ground-truth boxes to match
cdef vector[int] gt_indices, dt_indices
for gt_idx in range(gt_boxes.size()):
gt_tag = gt_boxes.get(gt_idx).tag.labels[0]
if self._classes.find(gt_tag) == self._classes.end():
continue # skip objects within ignored category
gt_tid = gt_boxes.get(gt_idx).tid
summary.ngt[gt_tag] += 1
summary.ngt_ids[gt_tag][gt_tid] = 1
gt_tid_set.insert(gt_tid)
gt_indices.push_back(gt_idx)
# loop over score thres
cdef ObjectTarget3D gt_box, dt_box
for score_idx in range(self._pr_nsamples):
score_thres = self._pr_thresholds[score_idx]
# select detection boxes to match
dt_indices.clear()
dt_tid_set.clear()
for dt_idx in range(dt_boxes.size()):
dt_box = dt_boxes.get(dt_idx)
dt_tag = dt_box | Cython |
.tag.labels[0]
if self._classes.find(dt_tag) == self._classes.end():
continue # skip objects within ignored category
if dt_box.tag.scores[0] < score_thres:
continue # skip objects with lower scores
dt_tid = dt_box.tid
assert dt_tid > 0, "Tracking id should be greater than 0 for a valid object!"
dt_tid_set.insert(dt_tid)
summary.ndt[dt_tag][score_idx] += 1
summary.ndt_ids[dt_tag][score_idx][dt_tid] = 1
if self._last_dt_assignment[score_idx].find(dt_tid) == self._last_dt_assignment[score_idx].end():
dt_indices.push_back(dt_idx) # match objects without previous assignment
else:
# preserve previous assignments as many as possible
gt_tid = self._last_dt_assignment[score_idx][dt_tid]
for gt_idx in range(gt_boxes.size()):
if gt_tid == gt_boxes.get(gt_idx).tid: # find the gt boxes with stored tid
if matcher._distance_cache[dt_idx, gt_idx] > self._max_distance[dt_tag]:
dt_indices.push_back(dt_idx) # also match objects that are apart from previous assignment
else:
gt_assignment_idx[gt_tid] = dt_idx
dt_assignment_idx[dt_tid] = gt_idx
break
# match boxes
matcher.clear_match()
matcher.match(dt_indices, gt_indices, self._max_distance)
# process ground-truth match results (gt_indices will always have all objects)
for gt_idx in gt_indices:
gt_box = gt_boxes.get(gt_idx)
gt_tag = gt_box.tag.labels[0]
gt_tid = gt_box.tid
# update assignment
dt_idx = matcher.query_dst_match(gt_idx)
if dt_idx >= 0:
dt_box = dt_boxes.get(dt_idx)
dt_tid = dt_box.tid
if gt_assignment_idx.find(gt_tid)!= gt_assignment_idx.end():
# overwrite previous matching
dt_assignment_idx.erase(dt_boxes.get(gt_assignment_idx[gt_tid]).tid)
dt_tag = dt_box.tag.labels[0]
summary.fp[dt_tag][score_idx] += 1
gt_assignment_idx[gt_tid] = dt_idx
dt_assignment_idx[dt_tid] = gt_idx
if gt_assignment_idx.find(gt_tid) == gt_assignment_idx.end():
summary.fn[gt_tag][score_idx] += 1
continue
dt_idx = gt_assignment_idx[gt_tid]
dt_box = dt_boxes.get(dt_idx)
summary.tp[gt_tag][score_idx] += 1
summary.ngt_tracked[gt_tag][score_idx][gt_tid] = 1
# caculate accuracy values for various criteria
iou_acc[score_idx][gt_idx] = 1 - matcher._distance_cache[dt_idx, gt_idx] # FIXME: not elegant here
dist_acc[score_idx][gt_idx] = diffnorm3(gt_box.position_, dt_box.position_)
box_acc[score_idx][gt_idx] = diffnorm3(gt_box.dimension_, dt_box.dimension_)
angular_acc_cur = quatdiff(gt_box.orientation_, dt_box.orientation_)
angular_acc[score_idx][gt_idx] = angular_acc_cur / PI
if dt_boxes[dt_idx].orientation_var > 0:
var_acc_cur = sps.multivariate_normal.logpdf(gt_boxes[gt_idx].position,
dt_boxes[dt_idx].position, cov=dt_boxes[dt_idx].position_var)
var_acc_cur += sps.multivariate_normal.logpdf(gt_boxes[gt_idx].dimension,
dt_boxes[dt_idx].dimension, cov=dt_boxes[dt_idx].dimension_var)
var_acc_cur += sps.vonmises.logpdf(angular_acc_cur, kappa=1/dt_boxes[dt_idx].orientation_var)
var_acc[score_idx][gt_idx] = var_acc_cur
else:
var_acc[score_idx][gt_idx] = -INFINITY
# process detection match results
for dt_idx in dt_indices:
dt_tag = dt_boxes.get(dt_idx).tag.labels[0]
dt_tid = dt_boxes.get(dt_idx).tid
if dt_assignment_idx.find(dt_tid) == dt_assignment_idx.end():
summary.fp[dt_tag][score_idx] += 1
# calculate id_switches and fragments
for aiter in self._last_gt_assignment[score_idx]:
gt_tid, dt_tid = aiter.first, aiter.second
gt_tag = self._last_gt_tags[score_idx][gt_tid]
if gt_assignment_idx.find(gt_tid) == gt_assignment_idx.end():
if gt_tid_set.find(gt_tid)!= gt_tid_set.end():
summary.id_switches[gt_tag][score_idx] += 1
elif dt_boxes.get(gt_assignment_idx[gt_tid]).tid!= dt_tid:
summary.id_switches[gt_tag][score_idx] += 1
for aiter in self._last_dt_assignment[score_idx]:
dt_tid, gt_tid = aiter.first, aiter.second
dt_tag = self._last_dt_tags[score_idx][dt_tid]
if dt_assignment_idx.find(dt_tid) == dt_assignment_idx.end():
if dt_tid_set.find(dt_tid)!= dt_tid_set.end():
summary.fragments[dt_tag][score_idx] += 1
elif gt_boxes.get(dt_assignment_idx[dt_tid]).tid!= gt_tid:
summary.fragments[dt_tag][score_idx] += 1
# update assignment storage
self._last_gt_assignment[score_idx].clear()
self._last_dt_assignment[score_idx].clear()
self._last_gt_tags[score_idx].clear()
self._last_dt_tags[score_idx].clear()
for giter in gt_assignment_idx:
gt_tid, dt_idx = giter.first, giter.second
dt_tag = dt_boxes.get(dt_idx).tag.labels[0]
dt_tid = dt_boxes.get(dt_idx).tid
gt_idx = dt_assignment_idx[dt_tid]
gt_tag = gt_boxes.get(gt_idx).tag.labels[0]
self._last_gt_assignment[score_idx][gt_tid] = dt_tid
self._last_dt_assignment[score_idx][dt_tid] = gt_tid
self._last_gt_tags[score_idx][gt_tid] = gt_tag
self._last_dt_tags[score_idx][dt_tid] = dt_tag
gt_assignment_idx.clear()
dt_assignment_idx.clear()
# aggregates accuracy metrics
cdef vector[int] gt_tags
gt_tags.reserve(gt_boxes.size())
for gt_idx in range(gt_boxes.size()):
gt_tags.push_back(gt_boxes.get(gt_idx).tag.labels[0])
summary.acc_iou = self._aggregate_stats(iou_acc, gt_tags)
summary.acc_angular = self._aggregate_stats(angular_acc, gt_tags)
summary.acc_dist = self._aggregate_stats(dist_acc, gt_tags)
summary.acc_box = self._aggregate_stats(box_acc, gt_tags)
summary.acc_var = self._aggregate_stats(var_acc, gt_tags)
return summary
cpdef void add_stats(self, DetectionEvalStats stats) except*:
DetectionEvaluator.add_stats(self, stats)
cdef TrackingEvalStats tstats = <TrackingEvalStats> stats
cdef uint64_t gt_tid, dt_tid
cdef int gt_count, dt_count
for k in self._classes:
for giter in tstats.ngt_ids[k]:
gt_tid, gt_count = giter.first, giter.second
if self._tstats.ngt_ids[k].find(gt_tid) == self._tstats.ngt_ids[k].end():
self._tstats.ngt_ids[k][gt_tid] = gt_count
else:
self._tstats.ngt_ids[k][gt_tid] += gt_count
for i in range(self._pr_nsamples):
self._tstats.id_switches[k][i] += tstats.id_switches[k][i]
self._tstats.fragments[k][i] += tstats.fragments[k][i]
for giter in tstats.ngt_tracked[k][i]:
gt_tid, gt_count = giter.first, giter.second
if self._tstats.ngt_tracked[k][i].find(gt_tid) == self._tstats.ngt_tracked[k][i].end():
self._tstats.ngt_tracked[k][i][gt_tid] = gt_count
else:
self._tstats.ngt_tracked[k][i][gt_tid] += gt_count
for diter in tstats.ndt_ids[k][i]:
dt_tid, dt_count = diter.first, diter.second
if self._tstats.ndt_ids[k][i].find(dt_tid) == self._tstats.ndt_ids[k][i].end():
self._tstats.ndt_ids[k][i][dt_tid] = dt_count
else:
self._tstats.ndt_ids[k][i][dt_tid] += dt_count
cpdef TrackingEvalStats get_stats(self):
'''
Summarize current state of the benchmark counters
'''
return self._tstats
def id_switches(self, float score=NAN):
'''Return ID switch count. If score is not specified, return the median value'''
cdef int score_idx = self._get_score_idx(score)
return {self._class | Cython |
_type(diter.first): diter.second[score_idx] for diter in self._tstats.id_switches}
def fragments(self, float score=NAN):
'''Return fragments count. If score is not specified, return the median value'''
cdef int score_idx = self._get_score_idx(score)
return {self._class_type(diter.first): diter.second[score_idx] for diter in self._tstats.fragments}
def gt_traj_count(self):
'''Return total ground-truth trajectory count. gt() will return total bounding box count'''
return {self._class_type(diter.first): diter.second.size() for diter in self._tstats.ngt_ids}
cdef dict _calc_frame_ratio(self, float score, float frame_ratio_threshold, bint high_pass, bint return_all):
# helper function for tracked_ratio and lost_ratio
cdef int score_idx
cdef float frame_ratio
if return_all:
r = {k: [0] * self._pr_nsamples for k in self._classes}
for k in self._classes:
for i in range(self._pr_nsamples):
for diter in self._tstats.ngt_tracked[k][i]:
frame_ratio = float(diter.second) / self._tstats.ngt_ids[k][diter.first]
if high_pass and frame_ratio > frame_ratio_threshold:
r[k][i] += 1
if not high_pass and frame_ratio < frame_ratio_threshold:
r[k][i] += 1
r = {self._class_type(k): [
float(v) / self._tstats.ngt_ids[k].size() for v in l
] for k, l in r.items()}
else:
score_idx = self._get_score_idx(score)
r = {k: 0 for k in self._classes}
for k in self._classes:
for diter in self._tstats.ngt_tracked[k][score_idx]:
frame_ratio = float(diter.second) / self._tstats.ngt_ids[k][diter.first]
if high_pass and frame_ratio > frame_ratio_threshold:
r[k] += 1
if not high_pass and frame_ratio < frame_ratio_threshold:
r[k] += 1
r = {self._class_type(k): float(v) / self._tstats.ngt_ids[k].size() for k, v in r.items()}
return r
def tracked_ratio(self, float score=NAN, float frame_ratio_threshold=0.8, bint return_all=False):
'''
Return the ratio of mostly tracked trajectories.
:param frame_ratio_threshold: The threshold of ratio of tracked frames over total frames.
A trajectory with higher tracked frames ratio will be counted as mostly tracked
'''
return self._calc_frame_ratio(score, frame_ratio_threshold, high_pass=True, return_all=return_all)
def lost_ratio(self, float score=NAN, float frame_ratio_threshold=0.2, bint return_all=False):
'''
Return the ratio of mostly lost trajectories.
:param frame_ratio_threshold: The threshold of ratio of tracked frames over total frames.
A trajectory with lower tracked frames ratio will be counted as mostly tracked
'''
return self._calc_frame_ratio(score, frame_ratio_threshold, high_pass=False, return_all=return_all)
def mota(self, float score=NAN):
'''Return the MOTA metric defined by the CLEAR MOT metrics. For MOTP equivalents, see acc_* properties'''
# TODO: is this yielding negative value correct?
cdef int score_idx = self._get_score_idx(score)
ret = {self._class_type(k): 1 - float(self._stats.fp[k][score_idx] + self._stats.fn[k][score_idx] + self._tstats.id_switches[k][score_idx])
/ self._stats.ngt[k] for k in self._classes}
return ret
def summary(self, float score_thres = 0.8,
float tracked_ratio_thres = 0.8,
float lost_ratio_thres = 0.2,
str note = None,
bint verbose = False):
'''
Print default summary (into returned string)
'''
cdef int score_idx = self._get_score_idx(score_thres)
cdef list lines = [''] # prepend an empty line
precision, recall = self.precision(score_thres), self.recall(score_thres)
fscore, ap = self.fscore(return_all=True), self.ap()
mlt = self.tracked_ratio(score_thres, tracked_ratio_thres)
mll = self.lost_ratio(score_thres, lost_ratio_thres)
mota = self.mota(score_thres)
if note:
lines.append("========== Benchmark Summary (%s) ==========" % note)
else:
lines.append("========== Benchmark Summary ==========")
for k in self._classes:
typed_k = self._class_type(k)
if verbose:
lines.append("Results for %s:" % typed_k.name)
lines.append("\tTotal processed targets:\t%d gt boxes, %d dt boxes" % (
self._stats.ngt[k], max(self._stats.ndt[k])
))
lines.append("\tTotal processed trajectories:\t%d gt tracklets, %d dt tracklets" % (
self.gt_traj_count()[typed_k], max(len(self._tstats.ndt_ids[k][i]) for i in range(self._pr_nsamples))
))
lines.append("\tPrecision (score > %.2f):\t%.3f" % (score_thres, precision[typed_k]))
lines.append("\tRecall (score > %.2f):\t\t%.3f" % (score_thres, recall[typed_k]))
lines.append("\tMax F1:\t\t\t\t%.3f" % max(fscore[typed_k]))
lines.append("\tAP:\t\t\t\t%.3f" % ap[typed_k])
lines.append("")
lines.append("\tID switches (score > %.2f):\t\t\t%d" % (score_thres, self._tstats.id_switches[k][score_idx]))
lines.append("\tFragments (score > %.2f):\t\t\t%d" % (score_thres, self._tstats.fragments[k][score_idx]))
lines.append("\tMOTA (score > %.2f):\t\t\t\t%.2f" % (score_thres, mota[typed_k]))
lines.append("\tMostly tracked (score > %.2f, ratio > %.2f):\t%.3f" % (
score_thres, tracked_ratio_thres, mlt[typed_k]))
lines.append("\tMostly lost (score > %.2f, ratio < %.2f):\t%.3f" % (
score_thres, lost_ratio_thres, mll[typed_k]))
lines.append("")
lines.append("\tMean IoU (score > %.2f):\t\t%.3f" % (score_thres, self._stats.acc_iou[k][score_idx]))
lines.append("\tMean angular error (score > %.2f):\t%.3f" % (score_thres, self._stats.acc_angular[k][score_idx]))
lines.append("\tMean distance (score > %.2f):\t\t%.3f" % (score_thres, self._stats.acc_dist[k][score_idx]))
lines.append("\tMean box error (score > %.2f):\t\t%.3f" % (score_thres, self._stats.acc_box[k][score_idx]))
if not isinf(self._stats.acc_var[k][score_idx]):
lines.append("\tMean variance error (score > %.2f):\t%.3f" % (score_thres, self._stats.acc_var[k][score_idx]))
else:
lines.append("Results for %s: AP=%.3f, MOTA=%.3f" % (typed_k.name, ap[typed_k], mota[typed_k]))
lines.append("mAP: %.3f" % np.mean(list(ap.values())))
lines.append("========== Summary End ==========")
return '\n'.join(lines)
@cython.auto_pickle(True)
cdef class SegmentationStats:
''' Tracking stats summary of a data frame '''
cdef public unordered_map[uint8_t, int] tp
''' Number of true negative data points in semantic segmentation'''
cdef public unordered_map[uint8_t, int] fp
''' Number of false positive data points in semantic segmentation '''
cdef public unordered_map[uint8_t, int] fn
''' Number of false negative data points in semantic segmentation '''
cdef public unordered_map[uint8_t, int] itp
''' Number of true negative data segments in instance segmentation'''
cdef public unordered_map[uint8_t, int] ifp
''' Number of false positives data segments in instance segmentation '''
cdef public unordered_map[uint8_t, int] ifn
''' Number of false negative data segments in instance segmentation '''
cdef public unordered_map[uint8_t, float] cumiou
''' Summation of IoU of TP segments in instance segmentation '''
cdef void initialize(self, unordered_set[uint8_t] &classes):
for k in classes:
self.tp[k] = 0
self.fp[k] = 0
self.fn[k] = 0
self.itp[k] = 0 | Cython |
self.ifp[k] = 0
self.ifn[k] = 0
self.cumiou[k] = 0
def as_object(self):
return dict(tp=self.tp, fp=self.fp, fn=self.fn,
itp=self.itp, ifp=self.ifp, ifn=self.ifn,
cumiou=self.cumiou)
@cython.auto_pickle(True)
cdef class SegmentationEvaluator:
'''Benchmark for semgentation'''
# REF: https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/evaluation/evalPanopticSemanticLabeling.py
cdef unordered_set[uint8_t] _classes
cdef SegmentationStats _stats
cdef uint8_t _background
cdef int _min_points
cdef object _class_type
def __init__(self, classes, background=0, min_points=0):
'''
:param classes: classes to be considered during evaluation, other classes are all considered as background
:param background: class to be considered as background class
:param min_points: minimum number of points when calculating segments in panoptic evaluation
'''
# parse parameters
if not isinstance(classes, (list, tuple)):
classes = [classes]
assert len(classes) > 0
if isinstance(classes[0], Enum):
self._class_type = type(classes[0])
self._classes = set(c.value for c in classes)
elif isinstance(classes[0], int):
self._class_type = None
self._classes = set(classes)
else:
raise ValueError("Classes should be int or Enum")
if isinstance(background, Enum):
background = background.value
self._background = background if background >= 0 else 256 + background
self._min_points = min_points
self._stats = SegmentationStats()
self._stats.initialize(self._classes)
if len(self._classes) > 255:
raise ValueError("Only support up to 255 different categories!")
cpdef void reset(self):
self._stats.initialize(self._classes)
@cython.boundscheck(False)
@cython.wraparound(False)
cdef void collect_labels(self, SegmentationStats stats, const uint8_t[:] gt_labels, const uint8_t[:] pred_labels) nogil:
for i in range(len(gt_labels)):
if gt_labels[i]!= self._background and self._classes.find(gt_labels[i])!= self._classes.end():
if gt_labels[i] == pred_labels[i]:
stats.tp[gt_labels[i]] += 1
else:
stats.fn[gt_labels[i]] += 1
if pred_labels[i]!= self._background and self._classes.find(pred_labels[i])!= self._classes.end() and gt_labels[i]!= pred_labels[i]:
stats.fp[pred_labels[i]] += 1
@cython.boundscheck(False)
@cython.wraparound(False)
cdef void collect_labels_pano(self, SegmentationStats stats,
const uint8_t[:] gt_labels, const uint8_t[:] pred_labels,
const uint16_t[:] gt_ids, const uint16_t[:] pred_ids) nogil:
self.collect_labels(stats, gt_labels, pred_labels)
# collect mappings
cdef unordered_map[uint32_t, int] gt_counter, pred_counter
cdef unordered_set[uint32_t] pred_unmatched
# (gt_label + gt_id) -> {(dt_label + dt_id) -> count}
cdef unordered_map[uint32_t, unordered_map[uint32_t, int]] counter = unordered_map[uint32_t, unordered_map[uint32_t, int]]()
cdef unordered_map[uint32_t, unordered_map[uint32_t, int]].iterator gt_iter
cdef unordered_map[uint32_t, int].iterator pred_iter
cdef uint32_t gt_key, pred_key, bg_key = self._background << 16
for i in range(len(gt_labels)):
if self._classes.find(gt_labels[i]) == self._classes.end():
gt_key = bg_key
else:
gt_key = gt_labels[i] << 16 | gt_ids[i]
if self._classes.find(pred_labels[i]) == self._classes.end():
pred_key = bg_key
else:
pred_key = pred_labels[i] << 16 | pred_ids[i]
# increase counter
gt_iter = counter.find(gt_key)
if gt_iter == counter.end():
gt_iter = counter.insert(gt_iter, pair[uint32_t, unordered_map[uint32_t, int]](gt_key, unordered_map[uint32_t, int]()))
gt_counter[gt_key] = 0
gt_counter[gt_key] += 1
pred_iter = deref(gt_iter).second.find(pred_key)
if pred_iter == deref(gt_iter).second.end():
pred_iter = deref(gt_iter).second.insert(pred_iter, pair[uint32_t, int](pred_key, 0))
deref(pred_iter).second = deref(pred_iter).second + 1
if pred_counter.find(pred_key) == pred_counter.end():
pred_counter[pred_key] = 0
pred_counter[pred_key] += 1
# collect predictions
if pred_unmatched.find(pred_key) == pred_unmatched.end():
pred_unmatched.insert(pred_key)
# collect tp
cdef uint8_t gt_label, pred_label
cdef float total, iou
cdef bint matched
for citer in counter:
matched = False
gt_key = citer.first
gt_label = gt_key >> 16
if gt_label == self._background:
continue
if gt_counter[gt_key] < self._min_points: # ignore segments with too few points
continue
for piter in citer.second:
pred_key = piter.first
pred_label = pred_key >> 16
if pred_label == self._background:
continue
if gt_label!= pred_label:
continue
total = gt_counter[gt_key] + pred_counter[pred_key] - piter.second
if counter[bg_key].find(pred_key) == counter[bg_key].end():
total -= counter[bg_key][pred_key] # TODO: is this necessary?
iou = piter.second / total
if iou > 0.5:
stats.itp[gt_label] += 1
stats.cumiou[gt_label] += iou
matched = True
if pred_unmatched.find(pred_key)!= pred_unmatched.end():
pred_unmatched.erase(pred_key)
if not matched:
stats.ifn[gt_label] += 1
for pred_key in pred_unmatched:
if pred_counter[pred_key] < self._min_points:
continue
pred_label = pred_key >> 16
if pred_label!= self._background:
stats.ifp[pred_label] += 1
cpdef SegmentationStats calc_stats(self,
np.ndarray[ndim=1, dtype=uint8_t] gt_labels,
np.ndarray[ndim=1, dtype=uint8_t] pred_labels,
np.ndarray gt_ids=None, np.ndarray pred_ids=None):
'''
Please make sure the id are 0 if the label is in stuff category
'''
cdef SegmentationStats stats = SegmentationStats()
stats.initialize(self._classes)
if gt_ids is None or pred_ids is None:
self.collect_labels(stats, gt_labels, pred_labels)
else:
if gt_ids.dtype!= np.uint16 or pred_ids.dtype!= np.uint16:
raise ValueError("Please convert ids to uint16!")
self.collect_labels_pano(stats, gt_labels, pred_labels, gt_ids, pred_ids)
return stats
cpdef void add_stats(self, SegmentationStats stats) except*:
for k in self._classes:
self._stats.tp[k] += stats.tp[k]
self._stats.fp[k] += stats.fp[k]
self._stats.fn[k] += stats.fn[k]
self._stats.itp[k] += stats.itp[k]
self._stats.ifp[k] += stats.ifp[k]
self._stats.ifn[k] += stats.ifn[k]
self._stats.cumiou[k] += stats.cumiou[k]
cpdef SegmentationStats get_stats(self):
'''
Summarize current state of the benchmark counters
'''
return self._stats
def tp(self, bint instance=False):
if instance:
if self._class_type is None:
return self._stats.itp
return {self._class_type(diter.first): diter.second for diter in self._stats.itp}
else:
if self._class_type is None:
return self._stats.tp
return {self._class_type(diter.first): diter.second for diter in self._stats.tp}
def fp(self, bint instance=False):
if instance:
if self._class_type is None:
return self._stats.ifp
return {self._class_type(diter.first): diter.second for diter in self._stats.ifp}
else:
if self._class_type is None:
return self._stats.fp
return {self._class_type(diter.first): diter.second for diter in self._stats.fp | Cython |
}
def fn(self, bint instance=False):
if instance:
if self._class_type is None:
return self._stats.ifn
return {self._class_type(diter.first): diter.second for diter in self._stats.ifn}
else:
if self._class_type is None:
return self._stats.fn
return {self._class_type(diter.first): diter.second for diter in self._stats.fn}
def iou(self, bint instance=False):
cdef float iou, d
result = {}
for k in self._classes:
if instance:
d = self._stats.itp[k]
iou = (self._stats.cumiou[k] / d) if self._stats.itp[k] > 0 else NAN
else:
d = self._stats.tp[k] + self._stats.fp[k] + self._stats.fn[k]
iou = (self._stats.tp[k] / d) if d > 0 else NAN
if self._class_type is None:
result[k] = iou
else:
result[self._class_type(k)] = iou
return result
def sq(self):
''' Segmentation Quality (SQ) in panoptic segmentation '''
return self.iou(instance=True)
def rq(self):
''' Recognition Quality (RQ) in panoptic segmentation '''
cdef float rq, d
result = {}
for k in self._classes:
d = self._stats.itp[k] + self._stats.ifp[k] * 0.5 + self._stats.ifn[k] * 0.5
rq = (self._stats.itp[k] / d) if d > 0 else NAN
if self._class_type is None:
result[k] = rq
else:
result[self._class_type(k)] = rq
return result
def pq(self):
''' Panoptic Quality (PQ) in panoptic segmentation '''
sq, rq = self.sq(), self.rq()
return {k: sq[k] * rq[k] for k in sq}
def summary(self):
lines = []
def mean_wo_nan(values):
valid = [v for v in values if not isnan(v)]
if len(valid) == 0:
return NAN
return sum(valid) / len(valid)
lines.append("========== Benchmark Summary ==========")
iou = self.iou()
sq, rq, pq = self.sq(), self.rq(), self.pq()
for k in self._classes:
if k == self._background:
continue
typed_k = k if self._class_type is None else self._class_type(k)
name = str(k).rjust(4, " ") if self._class_type is None else typed_k.name.rjust(20, " ")
if isnan(pq[typed_k]):
lines.append("%s: iou=%.3f" % (name, iou[typed_k]))
else:
lines.append("%s: iou=%.3f, sq=%.3f, rq=%.3f, pq=%.3f" % (name,
iou[typed_k], sq[typed_k], rq[typed_k], pq[typed_k]))
lines.append("mean IoU: %.4f" % mean_wo_nan(iou.values()))
if not isnan(mean_wo_nan(pq.values())):
lines.append("mean SQ: %.4f" % mean_wo_nan(sq.values()))
lines.append("mean RQ: %.4f" % mean_wo_nan(rq.values()))
lines.append("mean PQ: %.4f" % mean_wo_nan(pq.values()))
lines.append("========== Summary End ==========")
return '\n'.join(lines)
<|end_of_text|># cython: language_level=3
from os.path import abspath, expanduser
from cpython cimport bool as py_bool
from libc.stdlib cimport malloc, free
from libc.string cimport const_char
from libc.stdint cimport uint64_t
from libcpp cimport bool as c_bool
from libcpp.string cimport string
cimport leveldb
from pycomparator cimport PyComparator_FromPyFunction
from weakref import ref as weak_ref
# status handling
class NotFoundError(Exception):
pass
class CorruptionError(Exception):
pass
class IOError(Exception):
pass
class NotSupportedError(Exception):
pass
class InvalidArgumentError(Exception):
pass
cdef int check_status(leveldb.Status& st) except -1:
if st.ok():
return 0
elif st.IsNotFound():
raise NotFoundError(st.ToString().decode('UTF-8'))
elif st.IsCorruption():
raise CorruptionError(st.ToString().decode('UTF-8'))
elif st.IsIOError():
raise IOError(st.ToString().decode('UTF-8'))
elif st.IsNotSupportedError():
raise NotSupportedError(st.ToString().decode('UTF-8'))
elif st.IsInvalidArgument():
raise InvalidArgumentError(st.ToString().decode('UTF-8'))
return -1
# Option wrapper
cdef class Options:
cdef leveldb.Options _options
def __cinit__(self, compare_function=None, py_bool create_if_missing=True,
py_bool error_if_exists=None, py_bool paranoid_checks=None,
write_buffer_size=None, max_open_files=None,
block_restart_interval=None, max_file_size=None,
compression=None):
if compare_function is None:
self._options.comparator = leveldb.BytewiseComparator()
else:
self._options.comparator = PyComparator_FromPyFunction(
compare_function, compare_function.__name__.encode('UTF-8')
)
if create_if_missing is not None:
self._options.create_if_missing = create_if_missing
if error_if_exists is not None:
self._options.error_if_exists = error_if_exists
if paranoid_checks is not None:
self._options.paranoid_checks = paranoid_checks
if write_buffer_size is not None:
self._options.write_buffer_size = write_buffer_size
if max_open_files is not None:
self._options.max_open_files = max_open_files
if block_restart_interval is not None:
self._options.write_buffer_size = write_buffer_size
if max_file_size is not None:
self._options.max_file_size = max_file_size
if compression is None:
compression = leveldb.CompressionType.kNoCompression
elif compression in (leveldb.CompressionType.kNoCompression, leveldb.CompressionType.kSnappyCompression):
self._options.compression = compression
elif isinstance(compression, bytes):
compression_str = compression.decode('UTF-8')
if compression_str == u'snappy':
self._options.compression = leveldb.CompressionType.kSnappyCompression
else:
raise RuntimeError(f'Unknown compression type {compression}')
cdef class WriteOptions:
cdef leveldb.WriteOptions _writeOptions
def __cinit__(self, py_bool sync=None):
if sync is not None:
self._writeOptions.sync = sync
cdef class ReadOptions:
cdef leveldb.ReadOptions _readOptions
cdef Snapshot _snapshot_handler
def __cinit__(self, py_bool verify_checksums=None, py_bool fill_cache=None):
if verify_checksums is not None:
self._readOptions.verify_checksums = verify_checksums
if fill_cache is not None:
self._readOption.fill_cache = fill_cache
def register_snapshot(self, Snapshot snapshot not None):
self._readOptions.snapshot = snapshot._snapshot_ptr
self._snapshot_handler = snapshot
def release_snapshot(self):
if self._readOptions.snapshot!= NULL:
self._readOptions.snapshot = NULL
self._snapshot_handler = None
cdef class Snapshot:
cdef DB _db_handler
cdef const leveldb.Snapshot* _snapshot_ptr
def __cinit__(self):
pass
cdef _set(self, DB db, const leveldb.Snapshot* snapshot):
self._db_handler = db
self._snapshot_ptr = snapshot
cdef _close(self):
if self._snapshot_ptr == NULL or self._db_handler.closed:
return
self._db_handler._db.ReleaseSnapshot(self._snapshot_ptr)
self._snapshot_ptr = NULL
self._db_handler = None
def __dealloc__(self):
self._close()
# Write batch wrapper
cdef class WriteBatch:
cdef leveldb.WriteBatch _batch
def __cinit__(self):
pass
def put(self, str key not None, str value not None):
cdef string keyEncoded = key.encode('UTF-8')
cdef string valueEncoded = value.encode('UTF-8')
self._batch.Put(leveldb.Slice(keyEncoded), leveldb.Slice(valueEncoded))
def delete(self, str key not None):
cdef string keyEncoded = key.encode('UTF-8')
self._batch.Delete(leveldb.Slice(keyEncoded))
def clear(self):
self._batch.Clear()
def size(self):
return self._batch.ApproximateSize()
def append(self, WriteBatch other):
self._batch.Append(other._batch)
# DB iterator wrapper
cdef class Iterator:
cdef leveldb.Iterator* _iter_ptr
cdef c_bool reversed
cdef | Cython |
_set_iter(self, leveldb.Iterator* iter, py_bool reversed):
self._iter_ptr = iter
self.reversed = reversed
if not reversed:
self._iter_ptr.SeekToFirst()
else:
self._iter_ptr.SeekToLast()
def __next__(self):
if not self._iter_ptr.Valid():
raise StopIteration
cdef str key = self._iter_ptr.key().ToString().decode('UTF-8')
cdef str value = self._iter_ptr.value().ToString().decode('UTF-8')
if not self.reversed:
self._iter_ptr.Next()
else:
self._iter_ptr.Prev()
cdef leveldb.Status st = self._iter_ptr.status()
check_status(st)
return key, value
def seek(self, str key not None, py_bool sanity_check=False):
cdef string keyEncoded = key.encode('UTF-8')
cdef leveldb.Slice keySlice = leveldb.Slice(keyEncoded)
cdef leveldb.Slice seeked
self._iter_ptr.Seek(keySlice)
if self.reversed:
seeked = self._iter_ptr.key()
if seeked.compare(keySlice)!= 0:
self._iter_ptr.Prev()
cdef leveldb.Status st
if sanity_check:
st = self._iter_ptr.status()
check_status(st)
def seek_first(self, py_bool sanity_check=False):
if not self.reversed:
self._iter_ptr.SeekToFirst()
else:
self._iter_ptr.SeekToLast()
cdef leveldb.Status st
if sanity_check:
st = self._iter_ptr.status()
check_status(st)
def seek_last(self, py_bool sanity_check=False):
if not self.reversed:
self._iter_ptr.SeekToLast()
else:
self._iter_ptr.SeekToFirst()
cdef leveldb.Status st
if sanity_check:
st = self._iter_ptr.status()
check_status(st)
def move_forward(self, py_bool sanity_check=False):
if not self.reversed:
self._iter_ptr.Next()
else:
self._iter_ptr.Prev()
cdef leveldb.Status st
if sanity_check:
st = self._iter_ptr.status()
check_status(st)
def move_backward(self, py_bool sanity_check=False):
if not self.reversed:
self._iter_ptr.Prev()
else:
self._iter_ptr.Next()
cdef leveldb.Status st
if sanity_check:
st = self._iter_ptr.status()
check_status(st)
def __iter__(self):
return self
cdef _close(self):
if self._iter_ptr!= NULL:
del self._iter_ptr
self._iter_ptr = NULL
def __dealloc__(self):
self._close()
# DB wrapper
cdef class DB:
cdef leveldb.DB* _db
cdef list _snapshots
cdef list _iterators
def __cinit__(self, str name not None, Options options=None):
if options is None:
options = Options()
cdef leveldb.Status st
cdef str full_path = abspath(expanduser(name))
cdef string full_path_encoded = full_path.encode('UTF-8')
st = leveldb.DB.Open(options._options, full_path_encoded, &self._db)
check_status(st)
self._snapshots = list()
self._iterators = list()
def __setitem__(self, str key not None, str value):
if value is None: # delete
self.delete(key)
else:
self.put(key, value)
def put(self, str key not None, str value not None, WriteOptions options=None):
if options is None:
options = WriteOptions()
cdef leveldb.Status st
cdef string keyEncoded = key.encode('UTF-8')
cdef string valueEncoded = value.encode('UTF-8')
st = self._db.Put(options._writeOptions, leveldb.Slice(keyEncoded), leveldb.Slice(valueEncoded))
check_status(st)
def delete(self, str key not None, WriteOptions options=None):
if options is None:
options = WriteOptions()
cdef string keyEncoded = key.encode('UTF-8')
cdef leveldb.Status st
st = self._db.Delete(options._writeOptions, leveldb.Slice(keyEncoded))
check_status(st)
def write_batch(self, WriteBatch batch not None, WriteOptions options=None):
cdef leveldb.Status st
if options is None:
options = WriteOptions()
st = self._db.Write(options._writeOptions, &batch._batch)
check_status(st)
def __getitem__(self, str key not None):
return self.get(key)
def get(self, str key not None, ReadOptions options=None, str default=None):
cdef string keyEncoded = key.encode('UTF-8')
cdef leveldb.Status st
cdef string result
if options is None:
options = ReadOptions()
st = self._db.Get(options._readOptions, leveldb.Slice(keyEncoded), &result)
if st.IsNotFound():
return default
check_status(st)
return result.decode('UTF-8')
def get_iterator(self, ReadOptions options=None, py_bool reversed=False):
cdef Iterator it = Iterator()
if options is None:
options = ReadOptions()
cdef leveldb.Iterator* it_ptr = self._db.NewIterator(options._readOptions)
it._set_iter(it_ptr, reversed)
self._iterators.append(it)
return it
def __iter__(self): # default iterator
return self.get_iterator()
def get_snapshot(self):
cdef const leveldb.Snapshot* snapshot = self._db.GetSnapshot()
cdef Snapshot ret = Snapshot()
ret._set(self, snapshot)
self._snapshots.append(ret)
return ret
def get_property(self, str property not None):
cdef string propName = property.encode('UTF-8')
cdef string result
cdef c_bool hasProperty = self._db.GetProperty(leveldb.Slice(propName), &result)
if hasProperty:
return result.decode('UTF-8')
else:
return None
def get_size(self, str begin not None, str end not None):
cdef string beginEncoded = begin.encode('UTF-8')
cdef string endEncoded = end.encode('UTF-8')
cdef uint64_t* size = <uint64_t*>malloc(sizeof(uint64_t))
cdef leveldb.Range* range = new leveldb.Range(leveldb.Slice(beginEncoded), leveldb.Slice(endEncoded))
self._db.GetApproximateSizes(range, 1, size)
cdef uint64_t ret = size[0]
free(size)
return ret
def compact_range(self, str begin, str end):
cdef leveldb.Slice *beginSlice
cdef leveldb.Slice *endSlice
cdef string beginEncoded, endEncoded
if begin is not None:
beginEncoded = begin.encode('UTF-8')
beginSlice = new leveldb.Slice(beginEncoded)
else:
beginSlice = NULL
if end is not None:
endEncoded = end.encode('UTF-8')
endSlice = new leveldb.Slice(endEncoded)
else:
endSlice = NULL
self._db.CompactRange(beginSlice, endSlice)
del beginSlice, endSlice
def __dealloc__(self):
self.close()
def close(self):
cdef Snapshot snapshot
cdef Iterator iterator
if self._db!= NULL:
for snapshot in self._snapshots:
snapshot._close()
for iterator in self._iterators:
iterator._close()
del self._db
self._db = NULL
@property
def closed(self):
return self._db == NULL
# DB static function wrapper
def destroy_DB(str name not None, Options options):
cdef string nameEncoded = name.encode('UTF-8')
if options is None:
options = Options()
leveldb.DestroyDB(nameEncoded, options._options)
def repair_DB(str name not None, Options options):
cdef string nameEncoded = name.encode('UTF-8')
if options is None:
options = Options()
leveldb.RepairDB(nameEncoded, options._options)
<|end_of_text|>from exception.custom_exception cimport raise_py_error
from base.cgcbase cimport gcstring
from libcpp cimport bool
from libc.stdint cimport int64_t
from baslerpylon.genapi.enum cimport EAccessMode
cdef extern from "GenApi/IBase.h" namespace 'GENAPI_NAMESPACE':
cdef cppclass IBase:
EAccessMode GetAccessMode() except +raise_py_error
# Virtual destructor enforcing virtual destructor on all derived classes
void delete "~IBase"() except +raise_py_error
<|end_of_text|>
from cython.operator cimport dereference as deref
import sys
# referenced from
# http://stackoverflow.com/questions/5242051/cython-implementing-callbacks
ctypedef double (*method_type)(void *param, void *user_data)
cdef extern from "backend.hpp":
cdef cppclass | Cython |
Callback:
Callback(method_type method, void *user_data)
double cy_execute(void *parameter)
cdef double callback_template(void *parameter, void *method):
return (<object>method)(<object>parameter)
cdef class PyCallback:
cdef Callback *thisptr
def __cinit__(self, method):
self.thisptr = new Callback(callback_template, <void*>method)
def __dealloc__(self):
if self.thisptr:
del self.thisptr
cpdef double execute(self, parameter):
return self.thisptr.cy_execute(<void*>parameter)
<|end_of_text|># Copyright (c) 2021, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
cdef extern from "cudf/strings/convert/convert_lists.hpp" namespace \
"cudf::strings" nogil:
cdef unique_ptr[column] format_list_column(
column_view input_col,
string_scalar na_rep,
column_view separators) except +
<|end_of_text|># Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
# Copyright (c) 2020-2021, UT-Battelle, LLC. All rights reserved.
# See file LICENSE for terms.
# cython: language_level=3
import logging
import warnings
from libc.stdint cimport uintptr_t
from libc.stdio cimport FILE
from.ucx_api_dep cimport *
from..exceptions import UCXConnectionReset, UCXError
logger = logging.getLogger("ucx")
cdef void _err_cb(void *arg, ucp_ep_h ep, ucs_status_t status):
cdef UCXEndpoint ucx_ep = <UCXEndpoint> arg
assert ucx_ep.worker.initialized
cdef ucs_status_t *ep_status = <ucs_status_t *> <uintptr_t>ucx_ep._status
ep_status[0] = status
cdef str status_str = ucs_status_string(status).decode("utf-8")
cdef str msg = (
"Error callback for endpoint %s called with status %d: %s" % (
hex(int(<uintptr_t>ep)), status, status_str
)
)
logger.debug(msg)
cdef (ucp_err_handler_cb_t, uintptr_t) _get_error_callback(
str tls, bint endpoint_error_handling
) except *:
cdef ucp_err_handler_cb_t err_cb = <ucp_err_handler_cb_t>NULL
cdef ucs_status_t *cb_status = <ucs_status_t *>NULL
if endpoint_error_handling:
if get_ucx_version() < (1, 11, 0) and "cuda_ipc" in tls:
warnings.warn(
"CUDA IPC endpoint error handling is only supported in "
"UCX 1.11 and above, CUDA IPC will be disabled!",
RuntimeWarning
)
err_cb = <ucp_err_handler_cb_t>_err_cb
cb_status = <ucs_status_t *> malloc(sizeof(ucs_status_t))
cb_status[0] = UCS_OK
return (err_cb, <uintptr_t> cb_status)
def _ucx_endpoint_finalizer(
uintptr_t handle_as_int,
uintptr_t status_handle_as_int,
bint endpoint_error_handling,
worker,
set inflight_msgs
):
assert worker.initialized
cdef ucp_ep_h handle = <ucp_ep_h>handle_as_int
cdef ucs_status_ptr_t status
cdef ucs_status_t ep_status
if <void *>status_handle_as_int == NULL:
ep_status = UCS_OK
else:
ep_status = (<ucs_status_t *>status_handle_as_int)[0]
free(<void *>status_handle_as_int)
# Cancel all inflight messages
cdef UCXRequest req
cdef dict req_info
cdef str name
for req in list(inflight_msgs):
assert not req.closed()
req_info = <dict>req._handle.info
name = req_info["name"]
logger.debug("Future cancelling: %s" % name)
# Notice, `request_cancel()` evoke the send/recv callback functions
worker.request_cancel(req)
# Close the endpoint
cdef str msg
cdef unsigned close_mode = UCP_EP_CLOSE_MODE_FLUSH
if (endpoint_error_handling and <void *>ep_status!= NULL and ep_status!= UCS_OK):
# We force close endpoint if endpoint error handling is enabled and
# the endpoint status is not UCS_OK
close_mode = UCP_EP_CLOSE_MODE_FORCE
status = ucp_ep_close_nb(handle, close_mode)
if UCS_PTR_IS_PTR(status):
while ucp_request_check_status(status) == UCS_INPROGRESS:
worker.progress()
ucp_request_free(status)
elif UCS_PTR_STATUS(status)!= UCS_OK:
msg = ucs_status_string(UCS_PTR_STATUS(status)).decode("utf-8")
raise UCXError("Error while closing endpoint: %s" % msg)
cdef class UCXEndpoint(UCXObject):
"""Python representation of `ucp_ep_h`"""
cdef:
ucp_ep_h _handle
uintptr_t _status
bint _endpoint_error_handling
set _inflight_msgs
cdef readonly:
UCXWorker worker
def __init__(
self,
UCXWorker worker,
uintptr_t params_as_int,
bint endpoint_error_handling
):
"""The Constructor"""
assert worker.initialized
self.worker = worker
self._inflight_msgs = set()
cdef ucp_err_handler_cb_t err_cb
cdef uintptr_t ep_status
err_cb, ep_status = (
_get_error_callback(worker._context._config["TLS"], endpoint_error_handling)
)
cdef ucp_ep_params_t *params = <ucp_ep_params_t *>params_as_int
if err_cb == NULL:
params.err_mode = UCP_ERR_HANDLING_MODE_NONE
else:
params.err_mode = UCP_ERR_HANDLING_MODE_PEER
params.err_handler.cb = err_cb
params.err_handler.arg = <void *>self
cdef ucp_ep_h ucp_ep
cdef ucs_status_t status = ucp_ep_create(worker._handle, params, &ucp_ep)
assert_ucs_status(status)
self._handle = ucp_ep
self._status = <uintptr_t>ep_status
self._endpoint_error_handling = endpoint_error_handling
self.add_handle_finalizer(
_ucx_endpoint_finalizer,
int(<uintptr_t>ucp_ep),
int(<uintptr_t>ep_status),
endpoint_error_handling,
worker,
self._inflight_msgs
)
worker.add_child(self)
@classmethod
def create(
cls,
UCXWorker worker,
str ip_address,
uint16_t port,
bint endpoint_error_handling
):
assert worker.initialized
cdef ucp_ep_params_t *params = (
<ucp_ep_params_t *>malloc(sizeof(ucp_ep_params_t))
)
ip_address = socket.gethostbyname(ip_address)
params.field_mask = (
UCP_EP_PARAM_FIELD_FLAGS |
UCP_EP_PARAM_FIELD_SOCK_ADDR |
UCP_EP_PARAM_FIELD_ERR_HANDLING_MODE |
UCP_EP_PARAM_FIELD_ERR_HANDLER
)
params.flags = UCP_EP_PARAMS_FLAGS_CLIENT_SERVER
if c_util_set_sockaddr(¶ms.sockaddr, ip_address.encode(), port):
raise MemoryError("Failed allocation of sockaddr")
try:
return cls(worker, <uintptr_t>params, endpoint_error_handling)
finally:
c_util_sockaddr_free(¶ms.sockaddr)
free(<void *>params)
@classmethod
def create_from_worker_address(
cls, UCXWorker worker, UCXAddress address, bint endpoint_error_handling
):
assert worker.initialized
cdef ucp_ep_params_t *params = (
<ucp_ep_params_t *>malloc(sizeof(ucp_ep_params_t))
)
params.field_mask = (
UCP_EP_PARAM_FIELD_REMOTE_ADDRESS |
UCP_EP_PARAM_FIELD_ERR_HANDLING_MODE |
UCP_EP_PARAM_FIELD_ERR_HANDLER
)
params.address = address._address
try:
return cls(worker, <uintptr_t>params, endpoint_error_handling)
finally:
free(<void *>params)
@classmethod
def create_from_conn_request(
cls, UCXWorker worker, uintptr_t conn_request, bint endpoint_error_handling
):
assert worker.initialized
cdef ucp_ep_params_t *params = (
<ucp_ep_params_t *>malloc(sizeof(ucp_ep_params_t))
)
params.field_mask = (
UCP_EP_PARAM_FIELD_FLAGS |
UCP_EP_PARAM_FIELD_CONN_REQUEST |
UCP_EP_PARAM_FIELD_ERR_HANDLING_MODE |
UCP_EP_PARAM_FIELD_ERR_HANDLER
)
params.flags = UCP_EP_PARAMS_FLAGS_NO_LOOPBACK
params.conn_request = <ucp_conn_request_h> conn_request
try:
return cls(worker, <uintptr_t>params, endpoint_error_handling)
finally:
free(<void *>params)
def info(self):
assert self.initialized
cdef FILE *text_fd = create_text_fd()
ucp_ep_print_info(self._handle, text | Cython |
_fd)
return decode_text_fd(text_fd)
def _get_status_and_str(self):
cdef ucs_status_t *_status = <ucs_status_t *>self._status
cdef str status_str = ucs_status_string(_status[0]).decode("utf-8")
status = int(_status[0])
return (status, str(status_str))
def is_alive(self):
if not self._endpoint_error_handling:
return True
status, _ = self._get_status_and_str()
return status == UCS_OK
def raise_on_error(self):
if not self._endpoint_error_handling:
return
status, status_str = self._get_status_and_str()
if status == UCS_OK:
return
ep_str = str(hex(int(<uintptr_t>self._handle)))
error_msg = f"Endpoint {ep_str} error: {status_str}"
if status == UCS_ERR_CONNECTION_RESET:
raise UCXConnectionReset(error_msg)
else:
raise UCXError(error_msg)
@property
def handle(self):
assert self.initialized
return int(<uintptr_t>self._handle)
def flush(self, cb_func, tuple cb_args=None, dict cb_kwargs=None):
if cb_args is None:
cb_args = ()
if cb_kwargs is None:
cb_kwargs = {}
cdef ucs_status_ptr_t req
cdef ucp_send_callback_t _send_cb = <ucp_send_callback_t>_send_callback
cdef ucs_status_ptr_t status = ucp_ep_flush_nb(self._handle, 0, _send_cb)
return _handle_status(
status, 0, cb_func, cb_args, cb_kwargs, u'flush', self._inflight_msgs
)
def unpack_rkey(self, rkey):
return UCXRkey(self, rkey)
<|end_of_text|>import proteus
import numpy
from math import fabs
cimport numpy
import os
from proteus import cfemIntegrals, Quadrature, Norms, Comm
from proteus.NonlinearSolvers import NonlinearEquation
from proteus.FemTools import (DOFBoundaryConditions,
FluxBoundaryConditions,
C0_AffineLinearOnSimplexWithNodalBasis)
from proteus.flcbdfWrappers import globalMax
from proteus.Profiling import memory
from proteus.Profiling import logEvent as log
from proteus.Transport import OneLevelTransport
from proteus.TransportCoefficients import TC_base
from proteus.SubgridError import SGE_base
from proteus.ShockCapturing import ShockCapturing_base
cdef extern from "mprans/NCLS3P.h" namespace "proteus":
cdef cppclass cppNCLS3P_base:
void calculateResidual(double * mesh_trial_ref,
double * mesh_grad_trial_ref,
double * mesh_dof,
double * mesh_velocity_dof,
double MOVING_DOMAIN,
int * mesh_l2g,
double * dV_ref,
double * u_trial_ref,
double * u_grad_trial_ref,
double * u_test_ref,
double * u_grad_test_ref,
double * mesh_trial_trace_ref,
double * mesh_grad_trial_trace_ref,
double * dS_ref,
double * u_trial_trace_ref,
double * u_grad_trial_trace_ref,
double * u_test_trace_ref,
double * u_grad_test_trace_ref,
double * normal_ref,
double * boundaryJac_ref,
int nElements_global,
double useMetrics,
double alphaBDF,
int lag_shockCapturing,
double shockCapturingDiffusion,
double sc_uref, double sc_alpha,
int * u_l2g,
double * elementDiameter,
double * u_dof, double * u_dof_old,
double * velocity,
double * q_m,
double * q_u,
double * q_n,
double * q_dH,
double * q_m_betaBDF,
double * q_dV,
double * q_dV_last,
double * cfl,
double * q_numDiff_u,
double * q_numDiff_u_last,
int offset_u, int stride_u,
double * globalResidual,
int nExteriorElementBoundaries_global,
int * exteriorElementBoundariesArray,
int * elementBoundaryElementsArray,
int * elementBoundaryLocalElementBoundariesArray,
double * ebqe_velocity_ext,
int * isDOFBoundary_u,
double * ebqe_rd_u_ext,
double * ebqe_bc_u_ext,
double * ebqe_u)
void calculateJacobian(double * mesh_trial_ref,
double * mesh_grad_trial_ref,
double * mesh_dof,
double * mesh_velocity_dof,
double MOVING_DOMAIN,
int * mesh_l2g,
double * dV_ref,
double * u_trial_ref,
double * u_grad_trial_ref,
double * u_test_ref,
double * u_grad_test_ref,
double * mesh_trial_trace_ref,
double * mesh_grad_trial_trace_ref,
double * dS_ref,
double * u_trial_trace_ref,
double * u_grad_trial_trace_ref,
double * u_test_trace_ref,
double * u_grad_test_trace_ref,
double * normal_ref,
double * boundaryJac_ref,
int nElements_global,
double useMetrics,
double alphaBDF,
int lag_shockCapturing,
double shockCapturingDiffusion,
int * u_l2g,
double * elementDiameter,
double * u_dof,
double * velocity,
double * q_m_betaBDF,
double * cfl,
double * q_numDiff_u_last,
int * csrRowIndeces_u_u, int * csrColumnOffsets_u_u,
double * globalJacobian,
int nExteriorElementBoundaries_global,
int * exteriorElementBoundariesArray,
int * elementBoundaryElementsArray,
int * elementBoundaryLocalElementBoundariesArray,
double * ebqe_velocity_ext,
int * isDOFBoundary_u,
double * ebqe_rd_u_ext,
double * ebqe_bc_u_ext,
int * csrColumnOffsets_eb_u_u)
void calculateWaterline(
int * wlc,
double * waterline,
double * mesh_trial_ref,
double * mesh_grad_trial_ref,
double * mesh_dof,
double * mesh_velocity_dof,
double MOVING_DOMAIN,
int * mesh_l2g,
double * dV_ref,
double * u_trial_ref,
double * u_grad_trial_ref,
double * u_test_ref,
double * u_grad_test_ref,
double * mesh_trial_trace_ref,
double * mesh_grad_trial_trace_ref,
double * dS_ref,
double * u_trial_trace_ref,
double * u_grad_trial_trace_ref,
double * u_test_trace_ref,
double * u_grad_test_trace_ref,
double * normal_ref,
double * boundaryJac_ref,
int nElements_global,
double useMetrics,
double alphaBDF,
int lag_shockCapturing,
double shockCapturingDiffusion,
double sc_uref, double sc_alpha,
int * u_l2g,
double * elementDiameter,
double * u_dof, double * u_dof_old,
double * velocity,
double * q_m,
double * q_u,
double * q_n,
double * q_dH,
double * q_m_betaBDF,
double * cfl,
double * q_numDiff_u,
double * q_numDiff_u_last,
int offset_u, int stride_u,
int nExteriorElementBoundaries_global,
int * exteriorElementBoundariesArray,
int * elementBoundaryElementsArray,
int * elementBoundaryLocalElementBoundariesArray,
int * elementBoundaryMaterialTypes,
double * ebqe_velocity_ext,
int * isDOFBoundary_u,
double * ebqe_bc_u_ext,
double * ebqe_u)
cppNCLS3P_base * newNCLS3P(int nSpaceIn,
int nQuadraturePoints_elementIn,
int nDOF_mesh_trial_elementIn,
int nDOF_trial_elementIn,
int nDOF_test_elementIn,
int nQuadraturePoints_elementBoundaryIn,
int CompKernelFlag)
cdef class NCLS3P:
cdef cppNCLS3P_base * thisptr
def __cinit__(self,
int nSpaceIn,
int nQuadraturePoints_elementIn,
int nDOF_mesh_trial_elementIn,
int nDOF_trial_elementIn,
int nDOF_test_elementIn,
int nQuadraturePoints_elementBoundaryIn,
int CompKernelFlag):
self.thisptr = newNCLS3P(nSpaceIn,
nQuadraturePoints_elementIn,
nDOF_mesh_trial_elementIn,
nDOF_trial_elementIn,
nDOF_test_elementIn,
nQuadraturePoints_elementBoundaryIn,
CompKernelFlag)
def __dealloc__(self):
del self.thisptr
def calculateResidual(self,
numpy.ndarray mesh_trial_ref,
numpy.ndarray mesh_grad_trial_ref,
numpy.ndarray mesh_dof,
numpy.ndarray mesh_velocity_dof,
double MOVING_DOMAIN,
numpy.ndarray mesh_l2g,
numpy.ndarray dV_ref,
numpy.ndarray u_trial_ref,
numpy.ndarray u_grad_trial_ref,
| Cython |
numpy.ndarray u_test_ref,
numpy.ndarray u_grad_test_ref,
numpy.ndarray mesh_trial_trace_ref,
numpy.ndarray mesh_grad_trial_trace_ref,
numpy.ndarray dS_ref,
numpy.ndarray u_trial_trace_ref,
numpy.ndarray u_grad_trial_trace_ref,
numpy.ndarray u_test_trace_ref,
numpy.ndarray u_grad_test_trace_ref,
numpy.ndarray normal_ref,
numpy.ndarray boundaryJac_ref,
int nElements_global,
double useMetrics,
double alphaBDF,
int lag_shockCapturing,
double shockCapturingDiffusion,
double sc_uref, double sc_alpha,
numpy.ndarray u_l2g,
numpy.ndarray elementDiameter,
numpy.ndarray u_dof,
numpy.ndarray u_dof_old,
numpy.ndarray velocity,
numpy.ndarray q_m,
numpy.ndarray q_u,
numpy.ndarray q_n,
numpy.ndarray q_dH,
numpy.ndarray q_m_betaBDF,
numpy.ndarray q_dV,
numpy.ndarray q_dV_last,
numpy.ndarray cfl,
numpy.ndarray q_numDiff_u,
numpy.ndarray q_numDiff_u_last,
int offset_u, int stride_u,
numpy.ndarray globalResidual,
int nExteriorElementBoundaries_global,
numpy.ndarray exteriorElementBoundariesArray,
numpy.ndarray elementBoundaryElementsArray,
numpy.ndarray elementBoundaryLocalElementBoundariesArray,
numpy.ndarray ebqe_velocity_ext,
numpy.ndarray isDOFBoundary_u,
numpy.ndarray ebqe_rd_u_ext,
numpy.ndarray ebqe_bc_u_ext,
numpy.ndarray ebqe_u):
self.thisptr.calculateResidual( < double*>mesh_trial_ref.data,
< double * >mesh_grad_trial_ref.data,
< double * >mesh_dof.data,
< double * >mesh_velocity_dof.data,
MOVING_DOMAIN,
< int * >mesh_l2g.data,
< double * >dV_ref.data,
< double * >u_trial_ref.data,
< double * >u_grad_trial_ref.data,
< double * >u_test_ref.data,
< double * >u_grad_test_ref.data,
< double * >mesh_trial_trace_ref.data,
< double * >mesh_grad_trial_trace_ref.data,
< double * >dS_ref.data,
< double * >u_trial_trace_ref.data,
< double * >u_grad_trial_trace_ref.data,
< double * >u_test_trace_ref.data,
< double * >u_grad_test_trace_ref.data,
< double * >normal_ref.data,
< double * >boundaryJac_ref.data,
nElements_global,
useMetrics,
alphaBDF,
lag_shockCapturing,
shockCapturingDiffusion,
sc_uref, sc_alpha,
< int * >u_l2g.data,
< double * >elementDiameter.data,
< double * >u_dof.data,
< double * >u_dof_old.data,
< double * >velocity.data,
< double * >q_m.data,
< double * >q_u.data,
< double * >q_n.data,
< double * >q_dH.data,
< double * >q_m_betaBDF.data,
< double * > q_dV.data,
< double * > q_dV_last.data,
< double * >cfl.data,
< double * >q_numDiff_u.data,
< double * >q_numDiff_u_last.data,
offset_u,
stride_u,
< double * >globalResidual.data,
nExteriorElementBoundaries_global,
< int * >exteriorElementBoundariesArray.data,
< int * >elementBoundaryElementsArray.data,
< int * >elementBoundaryLocalElementBoundariesArray.data,
< double * >ebqe_velocity_ext.data,
< int * >isDOFBoundary_u.data,
< double * >ebqe_rd_u_ext.data,
< double * >ebqe_bc_u_ext.data,
< double * >ebqe_u.data)
def calculateJacobian(self,
numpy.ndarray mesh_trial_ref,
numpy.ndarray mesh_grad_trial_ref,
numpy.ndarray mesh_dof,
numpy.ndarray mesh_velocity_dof,
double MOVING_DOMAIN,
numpy.ndarray mesh_l2g,
numpy.ndarray dV_ref,
numpy.ndarray u_trial_ref,
numpy.ndarray u_grad_trial_ref,
numpy.ndarray u_test_ref,
numpy.ndarray u_grad_test_ref,
numpy.ndarray mesh_trial_trace_ref,
numpy.ndarray mesh_grad_trial_trace_ref,
numpy.ndarray dS_ref,
numpy.ndarray u_trial_trace_ref,
numpy.ndarray u_grad_trial_trace_ref,
numpy.ndarray u_test_trace_ref,
numpy.ndarray u_grad_test_trace_ref,
numpy.ndarray normal_ref,
numpy.ndarray boundaryJac_ref,
int nElements_global,
double useMetrics,
double alphaBDF,
int lag_shockCapturing,
double shockCapturingDiffusion,
numpy.ndarray u_l2g,
numpy.ndarray elementDiameter,
numpy.ndarray u_dof,
numpy.ndarray velocity,
numpy.ndarray q_m_betaBDF,
numpy.ndarray cfl,
numpy.ndarray q_numDiff_u_last,
numpy.ndarray csrRowIndeces_u_u, numpy.ndarray csrColumnOffsets_u_u,
globalJacobian,
int nExteriorElementBoundaries_global,
numpy.ndarray exteriorElementBoundariesArray,
numpy.ndarray elementBoundaryElementsArray,
numpy.ndarray elementBoundaryLocalElementBoundariesArray,
numpy.ndarray ebqe_velocity_ext,
numpy.ndarray isDOFBoundary_u,
numpy.ndarray ebqe_rd_u_ext,
numpy.ndarray ebqe_bc_u_ext,
numpy.ndarray csrColumnOffsets_eb_u_u):
cdef numpy.ndarray rowptr, colind, globalJacobian_a
(rowptr, colind, globalJacobian_a) = globalJacobian.getCSRrepresentation()
self.thisptr.calculateJacobian( < double*>mesh_trial_ref.data,
< double * >mesh_grad_trial_ref.data,
< double * >mesh_dof.data,
< double * >mesh_velocity_dof.data,
MOVING_DOMAIN,
< int * >mesh_l2g.data,
< double * >dV_ref.data,
< double * >u_trial_ref.data,
< double * >u_grad_trial_ref.data,
< double * >u_test_ref.data,
< double * >u_grad_test_ref.data,
< double * >mesh_trial_trace_ref.data,
< double * >mesh_grad_trial_trace_ref.data,
< double * >dS_ref.data,
< double * >u_trial_trace_ref.data,
< double * >u_grad_trial_trace_ref.data,
< double * >u_test_trace_ref.data,
< double * >u_grad_test_trace_ref.data,
< double * >normal_ref.data,
< double * >boundaryJac_ref.data,
nElements_global,
useMetrics,
alphaBDF,
lag_shockCapturing,
shockCapturingDiffusion,
< int * >u_l2g.data,
< double * >elementDiameter.data,
< double * >u_dof.data,
< double * >velocity.data,
< double * >q_m_betaBDF.data,
< double * >cfl.data,
< double * >q_numDiff_u_last.data,
< int*>csrRowIndeces_u_u.data, < int*>csrColumnOffsets_u_u.data,
< double * >globalJacobian_a.data,
nExteriorElementBoundaries_global,
< int * >exteriorElementBoundariesArray.data,
< int * >elementBoundaryElementsArray.data,
< int * >elementBoundaryLocalElementBoundariesArray.data,
< double * >ebqe_velocity_ext.data,
< int * >isDOFBoundary_u.data,
< double * >ebqe_rd_u_ext.data,
< double * >ebqe_bc_u_ext.data,
< int * >csrColumnOffsets_eb_u_u.data)
def calculateWaterline(self,
numpy.ndarray wlc,
numpy.ndarray waterline,
numpy.ndarray mesh_trial_ref,
numpy.ndarray mesh_grad_trial_ref,
numpy.ndarray mesh_dof,
numpy.ndarray mesh_velocity_dof,
double MOVING_DOMAIN,
numpy.ndarray mesh_l2g,
numpy.ndarray dV_ref,
numpy.ndarray u_trial_ref,
numpy.ndarray u_grad_trial_ref,
numpy.ndarray u_test_ref,
numpy.ndarray u_grad_test_ref,
numpy.ndarray mesh_trial_trace_ref,
numpy.ndarray mesh_grad_trial_trace_ref,
numpy.ndarray dS_ref,
numpy.ndarray u_trial_trace_ref,
numpy.ndarray u_grad_trial_trace_ref,
numpy.ndarray u_test_trace_ref,
numpy.ndarray u_grad_test_trace_ref,
numpy.ndarray normal_ref,
numpy.ndarray boundaryJac_ref,
int nElements_global,
double useMetrics,
double alphaBDF,
int lag_shockCapturing,
double shockCapturingDiffusion,
double sc_uref, double sc_alpha,
numpy.ndarray u_l2g,
numpy.ndarray elementDiameter,
numpy.ndarray u_dof,
numpy.ndarray u_dof_old,
numpy.ndarray velocity,
numpy.ndarray q_m,
numpy.ndarray q_u,
numpy.ndarray q_n,
numpy.ndarray q_dH,
numpy.ndarray q_m_betaBDF,
numpy.ndarray cfl,
numpy.ndarray q_numDiff_u,
numpy.ndarray q_numDiff_u_last,
int offset_u, int stride_u,
int nExteriorElementBoundaries_global,
numpy.ndarray exteriorElementBoundariesArray,
numpy.ndarray elementBoundaryElementsArray,
numpy.ndarray element | Cython |
BoundaryLocalElementBoundariesArray,
numpy.ndarray elementBoundaryMaterialTypes,
numpy.ndarray ebqe_velocity_ext,
numpy.ndarray isDOFBoundary_u,
numpy.ndarray ebqe_bc_u_ext,
numpy.ndarray ebqe_u):
self.thisptr.calculateWaterline( < int*>wlc.data,
< double * >waterline.data,
< double * >mesh_trial_ref.data,
< double * >mesh_grad_trial_ref.data,
< double * >mesh_dof.data,
< double * >mesh_velocity_dof.data,
MOVING_DOMAIN,
< int * >mesh_l2g.data,
< double * >dV_ref.data,
< double * >u_trial_ref.data,
< double * >u_grad_trial_ref.data,
< double * >u_test_ref.data,
< double * >u_grad_test_ref.data,
< double * >mesh_trial_trace_ref.data,
< double * >mesh_grad_trial_trace_ref.data,
< double * >dS_ref.data,
< double * >u_trial_trace_ref.data,
< double * >u_grad_trial_trace_ref.data,
< double * >u_test_trace_ref.data,
< double * >u_grad_test_trace_ref.data,
< double * >normal_ref.data,
< double * >boundaryJac_ref.data,
nElements_global,
useMetrics,
alphaBDF,
lag_shockCapturing,
shockCapturingDiffusion,
sc_uref, sc_alpha,
< int * >u_l2g.data,
< double * >elementDiameter.data,
< double * >u_dof.data,
< double * >u_dof_old.data,
< double * >velocity.data,
< double * >q_m.data,
< double * >q_u.data,
< double * >q_n.data,
< double * >q_dH.data,
< double * >q_m_betaBDF.data,
< double * >cfl.data,
< double * >q_numDiff_u.data,
< double * >q_numDiff_u_last.data,
offset_u,
stride_u,
nExteriorElementBoundaries_global,
< int * >exteriorElementBoundariesArray.data,
< int * >elementBoundaryElementsArray.data,
< int * >elementBoundaryLocalElementBoundariesArray.data,
< int * >elementBoundaryMaterialTypes.data,
< double * >ebqe_velocity_ext.data,
< int * >isDOFBoundary_u.data,
< double * >ebqe_bc_u_ext.data,
< double * >ebqe_u.data)
class SubgridError(proteus.SubgridError.SGE_base):
def __init__(self, coefficients, nd):
proteus.SubgridError.SGE_base.__init__(self, coefficients, nd, False)
def initializeElementQuadrature(self, mesh, t, cq):
for ci in range(self.nc):
cq[('dH_sge', ci, ci)] = cq[('dH', ci, ci)]
def calculateSubgridError(self, q):
pass
def updateSubgridErrorHistory(self, initializationPhase=False):
pass
class ShockCapturing(proteus.ShockCapturing.ShockCapturing_base):
def __init__(
self,
coefficients,
nd,
shockCapturingFactor=0.25,
lag=True,
nStepsToDelay=None):
proteus.ShockCapturing.ShockCapturing_base.__init__(
self, coefficients, nd, shockCapturingFactor, lag)
self.nStepsToDelay = nStepsToDelay
self.nSteps = 0
if self.lag:
log("NCLS3P.ShockCapturing: lagging requested but must lag the first step; switching lagging off and delaying")
self.nStepsToDelay = 1
self.lag = False
def initializeElementQuadrature(self, mesh, t, cq):
self.mesh = mesh
self.numDiff = []
self.numDiff_last = []
for ci in range(self.nc):
self.numDiff.append(cq[('numDiff', ci, ci)])
self.numDiff_last.append(cq[('numDiff', ci, ci)])
def updateShockCapturingHistory(self):
self.nSteps += 1
if self.lag:
for ci in range(self.nc):
self.numDiff_last[ci][:] = self.numDiff[ci]
if self.lag == False and self.nStepsToDelay!= None and self.nSteps > self.nStepsToDelay:
log("NCLS3P.ShockCapturing: switched to lagged shock capturing")
self.lag = True
self.numDiff_last = []
for ci in range(self.nc):
self.numDiff_last.append(self.numDiff[ci].copy())
log("NCLS3P: max numDiff %e" %
(globalMax(self.numDiff_last[0].max()),))
class NumericalFlux(
proteus.NumericalFlux.HamiltonJacobi_DiagonalLesaintRaviart):
def __init__(self, vt, getPointwiseBoundaryConditions,
getAdvectiveFluxBoundaryConditions,
getDiffusiveFluxBoundaryConditions):
proteus.NumericalFlux.HamiltonJacobi_DiagonalLesaintRaviart.__init__(
self,
vt,
getPointwiseBoundaryConditions,
getAdvectiveFluxBoundaryConditions,
getDiffusiveFluxBoundaryConditions)
class Coefficients(proteus.TransportCoefficients.TC_base):
from proteus.ctransportCoefficients import ncLevelSetCoefficientsEvaluate
from proteus.UnstructuredFMMandFSWsolvers import FMMEikonalSolver, FSWEikonalSolver
from proteus.NonlinearSolvers import EikonalSolver
def __init__(self,
V_model=0,
RD_model=None,
ME_model=1,
EikonalSolverFlag=0,
checkMass=True, epsFact=1.5,
useMetrics=0.0, sc_uref=1.0, sc_beta=1.0,
waterline_interval=-1,
movingDomain=False):
self.movingDomain = movingDomain
self.useMetrics = useMetrics
self.epsFact = epsFact
self.variableNames = ['phi']
nc = 1
mass = {0: {0: 'linear'}}
hamiltonian = {0: {0: 'linear'}}
advection = {}
diffusion = {}
potential = {}
reaction = {}
TC_base.__init__(self,
nc,
mass,
advection,
diffusion,
potential,
reaction,
hamiltonian,
['phi'],
movingDomain=movingDomain)
self.flowModelIndex = V_model
self.modelIndex = ME_model
self.RD_modelIndex = RD_model
# mwf added
self.eikonalSolverFlag = EikonalSolverFlag
if self.eikonalSolverFlag >= 1: # FMM
assert self.RD_modelIndex is None, "no redistance with eikonal solver too"
self.checkMass = checkMass
self.sc_uref = sc_uref
self.sc_beta = sc_beta
self.waterline_interval = waterline_interval
def attachModels(self, modelList):
# the level set model
self.model = modelList[self.modelIndex]
#self.u_old_dof = numpy.zeros(self.model.u[0].dof.shape,'d')
self.u_old_dof = self.model.u[0].dof.copy()
# the velocity
if self.flowModelIndex >= 0:
self.flowModel = modelList[self.flowModelIndex]
self.q_v = modelList[self.flowModelIndex].q[('velocity', 0)]
self.ebqe_v = modelList[self.flowModelIndex].ebqe[('velocity', 0)]
if modelList[self.flowModelIndex].ebq.has_key(('velocity', 0)):
self.ebq_v = modelList[
self.flowModelIndex].ebq[
('velocity', 0)]
else:
self.ebq_v = None
if not self.model.ebq.has_key(
('u', 0)) and self.flowModel.ebq.has_key(
('u', 0)):
self.model.ebq[('u', 0)] = numpy.zeros(
self.flowModel.ebq[('u', 0)].shape, 'd')
self.model.ebq[('grad(u)', 0)] = numpy.zeros(
self.flowModel.ebq[('grad(u)', 0)].shape, 'd')
if self.flowModel.ebq.has_key(('v', 1)):
self.model.u[0].getValuesTrace(
self.flowModel.ebq[
('v', 1)], self.model.ebq[
('u', 0)])
self.model.u[0].getGradientValuesTrace(
self.flowModel.ebq[
('grad(v)', 1)], self.model.ebq[
('grad(u)', 0)])
if self.RD_modelIndex is not None:
# print self.RD_modelIndex,len(modelList)
self.rdModel = modelList[self.RD_modelIndex]
if self.eikonalSolverFlag == 2: # FSW
self.resDummy = numpy.zeros(self.model.u[0].dof.shape, 'd')
e | Cython |
ikonalSolverType = self.FSWEikonalSolver
self.eikonalSolver = self.EikonalSolver(eikonalSolverType,
self.model,
relativeTolerance=0.0, absoluteTolerance=1.0e-12,
frontTolerance=1.0e-8, # default 1.0e-4
frontInitType='frontIntersection')
#,#'frontIntersection',#or'magnitudeOnly'
elif self.eikonalSolverFlag == 1: # FMM
self.resDummy = numpy.zeros(self.model.u[0].dof.shape, 'd')
eikonalSolverType = self.FMMEikonalSolver
self.eikonalSolver = self.EikonalSolver(eikonalSolverType,
self.model,
frontTolerance=1.0e-8, # default 1.0e-4
frontInitType='frontIntersection')
#,#'frontIntersection',#or'magnitudeOnly'
# if self.checkMass:
# self.m_pre = Norms.scalarSmoothedHeavisideDomainIntegral(self.epsFact,
# self.model.mesh.elementDiametersArray,
# self.model.q['dV'],
# self.model.q[('u',0)],
# self.model.mesh.nElements_owned)
# log("Attach Models NCLS3P: Phase 0 mass before NCLS3P step = %12.5e" % (self.m_pre,),level=2)
# self.totalFluxGlobal=0.0
# self.lsGlobalMassArray = [self.m_pre]
# self.lsGlobalMassErrorArray = [0.0]
# self.fluxArray = [0.0]
# self.timeArray = [self.model.timeIntegration.t]
def initializeElementQuadrature(self, t, cq):
if self.flowModelIndex is None:
self.q_v = numpy.zeros(cq[('grad(u)', 0)].shape, 'd')
def initializeElementBoundaryQuadrature(self, t, cebq, cebq_global):
if self.flowModelIndex is None:
self.ebq_v = numpy.zeros(cebq[('grad(u)', 0)].shape, 'd')
def initializeGlobalExteriorElementBoundaryQuadrature(self, t, cebqe):
if self.flowModelIndex is None:
self.ebqe_v = numpy.zeros(cebqe[('grad(u)', 0)].shape, 'd')
def preStep(self, t, firstStep=False):
# if self.checkMass:
# self.m_pre = Norms.scalarSmoothedHeavisideDomainIntegral(self.epsFact,
# self.model.mesh.elementDiametersArray,
# self.model.q['dV'],
# self.model.q[('m',0)],
# self.model.mesh.nElements_owned)
# log("Phase 0 mass before NCLS3P step = %12.5e" % (self.m_pre,),level=2)
# self.m_last = Norms.scalarSmoothedHeavisideDomainIntegral(self.epsFact,
# self.model.mesh.elementDiametersArray,
# self.model.q['dV'],
# self.model.timeIntegration.m_last[0],
# self.model.mesh.nElements_owned)
# log("Phase 0 mass before NCLS3P step (m_last) = %12.5e" % (self.m_last,),level=2)
# #cek todo why is this here
# if self.flowModelIndex >= 0 and self.flowModel.ebq.has_key(('v',1)):
# self.model.u[0].getValuesTrace(self.flowModel.ebq[('v',1)],self.model.ebq[('u',0)])
# self.model.u[0].getGradientValuesTrace(self.flowModel.ebq[('grad(v)',1)],self.model.ebq[('grad(u)',0)])
copyInstructions = {}
return copyInstructions
def postStep(self, t, firstStep=False):
self.u_old_dof[:] = self.model.u[0].dof
self.model.q['dV_last'][:] = self.model.q['dV']
# if self.checkMass:
# self.m_post = Norms.scalarSmoothedHeavisideDomainIntegral(self.epsFact,
# self.model.mesh.elementDiametersArray,
# self.model.q['dV'],
# self.model.q[('u',0)],
# self.model.mesh.nElements_owned)
# log("Phase 0 mass after NCLS3P step = %12.5e" % (self.m_post,),level=2)
# #need a flux here not a velocity
# self.fluxIntegral = Norms.fluxDomainBoundaryIntegralFromVector(self.flowModel.ebqe['dS'],
# self.flowModel.ebqe[('velocity',0)],
# self.flowModel.ebqe['n'],
# self.model.mesh)
# log("Flux integral = %12.5e" % (self.fluxIntegral,),level=2)
# log("Phase 0 mass conservation after NCLS3P step = %12.5e" % (self.m_post - self.m_last + self.model.timeIntegration.dt*self.fluxIntegral,),level=2)
# self.lsGlobalMass = self.m_post
# self.fluxGlobal = self.fluxIntegral*self.model.timeIntegration.dt
# self.totalFluxGlobal += self.fluxGlobal
# self.lsGlobalMassArray.append(self.lsGlobalMass)
# self.lsGlobalMassErrorArray.append(self.lsGlobalMass - self.lsGlobalMassArray[0] + self.totalFluxGlobal)
# self.fluxArray.append(self.fluxIntegral)
# self.timeArray.append(self.model.timeIntegration.t)
# if self.flowModelIndex >= 0 and self.flowModel.ebq.has_key(('v',1)):
# self.model.u[0].getValuesTrace(self.flowModel.ebq[('v',1)],self.model.ebq[('u',0)])
# self.model.u[0].getGradientValuesTrace(self.flowModel.ebq[('grad(v)',1)],self.model.ebq[('grad(u)',0)])
copyInstructions = {}
return copyInstructions
def updateToMovingDomain(self, t, c):
# in a moving domain simulation the velocity coming in is already for
# the moving domain
pass
def evaluate(self, t, c):
v = None
if c[('dH', 0, 0)].shape == self.q_v.shape:
v = self.q_v
elif c[('dH', 0, 0)].shape == self.ebqe_v.shape:
v = self.ebqe_v
elif self.ebq_v is not None and c[('dH', 0, 0)].shape == self.ebq_v.shape:
v = self.ebq_v
else:
raise RuntimeError, "don't have v for NC Level set of shape = " + \
`c[('dH', 0, 0)].shape`
if v is not None:
self.ncLevelSetCoefficientsEvaluate(v,
c[('u', 0)],
c[('grad(u)', 0)],
c[('m', 0)],
c[('dm', 0, 0)],
c[('H', 0)],
c[('dH', 0, 0)])
class LevelModel(OneLevelTransport):
nCalls = 0
def __init__(self,
uDict,
phiDict,
testSpaceDict,
matType,
dofBoundaryConditionsDict,
dofBoundaryConditionsSetterDict,
coefficients,
elementQuadrature,
elementBoundaryQuadrature,
fluxBoundaryConditionsDict=None,
advectiveFluxBoundaryConditionsSetterDict=None,
diffusiveFluxBoundaryConditionsSetterDictDict=None,
stressTraceBoundaryConditionsSetterDict=None,
stabilization=None,
shockCapturing=None,
conservativeFluxDict=None,
numericalFluxType=None,
TimeIntegrationClass=None,
massLumping=False,
reactionLumping=False,
options=None,
name='defaultName',
reuse_trial_and_test_quadrature=True,
sd=True,
movingDomain=False):
#
# set the objects describing the method and boundary conditions
#
self.movingDomain = movingDomain
self.tLast_mesh = None
#
self.name = name
self.sd = sd
self.Hess = False
self.lowmem = True
self.timeTerm = True # allow turning off the time derivative
# self.lowmem=False
self.testIsTrial = True
self.phiTrialIsTrial = True
self.u = uDict
self.ua = {} # analytical solutions
self.phi = phiDict
self.dphi = {}
self.matType = matType
# mwf try to reuse test and trial information across components if
# spaces are the same
self.reuse_test_trial_quadrature = reuse_trial_and_test_quadrature # True#False
if self.reuse_test_trial_quadrature:
for ci in range( | Cython |
1, coefficients.nc):
assert self.u[ci].femSpace.__class__.__name__ == self.u[
0].femSpace.__class__.__name__, "to reuse_test_trial_quad all femSpaces must be the same!"
# Simplicial Mesh
# assume the same mesh for all components for now
self.mesh = self.u[0].femSpace.mesh
self.testSpace = testSpaceDict
self.dirichletConditions = dofBoundaryConditionsDict
# explicit Dirichlet conditions for now, no Dirichlet BC constraints
self.dirichletNodeSetList = None
self.coefficients = coefficients
self.coefficients.initializeMesh(self.mesh)
self.nc = self.coefficients.nc
self.stabilization = stabilization
self.shockCapturing = shockCapturing
# no velocity post-processing for now
self.conservativeFlux = conservativeFluxDict
self.fluxBoundaryConditions = fluxBoundaryConditionsDict
self.advectiveFluxBoundaryConditionsSetterDict = advectiveFluxBoundaryConditionsSetterDict
self.diffusiveFluxBoundaryConditionsSetterDictDict = diffusiveFluxBoundaryConditionsSetterDictDict
# determine whether the stabilization term is nonlinear
self.stabilizationIsNonlinear = False
# cek come back
if self.stabilization is not None:
for ci in range(self.nc):
if coefficients.mass.has_key(ci):
for flag in coefficients.mass[ci].values():
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if coefficients.advection.has_key(ci):
for flag in coefficients.advection[ci].values():
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if coefficients.diffusion.has_key(ci):
for diffusionDict in coefficients.diffusion[ci].values():
for flag in diffusionDict.values():
if flag!= 'constant':
self.stabilizationIsNonlinear = True
if coefficients.potential.has_key(ci):
for flag in coefficients.potential[ci].values():
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if coefficients.reaction.has_key(ci):
for flag in coefficients.reaction[ci].values():
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if coefficients.hamiltonian.has_key(ci):
for flag in coefficients.hamiltonian[ci].values():
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
# determine if we need element boundary storage
self.elementBoundaryIntegrals = {}
for ci in range(self.nc):
self.elementBoundaryIntegrals[ci] = (
(self.conservativeFlux is not None) or (
numericalFluxType is not None) or (
self.fluxBoundaryConditions[ci] == 'outFlow') or (
self.fluxBoundaryConditions[ci] =='mixedFlow') or (
self.fluxBoundaryConditions[ci] =='setFlow'))
#
# calculate some dimensions
#
# assume same space dim for all variables
self.nSpace_global = self.u[0].femSpace.nSpace_global
self.nDOF_trial_element = [
u_j.femSpace.max_nDOF_element for u_j in self.u.values()]
self.nDOF_phi_trial_element = [
phi_k.femSpace.max_nDOF_element for phi_k in self.phi.values()]
self.n_phi_ip_element = [
phi_k.femSpace.referenceFiniteElement.interpolationConditions.nQuadraturePoints for phi_k in self.phi.values()]
self.nDOF_test_element = [
femSpace.max_nDOF_element for femSpace in self.testSpace.values()]
self.nFreeDOF_global = [
dc.nFreeDOF_global for dc in self.dirichletConditions.values()]
self.nVDOF_element = sum(self.nDOF_trial_element)
self.nFreeVDOF_global = sum(self.nFreeDOF_global)
#
NonlinearEquation.__init__(self, self.nFreeVDOF_global)
#
# build the quadrature point dictionaries from the input (this
# is just for convenience so that the input doesn't have to be
# complete)
#
elementQuadratureDict = {}
elemQuadIsDict = isinstance(elementQuadrature, dict)
if elemQuadIsDict: # set terms manually
for I in self.coefficients.elementIntegralKeys:
if elementQuadrature.has_key(I):
elementQuadratureDict[I] = elementQuadrature[I]
else:
elementQuadratureDict[I] = elementQuadrature['default']
else:
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[I] = elementQuadrature
if self.stabilization is not None:
for I in self.coefficients.elementIntegralKeys:
if elemQuadIsDict:
if elementQuadrature.has_key(I):
elementQuadratureDict[
('stab',) + I[1:]] = elementQuadrature[I]
else:
elementQuadratureDict[
('stab',) + I[1:]] = elementQuadrature['default']
else:
elementQuadratureDict[
('stab',) + I[1:]] = elementQuadrature
if self.shockCapturing is not None:
for ci in self.shockCapturing.components:
if elemQuadIsDict:
if elementQuadrature.has_key(('numDiff', ci, ci)):
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[
('numDiff', ci, ci)]
else:
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[
'default']
else:
elementQuadratureDict[
('numDiff', ci, ci)] = elementQuadrature
if massLumping:
for ci in self.coefficients.mass.keys():
elementQuadratureDict[('m', ci)] = Quadrature.SimplexLobattoQuadrature(
self.nSpace_global, 1)
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[
('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
if reactionLumping:
for ci in self.coefficients.mass.keys():
elementQuadratureDict[('r', ci)] = Quadrature.SimplexLobattoQuadrature(
self.nSpace_global, 1)
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[
('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
elementBoundaryQuadratureDict = {}
if isinstance(elementBoundaryQuadrature, dict): # set terms manually
for I in self.coefficients.elementBoundaryIntegralKeys:
if elementBoundaryQuadrature.has_key(I):
elementBoundaryQuadratureDict[
I] = elementBoundaryQuadrature[I]
else:
elementBoundaryQuadratureDict[
I] = elementBoundaryQuadrature['default']
else:
for I in self.coefficients.elementBoundaryIntegralKeys:
elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature
#
# find the union of all element quadrature points and
# build a quadrature rule for each integral that has a
# weight at each point in the union
# mwf include tag telling me which indices are which quadrature rule?
(self.elementQuadraturePoints, self.elementQuadratureWeights,
self.elementQuadratureRuleIndeces) = Quadrature.buildUnion(elementQuadratureDict)
self.nQuadraturePoints_element = self.elementQuadraturePoints.shape[0]
self.nQuadraturePoints_global = self.nQuadraturePoints_element * \
self.mesh.nElements_global
#
# Repeat the same thing for the element boundary quadrature
#
(self.elementBoundaryQuadraturePoints, self.elementBoundaryQuadratureWeights,
self.elementBoundaryQuadratureRuleIndeces) = Quadrature.buildUnion(elementBoundaryQuadratureDict)
self.nElementBoundaryQuadraturePoints_elementBoundary = self.elementBoundaryQuadraturePoints.shape[
0]
self.nElementBoundaryQuadraturePoints_global = (
self.mesh.nElements_global *
self.mesh.nElementBoundaries_element *
self.nElementBoundaryQuadraturePoints_elementBoundary)
# if isinstance(self.u[0].femSpace,C0_AffineLinearOnSimplexWithNodalBasis):
# print self.nQuadraturePoints_element
# if self.nSpace_global == 3:
# assert(self.nQuadraturePoints_element == 5)
# elif self.nSpace_global == 2:
# assert(self.nQuadraturePoints_element == 6)
# elif self.nSpace_global == 1:
# assert(self.nQuadraturePoints_element == 3)
#
# print self.nElementBoundaryQuadraturePoints_elementBoundary
# if self.nSpace_global == 3:
# assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 4)
# elif self.nSpace_global == 2:
# assert(self.nElement | Cython |
BoundaryQuadraturePoints_elementBoundary == 4)
# elif self.nSpace_global == 1:
# assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 1)
#
# simplified allocations for test==trial and also check if space is mixed or not
#
self.q = {}
self.ebq = {}
self.ebq_global = {}
self.ebqe = {}
self.phi_ip = {}
# mesh
self.q['x'] = numpy.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element, 3), 'd')
self.ebqe['x'] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary,
3),
'd')
self.q[('dV_u', 0)] = (1.0 / self.mesh.nElements_global) * \
numpy.ones((self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[('u', 0)] = numpy.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[
('grad(u)',
0)] = numpy.zeros(
(self.mesh.nElements_global,
self.nQuadraturePoints_element,
self.nSpace_global),
'd')
self.q[('m_last', 0)] = numpy.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[('mt', 0)] = numpy.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q['dV'] = numpy.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q['dV_last'] = -1000 * \
numpy.ones((self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
# numpy.zeros((self.mesh.nElements_global,self.nQuadraturePoints_element),'d')
self.q[('m_tmp', 0)] = self.q[('u', 0)]
# numpy.zeros((self.mesh.nElements_global,self.nQuadraturePoints_element),'d')
self.q[('m', 0)] = self.q[('u', 0)]
# cek todo for NCLS3P we really don't need dH because it's just q_v
# from the flow model
self.q[('dH', 0, 0)] = numpy.zeros((self.mesh.nElements_global,
self.nQuadraturePoints_element, self.nSpace_global), 'd')
self.q[
('dH_sge',
0,
0)] = numpy.zeros(
(self.mesh.nElements_global,
self.nQuadraturePoints_element,
self.nSpace_global),
'd')
self.q[('cfl', 0)] = numpy.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[('numDiff', 0, 0)] = numpy.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.ebqe[
('u',
0)] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary),
'd')
self.ebqe[
('grad(u)',
0)] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary,
self.nSpace_global),
'd')
# mwf for running as standalone
self.ebqe[
('dH',
0,
0)] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary,
self.nSpace_global),
'd')
self.q[('dm', 0, 0)] = numpy.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[('H', 0)] = numpy.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.points_elementBoundaryQuadrature = set()
self.scalars_elementBoundaryQuadrature = set(
[('u', ci) for ci in range(self.nc)])
self.vectors_elementBoundaryQuadrature = set()
self.tensors_elementBoundaryQuadrature = set()
#
# allocate residual and Jacobian storage
#
self.inflowBoundaryBC = {}
self.inflowBoundaryBC_values = {}
self.inflowFlux = {}
for cj in range(self.nc):
self.inflowBoundaryBC[cj] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global,), 'i')
self.inflowBoundaryBC_values[cj] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global, self.nDOF_trial_element[cj]), 'd')
self.inflowFlux[cj] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary),
'd')
self.internalNodes = set(range(self.mesh.nNodes_global))
# identify the internal nodes this is ought to be in mesh
# \todo move this to mesh
for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
eN_global = self.mesh.elementBoundaryElementsArray[ebN, 0]
ebN_element = self.mesh.elementBoundaryLocalElementBoundariesArray[
ebN, 0]
for i in range(self.mesh.nNodes_element):
if i!= ebN_element:
I = self.mesh.elementNodesArray[eN_global, i]
self.internalNodes -= set([I])
self.nNodes_internal = len(self.internalNodes)
self.internalNodesArray = numpy.zeros((self.nNodes_internal,), 'i')
for nI, n in enumerate(self.internalNodes):
self.internalNodesArray[nI] = n
#
del self.internalNodes
self.internalNodes = None
log("Updating local to global mappings", 2)
self.updateLocal2Global()
log("Building time integration object", 2)
log(memory("inflowBC, internalNodes,updateLocal2Global",
"OneLevelTransport"), level=4)
# mwf for interpolating subgrid error for gradients etc
if self.stabilization and self.stabilization.usesGradientStabilization:
self.timeIntegration = TimeIntegrationClass(
self, integrateInterpolationPoints=True)
else:
self.timeIntegration = TimeIntegrationClass(self)
if options is not None:
self.timeIntegration.setFromOptions(options)
log(memory("TimeIntegration", "OneLevelTransport"), level=4)
log("Calculating numerical quadrature formulas", 2)
self.calculateQuadrature()
self.setupFieldStrides()
comm = Comm.get()
self.comm = comm
if comm.size() > 1:
assert numericalFluxType is not None and numericalFluxType.useWeakDirichletConditions, "You must use a numerical flux to apply weak boundary conditions for parallel runs"
log(memory("stride+offset", "OneLevelTransport"), level=4)
if numericalFluxType is not None:
if options is None or options.periodicDirichletConditions is None:
self.numericalFlux = numericalFluxType(
self,
dofBoundaryConditionsSetterDict,
advectiveFluxBoundaryConditionsSetterDict,
diffusiveFluxBoundaryConditionsSetterDictDict)
else:
self.numericalFlux = numericalFluxType(
self,
dofBoundaryConditionsSetterDict,
advectiveFluxBoundaryConditionsSetterDict,
diffusiveFluxBoundaryConditionsSetterDictDict,
options.periodicDirichletConditions)
else:
self.numericalFlux = None
# set penalty terms
# cek todo move into numerical flux initialization
if self.ebq_global.has_key('penalty'):
for ebN in range(self.mesh.nElementBoundaries_global):
for k in range(
self.nElementBoundaryQuadraturePoints_elementBoundary):
self.ebq_global['penalty'][ebN, k] = self.numericalFlux.penalty_constant / (
self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power)
# penalty term
# cek move to Numerical flux initialization
if self.ebqe.has_key('penalty'):
for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
for k in range(
self.nElementBoundaryQuadraturePoints_elementBoundary):
self.ebqe['penalty'][ebNE, k] = self.numericalFlux.penalty_constant / \
self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power
log(memory("numericalFlux", "OneLevelTransport"), level=4)
self.elementEffectiveDiametersArray = self.mesh.elementInnerDiametersArray
# use post processing tools to get conservative fluxes, None by | Cython |
default
from proteus import PostProcessingTools
self.velocityPostProcessor = PostProcessingTools.VelocityPostProcessingChooser(
self)
log(memory("velocity postprocessor", "OneLevelTransport"), level=4)
# helper for writing out data storage
from proteus import Archiver
self.elementQuadratureDictionaryWriter = Archiver.XdmfWriter()
self.elementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
self.exteriorElementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
# TODO get rid of this
# for ci,fbcObject in self.fluxBoundaryConditionsObjectsDict.iteritems():
# self.ebqe[('advectiveFlux_bc_flag',ci)] = numpy.zeros(self.ebqe[('advectiveFlux_bc',ci)].shape,'i')
# for t,g in fbcObject.advectiveFluxBoundaryConditionsDict.iteritems():
# if self.coefficients.advection.has_key(ci):
# self.ebqe[('advectiveFlux_bc',ci)][t[0],t[1]] = g(self.ebqe[('x')][t[0],t[1]],self.timeIntegration.t)
# self.ebqe[('advectiveFlux_bc_flag',ci)][t[0],t[1]] = 1
if hasattr(self.numericalFlux,'setDirichletValues'):
self.numericalFlux.setDirichletValues(self.ebqe)
if not hasattr(self.numericalFlux, 'isDOFBoundary'):
self.numericalFlux.isDOFBoundary = {
0: numpy.zeros(self.ebqe[('u', 0)].shape, 'i')}
if not hasattr(self.numericalFlux, 'ebqe'):
self.numericalFlux.ebqe = {
('u', 0): numpy.zeros(self.ebqe[('u', 0)].shape, 'd')}
# TODO how to handle redistancing calls for
# calculateCoefficients,calculateElementResidual etc
self.globalResidualDummy = None
compKernelFlag = 0
self.ncls3p = NCLS3P(
self.nSpace_global,
self.nQuadraturePoints_element,
self.u[0].femSpace.elementMaps.localFunctionSpace.dim,
self.u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
self.testSpace[0].referenceFiniteElement.localFunctionSpace.dim,
self.nElementBoundaryQuadraturePoints_elementBoundary,
compKernelFlag)
self.forceStrongConditions = False
if self.forceStrongConditions:
self.dirichletConditionsForceDOF = DOFBoundaryConditions(
self.u[0].femSpace,
dofBoundaryConditionsSetterDict[0],
weakDirichletConditions=False)
if self.movingDomain:
self.MOVING_DOMAIN = 1.0
else:
self.MOVING_DOMAIN = 0.0
if self.mesh.nodeVelocityArray is None:
self.mesh.nodeVelocityArray = numpy.zeros(
self.mesh.nodeArray.shape, 'd')
self.waterline_calls = 0
self.waterline_prints = 0
# mwf these are getting called by redistancing classes,
def calculateCoefficients(self):
pass
def calculateElementResidual(self):
if self.globalResidualDummy is not None:
self.getResidual(self.u[0].dof, self.globalResidualDummy)
def getResidual(self, u, r):
import pdb
import copy
"""
Calculate the element residuals and add in to the global residual
"""
# mwf debug
# pdb.set_trace()
r.fill(0.0)
# Load the unknowns into the finite element dof
self.timeIntegration.calculateCoefs()
self.timeIntegration.calculateU(u)
self.setUnknowns(self.timeIntegration.u)
# cek can put in logic to skip of BC's don't depend on t or u
# Dirichlet boundary conditions
# if hasattr(self.numericalFlux,'setDirichletValues'):
self.numericalFlux.setDirichletValues(self.ebqe)
# flux boundary conditions, SHOULDN'T HAVE
# cNCLS3P.calculateResidual(self.mesh.nElements_global,
# try to use 1d,2d,3d specific modules
if self.forceStrongConditions:
for dofN, g in self.dirichletConditionsForceDOF.DOFBoundaryConditionsDict.iteritems():
self.u[0].dof[dofN] = g(
self.dirichletConditionsForceDOF.DOFBoundaryPointDict[dofN],
self.timeIntegration.t)
self.ncls3p.calculateResidual( # element
self.u[0].femSpace.elementMaps.psi,
self.u[0].femSpace.elementMaps.grad_psi,
self.mesh.nodeArray,
self.mesh.nodeVelocityArray,
self.MOVING_DOMAIN,
self.mesh.elementNodesArray,
self.elementQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
# element boundary
self.u[0].femSpace.elementMaps.psi_trace,
self.u[0].femSpace.elementMaps.grad_psi_trace,
self.elementBoundaryQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.elementMaps.boundaryNormals,
self.u[0].femSpace.elementMaps.boundaryJacobians,
# physics
self.mesh.nElements_global,
self.coefficients.useMetrics,
self.timeIntegration.alpha_bdf, # mwf was self.timeIntegration.dt,
self.shockCapturing.lag,
self.shockCapturing.shockCapturingFactor,
self.coefficients.sc_uref,
self.coefficients.sc_beta,
self.u[0].femSpace.dofMap.l2g,
self.mesh.elementDiametersArray,
self.u[0].dof,
self.coefficients.u_old_dof,
self.coefficients.q_v,
self.timeIntegration.m_tmp[0],
self.q[('u', 0)],
self.q[('grad(u)', 0)],
self.q[('dH_sge', 0, 0)],
# mwf was self.timeIntegration.m_last[0],
self.timeIntegration.beta_bdf[0],
self.q['dV'],
self.q['dV_last'],
self.q[('cfl', 0)],
self.shockCapturing.numDiff[0],
self.shockCapturing.numDiff_last[0],
self.offset[0], self.stride[0],
r,
self.mesh.nExteriorElementBoundaries_global,
self.mesh.exteriorElementBoundariesArray,
self.mesh.elementBoundaryElementsArray,
self.mesh.elementBoundaryLocalElementBoundariesArray,
self.coefficients.ebqe_v,
self.numericalFlux.isDOFBoundary[0],
self.coefficients.rdModel.ebqe[('u', 0)],
self.numericalFlux.ebqe[('u', 0)],
self.ebqe[('u', 0)])
if self.forceStrongConditions:
for dofN, g in self.dirichletConditionsForceDOF.DOFBoundaryConditionsDict.iteritems():
r[dofN] = 0
# print "velocity in ncls",self.coefficients.q_v,
# print "cfl",self.q[('cfl',0)]
if self.stabilization:
self.stabilization.accumulateSubgridMassHistory(self.q)
log("Global residual", level=9, data=r)
# mwf debug
# pdb.set_trace()
# mwf decide if this is reasonable for keeping solver statistics
self.nonlinear_function_evaluations += 1
if self.globalResidualDummy is None:
self.globalResidualDummy = numpy.zeros(r.shape, 'd')
def getJacobian(self, jacobian):
#import superluWrappers
#import numpy
import pdb
cfemIntegrals.zeroJacobian_CSR(self.nNonzerosInJacobian,
jacobian)
# mwf debug
# pdb.set_trace()
# cNCLS3P.calculateJacobian(self.mesh.nElements_global,
self.ncls3p.calculateJacobian( # element
self.u[0].femSpace.elementMaps.psi,
self.u[0].femSpace.elementMaps.grad_psi,
self.mesh.nodeArray,
self.mesh.nodeVelocityArray,
self.MOVING_DOMAIN,
self.mesh.elementNodesArray,
self.elementQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
# element boundary
self.u[0].femSpace.elementMaps.psi | Cython |
_trace,
self.u[0].femSpace.elementMaps.grad_psi_trace,
self.elementBoundaryQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.elementMaps.boundaryNormals,
self.u[0].femSpace.elementMaps.boundaryJacobians,
self.mesh.nElements_global,
self.coefficients.useMetrics,
self.timeIntegration.alpha_bdf, # mwf was dt
self.shockCapturing.lag,
self.shockCapturing.shockCapturingFactor,
self.u[0].femSpace.dofMap.l2g,
self.mesh.elementDiametersArray,
self.u[0].dof,
self.coefficients.q_v,
# mwf was self.timeIntegration.m_last[0],
self.timeIntegration.beta_bdf[0],
self.q[('cfl', 0)],
self.shockCapturing.numDiff_last[0],
self.csrRowIndeces[(0, 0)], self.csrColumnOffsets[(0, 0)],
jacobian,
self.mesh.nExteriorElementBoundaries_global,
self.mesh.exteriorElementBoundariesArray,
self.mesh.elementBoundaryElementsArray,
self.mesh.elementBoundaryLocalElementBoundariesArray,
self.coefficients.ebqe_v,
self.numericalFlux.isDOFBoundary[0],
self.coefficients.rdModel.ebqe[('u', 0)],
self.numericalFlux.ebqe[('u', 0)],
self.csrColumnOffsets_eb[(0, 0)])
# Load the Dirichlet conditions directly into residual
if self.forceStrongConditions:
scaling = 1.0 # probably want to add some scaling to match non-dirichlet diagonals in linear system
for dofN in self.dirichletConditionsForceDOF.DOFBoundaryConditionsDict.keys():
global_dofN = dofN
for i in range(
self.rowptr[global_dofN],
self.rowptr[
global_dofN + 1]):
if (self.colind[i] == global_dofN):
# print "RBLES forcing residual cj = %s dofN= %s
# global_dofN= %s was self.nzval[i]= %s now =%s " %
# (cj,dofN,global_dofN,self.nzval[i],scaling)
self.nzval[i] = scaling
else:
self.nzval[i] = 0.0
# print "RBLES zeroing residual cj = %s dofN= %s
# global_dofN= %s " % (cj,dofN,global_dofN)
log("Jacobian ", level=10, data=jacobian)
# mwf decide if this is reasonable for solver statistics
self.nonlinear_function_jacobian_evaluations += 1
return jacobian
def calculateElementQuadrature(self):
"""
Calculate the physical location and weights of the quadrature rules
and the shape information at the quadrature points.
This function should be called only when the mesh changes.
"""
self.u[0].femSpace.elementMaps.getValues(self.elementQuadraturePoints,
self.q['x'])
self.u[0].femSpace.elementMaps.getBasisValuesRef(
self.elementQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesRef(
self.elementQuadraturePoints)
self.u[0].femSpace.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesRef(
self.elementQuadraturePoints)
self.coefficients.initializeElementQuadrature(
self.timeIntegration.t, self.q)
if self.stabilization is not None:
self.stabilization.initializeElementQuadrature(
self.mesh, self.timeIntegration.t, self.q)
self.stabilization.initializeTimeIntegration(self.timeIntegration)
if self.shockCapturing is not None:
self.shockCapturing.initializeElementQuadrature(
self.mesh, self.timeIntegration.t, self.q)
def calculateElementBoundaryQuadrature(self):
pass
def calculateExteriorElementBoundaryQuadrature(self):
"""
Calculate the physical location and weights of the quadrature rules
and the shape information at the quadrature points on global element boundaries.
This function should be called only when the mesh changes.
"""
#
# get physical locations of element boundary quadrature points
#
# assume all components live on the same mesh
self.u[0].femSpace.elementMaps.getBasisValuesTraceRef(
self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesTraceRef(
self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisValuesTraceRef(
self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesTraceRef(
self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getValuesGlobalExteriorTrace(
self.elementBoundaryQuadraturePoints, self.ebqe['x'])
self.fluxBoundaryConditionsObjectsDict = dict([(cj, FluxBoundaryConditions(self.mesh,
self.nElementBoundaryQuadraturePoints_elementBoundary,
self.ebqe[('x')],
self.advectiveFluxBoundaryConditionsSetterDict[cj],
self.diffusiveFluxBoundaryConditionsSetterDictDict[cj]))
for cj in self.advectiveFluxBoundaryConditionsSetterDict.keys()])
self.coefficients.initializeGlobalExteriorElementBoundaryQuadrature(
self.timeIntegration.t, self.ebqe)
def estimate_mt(self):
pass
def calculateSolutionAtQuadrature(self):
pass
def calculateAuxiliaryQuantitiesAfterStep(self):
pass
def computeWaterline(self, t):
self.waterline_calls += 1
if self.coefficients.waterline_interval > 0 and self.waterline_calls % self.coefficients.waterline_interval == 0:
self.waterline_npoints = numpy.zeros((1,), 'i')
self.waterline_data = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global, self.nSpace_global), 'd')
self.ncls3p.calculateWaterline( # element
self.waterline_npoints,
self.waterline_data,
self.u[0].femSpace.elementMaps.psi,
self.u[0].femSpace.elementMaps.grad_psi,
self.mesh.nodeArray,
self.mesh.nodeVelocityArray,
self.MOVING_DOMAIN,
self.mesh.elementNodesArray,
self.elementQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
# element boundary
self.u[0].femSpace.elementMaps.psi_trace,
self.u[0].femSpace.elementMaps.grad_psi_trace,
self.elementBoundaryQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.elementMaps.boundaryNormals,
self.u[0].femSpace.elementMaps.boundaryJacobians,
# physics
self.mesh.nElements_global,
self.coefficients.useMetrics,
self.timeIntegration.alpha_bdf, # mwf was self.timeIntegration.dt,
self.shockCapturing.lag,
self.shockCapturing.shockCapturingFactor,
self.coefficients.sc_uref,
self.coefficients.sc_beta,
self.u[0].femSpace.dofMap.l2g,
self.mesh.elementDiametersArray,
self.u[0].dof,
self.coefficients.u_old_dof,
self.coefficients.q_v,
self.timeIntegration.m_tmp[0],
self.q[('u', 0)],
self.q[('grad(u)', 0)],
self.q[('dH_sge', 0, 0)],
# mwf was self.timeIntegration.m_last[0],
self.timeIntegration.beta_bdf[0],
self.q[('cfl', 0)],
self.shockCapturing.numDiff[0],
self.shockCapturing.numDiff_last[0],
self.offset[0], self.stride[0],
self.mesh.nExteriorElementBoundaries_global,
self.mesh.exteriorElementBoundariesArray,
self.mesh.elementBoundaryElementsArray,
self.mesh.elementBoundaryLocalElementBoundariesArray,
self.mesh.elementBoundaryMaterialTypes,
self.coefficients.ebqe_v,
self.numericalFlux.isDOFBoundary[0],
self.numericalFlux.ebqe[('u', 0)],
self.ebqe[('u', 0)])
from proteus import Comm
comm = Comm.get()
filename = os.path.join | Cython |
(self.coefficients.opts.dataDir,
"waterline." + str(comm.rank()) + "." + str(self.waterline_prints))
numpy.save(
filename, self.waterline_data[
0:self.waterline_npoints[0]])
self.waterline_prints += 1
def updateAfterMeshMotion(self):
pass
<|end_of_text|># Copyright 2018 The Cornac Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
# cython: language_level=3
import multiprocessing
cimport cython
from cython.parallel import prange
from cython cimport floating, integral
from libcpp cimport bool
from libc.math cimport abs
import numpy as np
cimport numpy as np
from tqdm.auto import trange
from..recommender import Recommender
from...exception import ScoreException
from...utils import fast_dot
from...utils import get_rng
from...utils.init_utils import normal, zeros
class MF(Recommender):
"""Matrix Factorization.
Parameters
----------
k: int, optional, default: 10
The dimension of the latent factors.
max_iter: int, optional, default: 100
Maximum number of iterations or the number of epochs for SGD.
learning_rate: float, optional, default: 0.01
The learning rate.
lambda_reg: float, optional, default: 0.001
The lambda value used for regularization.
use_bias: boolean, optional, default: True
When True, user, item, and global biases are used.
early_stop: boolean, optional, default: False
When True, delta loss will be checked after each iteration to stop learning earlier.
num_threads: int, optional, default: 0
Number of parallel threads for training. If num_threads=0, all CPU cores will be utilized.
If seed is not None, num_threads=1 to remove randomness from parallelization.
trainable: boolean, optional, default: True
When False, the model will not be re-trained, and input of pre-trained parameters are required.
verbose: boolean, optional, default: True
When True, running logs are displayed.
init_params: dictionary, optional, default: None
Initial parameters, e.g., init_params = {'U': user_factors, 'V': item_factors,
'Bu': user_biases, 'Bi': item_biases}
seed: int, optional, default: None
Random seed for weight initialization.
If specified, training will take longer because of single-thread (no parallelization).
References
----------
* Koren, Y., Bell, R., & Volinsky, C. Matrix factorization techniques for recommender systems. \
In Computer, (8), 30-37. 2009.
"""
def __init__(
self,
name='MF',
k=10,
max_iter=20,
learning_rate=0.01,
lambda_reg=0.02,
use_bias=True,
early_stop=False,
num_threads=0,
trainable=True,
verbose=False,
init_params=None,
seed=None
):
super().__init__(name=name, trainable=trainable, verbose=verbose)
self.k = k
self.max_iter = max_iter
self.learning_rate = learning_rate
self.lambda_reg = lambda_reg
self.use_bias = use_bias
self.early_stop = early_stop
self.seed = seed
if seed is not None:
self.num_threads = 1
elif num_threads > 0 and num_threads < multiprocessing.cpu_count():
self.num_threads = num_threads
else:
self.num_threads = multiprocessing.cpu_count()
# Init params if provided
self.init_params = {} if init_params is None else init_params
self.u_factors = self.init_params.get('U', None)
self.i_factors = self.init_params.get('V', None)
self.u_biases = self.init_params.get('Bu', None)
self.i_biases = self.init_params.get('Bi', None)
self.global_mean = 0.0
def _init(self):
rng = get_rng(self.seed)
n_users, n_items = self.train_set.num_users, self.train_set.num_items
if self.u_factors is None:
self.u_factors = normal([n_users, self.k], std=0.01, random_state=rng)
if self.i_factors is None:
self.i_factors = normal([n_items, self.k], std=0.01, random_state=rng)
self.u_biases = zeros(n_users) if self.u_biases is None else self.u_biases
self.i_biases = zeros(n_items) if self.i_biases is None else self.i_biases
self.global_mean = self.train_set.global_mean if self.use_bias else 0.0
def fit(self, train_set, val_set=None):
"""Fit the model to observations.
Parameters
----------
train_set: :obj:`cornac.data.Dataset`, required
User-Item preference data as well as additional modalities.
val_set: :obj:`cornac.data.Dataset`, optional, default: None
User-Item preference data for model selection purposes (e.g., early stopping).
Returns
-------
self : object
"""
Recommender.fit(self, train_set, val_set)
self._init()
if self.trainable:
(rid, cid, val) = train_set.uir_tuple
self._fit_sgd(rid, cid, val.astype(np.float32),
self.u_factors, self.i_factors,
self.u_biases, self.i_biases)
return self
@cython.boundscheck(False)
@cython.wraparound(False)
def _fit_sgd(self, integral[:] rid, integral[:] cid, floating[:] val,
floating[:, :] U, floating[:, :] V, floating[:] Bu, floating[:] Bi):
"""Fit the model parameters (U, V, Bu, Bi) with SGD
"""
cdef:
long num_users = self.train_set.num_users
long num_items = self.train_set.num_items
long num_ratings = val.shape[0]
int num_factors = self.k
int max_iter = self.max_iter
int num_threads = self.num_threads
floating reg = self.lambda_reg
floating mu = self.global_mean
bool use_bias = self.use_bias
bool early_stop = self.early_stop
bool verbose = self.verbose
floating lr = self.learning_rate
floating loss = 0
floating last_loss = 0
floating r, r_pred, error, u_f, i_f, delta_loss
integral u, i, f, j
floating * user
floating * item
progress = trange(max_iter, disable=not self.verbose)
for epoch in progress:
last_loss = loss
loss = 0
for j in prange(num_ratings, nogil=True, schedule='static', num_threads=num_threads):
u, i, r = rid[j], cid[j], val[j]
user, item = &U[u, 0], &V[i, 0]
# predict rating
r_pred = mu + Bu[u] + Bi[i]
for f in range(num_factors):
r_pred = r_pred + user[f] * item[f]
error = r - r_pred
loss += error * error
# update factors
for f in range(num_factors):
u_f, i_f = user[f], item[f]
user[f] += lr * (error * i_f - reg * u_f)
item[f] += lr * (error * u_f - reg * i_f)
# update biases
if use_bias:
Bu[u] += lr * (error - reg * Bu[u])
Bi[i] += lr * (error - reg * Bi[i])
loss = 0.5 * loss
progress.update(1)
progress.set_postfix({"loss": "%.2f" % loss})
delta_loss = loss - last_loss
if early_stop and abs(delta_loss) < 1e-5:
if verbose:
print('Early stopping, delta_loss = %.4f' % delta_loss)
break
progress.close()
if verbose:
print('Optimization finished!')
def score(self, user_idx, item_idx=None):
"""Predict the scores/ratings of a user for an item.
Parameters
----------
user_idx: int, required
The index of the user for whom to perform score prediction.
item_idx: int, optional, default: None
The index of the item for which to perform score prediction.
If None, scores for all known items will be returned.
Returns
-------
res : A scalar or a Numpy array
Relative scores that the user | Cython |
gives to the item or to all known items
"""
unk_user = self.train_set.is_unk_user(user_idx)
if item_idx is None:
known_item_scores = np.add(self.i_biases, self.global_mean)
if not unk_user:
known_item_scores = np.add(known_item_scores, self.u_biases[user_idx])
fast_dot(self.u_factors[user_idx], self.i_factors, known_item_scores)
return known_item_scores
else:
unk_item = self.train_set.is_unk_item(item_idx)
if self.use_bias:
item_score = self.global_mean
if not unk_user:
item_score += self.u_biases[user_idx]
if not unk_item:
item_score += self.i_biases[item_idx]
if not unk_user and not unk_item:
item_score += np.dot(self.u_factors[user_idx], self.i_factors[item_idx])
else:
if unk_user or unk_item:
raise ScoreException("Can't make score prediction for (user_id=%d, item_id=%d)" % (user_idx, item_idx))
item_score = np.dot(self.u_factors[user_idx], self.i_factors[item_idx])
return item_score
<|end_of_text|>cimport cvad
cimport numpy as np
from spokestack.extensions.webrtc import ProcessError
cdef class WebRtcVad:
cdef cvad.VadInst* _vad
cdef int _sample_rate
def __dealloc__(self):
cvad.WebRtcVad_Free(self._vad)
def __init__(self, sample_rate, mode):
self._vad = NULL
self._sample_rate = sample_rate
result = cvad.WebRtcVad_Create(&self._vad)
if result!= 0:
raise MemoryError("out_of_memory")
result = cvad.WebRtcVad_Init(self._vad)
if result!= 0:
raise ValueError("invalid_config")
result = cvad.WebRtcVad_set_mode(self._vad, mode)
if result!= 0:
raise ValueError("invalid_config")
def is_speech(self, frame):
result = cvad.WebRtcVad_Process(
self._vad,
self._sample_rate,
<short*> np.PyArray_DATA(frame),
len(frame)
)
return result
<|end_of_text|>include "config.pxi"
from api_types_hdf5 cimport *
from api_types_ext cimport *
cdef herr_t H5open() except *
cdef herr_t H5close() except *
cdef herr_t H5get_libversion(unsigned *majnum, unsigned *minnum, unsigned *relnum) except *
cdef hid_t H5Dcreate2(hid_t loc_id, char *name, hid_t type_id, hid_t space_id, hid_t lcpl_id, hid_t dcpl_id, hid_t dapl_id) except *
cdef hid_t H5Dcreate_anon(hid_t file_id, hid_t type_id, hid_t space_id, hid_t plist_id, hid_t dapl_id) except *
cdef hid_t H5Dopen(hid_t file_id, char *name) except *
cdef hid_t H5Dopen2(hid_t loc_id, char *name, hid_t dapl_id ) except *
cdef herr_t H5Dclose(hid_t dset_id) except *
cdef hid_t H5Dget_space(hid_t dset_id) except *
cdef herr_t H5Dget_space_status(hid_t dset_id, H5D_space_status_t *status) except *
cdef hid_t H5Dget_type(hid_t dset_id) except *
cdef hid_t H5Dget_create_plist(hid_t dataset_id) except *
cdef hid_t H5Dget_access_plist(hid_t dataset_id) except *
cdef haddr_t H5Dget_offset(hid_t dset_id) except *
cdef hsize_t H5Dget_storage_size(hid_t dset_id) except *
cdef herr_t H5Dread(hid_t dset_id, hid_t mem_type_id, hid_t mem_space_id, hid_t file_space_id, hid_t plist_id, void *buf) except *
cdef herr_t H5Dwrite(hid_t dset_id, hid_t mem_type, hid_t mem_space, hid_t file_space, hid_t xfer_plist, void* buf) except *
cdef herr_t H5Dextend(hid_t dataset_id, hsize_t *size) except *
cdef herr_t H5Dfill(void *fill, hid_t fill_type_id, void *buf, hid_t buf_type_id, hid_t space_id ) except *
cdef herr_t H5Dvlen_get_buf_size(hid_t dset_id, hid_t type_id, hid_t space_id, hsize_t *size) except *
cdef herr_t H5Dvlen_reclaim(hid_t type_id, hid_t space_id, hid_t plist, void *buf) except *
cdef herr_t H5Diterate(void *buf, hid_t type_id, hid_t space_id, H5D_operator_t op, void* operator_data) except *
cdef herr_t H5Dset_extent(hid_t dset_id, hsize_t* size) except *
cdef hid_t H5Fcreate(char *filename, unsigned int flags, hid_t create_plist, hid_t access_plist) except *
cdef hid_t H5Fopen(char *name, unsigned flags, hid_t access_id) except *
cdef herr_t H5Fclose(hid_t file_id) except *
cdef htri_t H5Fis_hdf5(char *name) except *
cdef herr_t H5Fflush(hid_t object_id, H5F_scope_t scope) except *
cdef hid_t H5Freopen(hid_t file_id) except *
cdef herr_t H5Fmount(hid_t loc_id, char *name, hid_t child_id, hid_t plist_id) except *
cdef herr_t H5Funmount(hid_t loc_id, char *name) except *
cdef herr_t H5Fget_filesize(hid_t file_id, hsize_t *size) except *
cdef hid_t H5Fget_create_plist(hid_t file_id ) except *
cdef hid_t H5Fget_access_plist(hid_t file_id) except *
cdef hssize_t H5Fget_freespace(hid_t file_id) except *
cdef ssize_t H5Fget_name(hid_t obj_id, char *name, size_t size) except *
cdef int H5Fget_obj_count(hid_t file_id, unsigned int types) except *
cdef int H5Fget_obj_ids(hid_t file_id, unsigned int types, int max_objs, hid_t *obj_id_list) except *
cdef herr_t H5Fget_vfd_handle(hid_t file_id, hid_t fapl_id, void **file_handle) except *
cdef herr_t H5Fget_intent(hid_t file_id, unsigned int *intent) except *
cdef herr_t H5Fget_mdc_config(hid_t file_id, H5AC_cache_config_t *config_ptr) except *
cdef herr_t H5Fget_mdc_hit_rate(hid_t file_id, double *hit_rate_ptr) except *
cdef herr_t H5Fget_mdc_size(hid_t file_id, size_t *max_size_ptr, size_t *min_clean_size_ptr, size_t *cur_size_ptr, int *cur_num_entries_ptr) except *
cdef herr_t H5Freset_mdc_hit_rate_stats(hid_t file_id) except *
cdef herr_t H5Fset_mdc_config(hid_t file_id, H5AC_cache_config_t *config_ptr) except *
cdef hid_t H5Gcreate(hid_t loc_id, char *name, size_t size_hint) except *
cdef hid_t H5Gopen(hid_t loc_id, char *name) except *
cdef herr_t H5Gclose(hid_t group_id) except *
cdef herr_t H5Glink2( hid_t curr_loc_id, char *current_name, H5G_link_t link_type, hid_t new_loc_id, char *new_name) except *
cdef herr_t H5Gunlink(hid_t file_id, char *name) except *
cdef herr_t H5Gmove2(hid_t src_loc_id, char *src_name, hid_t dst_loc_id, char *dst_name) except *
cdef herr_t H5Gget_num_objs(hid_t loc_id, hsize_t* num_obj) except *
cdef int H5Gget_objname_by_idx(hid_t loc_id, hsize_t idx, char *name, size_t size) except *
cdef int H5Gget_objtype_by_idx(hid_t loc_id, hsize_t idx) except *
cdef herr_t H5Giterate(hid_t loc_id, char *name, int *idx, H5G_iterate_t op, void* data) except *
cdef herr_t H5Gget_objinfo(hid_t loc_id, char* name, int follow_link, H5G_stat_t *statbuf) except *
cdef herr_t H5Gget_linkval(hid_t loc_id, char *name, size_t size, char *value) except *
cdef herr_t H5Gset_comment(hid_t loc_id, char *name, char *comment) | Cython |
except *
cdef int H5Gget_comment(hid_t loc_id, char *name, size_t bufsize, char *comment) except *
cdef hid_t H5Gcreate_anon( hid_t loc_id, hid_t gcpl_id, hid_t gapl_id) except *
cdef hid_t H5Gcreate2(hid_t loc_id, char *name, hid_t lcpl_id, hid_t gcpl_id, hid_t gapl_id) except *
cdef hid_t H5Gopen2( hid_t loc_id, char * name, hid_t gapl_id) except *
cdef herr_t H5Gget_info( hid_t group_id, H5G_info_t *group_info) except *
cdef herr_t H5Gget_info_by_name( hid_t loc_id, char *group_name, H5G_info_t *group_info, hid_t lapl_id) except *
cdef hid_t H5Gget_create_plist(hid_t group_id) except *
cdef H5I_type_t H5Iget_type(hid_t obj_id) except *
cdef ssize_t H5Iget_name( hid_t obj_id, char *name, size_t size) except *
cdef hid_t H5Iget_file_id(hid_t obj_id) except *
cdef int H5Idec_ref(hid_t obj_id) except *
cdef int H5Iget_ref(hid_t obj_id) except *
cdef int H5Iinc_ref(hid_t obj_id) except *
cdef herr_t H5Lmove(hid_t src_loc, char *src_name, hid_t dst_loc, char *dst_name, hid_t lcpl_id, hid_t lapl_id) except *
cdef herr_t H5Lcopy(hid_t src_loc, char *src_name, hid_t dst_loc, char *dst_name, hid_t lcpl_id, hid_t lapl_id) except *
cdef herr_t H5Lcreate_hard(hid_t cur_loc, char *cur_name, hid_t dst_loc, char *dst_name, hid_t lcpl_id, hid_t lapl_id) except *
cdef herr_t H5Lcreate_soft(char *link_target, hid_t link_loc_id, char *link_name, hid_t lcpl_id, hid_t lapl_id) except *
cdef herr_t H5Ldelete(hid_t loc_id, char *name, hid_t lapl_id) except *
cdef herr_t H5Ldelete_by_idx(hid_t loc_id, char *group_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t n, hid_t lapl_id) except *
cdef herr_t H5Lget_val(hid_t loc_id, char *name, void *bufout, size_t size, hid_t lapl_id) except *
cdef herr_t H5Lget_val_by_idx(hid_t loc_id, char *group_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t n, void *bufout, size_t size, hid_t lapl_id) except *
cdef htri_t H5Lexists(hid_t loc_id, char *name, hid_t lapl_id) except *
cdef herr_t H5Lget_info(hid_t loc_id, char *name, H5L_info_t *linfo, hid_t lapl_id) except *
cdef herr_t H5Lget_info_by_idx(hid_t loc_id, char *group_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t n, H5L_info_t *linfo, hid_t lapl_id) except *
cdef ssize_t H5Lget_name_by_idx(hid_t loc_id, char *group_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t n, char *name, size_t size, hid_t lapl_id) except *
cdef herr_t H5Literate(hid_t grp_id, H5_index_t idx_type, H5_iter_order_t order, hsize_t *idx, H5L_iterate_t op, void *op_data) except *
cdef herr_t H5Literate_by_name(hid_t loc_id, char *group_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t *idx, H5L_iterate_t op, void *op_data, hid_t lapl_id) except *
cdef herr_t H5Lvisit(hid_t grp_id, H5_index_t idx_type, H5_iter_order_t order, H5L_iterate_t op, void *op_data) except *
cdef herr_t H5Lvisit_by_name(hid_t loc_id, char *group_name, H5_index_t idx_type, H5_iter_order_t order, H5L_iterate_t op, void *op_data, hid_t lapl_id) except *
cdef herr_t H5Lunpack_elink_val(void *ext_linkval, size_t link_size, unsigned *flags, char **filename, char **obj_path) except *
cdef herr_t H5Lcreate_external(char *file_name, char *obj_name, hid_t link_loc_id, char *link_name, hid_t lcpl_id, hid_t lapl_id) except *
cdef hid_t H5Oopen(hid_t loc_id, char *name, hid_t lapl_id) except *
cdef hid_t H5Oopen_by_addr(hid_t loc_id, haddr_t addr) except *
cdef hid_t H5Oopen_by_idx(hid_t loc_id, char *group_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t n, hid_t lapl_id) except *
cdef herr_t H5Oget_info(hid_t loc_id, H5O_info_t *oinfo) except *
cdef herr_t H5Oget_info_by_name(hid_t loc_id, char *name, H5O_info_t *oinfo, hid_t lapl_id) except *
cdef herr_t H5Oget_info_by_idx(hid_t loc_id, char *group_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t n, H5O_info_t *oinfo, hid_t lapl_id) except *
IF HDF5_VERSION >= (1, 8, 5):
cdef htri_t H5Oexists_by_name(hid_t loc_id, char * name, hid_t lapl_id ) except *
cdef herr_t H5Olink(hid_t obj_id, hid_t new_loc_id, char *new_name, hid_t lcpl_id, hid_t lapl_id) except *
cdef herr_t H5Ocopy(hid_t src_loc_id, char *src_name, hid_t dst_loc_id, char *dst_name, hid_t ocpypl_id, hid_t lcpl_id) except *
cdef herr_t H5Oincr_refcount(hid_t object_id) except *
cdef herr_t H5Odecr_refcount(hid_t object_id) except *
cdef herr_t H5Oset_comment(hid_t obj_id, char *comment) except *
cdef herr_t H5Oset_comment_by_name(hid_t loc_id, char *name, char *comment, hid_t lapl_id) except *
cdef ssize_t H5Oget_comment(hid_t obj_id, char *comment, size_t bufsize) except *
cdef ssize_t H5Oget_comment_by_name(hid_t loc_id, char *name, char *comment, size_t bufsize, hid_t lapl_id) except *
cdef herr_t H5Ovisit(hid_t obj_id, H5_index_t idx_type, H5_iter_order_t order, H5O_iterate_t op, void *op_data) except *
cdef herr_t H5Ovisit_by_name(hid_t loc_id, char *obj_name, H5_index_t idx_type, H5_iter_order_t order, H5O_iterate_t op, void *op_data, hid_t lapl_id) except *
cdef herr_t H5Oclose(hid_t object_id) except *
cdef hid_t H5Pcreate(hid_t plist_id) except *
cdef hid_t H5Pcopy(hid_t plist_id) except *
cdef int H5Pget_class(hid_t plist_id) except *
cdef herr_t H5Pclose(hid_t plist_id) except *
cdef htri_t H5Pequal( hid_t id1, hid_t id2 ) except *
cdef herr_t H5Pclose_class(hid_t id) except *
cdef herr_t H5Pget_version(hid_t plist, unsigned int *super_, unsigned int* freelist, unsigned int *stab, unsigned int *shhdr) except *
cdef herr_t H5Pset_userblock(hid_t plist, hsize_t size) except *
cdef herr_t H5Pget_userblock(hid_t plist, hsize_t * size) except *
cdef herr_t H5Pset_sizes(hid_t plist, size_t sizeof_addr, size_t sizeof_size) except *
cdef herr_t H5Pget_sizes(hid_t plist, size_t *sizeof_addr, size_t *sizeof_size) except *
cdef herr_t H5Pset_sym_k(hid_t plist, unsigned int ik, unsigned int lk) except *
cdef herr_t H5Pget_sym_k(hid_t plist, unsigned int *ik, unsigned int *lk) except *
cdef herr_t H5Pset | Cython |
_istore_k(hid_t plist, unsigned int ik) except *
cdef herr_t H5Pget_istore_k(hid_t plist, unsigned int *ik) except *
cdef herr_t H5Pset_fclose_degree(hid_t fapl_id, H5F_close_degree_t fc_degree) except *
cdef herr_t H5Pget_fclose_degree(hid_t fapl_id, H5F_close_degree_t *fc_degree) except *
cdef herr_t H5Pset_fapl_core( hid_t fapl_id, size_t increment, hbool_t backing_store) except *
cdef herr_t H5Pget_fapl_core( hid_t fapl_id, size_t *increment, hbool_t *backing_store) except *
cdef herr_t H5Pset_fapl_family( hid_t fapl_id, hsize_t memb_size, hid_t memb_fapl_id ) except *
cdef herr_t H5Pget_fapl_family( hid_t fapl_id, hsize_t *memb_size, hid_t *memb_fapl_id ) except *
cdef herr_t H5Pset_family_offset( hid_t fapl_id, hsize_t offset) except *
cdef herr_t H5Pget_family_offset( hid_t fapl_id, hsize_t *offset) except *
cdef herr_t H5Pset_fapl_log(hid_t fapl_id, char *logfile, unsigned int flags, size_t buf_size) except *
cdef herr_t H5Pset_fapl_multi(hid_t fapl_id, H5FD_mem_t *memb_map, hid_t *memb_fapl, char **memb_name, haddr_t *memb_addr, hbool_t relax) except *
cdef herr_t H5Pset_cache(hid_t plist_id, int mdc_nelmts, int rdcc_nelmts, size_t rdcc_nbytes, double rdcc_w0) except *
cdef herr_t H5Pget_cache(hid_t plist_id, int *mdc_nelmts, int *rdcc_nelmts, size_t *rdcc_nbytes, double *rdcc_w0) except *
cdef herr_t H5Pset_fapl_sec2(hid_t fapl_id) except *
cdef herr_t H5Pset_fapl_stdio(hid_t fapl_id) except *
cdef hid_t H5Pget_driver(hid_t fapl_id) except *
cdef herr_t H5Pget_mdc_config(hid_t plist_id, H5AC_cache_config_t *config_ptr) except *
cdef herr_t H5Pset_mdc_config(hid_t plist_id, H5AC_cache_config_t *config_ptr) except *
cdef herr_t H5Pset_layout(hid_t plist, int layout) except *
cdef H5D_layout_t H5Pget_layout(hid_t plist) except *
cdef herr_t H5Pset_chunk(hid_t plist, int ndims, hsize_t * dim) except *
cdef int H5Pget_chunk(hid_t plist, int max_ndims, hsize_t * dims ) except *
cdef herr_t H5Pset_deflate( hid_t plist, int level) except *
cdef herr_t H5Pset_fill_value(hid_t plist_id, hid_t type_id, void *value ) except *
cdef herr_t H5Pget_fill_value(hid_t plist_id, hid_t type_id, void *value ) except *
cdef herr_t H5Pfill_value_defined(hid_t plist_id, H5D_fill_value_t *status ) except *
cdef herr_t H5Pset_fill_time(hid_t plist_id, H5D_fill_time_t fill_time ) except *
cdef herr_t H5Pget_fill_time(hid_t plist_id, H5D_fill_time_t *fill_time ) except *
cdef herr_t H5Pset_alloc_time(hid_t plist_id, H5D_alloc_time_t alloc_time ) except *
cdef herr_t H5Pget_alloc_time(hid_t plist_id, H5D_alloc_time_t *alloc_time ) except *
cdef herr_t H5Pset_filter(hid_t plist, H5Z_filter_t filter, unsigned int flags, size_t cd_nelmts, unsigned int* cd_values ) except *
cdef htri_t H5Pall_filters_avail(hid_t dcpl_id) except *
cdef int H5Pget_nfilters(hid_t plist) except *
cdef H5Z_filter_t H5Pget_filter(hid_t plist, unsigned int filter_number, unsigned int *flags, size_t *cd_nelmts, unsigned int* cd_values, size_t namelen, char* name ) except *
cdef herr_t H5Pget_filter_by_id( hid_t plist_id, H5Z_filter_t filter, unsigned int *flags, size_t *cd_nelmts, unsigned int* cd_values, size_t namelen, char* name) except *
cdef herr_t H5Pmodify_filter(hid_t plist, H5Z_filter_t filter, unsigned int flags, size_t cd_nelmts, unsigned int *cd_values) except *
cdef herr_t H5Premove_filter(hid_t plist, H5Z_filter_t filter ) except *
cdef herr_t H5Pset_fletcher32(hid_t plist) except *
cdef herr_t H5Pset_shuffle(hid_t plist_id) except *
cdef herr_t H5Pset_szip(hid_t plist, unsigned int options_mask, unsigned int pixels_per_block) except *
cdef herr_t H5Pset_scaleoffset(hid_t plist, H5Z_SO_scale_type_t scale_type, int scale_factor) except *
cdef herr_t H5Pset_edc_check(hid_t plist, H5Z_EDC_t check) except *
cdef H5Z_EDC_t H5Pget_edc_check(hid_t plist) except *
cdef herr_t H5Pset_chunk_cache( hid_t dapl_id, size_t rdcc_nslots, size_t rdcc_nbytes, double rdcc_w0 ) except *
cdef herr_t H5Pget_chunk_cache( hid_t dapl_id, size_t *rdcc_nslots, size_t *rdcc_nbytes, double *rdcc_w0 ) except *
cdef herr_t H5Pset_sieve_buf_size(hid_t fapl_id, size_t size) except *
cdef herr_t H5Pget_sieve_buf_size(hid_t fapl_id, size_t *size) except *
cdef herr_t H5Pset_nlinks(hid_t plist_id, size_t nlinks) except *
cdef herr_t H5Pget_nlinks(hid_t plist_id, size_t *nlinks) except *
cdef herr_t H5Pset_elink_prefix(hid_t plist_id, char *prefix) except *
cdef ssize_t H5Pget_elink_prefix(hid_t plist_id, char *prefix, size_t size) except *
cdef hid_t H5Pget_elink_fapl(hid_t lapl_id) except *
cdef herr_t H5Pset_elink_fapl(hid_t lapl_id, hid_t fapl_id) except *
cdef herr_t H5Pset_create_intermediate_group(hid_t plist_id, unsigned crt_intmd) except *
cdef herr_t H5Pget_create_intermediate_group(hid_t plist_id, unsigned *crt_intmd) except *
cdef herr_t H5Pset_copy_object(hid_t plist_id, unsigned crt_intmd) except *
cdef herr_t H5Pget_copy_object(hid_t plist_id, unsigned *crt_intmd) except *
cdef herr_t H5Pset_char_encoding(hid_t plist_id, H5T_cset_t encoding) except *
cdef herr_t H5Pget_char_encoding(hid_t plist_id, H5T_cset_t *encoding) except *
cdef herr_t H5Pset_obj_track_times( hid_t ocpl_id, hbool_t track_times ) except *
cdef herr_t H5Pget_obj_track_times( hid_t ocpl_id, hbool_t *track_times ) except *
cdef herr_t H5Pset_local_heap_size_hint(hid_t plist_id, size_t size_hint) except *
cdef herr_t H5Pget_local_heap_size_hint(hid_t plist_id, size_t *size_hint) except *
cdef herr_t H5Pset_link_phase_change(hid_t plist_id, unsigned max_compact, unsigned min_dense) except *
cdef herr_t H5Pget_link_phase_change(hid_t plist_id, unsigned *max_compact, unsigned *min_dense) except *
cdef herr_t H5Pset_est_link_info(hid_t plist_id, unsigned est_num_entries, unsigned est_name_len) except *
cdef herr_t H5Pget_est_link_info(hid_t plist_id, unsigned *est_num_entries, unsigned *est_name_len) except *
cdef herr_t H5Pset_link_creation_order(hid_t plist_id, unsigned crt_order_flags) except *
cdef herr_t H5Pget_link_creation_order(hid_t plist_id, unsigned *crt_order_flags) except *
cdef herr_t H5Pset_libver_bounds(hid_t fapl_id, H5F_libver_t libver_low, H5F_libver_t libver_high) except *
cdef herr_t H5Pget_libver_bounds(hid_t fapl_id, H5F_libver_t *libver_low, H5F_lib | Cython |
ver_t *libver_high) except *
cdef herr_t H5Rcreate(void *ref, hid_t loc_id, char *name, H5R_type_t ref_type, hid_t space_id) except *
cdef hid_t H5Rdereference(hid_t obj_id, H5R_type_t ref_type, void *ref) except *
cdef hid_t H5Rget_region(hid_t dataset, H5R_type_t ref_type, void *ref) except *
cdef H5G_obj_t H5Rget_obj_type(hid_t id, H5R_type_t ref_type, void *ref) except *
cdef ssize_t H5Rget_name(hid_t loc_id, H5R_type_t ref_type, void *ref, char *name, size_t size) except *
cdef hid_t H5Screate(H5S_class_t type) except *
cdef hid_t H5Scopy(hid_t space_id ) except *
cdef herr_t H5Sclose(hid_t space_id) except *
cdef hid_t H5Screate_simple(int rank, hsize_t *dims, hsize_t *maxdims) except *
cdef htri_t H5Sis_simple(hid_t space_id) except *
cdef herr_t H5Soffset_simple(hid_t space_id, hssize_t *offset ) except *
cdef int H5Sget_simple_extent_ndims(hid_t space_id) except *
cdef int H5Sget_simple_extent_dims(hid_t space_id, hsize_t *dims, hsize_t *maxdims) except *
cdef hssize_t H5Sget_simple_extent_npoints(hid_t space_id) except *
cdef H5S_class_t H5Sget_simple_extent_type(hid_t space_id) except *
cdef herr_t H5Sextent_copy(hid_t dest_space_id, hid_t source_space_id ) except *
cdef herr_t H5Sset_extent_simple(hid_t space_id, int rank, hsize_t *current_size, hsize_t *maximum_size ) except *
cdef herr_t H5Sset_extent_none(hid_t space_id) except *
cdef H5S_sel_type H5Sget_select_type(hid_t space_id) except *
cdef hssize_t H5Sget_select_npoints(hid_t space_id) except *
cdef herr_t H5Sget_select_bounds(hid_t space_id, hsize_t *start, hsize_t *end) except *
cdef herr_t H5Sselect_all(hid_t space_id) except *
cdef herr_t H5Sselect_none(hid_t space_id) except *
cdef htri_t H5Sselect_valid(hid_t space_id) except *
cdef hssize_t H5Sget_select_elem_npoints(hid_t space_id) except *
cdef herr_t H5Sget_select_elem_pointlist(hid_t space_id, hsize_t startpoint, hsize_t numpoints, hsize_t *buf) except *
cdef herr_t H5Sselect_elements(hid_t space_id, H5S_seloper_t op, size_t num_elements, hsize_t **coord) except *
cdef hssize_t H5Sget_select_hyper_nblocks(hid_t space_id ) except *
cdef herr_t H5Sget_select_hyper_blocklist(hid_t space_id, hsize_t startblock, hsize_t numblocks, hsize_t *buf ) except *
cdef herr_t H5Sselect_hyperslab(hid_t space_id, H5S_seloper_t op, hsize_t *start, hsize_t *_stride, hsize_t *count, hsize_t *_block) except *
cdef herr_t H5Sencode(hid_t obj_id, void *buf, size_t *nalloc) except *
cdef hid_t H5Sdecode(void *buf) except *
cdef hid_t H5Tcreate(H5T_class_t type, size_t size) except *
cdef hid_t H5Topen(hid_t loc, char* name) except *
cdef herr_t H5Tcommit(hid_t loc_id, char* name, hid_t type) except *
cdef htri_t H5Tcommitted(hid_t type) except *
cdef hid_t H5Tcopy(hid_t type_id) except *
cdef htri_t H5Tequal(hid_t type_id1, hid_t type_id2 ) except *
cdef herr_t H5Tlock(hid_t type_id) except *
cdef H5T_class_t H5Tget_class(hid_t type_id) except *
cdef size_t H5Tget_size(hid_t type_id) except *
cdef hid_t H5Tget_super(hid_t type) except *
cdef htri_t H5Tdetect_class(hid_t type_id, H5T_class_t dtype_class) except *
cdef herr_t H5Tclose(hid_t type_id) except *
cdef hid_t H5Tget_native_type(hid_t type_id, H5T_direction_t direction) except *
cdef herr_t H5Tconvert(hid_t src_id, hid_t dst_id, size_t nelmts, void *buf, void *background, hid_t plist_id) except *
cdef herr_t H5Tset_size(hid_t type_id, size_t size) except *
cdef H5T_order_t H5Tget_order(hid_t type_id) except *
cdef herr_t H5Tset_order(hid_t type_id, H5T_order_t order) except *
cdef hsize_t H5Tget_precision(hid_t type_id) except *
cdef herr_t H5Tset_precision(hid_t type_id, size_t prec) except *
cdef int H5Tget_offset(hid_t type_id) except *
cdef herr_t H5Tset_offset(hid_t type_id, size_t offset) except *
cdef herr_t H5Tget_pad(hid_t type_id, H5T_pad_t * lsb, H5T_pad_t * msb ) except *
cdef herr_t H5Tset_pad(hid_t type_id, H5T_pad_t lsb, H5T_pad_t msb ) except *
cdef H5T_sign_t H5Tget_sign(hid_t type_id) except *
cdef herr_t H5Tset_sign(hid_t type_id, H5T_sign_t sign) except *
cdef herr_t H5Tget_fields(hid_t type_id, size_t *spos, size_t *epos, size_t *esize, size_t *mpos, size_t *msize ) except *
cdef herr_t H5Tset_fields(hid_t type_id, size_t spos, size_t epos, size_t esize, size_t mpos, size_t msize ) except *
cdef size_t H5Tget_ebias(hid_t type_id) except *
cdef herr_t H5Tset_ebias(hid_t type_id, size_t ebias) except *
cdef H5T_norm_t H5Tget_norm(hid_t type_id) except *
cdef herr_t H5Tset_norm(hid_t type_id, H5T_norm_t norm) except *
cdef H5T_pad_t H5Tget_inpad(hid_t type_id) except *
cdef herr_t H5Tset_inpad(hid_t type_id, H5T_pad_t inpad) except *
cdef H5T_cset_t H5Tget_cset(hid_t type_id) except *
cdef herr_t H5Tset_cset(hid_t type_id, H5T_cset_t cset) except *
cdef H5T_str_t H5Tget_strpad(hid_t type_id) except *
cdef herr_t H5Tset_strpad(hid_t type_id, H5T_str_t strpad) except *
cdef hid_t H5Tvlen_create(hid_t base_type_id) except *
cdef htri_t H5Tis_variable_str(hid_t dtype_id) except *
cdef int H5Tget_nmembers(hid_t type_id) except *
cdef H5T_class_t H5Tget_member_class(hid_t type_id, int member_no) except *
cdef char* H5Tget_member_name(hid_t type_id, unsigned membno) except *
cdef hid_t H5Tget_member_type(hid_t type_id, unsigned membno) except *
cdef int H5Tget_member_offset(hid_t type_id, int membno) except *
cdef int H5Tget_member_index(hid_t type_id, char* name) except *
cdef herr_t H5Tinsert(hid_t parent_id, char *name, size_t offset, hid_t member_id) except *
cdef herr_t H5Tpack(hid_t type_id) except *
cdef hid_t H5Tenum_create(hid_t base_id) except *
cdef herr_t H5Tenum_insert(hid_t type, char *name, void *value) except *
cdef herr_t H5Tenum_nameof( hid_t type, void *value, char *name, size_t size ) except *
cdef herr_t H5Tenum_valueof( hid_t type, char *name, void *value ) except *
cdef herr_t H5Tget_member_value(hid_t type, unsigned int memb_no, void *value ) except *
cdef hid_t H5Tarray_create(hid_t base_id, int ndims, | Cython |
hsize_t *dims, int *perm) except *
cdef int H5Tget_array_ndims(hid_t type_id) except *
cdef int H5Tget_array_dims(hid_t type_id, hsize_t *dims, int *perm) except *
cdef herr_t H5Tset_tag(hid_t type_id, char* tag) except *
cdef char* H5Tget_tag(hid_t type_id) except *
cdef hid_t H5Tdecode(unsigned char *buf) except *
cdef herr_t H5Tencode(hid_t obj_id, unsigned char *buf, size_t *nalloc) except *
cdef herr_t H5Tcommit2(hid_t loc_id, char *name, hid_t dtype_id, hid_t lcpl_id, hid_t tcpl_id, hid_t tapl_id) except *
cdef H5T_conv_t H5Tfind(hid_t src_id, hid_t dst_id, H5T_cdata_t **pcdata) except *
cdef herr_t H5Tregister(H5T_pers_t pers, char *name, hid_t src_id, hid_t dst_id, H5T_conv_t func) except *
cdef herr_t H5Tunregister(H5T_pers_t pers, char *name, hid_t src_id, hid_t dst_id, H5T_conv_t func) except *
cdef htri_t H5Zfilter_avail(H5Z_filter_t id_) except *
cdef herr_t H5Zget_filter_info(H5Z_filter_t filter_, unsigned int *filter_config_flags) except *
cdef hid_t H5Acreate(hid_t loc_id, char *name, hid_t type_id, hid_t space_id, hid_t create_plist) except *
cdef hid_t H5Aopen_idx(hid_t loc_id, unsigned int idx) except *
cdef hid_t H5Aopen_name(hid_t loc_id, char *name) except *
cdef herr_t H5Aclose(hid_t attr_id) except *
cdef herr_t H5Adelete(hid_t loc_id, char *name) except *
cdef herr_t H5Aread(hid_t attr_id, hid_t mem_type_id, void *buf) except *
cdef herr_t H5Awrite(hid_t attr_id, hid_t mem_type_id, void *buf ) except *
cdef int H5Aget_num_attrs(hid_t loc_id) except *
cdef ssize_t H5Aget_name(hid_t attr_id, size_t buf_size, char *buf) except *
cdef hid_t H5Aget_space(hid_t attr_id) except *
cdef hid_t H5Aget_type(hid_t attr_id) except *
cdef herr_t H5Aiterate(hid_t loc_id, unsigned * idx, H5A_operator_t op, void* op_data) except *
cdef herr_t H5Adelete_by_name(hid_t loc_id, char *obj_name, char *attr_name, hid_t lapl_id) except *
cdef herr_t H5Adelete_by_idx(hid_t loc_id, char *obj_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t n, hid_t lapl_id) except *
cdef hid_t H5Acreate_by_name(hid_t loc_id, char *obj_name, char *attr_name, hid_t type_id, hid_t space_id, hid_t acpl_id, hid_t aapl_id, hid_t lapl_id) except *
cdef herr_t H5Aopen(hid_t obj_id, char *attr_name, hid_t aapl_id) except *
cdef herr_t H5Aopen_by_name( hid_t loc_id, char *obj_name, char *attr_name, hid_t aapl_id, hid_t lapl_id) except *
cdef herr_t H5Aopen_by_idx(hid_t loc_id, char *obj_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t n, hid_t aapl_id, hid_t lapl_id) except *
cdef htri_t H5Aexists_by_name( hid_t loc_id, char *obj_name, char *attr_name, hid_t lapl_id) except *
cdef htri_t H5Aexists(hid_t obj_id, char *attr_name) except *
cdef herr_t H5Arename(hid_t loc_id, char *old_attr_name, char *new_attr_name) except *
cdef herr_t H5Arename_by_name(hid_t loc_id, char *obj_name, char *old_attr_name, char *new_attr_name, hid_t lapl_id) except *
cdef herr_t H5Aget_info( hid_t attr_id, H5A_info_t *ainfo) except *
cdef herr_t H5Aget_info_by_name(hid_t loc_id, char *obj_name, char *attr_name, H5A_info_t *ainfo, hid_t lapl_id) except *
cdef herr_t H5Aget_info_by_idx(hid_t loc_id, char *obj_name, H5_index_t idx_type, H5_iter_order_t order, hsize_t n, H5A_info_t *ainfo, hid_t lapl_id) except *
cdef herr_t H5Aiterate2(hid_t obj_id, H5_index_t idx_type, H5_iter_order_t order, hsize_t *n, H5A_operator2_t op, void *op_data) except *
cdef hsize_t H5Aget_storage_size(hid_t attr_id) except *
IF MPI:
cdef herr_t H5Pset_fapl_mpio(hid_t fapl_id, MPI_Comm comm, MPI_Info info) except *
IF MPI:
cdef herr_t H5Pget_fapl_mpio(hid_t fapl_id, MPI_Comm *comm, MPI_Info *info) except *
IF HDF5_VERSION >= (1, 8, 9):
IF MPI:
cdef herr_t H5Fset_mpi_atomicity(hid_t file_id, hbool_t flag) except *
IF HDF5_VERSION >= (1, 8, 9):
IF MPI:
cdef herr_t H5Fget_mpi_atomicity(hid_t file_id, hbool_t *flag) except *
cdef herr_t H5DSattach_scale(hid_t did, hid_t dsid, unsigned int idx) except *
cdef herr_t H5DSdetach_scale(hid_t did, hid_t dsid, unsigned int idx) except *
cdef herr_t H5DSset_scale(hid_t dsid, char *dimname) except *
cdef int H5DSget_num_scales(hid_t did, unsigned int dim) except *
cdef herr_t H5DSset_label(hid_t did, unsigned int idx, char *label) except *
cdef ssize_t H5DSget_label(hid_t did, unsigned int idx, char *label, size_t size) except *
cdef ssize_t H5DSget_scale_name(hid_t did, char *name, size_t size) except *
cdef htri_t H5DSis_scale(hid_t did) except *
cdef herr_t H5DSiterate_scales(hid_t did, unsigned int dim, int *idx, H5DS_iterate_t visitor, void *visitor_data) except *
cdef htri_t H5DSis_attached(hid_t did, hid_t dsid, unsigned int idx) except *
<|end_of_text|>__doc__ = """
Basic model typedefs, constants and common methods.
"""
cdef bytes buffer_dump(const Buffer* buf):
"""
Return a buffer's content as a string.
:param const Buffer* buf Pointer to a buffer to be read.
:rtype: str
"""
cdef unsigned char* buf_stream = (<unsigned char*>buf.addr)
return buf_stream[:buf.sz]
<|end_of_text|>import cython
from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free
from dendropy import Tree
from random import sample
from itertools import combinations
import numpy as np
cimport numpy as np
import pandas as pd
from scipy.linalg.cython_lapack cimport dsyev
from numbers import Integral, Real
# if igraph is available, enable
# SuchLinkedTrees.to_igraph()
try :
from igraph import Graph, ADJ_UNDIRECTED
with_igraph = True
except ImportError :
with_igraph = False
cdef extern from'stdint.h' :
ctypedef unsigned long int uint64_t
uint64_t UINT64_MAX
# Trees are built from arrays of Node structs. 'parent', 'left_child'
# and 'right_child' attributes represent integer offsets within the
# array that specify other Node structs.
#
# WARNING : When part of a SuchLinkedTree, the right_child is used to
# store the column ID for leaf nodes. Check *ONLY* left_child == -1 to
# to see if a Node is a leaf!
cdef struct Node :
int parent
int left_child
int right_child
float distance
@cython.boundscheck(False)
cdef double _pearson( double[:] x, double[:] y, unsigned int n ) nogil :
#cdef unsigned int n = len(x)
cdef unsigned long j
cdef float yt, xt, t, df
cdef float syy=0.0, sxy=0.0, sxx=0.0, ay=0.0, ax=0.0
| Cython |
../cython/cy_cpp_utils.pxd<|end_of_text|># distutils: language = c++
from libcpp.string cimport string
from pytraj.NameType cimport *
cdef extern from "MaskToken.h":
# MaskToken.h
ctypedef enum MaskTokenType "MaskToken::MaskTokenType":
OP_NONE "MaskToken::OP_NONE"
ResNum "MaskToken::ResNum"
ResName "MaskToken::ResName"
AtomNum "MaskToken::AtomNum"
AtomName "MaskToken::AtomName"
AtomType "MaskToken::AtomType"
AtomElement "MaskToken::AtomElement"
SelectAll "MaskToken::SelectAll"
OP_AND "MaskToken::OP_AND"
OP_OR "MaskToken::OP_OR"
OP_NEG "MaskToken::OP_NEG"
OP_DIST "MaskToken::OP_DIST"
cdef cppclass _MaskToken "MaskToken":
_MaskToken()
const char* MaskTypeString[]
const char * TypeName() const
void Print() const
int SetToken(MaskTokenType, const string&)
int SetDistance(string&)
void SetOperator(MaskTokenType)
inline MaskTokenType Type() const
inline int Res1() const
inline int Res2() const
inline const _NameType& Name() const
inline bint OnStack() const
inline bint Within() const
inline bint ByAtom() const
inline double Distance() const
void SetOnStack()
cdef class MaskToken:
cdef _MaskToken* thisptr
<|end_of_text|># -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
cdef extern from "stdlib.h":
void abort()
<|end_of_text|>
## def __iter__(self):
## _r = self.inst.get().getSequence()
## cdef libcpp_vector[const _Ribonucleotide *].iterator it__r = _r.begin()
## cdef Ribonucleotide item_py_result
## while it__r!= _r.end():
## item_py_result = Ribonucleotide.__new__(Ribonucleotide)
## item_py_result.inst = shared_ptr[_Ribonucleotide](new _Ribonucleotide(deref(deref(it__r))))
## yield py_result
## inc(it__r)
def __iter__(self):
for r in self.getSequence():
yield r
<|end_of_text|>../cython/cy_flexible_type.pxd<|end_of_text|>"""
Copyright (C) 2011, Enthought Inc
Copyright (C) 2011, Patrick Henaff
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
"""
include '../../types.pxi'
cimport pybg.version
from libcpp cimport bool
from pybg.quantlib.handle cimport shared_ptr, Handle, RelinkableHandle
from pybg.quantlib._quote cimport Quote
from pybg.quantlib.time._calendar cimport BusinessDayConvention, Calendar
from pybg.quantlib.time._date cimport Date
from pybg.quantlib.time._daycounter cimport DayCounter
from pybg.quantlib.time._period cimport Period, Frequency
from _flat_forward cimport YieldTermStructure
from pybg.quantlib.indexes._ibor_index cimport IborIndex
cimport pybg.quantlib.indexes._ibor_index as _ib
cdef extern from 'ql/termstructures/bootstraphelper.hpp' namespace 'QuantLib':
cdef cppclass BootstrapHelper[T]:
BootstrapHelper(Handle[Quote]& quote)
BoostrapHelper(Real quote)
cdef cppclass RelativeDateBootstrapHelper[T](BootstrapHelper):
pass
cdef extern from 'ql/termstructures/yield/ratehelpers.hpp' namespace 'QuantLib':
# Cython does not support this ctypedef - thus trying to expose a class
#ctypedef BootstrapHelper[YieldTermStructure] RateHelper
cdef cppclass RateHelper:
Handle[Quote] quote()
cdef cppclass RelativeDateRateHelper:
Handle[Quote] quote()
cdef cppclass DepositRateHelper(RateHelper):
DepositRateHelper(Handle[Quote]& rate,
Period& tenor,
Natural fixingDays,
Calendar& calendar,
BusinessDayConvention convention,
bool endOfMonth,
DayCounter& dayCounter)
DepositRateHelper(Rate rate,
Period& tenor,
Natural fixingDays,
Calendar& calendar,
BusinessDayConvention convention,
bool endOfMonth,
DayCounter& dayCounter)
# Not supporting IborIndex at this stage
DepositRateHelper(Handle[Quote]& rate,
shared_ptr[IborIndex]& iborIndex)
DepositRateHelper(Rate rate,
shared_ptr[IborIndex]& iborIndex)
cdef cppclass FraRateHelper(RelativeDateRateHelper):
FraRateHelper(Handle[Quote]& rate,
Natural monthsToStart,
Natural monthsToEnd,
Natural fixingDays,
Calendar& calendar,
BusinessDayConvention convention,
bool endOfMonth,
DayCounter& dayCounter)
cdef cppclass SwapRateHelper(RelativeDateRateHelper):
SwapRateHelper(Handle[Quote]& rate,
Period& tenor,
Calendar& calendar,
Frequency& fixedFrequency,
BusinessDayConvention fixedConvention,
DayCounter& fixedDayCount,
shared_ptr[_ib.IborIndex]& iborIndex,
Handle[Quote]& spread,
Period& fwdStart)
cdef cppclass FuturesRateHelper(RateHelper):
FuturesRateHelper(Handle[Quote]& price,
Date& immDate,
Natural lengthInMonths,
Calendar& calendar,
BusinessDayConvention convention,
bool endOfMonth,
DayCounter& dayCounter) except +
<|end_of_text|>from sklearn.tree._criterion cimport ClassificationCriterion
from sklearn.tree._criterion cimport SIZE_t
from libc.math cimport sqrt, pow
from libc.math cimport abs
cdef class BetaEntropy(ClassificationCriterion):
cdef double beta = 0.001
cdef double node_impurity(self) nogil:
"""Evaluate the impurity of the current node, i.e. the impurity of
samples[start:end], using the cross-entropy criterion."""
cdef SIZE_t* n_classes = self.n_classes
cdef double* sum_total = self.sum_total
cdef double entropy = 0.0
cdef double count_k
cdef SIZE_t k
cdef SIZE_t c
for k in range(self.n_outputs):
for c in range(n_classes[k]):
count_k = sum_total[c]
if count_k > 0.0:
count_k /= self.weighted_n_node_samples
entropy += pow(count_k,beta)
sum_total += self.sum_stride
entropy = (1-entropy)/(1-pow(2,float(1-beta)))
return entropy / self.n_outputs
cdef void children_impurity(self, double* impurity_left,
double* impurity_right) nogil:
cdef SIZE_t* n_classes = self.n_classes
cdef double* sum_left = self.sum_left
cdef double* sum_right = self.sum_right
cdef double entropy_left = 0.0
cdef double entropy_right = 0.0
cdef double count_k
cdef SIZE_t k
cdef SIZE_t c
for k in range(self.n_outputs):
for c in range(n_classes[k]):
count_k = sum_left[c]
if count_k > 0.0:
count_k /= self.weighted_n_left
entropy_left += pow(count_k,beta)
count_k = sum_right[c]
if count_k > 0.0:
count_k /= self.weighted_n_right
entropy_right += pow(count_k,beta)
sum_left += self.sum_stride
sum_right += self.sum_stride
entropy_left = (1-entropy_left)/(1-pow(2,float(1-beta)))
entropy_right = (1-entropy_right)/(1-pow(2,float(1-beta)))
impurity_left[0] = entropy_left / self.n_outputs
impurity_right[0] = entropy_right / self.n_outputs
<|end_of_text|>from hummingbot.core.event.event_reporter cimport EventReporter
from hummingbot.core.event.event_logger cimport EventLogger
from hummingbot.core.data_type.order_book cimport OrderBook
from hummingbot.connector.connector_base cimport ConnectorBase
from hummingbot.core.data_type.order_book_query_result cimport(
OrderBookQueryResult,
ClientOrderBookQueryResult
)
cdef class ExchangeBase(ConnectorBase):
cdef:
object _order_book_tracker
cdef str c_buy(self, str trading_pair, object amount, object order_type=*, object price=*, dict kwargs=*)
cdef str c_sell(self, str trading_pair, object amount, object order_type=*, object price=*, dict kwargs=*)
cdef c_cancel(self, str trading_pair, str client_order_id)
cdef c_stop_tracking_order(self, str order_id)
cdef OrderBook c_get_order_book(self, str trading_pair)
cdef object c_get_price(self, | Cython |
str trading_pair, bint is_buy)
cdef ClientOrderBookQueryResult c_get_quote_volume_for_base_amount(self, str trading_pair, bint is_buy, object base_amount)
cdef ClientOrderBookQueryResult c_get_volume_for_price(self, str trading_pair, bint is_buy, object price)
cdef ClientOrderBookQueryResult c_get_quote_volume_for_price(self, str trading_pair, bint is_buy, object price)
cdef ClientOrderBookQueryResult c_get_vwap_for_volume(self, str trading_pair, bint is_buy, object volume)
cdef ClientOrderBookQueryResult c_get_price_for_volume(self, str trading_pair, bint is_buy, object volume)
cdef object c_get_fee(self, str base_currency, str quote_currency, object order_type, object order_side,
object amount, object price)
<|end_of_text|># -*- coding: utf-8 -*-
cimport pcl_defs as cpp
cimport pcl_octree_defs_172 as pcloct
# include "PointXYZtoPointXYZ.pxi" --> multiple define ng
# include "OctreePointCloud.pxi"
cdef class OctreePointCloudSearch(OctreePointCloud):
"""
Octree pointcloud search
"""
cdef pcloct.OctreePointCloudSearch_t *me2
def __cinit__(self, double resolution):
"""
Constructs octree pointcloud with given resolution at lowest octree level
"""
self.me2 = NULL
self.me = NULL
if resolution <= 0.:
raise ValueError("Expected resolution > 0., got %r" % resolution)
self.me2 = <pcloct.OctreePointCloudSearch_t*> new pcloct.OctreePointCloudSearch_t(resolution)
self.me = <pcloct.OctreePointCloud_t*> self.me2
def __dealloc__(self):
del self.me2
self.me2 = NULL
self.me = NULL
# nearestKSearch
###
def nearest_k_search_for_cloud(self, PointCloud pc not None, int k=1):
"""
Find the k nearest neighbours and squared distances for all points
in the pointcloud. Results are in ndarrays, size (pc.size, k)
Returns: (k_indices, k_sqr_distances)
"""
cdef cnp.npy_intp n_points = pc.size
cdef cnp.ndarray[float, ndim=2] sqdist = np.zeros((n_points, k),
dtype=np.float32)
cdef cnp.ndarray[int, ndim=2] ind = np.zeros((n_points, k),
dtype=np.int32)
for i in range(n_points):
self._nearest_k(pc, i, k, ind[i], sqdist[i])
return ind, sqdist
def nearest_k_search_for_point(self, PointCloud pc not None, int index, int k=1):
"""
Find the k nearest neighbours and squared distances for the point
at pc[index]. Results are in ndarrays, size (k)
Returns: (k_indices, k_sqr_distances)
"""
cdef cnp.ndarray[float] sqdist = np.zeros(k, dtype=np.float32)
cdef cnp.ndarray[int] ind = np.zeros(k, dtype=np.int32)
self._nearest_k(pc, index, k, ind, sqdist)
return ind, sqdist
@cython.boundscheck(False)
cdef void _nearest_k(self, PointCloud pc, int index, int k,
cnp.ndarray[ndim=1, dtype=int, mode='c'] ind,
cnp.ndarray[ndim=1, dtype=float, mode='c'] sqdist
) except +:
# k nearest neighbors query for a single point.
cdef vector[int] k_indices
cdef vector[float] k_sqr_distances
k_indices.resize(k)
k_sqr_distances.resize(k)
# self.me.nearestKSearch(pc.thisptr()[0], index, k, k_indices, k_sqr_distances)
(<pcloct.OctreePointCloudSearch_t*>self.me).nearestKSearch(pc.thisptr()[0], index, k, k_indices, k_sqr_distances)
for i in range(k):
sqdist[i] = k_sqr_distances[i]
ind[i] = k_indices[i]
###
# radius Search
###
def radius_search (self, point, double radius, unsigned int max_nn = 0):
"""
Search for all neighbors of query point that are within a given radius.
Returns: (k_indices, k_sqr_distances)
"""
cdef vector[int] k_indices
cdef vector[float] k_sqr_distances
if max_nn > 0:
k_indices.resize(max_nn)
k_sqr_distances.resize(max_nn)
cdef int k = (<pcloct.OctreePointCloudSearch_t*>self.me).radiusSearch(to_point_t(point), radius, k_indices, k_sqr_distances, max_nn)
cdef cnp.ndarray[float] np_k_sqr_distances = np.zeros(k, dtype=np.float32)
cdef cnp.ndarray[int] np_k_indices = np.zeros(k, dtype=np.int32)
for i in range(k):
np_k_sqr_distances[i] = k_sqr_distances[i]
np_k_indices[i] = k_indices[i]
return np_k_indices, np_k_sqr_distances
###
# Voxel Search
###
def VoxelSearch (self, PointCloud pc):
"""
Search for all neighbors of query point that are within a given voxel.
Returns: (v_indices)
"""
cdef vector[int] v_indices
# cdef bool isVexelSearch = (<pcloct.OctreePointCloudSearch_t*>self.me).voxelSearch(pc.thisptr()[0], v_indices)
# self._VoxelSearch(pc, v_indices)
result = pc.to_array()
cdef cpp.PointXYZ point
point.x = result[0, 0]
point.y = result[0, 1]
point.z = result[0, 2]
print ('VoxelSearch at (' + str(point.x) +'' + str(point.y) +'' + str(point.z) + ')')
# print('before v_indices count ='+ str(v_indices.size()))
self._VoxelSearch(point, v_indices)
v = v_indices.size()
# print('after v_indices count ='+ str(v))
cdef cnp.ndarray[int] np_v_indices = np.zeros(v, dtype=np.int32)
for i in range(v):
np_v_indices[i] = v_indices[i]
return np_v_indices
@cython.boundscheck(False)
cdef void _VoxelSearch(self, cpp.PointXYZ point, vector[int] &v_indices) except +:
cdef vector[int] voxel_indices
# k = 10
# voxel_indices.resize(k)
(<pcloct.OctreePointCloudSearch_t*>self.me).voxelSearch(point, voxel_indices)
# print('_VoxelSearch k ='+ str(k))
# print('_VoxelSearch voxel_indices ='+ str(voxel_indices.size()))
k = voxel_indices.size()
for i in range(k):
v_indices.push_back(voxel_indices[i])
###
# def radius_search_for_cloud(self, PointCloud pc not None, double radius):
# """
# Find the radius and squared distances for all points
# in the pointcloud. Results are in ndarrays, size (pc.size, k)
# Returns: (radius_indices, radius_distances)
# """
# k = 10
# cdef cnp.npy_intp n_points = pc.size
# cdef cnp.ndarray[float, ndim=2] sqdist = np.zeros((n_points, k),
# dtype=np.float32)
# cdef cnp.ndarray[int, ndim=2] ind = np.zeros((n_points, k),
# dtype=np.int32)
#
# for i in range(n_points):
# self._search_radius(pc, i, k, radius, ind[i], sqdist[i])
# return ind, sqdist
#
# @cython.boundscheck(False)
# cdef void _search_radius(self, PointCloud pc, int index, int k, double radius,
# cnp.ndarray[ndim=1, dtype=int, mode='c'] ind,
# cnp.ndarray[ndim=1, dtype=float, mode='c'] sqdist
# ) except +:
# # radius query for a single point.
# cdef vector[int] radius_indices
# cdef vector[float] radius_distances
# radius_indices.resize(k)
# radius_distances.resize(k)
# # self.me.radiusSearch(pc.thisptr()[0], index, radius, radius_indices, radius_distances)
# k = (<pcloct.OctreePointCloudSearch_t*>self.me).radiusSearch(pc.thisptr()[0], index, radius, radius_indices, radius_distances, 10)
#
# for i in range(k):
# sqdist[i] = radius_distances[i]
# ind[i] = radius_indices[i]
# base OctreePointCloud
def define_bounding_box(self):
"""
Investigate dimensions of pointcloud data set and define corresponding bounding box for octree.
"""
self.me2.defineBoundingBox | Cython |
()
# def define_bounding_box(self, double min_x, double min_y, double min_z, double max_x, double max_y, double max_z):
# """
# Define bounding box for octree. Bounding box cannot be changed once the octree contains elements.
# """
# self.me2.defineBoundingBox(min_x, min_y, min_z, max_x, max_y, max_z)
def add_points_from_input_cloud(self):
"""
Add points from input point cloud to octree.
"""
self.me2.addPointsFromInputCloud()
def is_voxel_occupied_at_point(self, point):
"""
Check if voxel at given point coordinates exist.
"""
return self.me2.isVoxelOccupiedAtPoint(point[0], point[1], point[2])
def get_occupied_voxel_centers(self):
"""
Get list of centers of all occupied voxels.
"""
cdef eig.AlignedPointTVector_t points_v
cdef int num = self.me2.getOccupiedVoxelCenters (points_v)
return [(points_v[i].x, points_v[i].y, points_v[i].z) for i in range(num)]
def delete_voxel_at_point(self, point):
"""
Delete leaf node / voxel at given point.
"""
self.me2.deleteVoxelAtPoint(to_point_t(point))
cdef class OctreePointCloudSearch_PointXYZI(OctreePointCloud_PointXYZI):
"""
Octree pointcloud search
"""
cdef pcloct.OctreePointCloudSearch_PointXYZI_t *me2
def __cinit__(self, double resolution):
"""
Constructs octree pointcloud with given resolution at lowest octree level
"""
self.me2 = NULL
self.me = NULL
if resolution <= 0.:
raise ValueError("Expected resolution > 0., got %r" % resolution)
self.me2 = <pcloct.OctreePointCloudSearch_PointXYZI_t*> new pcloct.OctreePointCloudSearch_PointXYZI_t(resolution)
self.me = <pcloct.OctreePointCloud_PointXYZI_t*> self.me2
def __dealloc__(self):
del self.me2
self.me2 = NULL
self.me = NULL
def radius_search (self, point, double radius, unsigned int max_nn = 0):
"""
Search for all neighbors of query point that are within a given radius.
Returns: (k_indices, k_sqr_distances)
"""
cdef vector[int] k_indices
cdef vector[float] k_sqr_distances
if max_nn > 0:
k_indices.resize(max_nn)
k_sqr_distances.resize(max_nn)
cdef int k = (<pcloct.OctreePointCloudSearch_PointXYZI_t*>self.me).radiusSearch(to_point2_t(point), radius, k_indices, k_sqr_distances, max_nn)
cdef cnp.ndarray[float] np_k_sqr_distances = np.zeros(k, dtype=np.float32)
cdef cnp.ndarray[int] np_k_indices = np.zeros(k, dtype=np.int32)
for i in range(k):
np_k_sqr_distances[i] = k_sqr_distances[i]
np_k_indices[i] = k_indices[i]
return np_k_indices, np_k_sqr_distances
# base OctreePointCloud
def define_bounding_box(self):
"""
Investigate dimensions of pointcloud data set and define corresponding bounding box for octree.
"""
self.me2.defineBoundingBox()
# def define_bounding_box(self, double min_x, double min_y, double min_z, double max_x, double max_y, double max_z):
# """
# Define bounding box for octree. Bounding box cannot be changed once the octree contains elements.
# """
# self.me2.defineBoundingBox(min_x, min_y, min_z, max_x, max_y, max_z)
def add_points_from_input_cloud(self):
"""
Add points from input point cloud to octree.
"""
self.me2.addPointsFromInputCloud()
def is_voxel_occupied_at_point(self, point):
"""
Check if voxel at given point coordinates exist.
"""
return self.me2.isVoxelOccupiedAtPoint(point[0], point[1], point[2])
def get_occupied_voxel_centers(self):
"""
Get list of centers of all occupied voxels.
"""
cdef eig.AlignedPointTVector_PointXYZI_t points_v
cdef int num = self.me2.getOccupiedVoxelCenters (points_v)
return [(points_v[i].x, points_v[i].y, points_v[i].z) for i in range(num)]
def delete_voxel_at_point(self, point):
"""
Delete leaf node / voxel at given point.
"""
self.me2.deleteVoxelAtPoint(to_point2_t(point))
cdef class OctreePointCloudSearch_PointXYZRGB(OctreePointCloud_PointXYZRGB):
"""
Octree pointcloud search
"""
cdef pcloct.OctreePointCloudSearch_PointXYZRGB_t *me2
def __cinit__(self, double resolution):
"""
Constructs octree pointcloud with given resolution at lowest octree level
"""
self.me2 = NULL
self.me = NULL
if resolution <= 0.:
raise ValueError("Expected resolution > 0., got %r" % resolution)
self.me2 = <pcloct.OctreePointCloudSearch_PointXYZRGB_t*> new pcloct.OctreePointCloudSearch_PointXYZRGB_t(resolution)
self.me = <pcloct.OctreePointCloud_PointXYZRGB_t*> self.me2
def __dealloc__(self):
del self.me2
self.me2 = NULL
self.me = NULL
def radius_search (self, point, double radius, unsigned int max_nn = 0):
"""
Search for all neighbors of query point that are within a given radius.
Returns: (k_indices, k_sqr_distances)
"""
cdef vector[int] k_indices
cdef vector[float] k_sqr_distances
if max_nn > 0:
k_indices.resize(max_nn)
k_sqr_distances.resize(max_nn)
cdef int k = (<pcloct.OctreePointCloudSearch_PointXYZRGB_t*>self.me).radiusSearch(to_point3_t(point), radius, k_indices, k_sqr_distances, max_nn)
cdef cnp.ndarray[float] np_k_sqr_distances = np.zeros(k, dtype=np.float32)
cdef cnp.ndarray[int] np_k_indices = np.zeros(k, dtype=np.int32)
for i in range(k):
np_k_sqr_distances[i] = k_sqr_distances[i]
np_k_indices[i] = k_indices[i]
return np_k_indices, np_k_sqr_distances
# base OctreePointCloud
def define_bounding_box(self):
"""
Investigate dimensions of pointcloud data set and define corresponding bounding box for octree.
"""
self.me2.defineBoundingBox()
# def define_bounding_box(self, double min_x, double min_y, double min_z, double max_x, double max_y, double max_z):
# """
# Define bounding box for octree. Bounding box cannot be changed once the octree contains elements.
# """
# self.me2.defineBoundingBox(min_x, min_y, min_z, max_x, max_y, max_z)
def add_points_from_input_cloud(self):
"""
Add points from input point cloud to octree.
"""
self.me2.addPointsFromInputCloud()
def is_voxel_occupied_at_point(self, point):
"""
Check if voxel at given point coordinates exist.
"""
return self.me2.isVoxelOccupiedAtPoint(point[0], point[1], point[2])
def get_occupied_voxel_centers(self):
"""
Get list of centers of all occupied voxels.
"""
cdef eig.AlignedPointTVector_PointXYZRGB_t points_v
cdef int num = self.me2.getOccupiedVoxelCenters (points_v)
return [(points_v[i].x, points_v[i].y, points_v[i].z) for i in range(num)]
def delete_voxel_at_point(self, point):
"""
Delete leaf node / voxel at given point.
"""
self.me2.deleteVoxelAtPoint(to_point3_t(point))
cdef class OctreePointCloudSearch_PointXYZRGBA(OctreePointCloud_PointXYZRGBA):
"""
Octree pointcloud search
"""
cdef pcloct.OctreePointCloudSearch_PointXYZRGBA_t *me2
def __cinit__(self, double resolution):
"""
Constructs octree pointcloud with given resolution at lowest octree level
"""
self.me2 = NULL
self.me = NULL
if resolution <= 0.:
raise ValueError("Expected resolution > 0., got %r" % resolution)
self.me2 = <pcloct.OctreePointCloudSearch_PointXYZRGBA_t*> new pcloct.OctreePointCloudSearch_PointXYZRGBA_t(resolution)
self.me = <pcloct.OctreePointCloud_PointXYZRGBA_t*> self.me2
def __dealloc__(self):
del self.me2
self.me2 = NULL
self.me = NULL | Cython |
def radius_search (self, point, double radius, unsigned int max_nn = 0):
"""
Search for all neighbors of query point that are within a given radius.
Returns: (k_indices, k_sqr_distances)
"""
cdef vector[int] k_indices
cdef vector[float] k_sqr_distances
if max_nn > 0:
k_indices.resize(max_nn)
k_sqr_distances.resize(max_nn)
cdef int k = (<pcloct.OctreePointCloudSearch_PointXYZRGBA_t*>self.me).radiusSearch(to_point4_t(point), radius, k_indices, k_sqr_distances, max_nn)
cdef cnp.ndarray[float] np_k_sqr_distances = np.zeros(k, dtype=np.float32)
cdef cnp.ndarray[int] np_k_indices = np.zeros(k, dtype=np.int32)
for i in range(k):
np_k_sqr_distances[i] = k_sqr_distances[i]
np_k_indices[i] = k_indices[i]
return np_k_indices, np_k_sqr_distances
# base OctreePointCloud
def define_bounding_box(self):
"""
Investigate dimensions of pointcloud data set and define corresponding bounding box for octree.
"""
self.me2.defineBoundingBox()
# def define_bounding_box(self, double min_x, double min_y, double min_z, double max_x, double max_y, double max_z):
# """
# Define bounding box for octree. Bounding box cannot be changed once the octree contains elements.
# """
# self.me2.defineBoundingBox(min_x, min_y, min_z, max_x, max_y, max_z)
def add_points_from_input_cloud(self):
"""
Add points from input point cloud to octree.
"""
self.me2.addPointsFromInputCloud()
def is_voxel_occupied_at_point(self, point):
"""
Check if voxel at given point coordinates exist.
"""
return self.me2.isVoxelOccupiedAtPoint(point[0], point[1], point[2])
def get_occupied_voxel_centers(self):
"""
Get list of centers of all occupied voxels.
"""
cdef eig.AlignedPointTVector_PointXYZRGBA_t points_v
cdef int num = self.me2.getOccupiedVoxelCenters (points_v)
return [(points_v[i].x, points_v[i].y, points_v[i].z) for i in range(num)]
def delete_voxel_at_point(self, point):
"""
Delete leaf node / voxel at given point.
"""
self.me2.deleteVoxelAtPoint(to_point4_t(point))
<|end_of_text|># cython: profile=True
cimport cython
cimport numpy as np
import numpy as np
import scipy.sparse as sps
@cython.boundscheck(False)
def calculate_error_matrix(R, P, Q):
cdef double [:] err_data = np.zeros(R.data.shape[0], dtype=np.float64), r_data = R.data
tup = R.nonzero()
cdef int [:]rows = tup[0], cols = tup[1]
cdef int i, n_inters = R.data.shape[0]
for i in range(n_inters):
err_data[i] = r_data[i] - P[rows[i], :].dot(Q[cols[i], :])
return sps.csr_matrix((err_data, (rows, cols)), R.shape, dtype=np.float64)<|end_of_text|>cpdef int incr(int i):
i = i + 1
return i
<|end_of_text|>#declare c-style function by cdef argument
# except? -2: usually followed after function declaration.
# except? -2: means an error will be checked for if -2 is returned
# Warning: using cdef to declare function causes that python can't call it again.
# if you use cpdef keyword, that will create a python wrapper
cpdef double f(double x) except? -2:
return x ** 2 - x
def integrate_f(double a, double b, int N):
cdef int i
cdef double s, dx
s = 0
dx = (b - a) / N
for i in range(N):
s += f(a + i * dx)
return s * dx
<|end_of_text|># coding: utf-8
#from __future__ import division, unicode_literals
"""
Utilities for manipulating coordinates or list of coordinates, under periodic
boundary conditions or otherwise.
"""
from six.moves import zip
__author__ = "Will Richards"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ = "1.0"
__maintainer__ = "Will Richards"
__email__ = "[email protected]"
__date__ = "Nov 27, 2011"
import numpy as np
from libc.stdlib cimport malloc, free
from libc.math cimport round, fabs, sqrt, acos, M_PI, cos, sin
cimport numpy as np
cimport cython
#create images, 2d array of all length 3 combinations of [-1,0,1]
r = np.arange(-1, 2, dtype=np.float_)
arange = r[:, None] * np.array([1, 0, 0])[None, :]
brange = r[:, None] * np.array([0, 1, 0])[None, :]
crange = r[:, None] * np.array([0, 0, 1])[None, :]
images_t = arange[:, None, None] + brange[None, :, None] + \
crange[None, None, :]
images = images_t.reshape((27, 3))
cdef np.float_t[:, ::1] images_view = images
@cython.boundscheck(False)
@cython.wraparound(False)
cdef void dot_2d(np.float_t[:, ::1] a, np.float_t[:, ::1] b, np.float_t[:, ::1] o) nogil:
cdef int i, j, k, I, J, K
I = a.shape[0]
J = b.shape[1]
K = a.shape[1]
for j in range(J):
for i in range(I):
o[i, j] = 0
for k in range(K):
for i in range(I):
o[i, j] += a[i, k] * b[k, j]
@cython.boundscheck(False)
@cython.wraparound(False)
cdef void dot_2d_mod(np.float_t[:, ::1] a, np.float_t[:, ::1] b, np.float_t[:, ::1] o) nogil:
cdef int i, j, k, I, J, K
I = a.shape[0]
J = b.shape[1]
K = a.shape[1]
for j in range(J):
for i in range(I):
o[i, j] = 0
for k in range(K):
for i in range(I):
o[i, j] += a[i, k] % 1 * b[k, j]
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def pbc_shortest_vectors(lattice, fcoords1, fcoords2, mask=None, return_d2=False, lll_frac_tol=None):
"""
Returns the shortest vectors between two lists of coordinates taking into
account periodic boundary conditions and the lattice.
Args:
lattice: lattice to use
fcoords1: First set of fractional coordinates. e.g., [0.5, 0.6, 0.7]
or [[1.1, 1.2, 4.3], [0.5, 0.6, 0.7]]. Must be np.float_
fcoords2: Second set of fractional coordinates.
mask (int_ array): Mask of matches that are not allowed.
i.e. if mask[1,2] == True, then subset[1] cannot be matched
to superset[2]
lll_frac_tol (float_ array of length 3): Fractional tolerance (per LLL lattice vector) over which
the calculation of minimum vectors will be skipped.
Can speed up calculation considerably for large structures.
Returns:
array of displacement vectors from fcoords1 to fcoords2
first index is fcoords1 index, second is fcoords2 index
"""
#ensure correct shape
fcoords1, fcoords2 = np.atleast_2d(fcoords1, fcoords2)
fcoords1 = lattice.get_lll_frac_coords(fcoords1)
fcoords2 = lattice.get_lll_frac_coords(fcoords2)
cdef np.float_t[:, ::1] lat = np.array(lattice.lll_matrix, dtype=np.float_, copy=False, order='C')
cdef int i, j, k, l, I, J, bestK
I = len(fcoords1)
J = len(fcoords2)
cdef np.float_t[:, ::1] fc1 = fcoords1
cdef np.float_t[:, ::1] fc2 = fcoords2
cdef np.float_t[:, ::1] cart_f1 = <np.float_t[:I, :3]> malloc(3 * I * sizeof(np.float_t))
cdef np.float_t[:, ::1] cart_f2 = <np.float_t[:J | Cython |
, :3]> malloc(3 * J * sizeof(np.float_t))
cdef np.float_t[:, ::1] cart_im = <np.float_t[:27, :3]> malloc(81 * sizeof(np.float_t))
cdef bint has_mask = mask is not None
cdef np.int_t[:, :] m
if has_mask:
m = np.array(mask, dtype=np.int_, copy=False, order='C')
cdef bint has_ftol = (lll_frac_tol is not None)
cdef np.float_t[:] ftol
if has_ftol:
ftol = np.array(lll_frac_tol, dtype=np.float_, order='C', copy=False)
dot_2d_mod(fc1, lat, cart_f1)
dot_2d_mod(fc2, lat, cart_f2)
dot_2d(images_view, lat, cart_im)
vectors = np.empty((I, J, 3))
d2 = np.empty((I, J))
cdef np.float_t[:, :, ::1] vs = vectors
cdef np.float_t[:, ::1] ds = d2
cdef np.float_t best, d, inc_d, da, db, dc, fdist
cdef bint within_frac = True
cdef np.float_t[:] pre_im = <np.float_t[:3]> malloc(3 * sizeof(np.float_t))
for i in range(I):
for j in range(J):
within_frac = False
if (not has_mask) or (m[i, j] == 0):
within_frac = True
if has_ftol:
for l in range(3):
fdist = fc2[j, l] - fc1[i, l]
if fabs(fdist - round(fdist)) > ftol[l]:
within_frac = False
break
if within_frac:
for l in range(3):
pre_im[l] = cart_f2[j, l] - cart_f1[i, l]
best = 1e100
for k in range(27):
# compilers have a hard time unrolling this
da = pre_im[0] + cart_im[k, 0]
db = pre_im[1] + cart_im[k, 1]
dc = pre_im[2] + cart_im[k, 2]
d = da * da + db * db + dc * dc
if d < best:
best = d
bestk = k
ds[i, j] = best
for l in range(3):
vs[i, j, l] = pre_im[l] + cart_im[bestk, l]
if not within_frac:
ds[i, j] = 1e20
for l in range(3):
vs[i, j, l] = 1e20
free(&cart_f1[0,0])
free(&cart_f2[0,0])
free(&cart_im[0,0])
free(&pre_im[0])
if return_d2:
return vectors, d2
else:
return vectors
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def is_coord_subset_pbc(subset, superset, atol, mask):
"""
Tests if all fractional coords in subset are contained in superset.
Allows specification of a mask determining pairs that are not
allowed to match to each other
Args:
subset, superset: List of fractional coords
Returns:
True if all of subset is in superset.
"""
cdef np.float_t[:, :] fc1 = subset
cdef np.float_t[:, :] fc2 = superset
cdef np.float_t[:] t = atol
cdef np.int_t[:, :] m = np.array(mask, dtype=np.int_, copy=False, order='C')
cdef int i, j, k, I, J
cdef np.float_t d
cdef bint ok
I = fc1.shape[0]
J = fc2.shape[0]
for i in range(I):
ok = False
for j in range(J):
if m[i, j]:
continue
ok = True
for k in range(3):
d = fc1[i, k] - fc2[j, k]
if fabs(d - round(d)) > t[k]:
ok = False
break
if ok:
break
if not ok:
break
return bool(ok)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def coord_list_mapping_pbc(subset, superset, atol=1e-8):
"""
Gives the index mapping from a subset to a superset.
Superset cannot contain duplicate matching rows
Args:
subset, superset: List of frac_coords
Returns:
list of indices such that superset[indices] = subset
"""
inds = np.zeros(len(subset), dtype=np.int) - 1
subset = np.atleast_2d(subset)
superset = np.atleast_2d(superset)
cdef np.float_t[:, :] fc1 = subset
cdef np.float_t[:, :] fc2 = superset
cdef np.float_t[:] t = atol
cdef np.int_t[:] c_inds = inds
cdef np.float_t d
cdef bint ok_inner, ok_outer
I = fc1.shape[0]
J = fc2.shape[0]
for i in range(I):
ok_outer = False
for j in range(J):
ok_inner = True
for k in range(3):
d = fc1[i, k] - fc2[j, k]
if fabs(d - round(d)) > t[k]:
ok_inner = False
break
if ok_inner:
if c_inds[i] >= 0:
raise ValueError("Something wrong with the inputs, likely duplicates "
"in superset")
c_inds[i] = j
ok_outer = True
# we don't break here so we can check for duplicates in superset
if not ok_outer:
break
if not ok_outer:
raise ValueError("subset is not a subset of superset")
return inds
<|end_of_text|>from numpy import zeros
from scipy import weave
from timeit import default_timer as clock
cimport numpy as np
dx = 0.1
dy = 0.1
dx2 = dx*dx
dy2 = dy*dy
def cy_update(np.ndarray[double, ndim=2] u, double dx2, double dy2):
cdef unsigned int i, j
for i in xrange(1,u.shape[0]-1):
for j in xrange(1, u.shape[1]-1):
u[i,j] = ((u[i+1, j] + u[i-1, j]) * dy2 +
(u[i, j+1] + u[i, j-1]) * dx2) / (2*(dx2+dy2))
def calc(N, Niter=100, func=cy_update, args=()):
u = zeros([N, N])
u[0] = 1
for i in range(Niter):
func(u,*args)
return u
def run():
t = clock()
u = calc(100, 8000, args=(dx2, dy2))
t = clock() - t
print t
print u[1, 1]
print sum(u.flat)
print sum((u**2).flat)
<|end_of_text|>cdef extern from "complex_numbers_c89_T398.h": pass
include "complex_numbers_T305.pyx"
<|end_of_text|>include '../types.pxi'
from libcpp cimport bool
from _instrument cimport Instrument
from quantlib.time._calendar cimport BusinessDayConvention
from quantlib.time._date cimport Date
from quantlib.time._daycounter cimport DayCounter
from quantlib.time._schedule cimport Schedule
cdef extern from 'ql/default.hpp' namespace 'QuantLib::Protection':
enum Side:
Buyer
Seller
cdef extern from 'ql/instruments/creditdefaultswap.hpp' namespace 'QuantLib':
cdef cppclass CreditDefaultSwap(Instrument):
CreditDefaultSwap(Side side,
Real notional,
Rate spread,
Schedule& schedule,
BusinessDayConvention paymentConvention,
DayCounter& dayCounter,
bool settlesAccrual, # = true,
bool paysAtDefaultTime, # = true,
Date& protectionStart #= Date(),
#const boost::shared_ptr<Claim>& =
# boost::shared_ptr<Claim>());
)
Rate fairUpfront()
Rate fairSpread()
Real couponLegBPS()
Real upfrontBPS()
Real couponLegNPV()
Real defaultLegNPV()
Real upfrontNPV()
<|end_of_text|>#cython: boundscheck=False
#cython: nonecheck=False
#cython: wraparound=False
#cython: cdivision=True
import numpy
cimport numpy
from constants cimport *
cimport cython
import matplotlib.pyplot as mpl
from matplotlib import rc
cdef extern from "math.h":
double exp(double x)
double sqrt(double x)
double atan2(double y, | Cython |
double x)
double fabs(double x)
double sin(double x)
double cos(double x)
cdef class FieldMap:
cdef:
object intObj
double brho, chargeOverMass, v0Abs, dt, angIn
unsigned int nSteps, nStepsPerCell
double[:,:] particleRefData
double[:,:] particleEnv1Data
double[:,:] particleEnv2Data
double[:,:] multipoleData
double[:] x0Ref
double[:] v0Ref
def __init__(self, object intObj):
self.set(intObj)
cpdef set(self, object intObj):
self.intObj = intObj
cpdef doRef(self, double[:] x0, double[:] v0, double[:] bScale, double angOut,
unsigned int nStepsPerCell = 10, double chargeOverMass = elementary_charge/m_p):
cdef:
double bScale1
unsigned int ii
double[:] ddir = numpy.empty(2)
self.v0Abs = sqrt(v0[0]*v0[0]+v0[1]*v0[1])
self.brho = self.v0Abs/chargeOverMass/sqrt(1.-(self.v0Abs/c)**2)
self.x0Ref = x0
self.v0Ref = v0
self.angIn = atan2(v0[1], v0[0])
self.chargeOverMass = chargeOverMass
self.nStepsPerCell = nStepsPerCell
self.dt = min(self.intObj.getDx(),self.intObj.getDy())/self.v0Abs/self.nStepsPerCell
bScale1 = _findBScale(x0, v0, bScale, angOut, self.dt, chargeOverMass, self.intObj)
self.intObj.setBScalePerma(bScale1)
self.nSteps = _findNSteps(x0, v0, self.intObj, self.dt, self.chargeOverMass)
self.particleRefData = numpy.empty((self.nSteps,4))
self.particleRefData[0,0] = x0[0]
self.particleRefData[0,1] = x0[1]
self.particleRefData[0,2] = v0[0]
self.particleRefData[0,3] = v0[1]
_trackAndSave(self.particleRefData, self.intObj, self.dt, self.chargeOverMass, self.nSteps)
self.multipoleData = numpy.empty((self.nSteps,6))
for ii in range(self.nSteps):
ddir[0] = self.particleRefData[ii,3]/self.v0Abs
ddir[1] = -self.particleRefData[ii,2]/self.v0Abs
self.intObj.interpolateD(self.particleRefData[ii,:2], ddir, self.multipoleData[ii,:])
# for jj in range(1,6):
# self.multipoleData[ii,jj] /= self.multipoleData[ii,0]
# self.multipoleData[ii,2]*= 2.
# self.multipoleData[ii,3]*= 6.
# self.multipoleData[ii,4]*= 24.
# self.multipoleData[ii,5]*= 120.
cpdef doEnv(self, double dx, double da, double delta):
cdef:
double gammar, chi, vFac1
gammar = 1./sqrt(1.-(self.v0Abs/c)**2)
chi = (delta+1.)*gammar*self.v0Abs
vFac2 = chi/sqrt(1.+(chi/c)**2)/self.v0Abs
chi = (-delta+1.)*gammar*self.v0Abs
vFac1 = chi/sqrt(1.+(chi/c)**2)/self.v0Abs
self.particleEnv1Data = numpy.empty((self.nSteps,4))
self.particleEnv1Data[0,0] = self.x0Ref[0]-dx*cos(self.angIn+0.5*pi)
self.particleEnv1Data[0,1] = self.x0Ref[1]-dx*sin(self.angIn+0.5*pi)
self.particleEnv1Data[0,2] = self.v0Ref[0]*cos(da) + self.v0Ref[1]*sin(da)
self.particleEnv1Data[0,2]*= vFac1
self.particleEnv1Data[0,3] = -self.v0Ref[0]*sin(da) + self.v0Ref[1]*cos(da)
self.particleEnv1Data[0,3]*= vFac1
_trackAndSave(self.particleEnv1Data, self.intObj, self.dt, self.chargeOverMass, self.nSteps)
self.particleEnv2Data = numpy.empty((self.nSteps,4))
self.particleEnv2Data[0,0] = self.x0Ref[0]+dx*cos(self.angIn+0.5*pi)
self.particleEnv2Data[0,1] = self.x0Ref[1]+dx*sin(self.angIn+0.5*pi)
self.particleEnv2Data[0,2] = self.v0Ref[0]*cos(-da) + self.v0Ref[1]*sin(-da)
self.particleEnv2Data[0,2]*= vFac2
self.particleEnv2Data[0,3] = -self.v0Ref[0]*sin(-da) + self.v0Ref[1]*cos(-da)
self.particleEnv2Data[0,3]*= vFac2
_trackAndSave(self.particleEnv2Data, self.intObj, self.dt, self.chargeOverMass, self.nSteps)
cpdef plotMultipoles(self, subPlotObj = None, scale = None, xlim = None):
rc('text', usetex=True)
rc('font', family='Helvetica')
rc('xtick', labelsize=15)
rc('ytick', labelsize=15)
if scale is None:
scale = [1., 1., 1., 1., 1., 1.]
s = numpy.linspace(0,self.nSteps*self.v0Abs*self.dt,self.nSteps)
if subPlotObj is None:
figObj = mpl.figure()
subPlotObj = figObj.add_subplot(111)
subPlotObj.plot(s, scale[0]*numpy.asarray(self.multipoleData[:,0]),'-', label='dipole ('+str(numpy.int(scale[0]))+'$\cdot$b$_1$)')
subPlotObj.plot(s, scale[1]*numpy.asarray(self.multipoleData[:,1]),'--', label='quadrupole ('+str(numpy.int(scale[1]))+'$\cdot$b$_2$)')
subPlotObj.plot(s, scale[2]*numpy.asarray(self.multipoleData[:,2]),'-.', label='sextupole ('+str(numpy.int(scale[2]))+'$\cdot$b$_3$)')
subPlotObj.plot(s, scale[3]*numpy.asarray(self.multipoleData[:,3]),':', label='octupole ('+str(numpy.int(scale[3]))+'$\cdot$b$_4$)')
subPlotObj.plot(s, scale[4]*numpy.asarray(self.multipoleData[:,4]),'-', label='decapole ('+str(numpy.int(scale[4]))+'$\cdot$b$_5$)')
subPlotObj.plot(s, scale[5]*numpy.asarray(self.multipoleData[:,5]),'--', label='dodecapole ('+str(numpy.int(scale[5]))+'$\cdot$b$_6$)')
subPlotObj.set_xlabel(r'$s\;\mathrm{in}\;\mathrm{m}$', fontsize=25)
subPlotObj.set_ylabel(r'$b_n\;\mathrm{in}\;\mathrm{T}\mathrm{m}^{-n}$', fontsize=25)
subPlotObj.legend(fancybox=True)
if xlim is not None:
subPlotObj.set_xlim(xlim)
return subPlotObj
cpdef plotRef(self, subPlotObj = None):
rc('text', usetex=True)
rc('font', family='Helvetica')
rc('xtick', labelsize=15)
rc('ytick', labelsize=15)
if subPlotObj is None:
figObj = mpl.figure()
subPlotObj = figObj.add_subplot(111)
plot = subPlotObj.plot(self.particleRefData[:,1],self.particleRefData[:,0],'w')
plot = subPlotObj.plot(self.particleRefData[:,1],self.particleRefData[:,0],'k--', label='reference particle')
subPlotObj.set_xlabel(r'$z\;\mathrm{in}\;\mathrm{m}$', fontsize=25)
subPlotObj.set_ylabel(r'$x\;\mathrm{in}\;\mathrm{m}$', fontsize=25)
subPlotObj.legend(fancybox=True)
return subPlotObj
cpdef plotEnv(self, subPlotObj = None):
rc('text', usetex=True)
rc('font', family=' | Cython |
Helvetica')
rc('xtick', labelsize=15)
rc('ytick', labelsize=15)
if subPlotObj is None:
figObj = mpl.figure()
subPlotObj = figObj.add_subplot(111)
subPlotObj.plot(self.particleEnv1Data[:,1],self.particleEnv1Data[:,0],'k:')
subPlotObj.plot(self.particleEnv2Data[:,1],self.particleEnv2Data[:,0],'k:', label='beam envelope')
subPlotObj.set_xlabel(r'$z\;\mathrm{in}\;\mathrm{m}$', fontsize=25)
subPlotObj.set_ylabel(r'$x\;\mathrm{in}\;\mathrm{m}$', fontsize=25)
subPlotObj.legend(fancybox=True)
return subPlotObj
cdef double _findBScale(double[:] x0, double[:] v0, double[:] bScale, double angOut,
double dt, double chargeOverMass, object intObj):
cdef:
double[2] x
double[2] v
double[:] vTemp
double v0Abs, bScale0, bScale1, bScale2, angErr1, angErr0, angErr2
x[1] = x0[1]
x[0] = x0[0]
v[0] = v0[0]
v[1] = v0[1]
v0Abs = sqrt(v0[0]*v0[0]+v0[1]*v0[1])
bScale2 = bScale[1]
intObj.setBScale(bScale2)
vTemp = _trackFinDir(x, v, intObj, dt, chargeOverMass)
angErr2 = atan2(vTemp[0],vTemp[1])-angOut
bScale0 = bScale[0]
intObj.setBScale(bScale0)
vTemp = _trackFinDir(x, v, intObj, dt, chargeOverMass)
angErr0 = atan2(vTemp[0],vTemp[1])-angOut
for ii in range(100):
bScale1 = (bScale2+bScale0)*0.5
intObj.setBScale(bScale1)
vTemp = _trackFinDir(x, v, intObj, dt, chargeOverMass)
angErr1 = atan2(vTemp[0],vTemp[1])-angOut
if angErr1*angErr2 > 0.:
bScale2 = bScale1
else:
bScale0 = bScale1
# print bScale1, angErr1, angErr2
if fabs(angErr1)<1.e-9:
break
if ii>=99:
raise ValueError('WARNING: Angle search has not converged. Try different bScale interval.')
bScale1 = (bScale2+bScale0)*0.5
return bScale1
cdef void _trackAndSave(double[:,:] particleData, object intObj, double dt, double chargeOverMass, unsigned int nSteps):
cdef:
double by, ts1, vs0, vs1, vAbsi
double chargeDtOverMassGammaHalf = 0.5*chargeOverMass*dt*sqrt(1.-(particleData[0,2]*particleData[0,2]+particleData[0,3]*particleData[0,3])/c**2)
for ii in range(nSteps-1):
by = intObj.interpolate(particleData[ii,0],particleData[ii,1])
ts1 = chargeDtOverMassGammaHalf*by
vs0 = particleData[ii,2] - particleData[ii,3]*ts1
vs2 = particleData[ii,3] + particleData[ii,2]*ts1
ts1 *= 2./(1. + ts1*ts1)
particleData[(ii+1),2] = particleData[ii,2] - vs2*ts1
particleData[(ii+1),3] = particleData[ii,3] + vs0*ts1
particleData[(ii+1),0] = particleData[ii,0] + dt*particleData[(ii+1),2]
particleData[(ii+1),1] = particleData[ii,1] + dt*particleData[(ii+1),3]
return
cdef double[::1] _trackFinDir(double[:] x0, double[:] v0, object intObj, double dt, double chargeOverMass):
cdef:
double by, ts1, vs0, vs1, vAbsi
double[2] xOld
double[2] xNew
double[2] vOld
double[::1] vNew = numpy.empty(2)
double[::1] xMinMax = intObj.getXMinMax()
double[::1] zMinMax = intObj.getYMinMax()
double chargeDtOverMassGammaHalf = 0.5*chargeOverMass*dt*sqrt(1-(v0[0]*v0[0]+v0[1]*v0[1])/c**2)
vNew[0] = v0[0]
vNew[1] = v0[1]
xNew[0] = x0[0]
xNew[1] = x0[1]
# mpl.figure()
while not (xNew[0]<xMinMax[0] or xNew[0]>xMinMax[1] or xNew[1]>zMinMax[1]):# or xNew[1]<zExt[0]
xOld[0] = xNew[0]
xOld[1] = xNew[1]
vOld[0] = vNew[0]
vOld[1] = vNew[1]
by = intObj.interpolate(xOld[0],xOld[1])
ts1 = chargeDtOverMassGammaHalf*by
vs0 = vOld[0] - vOld[1]*ts1
vs2 = vOld[1] + vOld[0]*ts1
ts1 *= 2./(1. + ts1*ts1)
vNew[0] = vOld[0] - vs2*ts1
vNew[1] = vOld[1] + vs0*ts1
xNew[0] = xOld[0] + dt*vNew[0]
xNew[1] = xOld[1] + dt*vNew[1]
# mpl.plot(xNew[0],xNew[1],'.')
# mpl.show()
return vNew
cdef unsigned int _findNSteps(double[:] x0, double[:] v0, object intObj, double dt, double chargeOverMass):
cdef:
double by, ts1, vs0, vs1, vAbsi
double[2] xOld
double[2] xNew
double[2] vOld
double[::1] vNew = numpy.empty(2)
double[::1] xMinMax = intObj.getXMinMax()
double[::1] zMinMax = intObj.getYMinMax()
double chargeDtOverMassGammaHalf = 0.5*chargeOverMass*dt*sqrt(1-(v0[0]*v0[0]+v0[1]*v0[1])/c**2)
unsigned int ii = 0
vNew[0] = v0[0]
vNew[1] = v0[1]
xNew[0] = x0[0]
xNew[1] = x0[1]
while not (xNew[0]<xMinMax[0] or xNew[0]>xMinMax[1] or xNew[1]>zMinMax[1]):# or xNew[1]<zExt[0]
xOld[0] = xNew[0]
xOld[1] = xNew[1]
vOld[0] = vNew[0]
vOld[1] = vNew[1]
by = intObj.interpolate(xOld[0],xOld[1])
ts1 = chargeDtOverMassGammaHalf*by
vs0 = vOld[0] - vOld[1]*ts1
vs2 = vOld[1] + vOld[0]*ts1
ts1 *= 2./(1. + ts1*ts1)
vNew[0] = vOld[0] - vs2*ts1
vNew[1] = vOld[1] + vs0*ts1
xNew[0] = xNew[0] + dt*vNew[0]
xNew[1] = xNew[1] + dt*vNew[1]
ii += 1
return ii
cdef class GaussianWavelet:
cdef:
double[::1] tempFx # Preallocate temporary arrays for interpolation
double[::1] tempFy
double[::1] xRedTemp, yRedTemp
double[::1] x, y, z
double[::1] xExt, yExt, zExt
double[::1] | Cython |
xMinMax, yMinMax
double S, dx, dy, dxi, dyi, bScale
unsigned int nx, ny, np, dn, nxExt, nyExt, npExt, dnExt
def __init__(self, x, y, double[::1] z, double S = 1.4):
self.make(x, y, z, S = S)
cpdef make(self, x, y, double[::1] z, double S = 1.4):
cdef:
unsigned int ii, jj
unsigned int dn3Half
self.bScale = 1.
self.x = numpy.array(x[:2])
self.y = numpy.array(y[:2])
self.z = z
self.nx = <unsigned int> x[2]
self.ny = <unsigned int> y[2]
self.np = self.z.shape[0]
self.dn = <unsigned int> (S*16.+1.)
self.dn += (self.dn % 2)
self.dnExt = <unsigned int> (S*2.+0.5)
self.nxExt = self.nx+2*self.dn+2*self.dnExt
self.nyExt = self.ny+2*self.dn+2*self.dnExt
self.npExt = self.nxExt*self.nyExt
self.S = S
self.zExt = numpy.zeros(self.npExt, dtype=numpy.double)
dn3Half = self.dn + self.dnExt
for ii in range(self.nx):
for jj in range(self.ny):
self.zExt[(jj+dn3Half)*self.nxExt+ii+dn3Half] = self.z[jj*self.nx+ii]
for ii in range(self.nx):
for jj in range(self.dnExt):
self.zExt[(jj+self.dn)*self.nxExt+ii+dn3Half] = (self.zExt[dn3Half*self.nxExt+ii+dn3Half] -
(self.zExt[(dn3Half+1)*self.nxExt+ii+dn3Half]-self.zExt[dn3Half*self.nxExt+ii+dn3Half])*(dn3Half-(jj+self.dn))
)
self.zExt[(jj+self.nyExt-dn3Half)*self.nxExt+ii+dn3Half] = (self.zExt[(self.nyExt-dn3Half-1)*self.nxExt+ii+dn3Half] +
(self.zExt[(self.nyExt-dn3Half-1)*self.nxExt+ii+dn3Half]-self.zExt[(self.nyExt-dn3Half-2)*self.nxExt+ii+dn3Half])*
((jj+self.nyExt-dn3Half)-(self.nyExt-dn3Half-1))
)
for ii in range(self.dnExt):
for jj in range(self.nyExt):
self.zExt[jj*self.nxExt+ii+self.dn] = (self.zExt[jj*self.nxExt+dn3Half] -
(self.zExt[jj*self.nxExt+dn3Half+1]-self.zExt[jj*self.nxExt+dn3Half])*(dn3Half-(ii+self.dn))
)
self.zExt[jj*self.nxExt+ii+self.nxExt-dn3Half] = (self.zExt[jj*self.nxExt+self.nxExt-dn3Half-1] +
(self.zExt[jj*self.nxExt+self.nxExt-dn3Half-1]-self.zExt[jj*self.nxExt+self.nxExt-dn3Half-2])*
((ii+self.nxExt-dn3Half)-(self.nxExt-dn3Half-1))
)
self.dx = (self.x[1]-self.x[0])/(self.nx-1)
self.dy = (self.y[1]-self.y[0])/(self.ny-1)
self.dxi = 1./self.dx
self.dyi = 1./self.dy
self.xExt = self.x.copy()
self.xExt[0] -= (self.dnExt+self.dn)*self.dx
self.xExt[1] += (self.dnExt+self.dn)*self.dx
self.yExt = self.y.copy()
self.yExt[0] -= (self.dnExt+self.dn)*self.dy
self.yExt[1] += (self.dnExt+self.dn)*self.dy
self.xMinMax = self.x.copy()
self.xMinMax[0] -= (self.dnExt+0.5*self.dn)*self.dx
self.xMinMax[1] += (self.dnExt+0.5*self.dn)*self.dx
self.yMinMax = self.y.copy()
self.yMinMax[0] -= (self.dnExt+0.5*self.dn)*self.dy
self.yMinMax[1] += (self.dnExt+0.5*self.dn)*self.dy
self.tempFx = numpy.empty(self.dn, dtype=numpy.double)
self.tempFy = numpy.empty(self.dn, dtype=numpy.double)
self.xRedTemp = numpy.empty(self.dn, dtype=numpy.double)
self.yRedTemp = numpy.empty(self.dn, dtype=numpy.double)
cpdef double interpolate(self, double xVal, double yVal):
if (xVal<=self.xMinMax[0] or xVal>=self.xMinMax[1] or yVal<=self.yMinMax[0] or yVal>=self.yMinMax[1]):
return 0.
else:
return self.bScale*_gwint(xVal, yVal, self.xExt, self.yExt, self.zExt, self.S, self.dxi, self.dyi, self.dn, self.nxExt, self.tempFx, self.tempFy)
cpdef double[:] interpolateD(self, double[:] pos, double[:] ddir, double[:] derivatives):
_gwintdtill5(pos[0], pos[1], self.xExt, self.yExt, self.zExt, self.S,
self.dxi, self.dyi, self.dn, self.nxExt, self.tempFx, self.tempFy,
self.xRedTemp, self.yRedTemp, derivatives, ddir)
return derivatives
cpdef numpy.ndarray getXExt(self):
return numpy.asarray(self.xExt)
cpdef numpy.ndarray getYExt(self):
return numpy.asarray(self.yExt)
cpdef numpy.ndarray getXMinMax(self):
return numpy.asarray(self.xMinMax)
cpdef numpy.ndarray getYMinMax(self):
return numpy.asarray(self.yMinMax)
cpdef numpy.ndarray getX(self):
return numpy.asarray(self.x)
cpdef numpy.ndarray getY(self):
return numpy.asarray(self.y)
cpdef numpy.ndarray getZExt(self):
return numpy.asarray(self.zExt)
cpdef unsigned int getNxExt(self):
return self.nxExt
cpdef unsigned int getNyExt(self):
return self.nyExt
cpdef setBScale(self, double bScale):
self.bScale = bScale
cpdef setBScalePerma(self, double bScale):
cdef:
unsigned int ii, jj
for ii in range(self.nx):
for jj in range(self.ny):
self.z[jj*self.nx+ii] *= bScale
for ii in range(self.nxExt):
for jj in range(self.nyExt):
self.zExt[jj*self.nxExt+ii] *= bScale
self.bScale = 1.
cpdef double getDx(self):
return self.dx
cpdef double getDy(self):
return self.dy
cpdef plot(self, xIn = None, yIn = None, object subPlotObj = None, unsigned int nMulti = 5):
cdef:
unsigned int nx, ny, np
numpy.ndarray x, y, vals, extend
nx = nMulti*self.nx; ny = nMulti*self.ny; np = nx*ny;
if xIn is None:
x = numpy.linspace(self.x[0],self.x[1],nx)
else:
x = numpy.linspace(xIn[0],xIn[1],nx)
if yIn is None:
y = numpy.linspace(self.y[0],self.y[1],ny)
else:
y = numpy.linspace(yIn[0],yIn[1],ny)
vals = numpy.empty(np)
for ii in range(nx):
for jj in range(ny):
vals[jj*nx+ii] = self.interpolate(x[ii],y[jj])
extent = numpy.array([y[0], y[ny-1], x[0], x[nx-1]])
rc('text', usetex=True)
rc('font', family='Helvetica')
rc('xtick', labelsize=15)
rc('ytick', labelsize=15)
if subPlotObj is None:
figObj = mpl.figure()
subPlotObj = figObj.add_subplot(111)
img = subPlotObj.imshow(numpy.reshape(vals,(ny,nx)).transpose(), extent=extent, origin='lower')
subPlotObj.set_xlabel(r'$z\;\mathrm{in}\;\mathrm{m}$', | Cython |
fontsize=25)
subPlotObj.set_ylabel(r'$x\;\mathrm{in}\;\mathrm{m}$', fontsize=25)
cbar = mpl.colorbar(img, shrink=0.75)
cbar.set_label(r'$B_y\;\mathrm{in}\;\mathrm{T}$', fontsize=25, rotation=90)
subPlotObj.set_xlim(extent[:2])
subPlotObj.set_ylim(extent[2:])
return subPlotObj
# See Berz book.
cdef double _gwint(double xVal, double yVal, double[:] x, double[:] y, double[:] z, double S,
double dxi, double dyi, unsigned int dn, unsigned int nx, double[::1] fx, double[::1] fy):
cdef:
unsigned int ii, jj
double res = 0.
double Ssqrt2inv = S*sqrt2inv
double xValRed, yValRed
unsigned int indx0, indy0
indx0 = (<unsigned int> ((xVal-x[0])*dxi)) - dn/2 + 1
indy0 = (<unsigned int> ((yVal-y[0])*dyi)) - dn/2 + 1
xValRed = (xVal-x[0])*dxi - indx0
yValRed = (yVal-y[0])*dyi - indy0
for ii in range(dn):
fx[ii] = _gnd((xValRed-ii)/Ssqrt2inv)/Ssqrt2inv
fy[ii] = _gnd((yValRed-ii)/Ssqrt2inv)/Ssqrt2inv
for ii in range(dn):
for jj in range(dn):
res += z[(indy0+jj)*nx+(indx0+ii)]*fx[ii]*fy[jj]
return res
cdef double _gnd(double x):
return pi2invsqrt*exp(-0.5*x*x)
cdef _gwintdtill5(double xVal, double yVal, double[:] x, double[:] y, double[:] z, double S,
double dxi, double dyi, unsigned int dn, unsigned int nx, double[::1] fx, double[::1] fy,
double[::1] xRedTemp, double[::1] yRedTemp, double[:] res, double[:] u):#In):
cdef:
unsigned int ii, jj
double xValRed, yValRed, temp
unsigned int indx0, indy0
# double[:] u = uIn.copy()
# double uAbsi = 1./sqrt(u[0]*u[0]+u[1]*u[1])
#
# u[0] *= uAbsi
# u[1] *= uAbsi
sig = S*sqrt2inv
sigi = 1./sig; sigi2 = sigi*sigi;
sigi3 = sigi2*sigi; sigi4 = sigi3*sigi; sigi5 = sigi4*sigi;
indx0 = (<unsigned int> ((xVal-x[0])*dxi)) - dn/2 + 1
indy0 = (<unsigned int> ((yVal-y[0])*dyi)) - dn/2 + 1
xValRed = (xVal-x[0])*dxi - indx0
yValRed = (yVal-y[0])*dyi - indy0
for ii in range(dn):
xRedTemp[ii] = (xValRed-ii)*sigi
yRedTemp[ii] = (yValRed-ii)*sigi
fx[ii] = _gnd(xRedTemp[ii])*sigi
fy[ii] = _gnd(yRedTemp[ii])*sigi
for ii in range(6):
res[ii] = 0.
for ii in range(dn):
for jj in range(dn):
t = u[0]*xRedTemp[ii] + u[1]*yRedTemp[jj]
temp = z[(indy0+jj)*nx+(indx0+ii)]*fx[ii]*fy[jj]
res[0] += temp
res[1] += -t*temp*sigi
res[2] += (t**2-1.)*sigi2*temp
res[3] += (-t**3+3.*t)*sigi3*temp
res[4] += (t**4-6.*t**2+3.)*sigi4*temp
res[5] += (-t**5+10.*t**3-15.*t)*sigi5*temp
<|end_of_text|># coding=utf-8
"""
Cython declaration file specifying what function(s) we are using from which external C header.
"""
cdef extern from "fibonacci.h":
int compute_fibonacci(int n)
<|end_of_text|>
cdef extern from "regression_kernels.hpp":
cdef cppclass RegressionKernel:
double evaluate(double x)
double deriv(double x)
object to_dict()
void from_dict(object dict_repr) except+<|end_of_text|>#
# Copyright (c) 2023, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# cython: profile=False
# distutils: language = c++
# cython: embedsignature = True
# cython: language_level = 3
import io
import numpy as np
from cpython.object cimport PyObject
from cython.operator cimport dereference as deref
from libc.stddef cimport size_t
from libc.stdint cimport int8_t, int32_t, int64_t, uint8_t, uint32_t, uintptr_t
from pylibraft.common.cpp.mdspan cimport (
col_major,
device_matrix_view,
host_matrix_view,
host_mdspan,
make_device_matrix_view,
make_host_matrix_view,
matrix_extent,
ostream,
ostringstream,
row_major,
serialize_mdspan,
)
from pylibraft.common.handle cimport device_resources
from pylibraft.common.optional cimport make_optional, optional
from pylibraft.common import DeviceResources
cdef extern from "Python.h":
Py_buffer* PyMemoryView_GET_BUFFER(PyObject* mview)
def run_roundtrip_test_for_mdspan(X, fortran_order=False):
if not isinstance(X, np.ndarray) or len(X.shape)!= 2:
raise ValueError("Please call this function with a NumPy array with"
"2 dimensions")
handle = DeviceResources()
cdef device_resources * handle_ = \
<device_resources *> <size_t> handle.getHandle()
cdef ostringstream oss
if X.dtype == np.float32:
if fortran_order:
serialize_mdspan[float, matrix_extent[size_t], col_major](
deref(handle_),
<ostream&>oss,
<const host_mdspan[float, matrix_extent[size_t],
col_major] &>
make_host_matrix_view[float, size_t, col_major](
<float *><uintptr_t>PyMemoryView_GET_BUFFER(
<PyObject *> X.data).buf,
X.shape[0], X.shape[1]))
else:
serialize_mdspan[float, matrix_extent[size_t], row_major](
deref(handle_),
<ostream&>oss,
<const host_mdspan[float, matrix_extent[size_t],
row_major]&>
make_host_matrix_view[float, size_t, row_major](
<float *><uintptr_t>PyMemoryView_GET_BUFFER(
<PyObject *> X.data).buf,
X.shape[0], X.shape[1]))
elif X.dtype == np.float64:
if fortran_order:
serialize_mdspan[double, matrix_extent[size_t], col_major](
deref(handle_),
<ostream&>oss,
<const host_mdspan[double, matrix_extent[size_t],
col_major]&>
make_host_matrix_view[double, size_t, col_major](
<double *><uintptr_t>PyMemoryView_GET_BUFFER(
<PyObject *> X.data).buf,
X.shape[0], X.shape[1]))
else:
serialize_mdspan[double, matrix_extent[size_t], row_major](
deref(handle_),
<ostream&>oss,
<const host_mdspan[double, matrix_extent[size_t],
row_major]&>
make_host_matrix_view[double, size_t, row_major](
<double *><uintptr_t>PyMemoryView_GET_BUFFER(
<PyObject *> X.data).buf,
X.shape[0], X.shape[1]))
elif X.dtype == np.int32:
if fortran_order:
serialize_mdspan[int32_t, matrix_extent[size_t], col_major](
deref(handle_),
<ostream&>oss,
<const host_mdspan[int32_t, | Cython |
matrix_extent[size_t],
col_major]&>
make_host_matrix_view[int32_t, size_t, col_major](
<int32_t *><uintptr_t>PyMemoryView_GET_BUFFER(
<PyObject *> X.data).buf,
X.shape[0], X.shape[1]))
else:
serialize_mdspan[int32_t, matrix_extent[size_t], row_major](
deref(handle_),
<ostream&>oss,
<const host_mdspan[int32_t, matrix_extent[size_t],
row_major]&>
make_host_matrix_view[int32_t, size_t, row_major](
<int32_t *><uintptr_t>PyMemoryView_GET_BUFFER(
<PyObject *> X.data).buf,
X.shape[0], X.shape[1]))
elif X.dtype == np.uint32:
if fortran_order:
serialize_mdspan[uint32_t, matrix_extent[size_t], col_major](
deref(handle_),
<ostream&>oss,
<const host_mdspan[uint32_t, matrix_extent[size_t],
col_major]&>
make_host_matrix_view[uint32_t, size_t, col_major](
<uint32_t *><uintptr_t>PyMemoryView_GET_BUFFER(
<PyObject *> X.data).buf,
X.shape[0], X.shape[1]))
else:
serialize_mdspan[uint32_t, matrix_extent[size_t], row_major](
deref(handle_),
<ostream&>oss,
<const host_mdspan[uint32_t, matrix_extent[size_t],
row_major]&>
make_host_matrix_view[uint32_t, size_t, row_major](
<uint32_t *><uintptr_t>PyMemoryView_GET_BUFFER(
<PyObject *> X.data).buf,
X.shape[0], X.shape[1]))
else:
raise NotImplementedError()
f = io.BytesIO(oss.str())
X2 = np.load(f)
assert np.all(X.shape == X2.shape)
assert np.all(X == X2)
cdef device_matrix_view[float, int64_t, row_major] \
get_dmv_float(cai, check_shape) except *:
if cai.dtype!= np.float32:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_device_matrix_view[float, int64_t, row_major](
<float*><uintptr_t>cai.data, shape[0], shape[1])
cdef device_matrix_view[uint8_t, int64_t, row_major] \
get_dmv_uint8(cai, check_shape) except *:
if cai.dtype!= np.uint8:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_device_matrix_view[uint8_t, int64_t, row_major](
<uint8_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef device_matrix_view[int8_t, int64_t, row_major] \
get_dmv_int8(cai, check_shape) except *:
if cai.dtype!= np.int8:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_device_matrix_view[int8_t, int64_t, row_major](
<int8_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef device_matrix_view[int64_t, int64_t, row_major] \
get_dmv_int64(cai, check_shape) except *:
if cai.dtype!= np.int64:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_device_matrix_view[int64_t, int64_t, row_major](
<int64_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef device_matrix_view[const_float, int64_t, row_major] \
get_const_dmv_float(cai, check_shape) except *:
if cai.dtype!= np.float32:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_device_matrix_view[const_float, int64_t, row_major](
<const float*><uintptr_t>cai.data, shape[0], shape[1])
cdef device_matrix_view[const_uint8_t, int64_t, row_major] \
get_const_dmv_uint8(cai, check_shape) except *:
if cai.dtype!= np.uint8:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_device_matrix_view[const_uint8_t, int64_t, row_major](
<const uint8_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef device_matrix_view[const_int8_t, int64_t, row_major] \
get_const_dmv_int8(cai, check_shape) except *:
if cai.dtype!= np.int8:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_device_matrix_view[const_int8_t, int64_t, row_major](
<const int8_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef optional[device_matrix_view[int64_t, int64_t, row_major]] \
make_optional_view_int64(device_matrix_view[int64_t, int64_t, row_major]& dmv) except *: # noqa: E501
return make_optional[device_matrix_view[int64_t, int64_t, row_major]](dmv)
# todo(dantegd): we can unify and simplify this functions a little bit
# defining extra functions as-is is the quickest way to get what we need for
# cagra.pyx
cdef device_matrix_view[uint32_t, int64_t, row_major] \
get_dmv_uint32(cai, check_shape) except *:
if cai.dtype!= np.uint32:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_device_matrix_view[uint32_t, int64_t, row_major](
<uint32_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef host_matrix_view[float, int64_t, row_major] \
get_hmv_float(cai, check_shape) except *:
if cai.dtype!= np.float32:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_host_matrix_view[float, int64_t, row_major](
<float*><uintptr_t>cai.data, shape[0], shape[1])
cdef host_matrix_view[uint8_t, int64_t, row_major] \
get_hmv_uint8(cai, check_shape) except *:
if cai.dtype!= np.uint8:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape | Cython |
)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_host_matrix_view[uint8_t, int64_t, row_major](
<uint8_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef host_matrix_view[int8_t, int64_t, row_major] \
get_hmv_int8(cai, check_shape) except *:
if cai.dtype!= np.int8:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_host_matrix_view[int8_t, int64_t, row_major](
<int8_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef host_matrix_view[int64_t, int64_t, row_major] \
get_hmv_int64(cai, check_shape) except *:
if cai.dtype!= np.int64:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_host_matrix_view[int64_t, int64_t, row_major](
<int64_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef host_matrix_view[uint32_t, int64_t, row_major] \
get_hmv_uint32(cai, check_shape) except *:
if cai.dtype!= np.int64:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_host_matrix_view[uint32_t, int64_t, row_major](
<uint32_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef host_matrix_view[const_float, int64_t, row_major] \
get_const_hmv_float(cai, check_shape) except *:
if cai.dtype!= np.float32:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_host_matrix_view[const_float, int64_t, row_major](
<const float*><uintptr_t>cai.data, shape[0], shape[1])
cdef host_matrix_view[const_uint8_t, int64_t, row_major] \
get_const_hmv_uint8(cai, check_shape) except *:
if cai.dtype!= np.uint8:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_host_matrix_view[const_uint8_t, int64_t, row_major](
<const uint8_t*><uintptr_t>cai.data, shape[0], shape[1])
cdef host_matrix_view[const_int8_t, int64_t, row_major] \
get_const_hmv_int8(cai, check_shape) except *:
if cai.dtype!= np.int8:
raise TypeError("dtype %s not supported" % cai.dtype)
if check_shape and len(cai.shape)!= 2:
raise ValueError("Expected a 2D array, got %d D" % len(cai.shape))
shape = (cai.shape[0], cai.shape[1] if len(cai.shape) == 2 else 1)
return make_host_matrix_view[const_int8_t, int64_t, row_major](
<const_int8_t*><uintptr_t>cai.data, shape[0], shape[1])
<|end_of_text|>#Copyright (c) 2010-2012, Gabriel Jacobo
#All rights reserved.
#Permission to use this file is granted under the conditions of the Ignifuga Game Engine License
#whose terms are available in the LICENSE file or at http://www.ignifuga.org/license
include "../include/config.pxi"
cdef extern from "SDL_joystick.h":
cdef struct SDL_Joystick
cdef int SDL_HAT_CENTERED = 0x00
cdef int SDL_HAT_UP = 0x01
cdef int SDL_HAT_RIGHT = 0x02
cdef int SDL_HAT_DOWN = 0x04
cdef int SDL_HAT_LEFT = 0x08
cdef extern from "SDL.h":
ctypedef unsigned char Uint8
ctypedef unsigned long Uint32
ctypedef signed long Sint32
ctypedef unsigned long long Uint64
ctypedef signed long long Sint64
ctypedef signed short Sint16
ctypedef unsigned short Uint16
ctypedef void *SDL_GLContext
ctypedef Uint32 SDL_Keycode
ctypedef Sint32 SDL_JoystickID
int SDL_WINDOWPOS_UNDEFINED
ctypedef enum:
SDL_PIXELFORMAT_BGRA8888
SDL_PIXELFORMAT_ARGB8888
SDL_PIXELFORMAT_RGBA8888
SDL_PIXELFORMAT_ABGR8888
SDL_PIXELFORMAT_RGB24
SDL_PIXELFORMAT_BGR24
ctypedef enum SDL_GLattr:
SDL_GL_RED_SIZE
SDL_GL_GREEN_SIZE
SDL_GL_BLUE_SIZE
SDL_GL_ALPHA_SIZE
SDL_GL_BUFFER_SIZE
SDL_GL_DOUBLEBUFFER
SDL_GL_DEPTH_SIZE
SDL_GL_STENCIL_SIZE
SDL_GL_ACCUM_RED_SIZE
SDL_GL_ACCUM_GREEN_SIZE
SDL_GL_ACCUM_BLUE_SIZE
SDL_GL_ACCUM_ALPHA_SIZE
SDL_GL_STEREO
SDL_GL_MULTISAMPLEBUFFERS
SDL_GL_MULTISAMPLESAMPLES
SDL_GL_ACCELERATED_VISUAL
SDL_GL_RETAINED_BACKING
SDL_GL_CONTEXT_MAJOR_VERSION
SDL_GL_CONTEXT_MINOR_VERSION
SDL_GL_CONTEXT_EGL
SDL_GL_CONTEXT_FLAGS
SDL_GL_CONTEXT_PROFILE_MASK
ctypedef enum SDL_SystemCursor:
SDL_SYSTEM_CURSOR_ARROW
SDL_SYSTEM_CURSOR_IBEAM
SDL_SYSTEM_CURSOR_WAIT
SDL_SYSTEM_CURSOR_CROSSHAIR
SDL_SYSTEM_CURSOR_WAITARROW
SDL_SYSTEM_CURSOR_SIZENWSE
SDL_SYSTEM_CURSOR_SIZENESW
SDL_SYSTEM_CURSOR_SIZEWE
SDL_SYSTEM_CURSOR_SIZENS
SDL_SYSTEM_CURSOR_SIZEALL
SDL_SYSTEM_CURSOR_NO
SDL_SYSTEM_CURSOR_HAND
ctypedef enum SDL_BlendMode:
SDL_BLENDMODE_NONE = 0x00000000
SDL_BLENDMODE_BLEND = 0x00000001
SDL_BLENDMODE_ADD = 0x00000002
SDL_BLENDMODE_MOD = 0x00000004
ctypedef enum SDL_TextureAccess:
SDL_TEXTUREACCESS_STATIC
SDL_TEXTUREACCESS_STREAMING
SDL_TEXTUREACCESS_TARGET
ctypedef enum SDL_RendererFlags:
SDL_RENDERER_SOFTWARE = 0x00000001
SDL_RENDERER_ACCELERATED = 0x00000002
SDL_RENDERER_PRESENTVSYNC = 0x00000004
ctypedef enum SDL_bool:
SDL_FALSE = 0
SDL_TRUE = 1
cdef struct SDL_version:
Uint8 major
Uint8 minor
Uint8 patch
cdef struct SDL_Rect:
int x, y
int w, h
ctypedef struct SDL_Point:
int x, y
cdef struct SDL_Color:
Uint8 r
Uint8 g
Uint8 b
Uint8 a
cdef struct SDL_Palette:
int ncolors
SDL_Color *colors
Uint32 version
int refcount
cdef struct SDL_PixelFormat:
Uint32 format
SDL_Palette *palette
Uint8 BitsPerPixel
Uint8 BytesPerPixel
Uint8 padding[2]
Uint32 Rmask
Uint32 Gmask
Uint32 Bmask
Uint32 Amask
Uint8 Rloss
Uint8 Gloss
Uint8 Bloss
Uint8 Aloss
Uint8 Rshift
Uint8 Gshift
Uint8 Bshift
Uint8 Ashift
int refcount
SDL_PixelFormat *next
cdef struct SDL_BlitMap
cdef struct SDL_C | Cython |
ursor
cdef struct SDL_Surface:
Uint32 flags
SDL_PixelFormat *format
int w, h
int pitch
void *pixels
void *userdata
int locked
void *lock_data
SDL_Rect clip_rect
SDL_BlitMap *map
int refcount
ctypedef enum SDL_EventType:
SDL_FIRSTEVENT = 0,
SDL_DROPFILE = 0x1000,
SDL_DROPTEXT
SDL_DROPBEGIN
SDL_DROPCOMPLETE
SDL_QUIT = 0x100
SDL_WINDOWEVENT = 0x200
SDL_SYSWMEVENT
SDL_KEYDOWN = 0x300
SDL_KEYUP
SDL_TEXTEDITING
SDL_TEXTINPUT
SDL_MOUSEMOTION = 0x400
SDL_MOUSEBUTTONDOWN = 0x401
SDL_MOUSEBUTTONUP = 0x402
SDL_MOUSEWHEEL = 0x403
SDL_INPUTMOTION = 0x500
SDL_INPUTBUTTONDOWN
SDL_INPUTBUTTONUP
SDL_INPUTWHEEL
SDL_INPUTPROXIMITYIN
SDL_INPUTPROXIMITYOUT
SDL_JOYAXISMOTION = 0x600
SDL_JOYBALLMOTION
SDL_JOYHATMOTION
SDL_JOYBUTTONDOWN
SDL_JOYBUTTONUP
SDL_FINGERDOWN = 0x700
SDL_FINGERUP
SDL_FINGERMOTION
SDL_TOUCHBUTTONDOWN
SDL_TOUCHBUTTONUP
SDL_DOLLARGESTURE = 0x800
SDL_DOLLARRECORD
SDL_MULTIGESTURE
SDL_CLIPBOARDUPDATE = 0x900
SDL_EVENT_COMPAT1 = 0x7000
SDL_EVENT_COMPAT2
SDL_EVENT_COMPAT3
SDL_USEREVENT = 0x8000
SDL_LASTEVENT = 0xFFFF
SDL_APP_TERMINATING
SDL_APP_LOWMEMORY
SDL_APP_WILLENTERBACKGROUND
SDL_APP_DIDENTERBACKGROUND
SDL_APP_WILLENTERFOREGROUND
SDL_APP_DIDENTERFOREGROUND
ctypedef enum SDL_WindowEventID:
SDL_WINDOWEVENT_NONE #< Never used */
SDL_WINDOWEVENT_SHOWN #< Window has been shown */
SDL_WINDOWEVENT_HIDDEN #< Window has been hidden */
SDL_WINDOWEVENT_EXPOSED #< Window has been exposed and should be
# redrawn */
SDL_WINDOWEVENT_MOVED #< Window has been moved to data1, data2
# */
SDL_WINDOWEVENT_RESIZED #< Window has been resized to data1xdata2 */
SDL_WINDOWEVENT_SIZE_CHANGED #< The window size has changed, either as a result of an API call or through the system or user changing the window size. */
SDL_WINDOWEVENT_MINIMIZED #< Window has been minimized */
SDL_WINDOWEVENT_MAXIMIZED #< Window has been maximized */
SDL_WINDOWEVENT_RESTORED #< Window has been restored to normal size
# and position */
SDL_WINDOWEVENT_ENTER #< Window has gained mouse focus */
SDL_WINDOWEVENT_LEAVE #< Window has lost mouse focus */
SDL_WINDOWEVENT_FOCUS_GAINED #< Window has gained keyboard focus */
SDL_WINDOWEVENT_FOCUS_LOST #< Window has lost keyboard focus */
SDL_WINDOWEVENT_CLOSE #< The window manager requests that the
# window be closed */
SDL_WINDOWEVENT_TAKE_FOCUS #< Window is being offered a focus (should SetWindowInputFocus() on itself or a subwindow, or ignore) */
SDL_WINDOWEVENT_HIT_TEST #< Window had a hit test that wasn't SDL_HITTEST_NORMAL */
SDL_WINDOWEVENT_ICCPROF_CHANGED # [Added in SDL 2.0.18] < The ICC profile of the window's display has changed. */
SDL_WINDOWEVENT_DISPLAY_CHANGED # [Added in SDL 2.0.18] < Window has been moved to display data1. */
ctypedef enum SDL_HintPriority:
SDL_HINT_DEFAULT
SDL_HINT_NORMAL
SDL_HINT_OVERRIDE
ctypedef enum SDL_RendererFlip:
SDL_FLIP_NONE = 0x00000000
SDL_FLIP_HORIZONTAL = 0x00000001
SDL_FLIP_VERTICAL = 0x00000002
ctypedef enum SDL_WindowFlags:
SDL_WINDOW_FULLSCREEN = 0x00000001 #, /**< fullscreen window */
SDL_WINDOW_OPENGL = 0x00000002 #, /**< window usable with OpenGL context */
SDL_WINDOW_SHOWN = 0x00000004 #, /**< window is visible */
SDL_WINDOW_HIDDEN = 0x00000008 #, /**< window is not visible */
SDL_WINDOW_BORDERLESS = 0x00000010 #, /**< no window decoration */
SDL_WINDOW_RESIZABLE = 0x00000020 #, /**< window can be resized */
SDL_WINDOW_MINIMIZED = 0x00000040 #, /**< window is minimized */
SDL_WINDOW_MAXIMIZED = 0x00000080 #, /**< window is maximized */
SDL_WINDOW_INPUT_GRABBED = 0x00000100 #, /**< window has grabbed input focus */
SDL_WINDOW_INPUT_FOCUS = 0x00000200 #, /**< window has input focus */
SDL_WINDOW_MOUSE_FOCUS = 0x00000400 #, /**< window has mouse focus */
SDL_WINDOW_FOREIGN = 0x00000800 # /**< window not created by SDL */
SDL_WINDOW_FULLSCREEN_DESKTOP
SDL_WINDOW_ALLOW_HIGHDPI
SDL_WINDOW_SKIP_TASKBAR = 0x00010000 #, /**< window should not be added to the taskbar */
ctypedef enum SDL_HitTestResult:
SDL_HITTEST_NORMAL
SDL_HITTEST_DRAGGABLE
SDL_HITTEST_RESIZE_TOPLEFT
SDL_HITTEST_RESIZE_TOP
SDL_HITTEST_RESIZE_TOPRIGHT
SDL_HITTEST_RESIZE_RIGHT
SDL_HITTEST_RESIZE_BOTTOMRIGHT
SDL_HITTEST_RESIZE_BOTTOM
SDL_HITTEST_RESIZE_BOTTOMLEFT
SDL_HITTEST_RESIZE_LEFT
cdef struct SDL_DropEvent:
Uint32 type
Uint32 timestamp
char* file
cdef struct SDL_MouseMotionEvent:
Uint32 type
Uint32 timestamp
Uint32 windowID
Uint32 which
Uint32 state
Sint32 x
Sint32 y
Sint32 xrel
Sint32 yrel
cdef struct SDL_MouseButtonEvent:
Uint32 type
Uint32 timestamp
Uint32 windowID
Uint32 which
Uint8 button
Uint8 state
Uint8 clicks
Sint32 x
Sint32 y
cdef struct SDL_WindowEvent:
Uint32 type
Uint32 timestamp
Uint32 windowID
Uint8 event
Sint32 data1
Sint32 data2
ctypedef Sint64 SDL_TouchID
ctypedef Sint64 SDL_FingerID
cdef struct SDL_TouchFingerEvent:
Uint32 type
Uint32 windowID
SDL_TouchID touchId
SDL_FingerID fingerId
float x
float y
float dx
float dy
float pressure
cdef struct SDL_Keysym:
SDL_Scancode scancode # SDL physical key code - see ::SDL_Scancode for details */
SDL_Keycode sym # SDL virtual key code - see ::SDL_Keycode for details */
Uint16 mod # current key modifiers */
Uint32 unused
cdef struct SDL_KeyboardEvent:
Uint32 type # ::SDL_KEYDOWN or ::SDL_KEYUP
Uint32 timestamp
Uint32 windowID # The window with keyboard focus, if any
Uint8 state # ::SDL_PRESSED or ::SDL_RELEASED
Uint8 repeat # Non-zero if this is a key repeat
SDL_Keysym keysym # The key that was pressed or released
cdef struct SDL_TextEditingEvent:
Uint32 type # ::SDL_TEXTEDITING */
Uint32 timestamp
Uint32 windowID # The window with keyboard focus, if any */
char *text # The editing text */
Sint32 start # The start cursor of selected editing text */
Sint32 length # The length of selected editing text */
cdef struct SDL_TextInputEvent:
Uint32 type # ::SDL_TEXTINPUT */
Uint32 timestamp
Uint32 windowID # The window with keyboard focus, if any */
char *text # The input text */
cdef struct SDL_MouseWheelEvent:
Uint32 type
Uint32 windowID
int x
int y
cdef struct SDL_JoyAxisEvent:
Uint32 type
Uint32 timestamp
SDL_JoystickID which
Uint8 axis
Sint16 value
cdef struct SDL_JoyBallEvent:
Uint32 type
Uint32 timestamp
SDL_JoystickID which
Uint8 ball
Sint16 xrel
Sint16 yrel
cdef struct SDL_JoyHatEvent:
| Cython |
Uint32 type
Uint32 timestamp
SDL_JoystickID which
Uint8 hat
Uint8 value
cdef struct SDL_JoyButtonEvent:
Uint32 type
Uint32 timestamp
SDL_JoystickID which
Uint8 button
Uint8 state
cdef struct SDL_QuitEvent:
pass
cdef struct SDL_UserEvent:
Uint32 type
Uint32 timestamp
Uint32 windowID
int code
void *data1
void *data2
cdef struct SDL_SysWMEvent:
pass
cdef struct SDL_TouchButtonEvent:
pass
cdef struct SDL_MultiGestureEvent:
pass
cdef struct SDL_DollarGestureEvent:
pass
cdef union SDL_Event:
Uint32 type
SDL_WindowEvent window
SDL_KeyboardEvent key
SDL_TextEditingEvent edit
SDL_TextInputEvent text
SDL_MouseMotionEvent motion
SDL_MouseButtonEvent button
SDL_DropEvent drop
SDL_MouseWheelEvent wheel
SDL_JoyAxisEvent jaxis
SDL_JoyBallEvent jball
SDL_JoyHatEvent jhat
SDL_JoyButtonEvent jbutton
SDL_QuitEvent quit
SDL_UserEvent user
SDL_SysWMEvent syswm
SDL_TouchFingerEvent tfinger
SDL_TouchButtonEvent tbutton
SDL_MultiGestureEvent mgesture
SDL_DollarGestureEvent dgesture
cdef struct SDL_RendererInfo:
char *name
Uint32 flags
Uint32 num_texture_formats
Uint32 texture_formats[16]
int max_texture_width
int max_texture_height
ctypedef struct SDL_Texture
ctypedef struct SDL_Renderer
ctypedef struct SDL_Window
ctypedef struct SDL_DisplayMode:
Uint32 format
int w
int h
int refresh_rate
void *driverdata
cdef struct SDL_RWops_union_unknown:
void *data1
cdef union SDL_RWops_union:
SDL_RWops_union_unknown unknown
cdef struct SDL_RWops:
Sint64 (* seek) (SDL_RWops * context, Sint64 offset,int whence)
size_t(* read) ( SDL_RWops * context, void *ptr, size_t size, size_t maxnum)
size_t(* write) (SDL_RWops * context, void *ptr,size_t size, size_t num)
int (* close) (SDL_RWops * context)
int type
SDL_RWops_union hidden
cdef enum SDL_Keymod:
KMOD_NONE
KMOD_LSHIFT
KMOD_RSHIFT
KMOD_LCTRL
KMOD_RCTRL
KMOD_LALT
KMOD_RALT
KMOD_LGUI
KMOD_RGUI
KMOD_NUM
KMOD_CAPS
KMOD_MODE
KMOD_RESERVED
ctypedef enum SDL_Scancode:
pass
ctypedef int SDL_EventFilter(void* userdata, SDL_Event* event)
# for windows only see
# https://github.com/LuaDist/sdl/blob/master/include/begin_code.h#L68
IF UNAME_SYSNAME == 'Windows':
ctypedef SDL_HitTestResult (__cdecl *SDL_HitTest) (SDL_Window *win, const SDL_Point *area, void *data)
ELSE:
ctypedef SDL_HitTestResult (*SDL_HitTest)(SDL_Window *win, const SDL_Point *area, void *data)
cdef char *SDL_HINT_ORIENTATIONS
cdef char *SDL_HINT_VIDEO_WIN_D3DCOMPILER
cdef char *SDL_HINT_ACCELEROMETER_AS_JOYSTICK
cdef char *SDL_HINT_ANDROID_TRAP_BACK_BUTTON
cdef char *SDL_HINT_WINDOWS_DPI_AWARENESS
cdef char *SDL_HINT_WINDOWS_DPI_SCALING
cdef int SDL_QUERY = -1
cdef int SDL_IGNORE = 0
cdef int SDL_DISABLE = 0
cdef int SDL_ENABLE = 1
cdef int SDL_INIT_TIMER = 0x00000001
cdef int SDL_INIT_AUDIO = 0x00000010
cdef int SDL_INIT_VIDEO = 0x00000020 # SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
cdef int SDL_INIT_JOYSTICK = 0x00000200 # SDL_INIT_JOYSTICK implies SDL_INIT_EVENTS */
cdef int SDL_INIT_HAPTIC = 0x00001000
cdef int SDL_INIT_GAMECONTROLLER = 0x00002000 # SDL_INIT_GAMECONTROLLER implies SDL_INIT_JOYSTICK */
cdef int SDL_INIT_EVENTS = 0x00004000
cdef int SDL_INIT_NOPARACHUTE = 0x00100000 # Don't catch fatal signals */
cdef void SDL_GetVersion(SDL_version * ver)
cdef SDL_Renderer * SDL_CreateRenderer(SDL_Window * window, int index, Uint32 flags)
cdef void SDL_DestroyRenderer (SDL_Renderer * renderer)
cdef SDL_Texture * SDL_CreateTexture(SDL_Renderer * renderer, Uint32 format, int access, int w, int h)
cdef SDL_Texture * SDL_CreateTextureFromSurface(SDL_Renderer * renderer, SDL_Surface * surface)
cdef SDL_Surface * SDL_CreateRGBSurface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) nogil
cdef int SDL_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture, SDL_Rect * srcrect, SDL_Rect * dstrect)
cdef int SDL_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture, SDL_Rect * srcrect, SDL_Rect * dstrect, double angle, SDL_Point *center, SDL_RendererFlip flip)
cdef void SDL_RenderPresent(SDL_Renderer * renderer)
cdef SDL_bool SDL_RenderTargetSupported(SDL_Renderer *renderer)
cdef int SDL_SetRenderTarget(SDL_Renderer *renderer, SDL_Texture *texture)
cdef void SDL_DestroyTexture(SDL_Texture * texture)
cdef void SDL_FreeSurface(SDL_Surface * surface) nogil
cdef int SDL_SetSurfaceBlendMode(SDL_Surface * surface, int blendMode)
cdef int SDL_SetSurfaceAlphaMod(SDL_Surface * surface, char alpha)
cdef int SDL_UpperBlit (SDL_Surface * src, SDL_Rect * srcrect, SDL_Surface * dst, SDL_Rect * dstrect)
cdef int SDL_BlitSurface(SDL_Surface * src, SDL_Rect * srcrect, SDL_Surface * dst, SDL_Rect * dstrect)
cdef int SDL_LockTexture(SDL_Texture * texture, SDL_Rect * rect, void **pixels, int *pitch)
cdef void SDL_UnlockTexture(SDL_Texture * texture)
cdef void SDL_GetWindowSize(SDL_Window * window, int *w, int *h)
cdef Uint32 SDL_GetWindowFlags(SDL_Window * window)
cdef SDL_Window * SDL_CreateWindow(char *title, int x, int y, int w, int h, Uint32 flags)
cdef void SDL_DestroyWindow (SDL_Window * window)
cdef int SDL_SetRenderDrawColor(SDL_Renderer * renderer, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
cdef int SDL_RenderClear(SDL_Renderer * renderer)
cdef int SDL_SetTextureBlendMode(SDL_Texture * texture, SDL_BlendMode blendMode)
cdef int SDL_GetTextureBlendMode(SDL_Texture * texture, SDL_BlendMode *blendMode)
cdef SDL_Surface * SDL_CreateRGBSurfaceFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask)
cdef SDL_Surface* SDL_ConvertSurfaceFormat(SDL_Surface* src, Uint32 pixel_format, Uint32 flags) nogil
cdef const char* SDL_GetPixelFormatName(Uint32 format)
cdef int SDL_GetColorKey(SDL_Surface *surface, Uint32 *key)
cdef int SDL_Init(Uint32 flags)
cdef void SDL_Quit()
cdef int SDL_EnableUNICODE(int enable)
cdef Uint32 SDL_GetTicks()
cdef void SDL_Delay(Uint32 ms) nogil
cdef Uint8 SDL_EventState(Uint32 type, int state)
cdef int SDL_PollEvent(SDL_Event * event) nogil
cdef void SDL_SetEventFilter(SDL_EventFilter *filter, void* userdata)
cdef SDL_RWops * SDL_RWFromFile(char *file, char *mode)
cdef SDL_RWops * SDL_RWFromMem(void *mem, int size)
cdef SDL_RWops * SDL_RWFromConstMem(void *mem, int size)
cdef SDL_RWops * SDL_AllocRW()
cdef void SDL_FreeRW(SDL_RWops *area)
cdef int SDL_GetRendererInfo(SDL_Renderer *renderer, SDL_RendererInfo *info)
cdef int SDL_RenderSetViewport(SDL_Renderer * renderer, SDL_Rect * rect)
cdef int SDL_GetCurrentDisplayMode(int displayIndex, SDL_DisplayMode * mode)
cdef int SDL_GetDesktopDisplayMode(int displayIndex, SDL_DisplayMode * mode)
cdef int SDL_SetTextureColorMod(SDL_Texture * texture, Uint8 r, Uint8 | Cython |
g, Uint8 b)
cdef int SDL_SetTextureAlphaMod(SDL_Texture * texture, Uint8 alpha)
cdef char * SDL_GetError()
cdef SDL_bool SDL_SetHint(char *name, char *value)
cdef SDL_bool SDL_SetHintWithPriority(char *name, char *value, SDL_HintPriority priority)
cdef Uint32 SDL_GetMouseState(int* x,int* y)
cdef Uint32 SDL_GetGlobalMouseState(int *x, int *y)
cdef SDL_GLContext SDL_GL_CreateContext(SDL_Window* window)
cdef int SDL_GetNumVideoDisplays()
cdef int SDL_GetNumDisplayModes(int displayIndex)
cdef int SDL_GetDisplayMode(int displayIndex, int index, SDL_DisplayMode * mode)
cdef SDL_bool SDL_HasIntersection(SDL_Rect * A, SDL_Rect * B) nogil
cdef SDL_bool SDL_IntersectRect(SDL_Rect * A, SDL_Rect * B, SDL_Rect * result) nogil
cdef void SDL_UnionRect(SDL_Rect * A, SDL_Rect * B, SDL_Rect * result) nogil
cdef Uint64 SDL_GetPerformanceCounter() nogil
cdef Uint64 SDL_GetPerformanceFrequency() nogil
cdef int SDL_GL_SetAttribute(SDL_GLattr attr, int value)
cdef int SDL_GetNumRenderDrivers()
cdef int SDL_GetRenderDriverInfo(int index, SDL_RendererInfo* info)
cdef int SDL_GL_BindTexture(SDL_Texture *texture, float *texw, float *texh)
cdef int SDL_GL_UnbindTexture(SDL_Texture *texture)
cdef int SDL_RenderReadPixels(SDL_Renderer * renderer, SDL_Rect * rect, Uint32 format, void *pixels, int pitch) nogil
cdef int SDL_PushEvent(SDL_Event * event) nogil
cdef int SDL_WaitEvent(SDL_Event * event) nogil
cdef void SDL_SetClipboardText(char * text)
cdef const char * SDL_GetClipboardText()
cdef SDL_bool SDL_HasClipboardText()
cdef int SDL_GetNumVideoDrivers()
cdef const char *SDL_GetVideoDriver(int index)
cdef int SDL_VideoInit(const char *driver_name)
cdef void SDL_VideoQuit()
cdef const char *SDL_GetCurrentVideoDriver()
cdef int SDL_GetNumVideoDisplays()
cdef const char * SDL_GetDisplayName(int displayIndex)
cdef int SDL_GetDisplayBounds(int displayIndex, SDL_Rect * rect)
cdef int SDL_GetNumDisplayModes(int displayIndex)
cdef int SDL_GetDesktopDisplayMode(int displayIndex, SDL_DisplayMode * mode)
cdef int SDL_GetCurrentDisplayMode(int displayIndex, SDL_DisplayMode * mode)
cdef SDL_DisplayMode * SDL_GetClosestDisplayMode(int displayIndex, const SDL_DisplayMode * mode, SDL_DisplayMode * closest)
cdef int SDL_SetWindowDisplayMode(SDL_Window * window, SDL_DisplayMode * mode)
cdef int SDL_GetWindowDisplayMode(SDL_Window * window, SDL_DisplayMode * mode)
cdef int SDL_GetWindowDisplayIndex(SDL_Window * window)
cdef Uint32 SDL_GetWindowPixelFormat(SDL_Window * window)
cdef SDL_Window * SDL_CreateWindowFrom(const void *data)
cdef Uint32 SDL_GetWindowID(SDL_Window * window)
cdef SDL_Window * SDL_GetWindowFromID(Uint32 id)
cdef Uint32 SDL_GetWindowFlags(SDL_Window * window)
cdef void SDL_SetWindowTitle(SDL_Window * window, char *title)
cdef const char *SDL_GetWindowTitle(SDL_Window * window)
cdef void SDL_SetWindowIcon(SDL_Window * window, SDL_Surface *icon)
cdef void* SDL_SetWindowData(SDL_Window * window, char *name, void *data)
cdef void *SDL_GetWindowData(SDL_Window * window, char *name)
cdef void SDL_SetWindowPosition(SDL_Window * window, int x, int y)
cdef void SDL_GetWindowPosition(SDL_Window * window, int *x, int *y)
cdef void SDL_SetWindowSize(SDL_Window * window, int w, int h)
cdef void SDL_GetWindowSize(SDL_Window * window, int *w, int *h)
cdef void SDL_SetWindowMinimumSize(SDL_Window * window, int min_w, int min_h)
cdef void SDL_SetWindowBordered(SDL_Window * window, SDL_bool bordered)
cdef void SDL_SetWindowAlwaysOnTop(SDL_Window * window, SDL_bool on_top)
cdef void SDL_ShowWindow(SDL_Window * window)
cdef int SDL_ShowCursor(int toggle)
cdef void SDL_SetCursor(SDL_Cursor * cursor)
cdef SDL_Cursor* SDL_CreateSystemCursor(SDL_SystemCursor id)
cdef void SDL_HideWindow(SDL_Window * window)
cdef void SDL_RaiseWindow(SDL_Window * window)
cdef void SDL_MaximizeWindow(SDL_Window * window)
cdef void SDL_MinimizeWindow(SDL_Window * window)
cdef void SDL_RestoreWindow(SDL_Window * window)
cdef int SDL_SetWindowFullscreen(SDL_Window * window, SDL_bool fullscreen)
cdef SDL_Surface * SDL_GetWindowSurface(SDL_Window * window)
cdef int SDL_UpdateWindowSurface(SDL_Window * window)
cdef void SDL_SetWindowGrab(SDL_Window * window, SDL_bool grabbed)
cdef SDL_bool SDL_GetWindowGrab(SDL_Window * window)
cdef int SDL_SetWindowBrightness(SDL_Window * window, float brightness)
cdef float SDL_GetWindowBrightness(SDL_Window * window)
cdef void SDL_DestroyWindow(SDL_Window * window)
cdef SDL_bool SDL_IsScreenSaverEnabled()
cdef void SDL_EnableScreenSaver()
cdef void SDL_DisableScreenSaver()
cdef int SDL_GL_LoadLibrary(const char *path)
cdef void *SDL_GL_GetProcAddress(const char *proc)
cdef void SDL_GL_UnloadLibrary()
cdef int SDL_GL_SetAttribute(SDL_GLattr attr, int value)
cdef int SDL_GL_GetAttribute(SDL_GLattr attr, int *value)
cdef int SDL_GL_MakeCurrent(SDL_Window * window, SDL_GLContext context)
cdef SDL_Window* SDL_GL_GetCurrentWindow()
cdef SDL_GLContext SDL_GL_GetCurrentContext()
cdef int SDL_GL_SetSwapInterval(int interval)
cdef int SDL_GL_GetSwapInterval()
cdef void SDL_GL_SwapWindow(SDL_Window * window) nogil
cdef void SDL_GL_DeleteContext(SDL_GLContext context)
cdef int SDL_NumJoysticks()
cdef SDL_Joystick * SDL_JoystickOpen(int index)
cdef SDL_Window * SDL_GetKeyboardFocus()
cdef Uint8 *SDL_GetKeyboardState(int *numkeys)
cdef SDL_Keymod SDL_GetModState()
cdef void SDL_SetModState(SDL_Keymod modstate)
cdef SDL_Keycode SDL_GetKeyFromScancode(SDL_Scancode scancode)
cdef SDL_Scancode SDL_GetScancodeFromKey(SDL_Keycode key)
cdef char *SDL_GetScancodeName(SDL_Scancode scancode)
cdef SDL_Scancode SDL_GetScancodeFromName(char *name)
cdef char *SDL_GetKeyName(SDL_Keycode key)
cdef SDL_Keycode SDL_GetKeyFromName(char *name)
cdef void SDL_StartTextInput()
cdef SDL_bool SDL_IsTextInputActive()
cdef void SDL_StopTextInput()
cdef void SDL_SetTextInputRect(SDL_Rect *rect)
cdef SDL_bool SDL_HasScreenKeyboardSupport()
cdef SDL_bool SDL_IsScreenKeyboardShown(SDL_Window *window)
cdef void SDL_GL_GetDrawableSize(SDL_Window *window, int *w, int *h)
cdef int SDL_SetWindowHitTest(SDL_Window *window, SDL_HitTest callback, void *callback_data)
# Sound audio formats
Uint16 AUDIO_U8 #0x0008 /**< Unsigned 8-bit samples */
Uint16 AUDIO_S8 #0x8008 /**< Signed 8-bit samples */
Uint16 AUDIO_U16LSB #0x0010 /**< Unsigned 16-bit samples */
Uint16 AUDIO_S16LSB #0x8010 /**< Signed 16-bit samples */
Uint16 AUDIO_U16MSB #0x1010 /**< As above, but big-endian byte order */
Uint16 AUDIO_S16MSB #0x9010 /**< As above, but big-endian byte order */
Uint16 AUDIO_U16 #AUDIO_U16LSB
Uint16 AUDIO_S16 #AUDIO_S16LSB
Uint16 AUDIO_S32LSB #0x8020 /**< 32-bit Uint16eger samples */
Uint16 AUDIO_S32MSB #0x9020 /**< As above, but big-endian byte order */
Uint16 AUDIO_S32 #AUDIO_S32LSB
Uint16 AUDIO_F32LSB #0x8120 /**< 32-bit floating point samples */
Uint16 AUDIO_F32MSB #0x9120 /**< As above, but big-endian byte order */
Uint16 AUDIO_F32 #AUDIO_F32LSB
# Endianness
Uint16 SDL_BYTEORDER
Uint16 SDL_LIL_ENDIAN
Uint16 SDL_BIG_ENDIAN
cdef extern from "SDL_shape.h":
cdef SDL_Window * SDL_CreateShapedWindow(
char *title,
unsigned int x,
unsigned | Cython |
int y,
unsigned int w,
unsigned int h,
Uint32 flags
)
# properties, flags, etc
ctypedef enum WindowShapeMode:
ShapeModeDefault
ShapeModeBinarizeAlpha
ShapeModeReverseBinarizeAlpha
ShapeModeColorKey
ctypedef union SDL_WindowShapeParams:
Uint8 binarizationCutoff
SDL_Color colorKey
ctypedef struct SDL_WindowShapeMode:
WindowShapeMode mode
SDL_WindowShapeParams parameters
int SDL_NONSHAPEABLE_WINDOW
int SDL_INVALID_SHAPE_ARGUMENT
int SDL_WINDOW_LACKS_SHAPE
# set & get
cdef SDL_bool SDL_IsShapedWindow(SDL_Window * window)
int SDL_SetWindowShape(
SDL_Window * window,
SDL_Surface * shape,
SDL_WindowShapeMode * shape_mode
)
int SDL_GetShapedWindowMode(
SDL_Window * window,
SDL_WindowShapeMode * shape_mode
)
cdef extern from "SDL_image.h":
ctypedef enum IMG_InitFlags:
IMG_INIT_JPG
IMG_INIT_PNG
IMG_INIT_TIF
IMG_INIT_WEBP
cdef int IMG_Init(IMG_InitFlags flags)
cdef char *IMG_GetError()
cdef SDL_Surface *IMG_Load(char *file)
cdef SDL_Surface *IMG_Load_RW(SDL_RWops *src, int freesrc)
cdef SDL_Surface *IMG_LoadTyped_RW(SDL_RWops *src, int freesrc, char *type)
cdef int IMG_SavePNG(SDL_Surface *src, char *file)
cdef int IMG_SavePNG_RW(SDL_Surface *surface, SDL_RWops *dst, int freedst)
cdef int IMG_SaveJPG(SDL_Surface *surface, const char *file, int quality)
cdef int IMG_SaveJPG_RW(SDL_Surface *surface, SDL_RWops *dst, int freedst, int quality)
cdef extern from "SDL_ttf.h":
ctypedef struct TTF_Font
cdef int TTF_Init()
cdef TTF_Font * TTF_OpenFont( char *file, int ptsize)
cdef TTF_Font * TTF_OpenFontIndex( char *file, int ptsize, long index)
cdef TTF_Font * TTF_OpenFontRW(SDL_RWops *src, int freesrc, int ptsize)
cdef TTF_Font * TTF_OpenFontIndexRW(SDL_RWops *src, int freesrc, int ptsize, long index)
#Set and retrieve the font style
##define TTF_STYLE_NORMAL 0x00
##define TTF_STYLE_BOLD 0x01
##define TTF_STYLE_ITALIC 0x02
##define TTF_STYLE_UNDERLINE 0x04
##define TTF_STYLE_STRIKETHROUGH 0x08
cdef int TTF_STYLE_NORMAL
cdef int TTF_STYLE_BOLD
cdef int TTF_STYLE_ITALIC
cdef int TTF_STYLE_UNDERLINE
cdef int TTF_STYLE_STRIKETHROUGH
cdef int TTF_GetFontStyle( TTF_Font *font)
cdef void TTF_SetFontStyle(TTF_Font *font, int style)
cdef int TTF_GetFontOutline( TTF_Font *font)
cdef void TTF_SetFontOutline(TTF_Font *font, int outline)
cdef int TTF_SetFontDirection(TTF_Font *font, int direction)
cdef int TTF_SetFontScriptName(TTF_Font *font, const char *script)
#Set and retrieve FreeType hinter settings */
##define TTF_HINTING_NORMAL 0
##define TTF_HINTING_LIGHT 1
##define TTF_HINTING_MONO 2
##define TTF_HINTING_NONE 3
cdef int TTF_HINTING_NORMAL
cdef int TTF_HINTING_LIGHT
cdef int TTF_HINTING_MONO
cdef int TTF_HINTING_NONE
cdef int TTF_GetFontHinting( TTF_Font *font)
cdef void TTF_SetFontHinting(TTF_Font *font, int hinting)
cdef int TTF_DIRECTION_LTR
cdef int TTF_DIRECTION_RTL
cdef int TTF_DIRECTION_TTB
cdef int TTF_DIRECTION_BTT
#Get the total height of the font - usually equal to point size
cdef int TTF_FontHeight( TTF_Font *font)
## Get the offset from the baseline to the top of the font
#This is a positive value, relative to the baseline.
#*/
cdef int TTF_FontAscent( TTF_Font *font)
## Get the offset from the baseline to the bottom of the font
# This is a negative value, relative to the baseline.
# */
cdef int TTF_FontDescent( TTF_Font *font)
## Get the recommended spacing between lines of text for this font */
cdef int TTF_FontLineSkip( TTF_Font *font)
## Get/Set whether or not kerning is allowed for this font */
cdef int TTF_GetFontKerning( TTF_Font *font)
cdef void TTF_SetFontKerning(TTF_Font *font, int allowed)
## Get the number of faces of the font */
cdef long TTF_FontFaces( TTF_Font *font)
## Get the font face attributes, if any */
cdef int TTF_FontFaceIsFixedWidth( TTF_Font *font)
cdef char * TTF_FontFaceFamilyName( TTF_Font *font)
cdef char * TTF_FontFaceStyleName( TTF_Font *font)
## Check whether a glyph is provided by the font or not */
cdef int TTF_GlyphIsProvided( TTF_Font *font, Uint16 ch)
## Get the metrics (dimensions) of a glyph
# To understand what these metrics mean, here is a useful link:
# http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html
# */
cdef int TTF_GlyphMetrics(TTF_Font *font, Uint16 ch,int *minx, int *maxx, int *miny, int *maxy, int *advance)
## Get the dimensions of a rendered string of text */
cdef int TTF_SizeText(TTF_Font *font, char *text, int *w, int *h)
cdef int TTF_SizeUTF8(TTF_Font *font, char *text, int *w, int *h)
cdef int TTF_SizeUNICODE(TTF_Font *font, Uint16 *text, int *w, int *h)
# Create an 8-bit palettized surface and render the given text at
# fast quality with the given font and color. The 0 pixel is the
# colorkey, giving a transparent background, and the 1 pixel is set
# to the text color.
# This function returns the new surface, or NULL if there was an error.
#*/
cdef SDL_Surface * TTF_RenderText_Solid(TTF_Font *font, char *text, SDL_Color fg)
cdef SDL_Surface * TTF_RenderUTF8_Solid(TTF_Font *font, char *text, SDL_Color fg)
cdef SDL_Surface * TTF_RenderUNICODE_Solid(TTF_Font *font, Uint16 *text, SDL_Color fg)
# Create an 8-bit palettized surface and render the given glyph at
# fast quality with the given font and color. The 0 pixel is the
# colorkey, giving a transparent background, and the 1 pixel is set
# to the text color. The glyph is rendered without any padding or
# centering in the X direction, and aligned normally in the Y direction.
# This function returns the new surface, or NULL if there was an error.
#*/
cdef SDL_Surface * TTF_RenderGlyph_Solid(TTF_Font *font, Uint16 ch, SDL_Color fg)
# Create an 8-bit palettized surface and render the given text at
# high quality with the given font and colors. The 0 pixel is background,
# while other pixels have varying degrees of the foreground color.
# This function returns the new surface, or NULL if there was an error.
#*/
cdef SDL_Surface * TTF_RenderText_Shaded(TTF_Font *font, char *text, SDL_Color fg, SDL_Color bg)
cdef SDL_Surface * TTF_RenderUTF8_Shaded(TTF_Font *font, char *text, SDL_Color fg, SDL_Color bg)
cdef SDL_Surface * TTF_RenderUNICODE_Shaded(TTF_Font *font, Uint16 *text, SDL_Color fg, SDL_Color bg)
# Create an 8-bit palettized surface and render the given glyph at
# high quality with the given font and colors. The 0 pixel is background,
# while other pixels have varying degrees of the foreground color.
# The glyph is rendered without | Cython |
any padding or centering in the X
# direction, and aligned normally in the Y direction.
# This function returns the new surface, or NULL if there was an error.
#
cdef SDL_Surface * TTF_RenderGlyph_Shaded(TTF_Font *font,
Uint16 ch, SDL_Color fg, SDL_Color bg)
# Create a 32-bit ARGB surface and render the given text at high quality,
# using alpha blending to dither the font with the given color.
# This function returns the new surface, or NULL if there was an error.
#*/
cdef SDL_Surface * TTF_RenderText_Blended(TTF_Font *font,
char *text, SDL_Color fg)
cdef SDL_Surface * TTF_RenderUTF8_Blended(TTF_Font *font,
char *text, SDL_Color fg)
cdef SDL_Surface * TTF_RenderUNICODE_Blended(TTF_Font *font,
Uint16 *text, SDL_Color fg)
# Create a 32-bit ARGB surface and render the given glyph at high quality,
# using alpha blending to dither the font with the given color.
# The glyph is rendered without any padding or centering in the X
# direction, and aligned normally in the Y direction.
# This function returns the new surface, or NULL if there was an error.
#*/
cdef SDL_Surface * TTF_RenderGlyph_Blended(TTF_Font *font,
Uint16 ch, SDL_Color fg)
# For compatibility with previous versions, here are the old functions */
##define TTF_RenderText(font, text, fg, bg) \
# TTF_RenderText_Shaded(font, text, fg, bg)
##define TTF_RenderUTF8(font, text, fg, bg) \
# TTF_RenderUTF8_Shaded(font, text, fg, bg)
##define TTF_RenderUNICODE(font, text, fg, bg) \
# TTF_RenderUNICODE_Shaded(font, text, fg, bg)
# Close an opened font file */
cdef void TTF_CloseFont(TTF_Font *font)
# De-initialize the TTF engine */
cdef void TTF_Quit()
# Check if the TTF engine is initialized */
cdef int TTF_WasInit()
# Get the kerning size of two glyphs */
cdef int TTF_GetFontKerningSize(TTF_Font *font, int prev_index, int index)
cdef extern from "SDL_audio.h":
cdef int AUDIO_S16SYS
ctypedef struct SDL_AudioFilter:
pass
ctypedef struct SDL_AudioCVT:
int needed
int src_format
int dst_format
double rate_incr
Uint8 *buf
int len
int len_cvt
int len_mult
double len_ratio
SDL_AudioFilter filters[10]
int filter_index
cdef int SDL_BuildAudioCVT(
SDL_AudioCVT *cvt,
int src_format,
Uint8 src_channels,
int src_rate,
int dst_format,
Uint8 dst_channels,
int dst_rate
)
cdef int SDL_ConvertAudio(SDL_AudioCVT *cvt)
cdef extern from "SDL_mixer.h":
cdef struct Mix_Chunk:
int allocated
Uint8 *abuf
Uint32 alen
Uint8 volume
ctypedef struct Mix_Music:
pass
ctypedef enum Mix_Fading:
MIX_NO_FADING
MIX_FADING_OUT
MIX_FADING_IN
ctypedef enum Mix_MusicType:
MUS_NONE
MUS_CMD
MUS_WAV
MUS_MOD
MUS_MID
MUS_OGG
MUS_MP3
MUS_MP3_MAD
MUS_FLAC
MUS_MODPLUG
ctypedef enum MIX_InitFlags:
MIX_INIT_FLAC = 0x00000001
MIX_INIT_MOD = 0x00000002
MIX_INIT_MODPLUG = 0x00000004 # Removed in mixer 2.0.2
MIX_INIT_MP3 = 0x00000008
MIX_INIT_OGG = 0x00000010
MIX_INIT_MID = 0x00000020 # Previously _FLUIDSYNTH
cdef int MIX_MAX_VOLUME
cdef int Mix_Init(int flags)
cdef void Mix_Quit()
cdef int Mix_OpenAudio(int frequency, Uint16 format, int channels, int chunksize)
cdef int Mix_AllocateChannels(int numchans)
cdef int Mix_QuerySpec(int *frequency,Uint16 *format,int *channels)
cdef Mix_Chunk * Mix_LoadWAV_RW(SDL_RWops *src, int freesrc)
cdef Mix_Chunk * Mix_LoadWAV(char *file)
cdef Mix_Music * Mix_LoadMUS(char *file)
cdef Mix_Music * Mix_LoadMUS_RW(SDL_RWops *rw)
cdef Mix_Music * Mix_LoadMUSType_RW(SDL_RWops *rw, Mix_MusicType type, int freesrc)
cdef Mix_Chunk * Mix_QuickLoad_WAV(Uint8 *mem)
cdef Mix_Chunk * Mix_QuickLoad_RAW(Uint8 *mem, Uint32 len)
cdef void Mix_FreeChunk(Mix_Chunk *chunk)
cdef void Mix_FreeMusic(Mix_Music *music)
cdef int Mix_GetNumChunkDecoders()
cdef char * Mix_GetChunkDecoder(int index)
cdef int Mix_GetNumMusicDecoders()
cdef char * Mix_GetMusicDecoder(int index)
cdef Mix_MusicType Mix_GetMusicType( Mix_Music *music)
cdef void Mix_SetPostMix(void (*mix_func)(void *udata, Uint8 *stream, int len), void *arg)
cdef void Mix_HookMusic(void (*mix_func) (void *udata, Uint8 *stream, int len), void *arg)
cdef void Mix_HookMusicFinished(void (*music_finished)())
cdef void * Mix_GetMusicHookData()
cdef void Mix_ChannelFinished(void (*channel_finished)(int channel))
# typedef void (*Mix_EffectFunc_t)(int chan, void *stream, int len, void *udata)
# typedef void (*Mix_EffectDone_t)(int chan, void *udata)
# cdef int Mix_RegisterEffect(int chan, Mix_EffectFunc_t f,
# cdef int Mix_UnregisterEffect(int channel, Mix_EffectFunc_t f)
cdef int Mix_UnregisterAllEffects(int channel)
cdef int Mix_SetPanning(int channel, Uint8 left, Uint8 right)
cdef int Mix_SetPosition(int channel, Sint16 angle, Uint8 distance)
cdef int Mix_SetDistance(int channel, Uint8 distance)
cdef int Mix_SetReverseStereo(int channel, int flip)
cdef int Mix_ReserveChannels(int num)
cdef int Mix_GroupChannel(int which, int tag)
cdef int Mix_GroupChannels(int _from, int to, int tag)
cdef int Mix_GroupAvailable(int tag)
cdef int Mix_GroupCount(int tag)
cdef int Mix_GroupOldest(int tag)
cdef int Mix_GroupNewer(int tag)
cdef int Mix_PlayChannel(int channel, Mix_Chunk *chunk, int loops)
cdef int Mix_PlayChannelTimed(int channel, Mix_Chunk *chunk, int loops, int ticks)
cdef int Mix_PlayMusic(Mix_Music *music, int loops)
cdef int Mix_FadeInMusic(Mix_Music *music, int loops, int ms)
cdef int Mix_FadeInMusicPos(Mix_Music *music, int loops, int ms, double position)
cdef int Mix_FadeInChannel(int channel, Mix_Chunk *chunk, int loops, int ms)
cdef int Mix_FadeInChannelTimed(int channel, Mix_Chunk *chunk, int loops, int ms, int ticks)
cdef int Mix_Volume(int channel, int volume)
cdef int Mix_VolumeChunk(Mix_Chunk *chunk, int volume)
cdef int Mix_VolumeMusic(int volume)
cdef int Mix_HaltChannel(int channel)
cdef int Mix_HaltGroup(int tag)
cdef int Mix_HaltMusic()
cdef int Mix_ExpireChannel(int channel, int ticks)
cdef int Mix_FadeOutChannel(int which, int ms)
cdef int Mix_FadeOutGroup(int tag, int ms)
cdef int Mix_FadeOutMusic(int ms)
cdef Mix_Fading Mix_FadingMusic()
cdef Mix_Fading Mix_FadingChannel(int which)
cdef void Mix_Pause(int channel)
cdef void Mix_Resume(int channel)
cdef int Mix | Cython |
_Paused(int channel)
cdef void Mix_PauseMusic()
cdef void Mix_ResumeMusic()
cdef void Mix_RewindMusic()
cdef int Mix_PausedMusic()
cdef int Mix_SetMusicPosition(double position)
cdef int Mix_Playing(int channel)
cdef int Mix_PlayingMusic()
cdef int Mix_SetMusicCMD( char *command)
cdef int Mix_SetSynchroValue(int value)
cdef int Mix_GetSynchroValue()
cdef int Mix_SetSoundFonts( char *paths)
cdef char* Mix_GetSoundFonts()
#cdef int Mix_EachSoundFont(int (*function)( char*, void*), void *data)
cdef Mix_Chunk * Mix_GetChunk(int channel)
cdef void Mix_CloseAudio()
cdef char * Mix_GetError()
include '../core/window/window_attrs.pxi'
cdef extern from "SDL_syswm.h":
cdef enum SDL_SYSWM_TYPE:
SDL_SYSWM_UNKNOWN
SDL_SYSWM_WINDOWS
SDL_SYSWM_X11
SDL_SYSWM_DIRECTFB
SDL_SYSWM_COCOA
SDL_SYSWM_UIKIT
SDL_SYSWM_WAYLAND
SDL_SYSWM_MIR
SDL_SYSWM_WINRT
SDL_SYSWM_ANDROID
SDL_SYSWM_VIVANTE
SDL_SYSWM_OS2
IF UNAME_SYSNAME == 'Windows':
cdef struct _wm_info_win:
HWND window
HDC hdc
ELSE:
cdef struct _wm_info_win:
int dummy
IF USE_WAYLAND:
cdef struct _wm_info_wl:
wl_display *display
wl_surface *surface
wl_shell_surface *shell_surface
ELSE:
cdef struct _wm_info_wl:
int dummy
IF USE_X11:
cdef struct _wm_info_x11:
Display *display
Window window
ELSE:
cdef struct _wm_info_x11:
int dummy
cdef union _wm_info:
_wm_info_win win
_wm_info_wl wl
_wm_info_x11 x11
cdef struct SDL_SysWMinfo:
SDL_version version
SDL_SYSWM_TYPE subsystem
_wm_info info
cdef SDL_bool SDL_GetWindowWMInfo(SDL_Window *window, SDL_SysWMinfo *info)
<|end_of_text|>include '../../types.pxi'
from libcpp.vector cimport vector
from quantlib.termstructures._yield_term_structure cimport YieldTermStructure
from quantlib.time._date cimport Date
from quantlib.time._daycounter cimport DayCounter
from quantlib.time._calendar cimport Calendar
from quantlib.math.interpolation cimport LogLinear
cdef extern from 'ql/termstructures/yield/discountcurve.hpp' namespace 'QuantLib':
cdef cppclass InterpolatedDiscountCurve[T](YieldTermStructure):
InterpolatedDiscountCurve(const vector[Date]& dates,
const vector[DiscountFactor]& dfs,
const DayCounter& dayCounter,
const Calendar& cal # = Calendar()
) except +
const vector[Time]& times()
const vector[Real]& data()
const vector[DiscountFactor]& discounts()
const vector[Date]& dates()
ctypedef InterpolatedDiscountCurve[LogLinear] DiscountCurve
<|end_of_text|>
cpdef fib(int n):
if n==0 or n==1 :
return n
result = fib(n-1) + fib(n-2)
return result
<|end_of_text|>from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t, int8_t, int16_t, int32_t, int64_t
from libcpp cimport bool
cdef extern from "json.h":
ctypedef enum JsonTag:
JSON_NULL,
JSON_BOOL,
JSON_STRING,
JSON_NUMBER,
JSON_ARRAY,
JSON_OBJECT
ctypedef struct JsonNode
#ctypedef struct JsonNode:
#/* only if parent is an object or array (NULL otherwise) */
#JsonNode *parent;
#JsonNode *prev, *next;
#/* only if parent is an object (NULL otherwise) */
#char *key; #/* Must be valid UTF-8. */
#JsonTag tag;
#union {
#/* JSON_BOOL */
#bool bool_;
#/* JSON_STRING */
#char *string_; #/* Must be valid UTF-8. */
#/* JSON_NUMBER */
#double number_;
#/* JSON_ARRAY */
#/* JSON_OBJECT */
#struct children:
#JsonNode *head, *tail;
#};
cdef extern from "imtq-config.h":
cdef extern from "json.h":
ctypedef enum JsonTag:
JSON_NULL,
JSON_BOOL,
JSON_STRING,
JSON_NUMBER,
JSON_ARRAY,
JSON_OBJECT
ctypedef struct JsonNode
ctypedef union imtq_config_value:
int8_t int8_val; #*< Storage for signed single-byte values */
uint8_t uint8_val; #*< Storage for unsigned single-byte values */
int16_t int16_val; #*< Storage for signed byte-pair values */
uint16_t uint16_val; #*< Storage for unsigned byte-pair values */
int32_t int32_val; #*< Storage for signed four-byte values */
uint32_t uint32_val; #*< Storage for unsigned four-byte values */
float float_val; #*< Storage for IEEE754 single-precision floating point values (four bytes) */
int64_t int64_val; #*< Storage for signed eight-byte values */
uint64_t uint64_val; #*< Storage for unsigned eight-byte values */
double double_val #*< Storage for IEEE754 double-precision floating point values (eight bytes) */
ctypedef struct imtq_resp_header:
uint8_t cmd;
uint8_t status;
ctypedef struct imtq_config_resp:
imtq_resp_header hdr; #*< Response message header */
uint16_t param; #*< Echo of requested parameter ID */
imtq_config_value value #*< Current value of requested parameter */
KADCSStatus k_adcs_configure(const JsonNode * config)
KADCSStatus k_imtq_get_param(uint16_t param, imtq_config_resp * response)
KADCSStatus k_imtq_set_param(uint16_t param, const imtq_config_value * value, imtq_config_resp * response)
KADCSStatus k_imtq_reset_param(uint16_t param, imtq_config_resp * response)
cdef extern from "imtq-data.h":
ctypedef enum ADCSTelemType:
NOMINAL, #*< System state, all system measurements */
DEBUG #*< System state, current configuration, last test results */
ctypedef struct imtq_axis_data:
int16_t x; #*< X-axis */
int16_t y; #*< Y-axis */
int16_t z #*< Z-axis */
ctypedef uint32_t adcs_power_status
ctypedef struct imtq_state:
imtq_resp_header hdr; #*< Response message header */
uint8_t mode; #*< Current system mode */
uint8_t error; #*< Error encountered during previous interation */
uint8_t config; #*< Parameter updated since system startup? 0 - No, 1 - Yes */
uint32_t uptime #*< System uptime in seconds */
ctypedef struct imtq_mtm_data:
int32_t x; #*< X-axis */
int32_t y; #*< Y-axis */
int32_t z #*< Z-axis */
ctypedef struct imtq_mtm_msg:
imtq_resp_header hdr; #*< Response message header */
imtq_mtm_data data; #*< MTM measurement data. Units dependent on function used */
uint8_t act_status #*< Coils actuation status during measurement. 0 - Not actuating, 1 - Actuating */
ctypedef struct imtq_axis_msg:
imtq_resp_header hdr; #*< Response message header */
imtq_axis_data data #*< Axes data */
ctypedef imtq_axis_msg imtq_coil_current #*< Coil currents in [10<sup>-4</sup> A] returned by ::k_imtq_get_coil_current */
ctypedef imtq_axis_msg imtq_coil_temp #*< Coil temperatures in [<sup>o</sup>C] returned by ::k_imtq_get_coil_temps */
ctypedef imtq_axis_msg imtq_dipole
ctypedef struct imtq_test_result:
imtq_resp_header hdr; #*< Response message header */
uint8_t error; #*< Return code for the step */
uint8_t step; #*< Axis being tested */
imtq_mtm_data mtm_raw; #*< Raw MTM data in [7.5*10<sup>-9</ | Cython |
sup> T] per count */
imtq_mtm_data mtm_calib; #*< Calibrated MTM data in [10<sup>-9</sup> T] */
imtq_axis_data coil_current; #*< Coil currents in [10<sup>-4</sup> A] */
imtq_axis_data coil_temp #*< Coil temperatures in [<sup>o</sup>C] */
ctypedef struct imtq_test_result_single:
imtq_test_result init; #*< Measurements before actuation */
imtq_test_result step; #*< Measurements during actuation of requested axis */
imtq_test_result final #*< Measurements after actuation */
ctypedef struct imtq_test_result_all:
imtq_test_result init; #*< Measurements before actuation */
imtq_test_result x_pos; #*< Measurements during actuation of positive x-axis */
imtq_test_result x_neg; #*< Measurements during actuation of negative x-axis */
imtq_test_result y_pos; #*< Measurements during actuation of positive y-axis */
imtq_test_result y_neg; #*< Measurements during actuation of negative y-axis */
imtq_test_result z_pos; #*< Measurements during actuation of positive z-axis */
imtq_test_result z_neg; #*< Measurements during actuation of negative z-axis */
imtq_test_result final #*< Measurements after actuation */
ctypedef struct imtq_detumble:
imtq_resp_header hdr; #*< Response message header */
imtq_mtm_data mtm_calib; #*< Calibrated MTM data in [10<sup>-9</sup> T] */
imtq_mtm_data mtm_filter; #*< Filtered MTM data in [10<sup>-9</sup> T] */
imtq_mtm_data bdot; #*< B-Dot in [10<sup>-9</sup> T*s<sup>-1</sup>] */
imtq_axis_data dipole; #*< Commanded actuation dipole in [10<sup>-4</sup> Am<sup>2</sup>] */
imtq_axis_data cmd_current; #*< Command current in [10<sup>-4</sup> A] */
imtq_axis_data coil_current #*< Coil currents in [10<sup>-4</sup> A] */
ctypedef struct imtq_axis_data_raw:
int16_t x; #*< X-axis */
int16_t y; #*< Y-axis */
int16_t z #*< Z-axis */
ctypedef struct imtq_housekeeping_raw:
imtq_resp_header hdr; #*< Response message header */
uint16_t voltage_d; #*< Digital supply voltage */
uint16_t voltage_a; #*< Analog supply voltage */
uint16_t current_d; #*< Digital supply current */
uint16_t current_a; #*< Analog supply current */
imtq_axis_data_raw coil_current; #*< Coil currents */
imtq_axis_data_raw coil_temp; #*< Coil temperatures */
uint16_t mcu_temp #*< MCU temperature */
ctypedef struct imtq_housekeeping_eng:
imtq_resp_header hdr; #*< Response message header */
uint16_t voltage_d; #*< Digital supply voltage in [mV] */
uint16_t voltage_a; #*< Analog supply voltage in [mV] */
uint16_t current_d; #*< Digital supply current in [10<sup>-4</sup> A] */
uint16_t current_a; #*< Analog supply current in [10<sup>-4</sup> A] */
imtq_axis_data coil_current; #*< Coil currents in [10<sup>-4</sup> A] */
imtq_axis_data coil_temp; #*< Coil temperatures in [<sup>o</sup>C] */
int16_t mcu_temp #*< MCU temperature in [<sup>o</sup>C] */
ctypedef struct adcs_orient
ctypedef struct adcs_spin
KADCSStatus k_adcs_get_power_status(adcs_power_status * data)
KADCSStatus k_adcs_get_mode(ADCSMode * mode)
KADCSStatus k_adcs_get_orientation(adcs_orient * data)
KADCSStatus k_adcs_get_spin(adcs_spin * data)
KADCSStatus k_adcs_get_telemetry(ADCSTelemType type, JsonNode * buffer)
KADCSStatus k_imtq_get_system_state(imtq_state * state)
KADCSStatus k_imtq_get_raw_mtm(imtq_mtm_msg * data)
KADCSStatus k_imtq_get_calib_mtm(imtq_mtm_msg * data)
KADCSStatus k_imtq_get_coil_current(imtq_coil_current * data)
KADCSStatus k_imtq_get_coil_temps(imtq_coil_temp * data)
KADCSStatus k_imtq_get_dipole(imtq_dipole * data)
KADCSStatus k_imtq_get_test_results_single(imtq_test_result_single * data)
KADCSStatus k_imtq_get_test_results_all(imtq_test_result_all * data)
KADCSStatus k_imtq_get_detumble(imtq_detumble * data)
KADCSStatus k_imtq_get_raw_housekeeping(imtq_housekeeping_raw * data)
KADCSStatus k_imtq_get_eng_housekeeping(imtq_housekeeping_eng * data)
KADCSStatus kprv_adcs_get_status_telemetry(JsonNode * buffer)
KADCSStatus kprv_adcs_get_nominal_telemetry(JsonNode * buffer)
KADCSStatus kprv_adcs_get_debug_telemetry(JsonNode * buffer)
void kprv_adcs_process_test(JsonNode * parent, imtq_test_result test)
cdef extern from "imtq-ops.h":
ctypedef enum KADCSReset:
SOFT_RESET #*< Software reset */
ctypedef enum ADCSTestType:
TEST_ALL, #*< Test all axes */
TEST_X_POS, #*< Test positive x-axis */
TEST_X_NEG, #*< Test negative x-axis */
TEST_Y_POS, #*< Test positive y-axis */
TEST_Y_NEG, #*< Test negative y-axis */
TEST_Z_POS, #*< Test positive z-axis */
TEST_Z_NEG #*< Test negative z-axis */
ctypedef uint16_t adcs_mode_param
ctypedef JsonNode * adcs_test_results
KADCSStatus k_adcs_noop()
KADCSStatus k_adcs_reset(KADCSReset type)
KADCSStatus k_adcs_set_mode(ADCSMode mode, const adcs_mode_param * params)
KADCSStatus k_adcs_run_test(ADCSTestType test, adcs_test_results buffer)
KADCSStatus k_imtq_cancel_op()
KADCSStatus k_imtq_start_measurement()
KADCSStatus k_imtq_start_actuation_current(imtq_axis_data current, uint16_t time)
KADCSStatus k_imtq_start_actuation_dipole(imtq_axis_data dipole, uint16_t time)
KADCSStatus k_imtq_start_actuation_PWM(imtq_axis_data pwm, uint16_t time)
KADCSStatus k_imtq_start_test(ADCSTestType axis)
KADCSStatus k_imtq_start_detumble(uint16_t time)
cdef extern from "imtq.h":
ctypedef enum KADCSStatus:
ADCS_OK,
ADCS_ERROR, #*< Generic error */
ADCS_ERROR_CONFIG, #*< Configuration error */
ADCS_ERROR_NO_RESPONSE, #*< No response received from subsystem */
ADCS_ERROR_INTERNAL, #*< An error was thrown by the subsystem */
ADCS_ERROR_MUTEX, #*< Mutex-related error */
ADCS_ERROR_NOT_IMPLEMENTED #*< Requested function has not been implemented for the subsystem */
ctypedef enum KIMTQStatus:
IMTQ_OK,
IMTQ_ERROR = 0x01, #*< Generic error */
IMTQ_ERROR_BAD_CMD = 0x02, #*< Invalid command */
IMTQ_ERROR_NO_PARAM = 0x03, #*< Parameter missing */
IMTQ_ERROR_BAD_PARAM = 0x04, #*< Parameter invalid */
IMTQ_ERROR_MODE = 0x05, #*< Command unavailable in current mode */
IMTQ_ERROR_RESERVED = 0x06, #*< (Internal reserved value) */
IMTQ_ERROR_INTERNAL = 0x07 #*< Internal error */
ctypedef struct imtq_resp_header:
uint8_t cmd;
uint8_t status;#*< Command which produced this response */
# *
# | Cython |
* Status byte
# *
# * Contains command response flags, like ::RESP_IVA_X, and a return code
# * which can be extracted with ::kprv_imtq_check_error
# */
ctypedef struct imtq_axis_data:
int16_t x; #*< X-axis */
int16_t y; #*< Y-axis */
int16_t z #*< Z-axis */
ctypedef enum ADCSMode:
IDLE, #*< Idle mode */
SELFTEST, #*< Self-test mode */
DETUMBLE #*< Detumble mode */
ctypedef struct adcs_orient
# Not an implemented structure/function. Need for compliance with generic API */
ctypedef struct adcs_spin
# Not an implemented structure/function. Need for compliance with generic API */
#ctypedef struct timespec
KADCSStatus k_adcs_init(char * bus, uint16_t addr, int timeout)
void k_adcs_terminate()
KADCSStatus k_imtq_watchdog_start()
KADCSStatus k_imtq_watchdog_stop()
KADCSStatus k_imtq_reset()
#KADCSStatus k_adcs_passthrough(const uint8_t * tx, int tx_len, uint8_t * rx, int rx_len, const timespec * delay)
#KADCSStatus kprv_imtq_transfer(const uint8_t * tx, int tx_len, uint8_t * rx, int rx_len, const timespec * delay)
def py_k_adcs_init(char * bus, addr, int timeout):
return k_adcs_init(bus, <uint16_t>addr, timeout)
def py_k_adcs_terminate():
return k_adcs_terminate()
def py_k_imtq_watchdog_start():
return k_imtq_watchdog_start()
def py_k_imtq_watchdog_stop():
return k_imtq_watchdog_stop()
def py_k_imtq_reset():
return k_imtq_reset()
def py_k_imtq_get_param(param, response):
return k_imtq_get_param(<uint16_t>param, <imtq_config_resp *>response)
#def py_k_imtq_set_param(param,value,response):
#return k_imtq_set_param(<uint16_t>param, <const imtq_config_value *>value, <imtq_config_resp *>response)
def py_k_imtq_reset_param(param, response):
return k_imtq_reset_param(<uint16_t>param, <imtq_config_resp *>response)
#def py_k_adcs_get_power_status(data):
#return k_adcs_get_power_status(<adcs_power_status *>data)
#def py_k_adcs_get_mode(mode):
# k_adcs_get_mode(<ADCSMode *>mode)
def py_k_adcs_get_orientation(data):
return k_adcs_get_orientation(<adcs_orient *>data)
def py_k_adcs_get_spin(data):
return k_adcs_get_spin(<adcs_spin *>data)
def py_k_adcs_get_telemetry(type, buffer):
return k_adcs_get_telemetry(<ADCSTelemType>type, <JsonNode *>buffer)
def py_k_imtq_get_system_state(state):
return k_imtq_get_system_state(<imtq_state *>state)
def py_k_imtq_get_raw_mtm(data):
return k_imtq_get_raw_mtm(<imtq_mtm_msg *>data)
def py_k_imtq_get_calib_mtm(data):
return k_imtq_get_calib_mtm(<imtq_mtm_msg *>data)
def py_k_imtq_get_coil_current(data):
return k_imtq_get_coil_current(<imtq_coil_current *>data)
def py_k_imtq_get_coil_temps(data):
return k_imtq_get_coil_temps(<imtq_coil_temp *>data)
def py_k_imtq_get_dipole(data):
return k_imtq_get_dipole(<imtq_dipole *>data)
def py_k_imtq_get_test_results_single(data):
return k_imtq_get_test_results_single(<imtq_test_result_single *>data)
def py_k_imtq_get_test_results_all(data):
return k_imtq_get_test_results_all(<imtq_test_result_all *>data)
def py_k_imtq_get_detumble(data):
return k_imtq_get_detumble(<imtq_detumble *>data)
def py_k_imtq_get_raw_housekeeping(data):
return k_imtq_get_raw_housekeeping(<imtq_housekeeping_raw *>data)
def py_k_imtq_get_eng_housekeeping(data):
return k_imtq_get_eng_housekeeping(<imtq_housekeeping_eng *>data)
def py_kprv_adcs_get_status_telemetry(buffer):
return kprv_adcs_get_status_telemetry(<JsonNode *>buffer)
def py_kprv_adcs_get_nominal_telemetry(buffer):
return kprv_adcs_get_nominal_telemetry(<JsonNode *>buffer)
def py_kprv_adcs_get_debug_telemetry(buffer):
return kprv_adcs_get_debug_telemetry(<JsonNode *>buffer)
def py_kprv_adcs_process_test(parent, test):
return kprv_adcs_process_test(<JsonNode *>parent, <imtq_test_result>test)
def py_k_adcs_noop():
return k_adcs_noop()
def py_k_adcs_reset(type):
return k_adcs_reset(<KADCSReset>type)
#def py_k_adcs_set_mode(mode, params):
#return k_adcs_set_mode(<ADCSMode>mode, <const adcs_mode_param *>params)
def py_k_adcs_run_test(test, buffer):
return k_adcs_run_test(<ADCSTestType>test, <adcs_test_results>buffer)
def py_k_imtq_cancel_op():
return k_imtq_cancel_op()
def py_k_imtq_start_measurement():
return k_imtq_start_measurement()
def py_k_imtq_start_actuation_current(current, time):
return k_imtq_start_actuation_current(<imtq_axis_data>current, <uint16_t>time)
def py_k_imtq_start_actuation_dipole(dipole, time):
return k_imtq_start_actuation_dipole(<imtq_axis_data>dipole, <uint16_t>time)
def py_k_imtq_start_actuation_PWM(pwm, time):
return k_imtq_start_actuation_PWM(<imtq_axis_data>pwm, <uint16_t>time)
def py_k_imtq_start_test(axis):
return k_imtq_start_test(<ADCSTestType>axis)
def py_k_imtq_start_detumble(time):
return k_imtq_start_detumble(<uint16_t>time)
<|end_of_text|>cimport libav as lib
from av.stream cimport Stream
from av.video.frame cimport VideoFrame
from av.video.swscontext cimport SwsContextProxy
cdef class VideoStream(Stream):
cdef readonly int buffer_size
# Hold onto the frames that we will decode until we have a full one.
cdef lib.AVFrame *raw_frame
cdef SwsContextProxy sws_proxy
cdef int last_w
cdef int last_h
cdef int encoded_frame_count
cpdef encode(self, VideoFrame frame=*)
<|end_of_text|>"""
flowfilter.gpu.update
--------------------
:copyright: 2015, Juan David Adarve, ANU. See AUTHORS for more details
:license: 3-clause BSD, see LICENSE for more details
"""
cimport flowfilter.gpu.image as gimg
import flowfilter.gpu.image as gimg
cdef class FlowUpdate:
def __cinit__(self,
gimg.GPUImage inputFlow = None,
gimg.GPUImage inputImage = None,
gimg.GPUImage inputImageGradient = None,
float gamma = 1.0,
float maxflow = 1.0):
if inputFlow == None or inputImage == None or inputImageGradient == None:
self.flowUpd.setGamma(gamma)
self.flowUpd.setMaxFlow(maxflow)
return
self.flowUpd = FlowUpdate_cpp(inputFlow.img, inputImage.img,
inputImageGradient.img, gamma, maxflow)
def __dealloc__(self):
# nothing to do
pass
def configure(self):
self.flowUpd.configure()
def compute(self):
self.flowUpd.compute()
def elapsedTime(self):
return self.flowUpd.elapsedTime()
def setInputFlow(self, gimg.GPUImage inputFlow):
self.flowUpd.setInputFlow(inputFlow.img)
def setInputImage(self, gimg.GPUImage image):
self.flowUpd.setInputImage(image.img)
def setInputImageGradient(self, gimg.GPUImage imageGradient):
self.flowUpd.setInputImageGradient(imageGradient.img)
def getUpdatedFlow(self):
cdef gimg.GPUImage updFlow = gimg.GPUImage()
updFlow.img = self.flowUpd.getUpdatedFlow()
return updFlow
def getUpdatedImage(self):
cdef gimg.GPUImage updImg = gimg.GPUImage()
updImg.img = self.flowUpd.getUpdatedImage()
return updImg | Cython |
property gamma:
def __get__(self):
return self.flowUpd.getGamma()
def __set__(self, float value):
self.flowUpd.setGamma(value)
def __del__(self):
pass
property maxflow:
def __get__(self):
return self.flowUpd.getMaxFlow()
def __set__(self, float value):
self.flowUpd.setMaxFlow(value)
def __del__(self):
pass
cdef class DeltaFlowUpdate:
def __cinit__(self,
gimg.GPUImage inputFlow = None,
gimg.GPUImage inputDeltaFlow = None,
gimg.GPUImage inputImageOld = None,
gimg.GPUImage inputImage = None,
gimg.GPUImage inputImageGradient = None,
float gamma = 1.0,
float maxflow = 1.0):
if (inputFlow == None or inputDeltaFlow == None or
inputImageOld == None or inputImage == None or
inputImageGradient == None):
self.deltaFlowUpd.setGamma(gamma)
self.deltaFlowUpd.setMaxFlow(maxflow)
return
self.deltaFlowUpd = DeltaFlowUpdate_cpp(inputFlow.img,
inputDeltaFlow.img, inputImageOld.img,
inputImage.img, inputImageGradient.img,
gamma, maxflow)
def __dealloc__(self):
# nothing to do
pass
def configure(self):
self.deltaFlowUpd.configure()
def compute(self):
self.deltaFlowUpd.compute()
def elapsedTime(self):
return self.deltaFlowUpd.elapsedTime()
def setInputFlow(self, gimg.GPUImage inputFlow):
self.deltaFlowUpd.setInputFlow(inputFlow.img)
def setInputDeltaFlow(self, gimg.GPUImage inputDeltaFlow):
self.deltaFlowUpd.setInputDeltaFlow(inputDeltaFlow.img)
def setInputImage(self, gimg.GPUImage image):
self.deltaFlowUpd.setInputImage(image.img)
def setInputImageGradient(self, gimg.GPUImage imageGradient):
self.deltaFlowUpd.setInputImageGradient(imageGradient.img)
def getUpdatedFlow(self):
cdef gimg.GPUImage updFlow = gimg.GPUImage()
updFlow.img = self.deltaFlowUpd.getUpdatedFlow()
return updFlow
def getUpdatedDeltaFlow(self):
cdef gimg.GPUImage updFlow = gimg.GPUImage()
updFlow.img = self.deltaFlowUpd.getUpdatedDeltaFlow()
return updFlow
def getUpdatedImage(self):
cdef gimg.GPUImage updImg = gimg.GPUImage()
updImg.img = self.deltaFlowUpd.getUpdatedImage()
return updImg
property gamma:
def __get__(self):
return self.deltaFlowUpd.getGamma()
def __set__(self, float value):
self.deltaFlowUpd.setGamma(value)
def __del__(self):
pass
property maxflow:
def __get__(self):
return self.deltaFlowUpd.getMaxFlow()
def __set__(self, float value):
self.deltaFlowUpd.setMaxFlow(value)
def __del__(self):
pass<|end_of_text|>from exception.custom_exception cimport raise_py_error
from genapi.cinode cimport INode
from baslerpylon.genapi.enum cimport ECallbackType
cdef extern from "GenApi/NodeCallBack.h" namespace 'GENAPI_NAMESPACE':
cdef cppclass CNodeCallback:
CNodeCallback(INode *pNode, ECallbackType CallbackType )
void delete "~CNodeCallback"() except +raise_py_error
#fires the callback if the type is right
void operator()( ECallbackType CallbackType ) except +raise_py_error
#destroys the object
void Destroy() except +raise_py_error
#returns the node the callback is registered to
INode* GetNode()<|end_of_text|># mode: run
# ticket: t723
# tag: lambda
def t723(a):
"""
>>> t723(2)()
4
>>> t723(2)(3)
9
"""
return lambda x=a: x * x
<|end_of_text|>"""
lluvia.core.image.image_filter_mode
-----------------------------------
:copyright: 2021, Juan David Adarve Bermudez. See AUTHORS for more details.
:license: Apache-2 license, see LICENSE for more details.
"""
from libc.stdint cimport uint32_t
cdef extern from 'lluvia/core/image/ImageFilterMode.h' namespace 'll':
cdef cppclass _ImageFilterMode 'll::ImageFilterMode':
pass
cdef enum _ImageFilterModeBits 'll::ImageFilterMode':
_ImageFilterModeBits_Nearest 'll::ImageFilterMode::Nearest'
_ImageFilterModeBits_Linear 'll::ImageFilterMode::Linear'
cpdef enum ImageFilterMode:
Nearest = <uint32_t> _ImageFilterModeBits_Nearest
Linear = <uint32_t> _ImageFilterModeBits_Linear
<|end_of_text|># -----------------------------------------------------------------------------
cdef extern from "Python.h":
bint PyBytes_CheckExact(object)
char* PyBytes_AsString(object) except NULL
Py_ssize_t PyBytes_Size(object) except -1
object PyBytes_FromStringAndSize(char*,Py_ssize_t)
object PyBytes_Join"_PyBytes_Join"(object,object)
# -----------------------------------------------------------------------------
cdef object PyPickle_dumps = None
cdef object PyPickle_loads = None
cdef object PyPickle_PROTOCOL = None
cdef object PyPickle_THRESHOLD = 1024**2 // 4 # 0.25 MiB
from pickle import dumps as PyPickle_dumps
from pickle import loads as PyPickle_loads
from pickle import HIGHEST_PROTOCOL as PyPickle_PROTOCOL
if Py_GETENV(b"MPI4PY_PICKLE_PROTOCOL")!= NULL:
PyPickle_PROTOCOL = int(Py_GETENV(b"MPI4PY_PICKLE_PROTOCOL"))
if Py_GETENV(b"MPI4PY_PICKLE_THRESHOLD")!= NULL:
PyPickle_THRESHOLD = int(Py_GETENV(b"MPI4PY_PICKLE_THRESHOLD"))
cdef class Pickle:
"""
Pickle/unpickle Python objects.
"""
cdef object ob_dumps
cdef object ob_loads
cdef object ob_PROTO
cdef object ob_THRES
def __cinit__(self, *args, **kwargs):
<void> args # unused
<void> kwargs # unused
self.ob_dumps = PyPickle_dumps
self.ob_loads = PyPickle_loads
self.ob_PROTO = PyPickle_PROTOCOL
self.ob_THRES = PyPickle_THRESHOLD
def __init__(
self,
dumps: Callable[[Any, int], bytes] | None = None,
loads: Callable[[Buffer], Any] | None = None,
protocol: int | None = None,
threshold: int | None = None,
) -> None:
if dumps is None:
dumps = PyPickle_dumps
if loads is None:
loads = PyPickle_loads
if protocol is None:
if dumps is PyPickle_dumps:
protocol = PyPickle_PROTOCOL
if threshold is None:
threshold = PyPickle_THRESHOLD
self.ob_dumps = dumps
self.ob_loads = loads
self.ob_PROTO = protocol
self.ob_THRES = threshold
def dumps(
self,
obj: Any,
) -> bytes:
"""
Serialize object to pickle data stream.
"""
return cdumps(self, obj)
def loads(
self,
data: Buffer,
) -> Any:
"""
Deserialize object from pickle data stream.
"""
return cloads(self, data)
def dumps_oob(
self,
obj: Any,
) -> tuple[bytes, list[memory]]:
"""
Serialize object to pickle data stream and out-of-band buffers.
"""
return cdumps_oob(self, obj)
def loads_oob(
self,
data: Buffer,
buffers: Iterable[Buffer],
) -> Any:
"""
Deserialize object from pickle data stream and out-of-band buffers.
"""
return cloads_oob(self, data, buffers)
property PROTOCOL:
"""Protocol version."""
def __get__(self) -> int | None:
return self.ob_PROTO
def __set__(self, protocol: int | None):
if protocol is None:
if self.ob_dumps is PyPickle_dumps:
protocol = PyPickle_PROTOCOL
self.ob_PROTO = protocol
property THRESHOLD:
"""Out-of-band threshold."""
def __get__(self) -> int:
return self.ob_THRES
def __set__(self, threshold: int | None):
if threshold is None:
threshold = PyPickle_THRESHOLD
self.ob_THRES = threshold
cdef Pickle PyMPI_PICKLE = Pickle()
pickle = PyMPI_PICKLE
# -----------------------------------------------------------------------------
cdef int have_pickle5 = -1 #~> legacy
cdef object PyPickle5_dumps = None #~> legacy
cdef object PyPickle5_loads = None #~> legacy
cdef int import_pickle5() except -1: #~> legacy
global | Cython |
have_pickle5 #~> legacy
global PyPickle5_dumps #~> legacy
global PyPickle5_loads #~> legacy
if have_pickle5 < 0: #~> legacy
try: #~> legacy
from pickle5 import dumps as PyPickle5_dumps #~> legacy
from pickle5 import loads as PyPickle5_loads #~> legacy
have_pickle5 = 1 #~> legacy
except ImportError: #~> legacy
PyPickle5_dumps = None #~> legacy
PyPickle5_loads = None #~> legacy
have_pickle5 = 0 #~> legacy
return have_pickle5 #~> legacy
cdef object get_buffer_callback(list buffers, Py_ssize_t threshold):
def buffer_callback(ob):
cdef memory buf = getbuffer(ob, 1, 0)
if buf.view.len >= threshold:
buffers.append(buf)
return False
else:
return True
return buffer_callback
cdef object cdumps_oob(Pickle pkl, object obj):
cdef object pkl_dumps = pkl.ob_dumps
if PY_VERSION_HEX < 0x03080000: #~> legacy
if pkl_dumps is PyPickle_dumps: #~> legacy
if not import_pickle5(): #~> legacy
return cdumps(pkl, obj), [] #~> legacy
pkl_dumps = PyPickle5_dumps #~> legacy
cdef object protocol = pkl.ob_PROTO
if protocol is None:
protocol = PyPickle_PROTOCOL #~> uncovered
protocol = max(protocol, 5)
cdef list buffers = []
cdef Py_ssize_t threshold = pkl.ob_THRES
cdef object buf_cb = get_buffer_callback(buffers, threshold)
cdef object data = pkl_dumps(obj, protocol, buffer_callback=buf_cb)
return data, buffers
cdef object cloads_oob(Pickle pkl, object data, object buffers):
cdef object pkl_loads = pkl.ob_loads
if PY_VERSION_HEX < 0x03080000: #~> legacy
if pkl_loads is PyPickle_loads: #~> legacy
if not import_pickle5(): #~> legacy
return cloads(pkl, data) #~> legacy
pkl_loads = PyPickle5_loads #~> legacy
return pkl_loads(data, buffers=buffers)
# -----------------------------------------------------------------------------
cdef object cdumps(Pickle pkl, object obj):
if pkl.ob_PROTO is not None:
return pkl.ob_dumps(obj, pkl.ob_PROTO)
else:
return pkl.ob_dumps(obj)
cdef object cloads(Pickle pkl, object buf):
return pkl.ob_loads(buf)
cdef object pickle_dump(Pickle pkl, object obj, void **p, MPI_Count *n):
cdef object buf = cdumps(pkl, obj)
p[0] = PyBytes_AsString(buf)
n[0] = PyBytes_Size(buf)
return buf
cdef object pickle_load(Pickle pkl, void *p, MPI_Count n):
if p == NULL or n == 0: return None
return cloads(pkl, mpibuf(p, n))
cdef object pickle_dumpv(Pickle pkl, object obj, void **p, int n, MPI_Count cnt[], MPI_Aint dsp[]):
cdef Py_ssize_t m=n
cdef object items
if obj is None: items = [None] * m
else: items = list(obj)
m = len(items)
if m!= n:
raise ValueError(f"expecting {n} items, got {m}")
cdef MPI_Count c=0
cdef MPI_Aint d=0
for i in range(m):
items[i] = pickle_dump(pkl, items[i], p, &c)
cnt[i] = c; dsp[i] = d; d = d + <MPI_Aint>c
cdef object buf = PyBytes_Join(b'', items)
p[0] = PyBytes_AsString(buf)
return buf
cdef object pickle_loadv(Pickle pkl, void *p, int n, MPI_Count cnt[], MPI_Aint dsp[]):
cdef Py_ssize_t m=n
cdef object items = [None] * m
if p == NULL: return items
for i in range(m):
items[i] = pickle_load(pkl, <char*>p + dsp[i], cnt[i])
return items
cdef object pickle_alloc(void **p, MPI_Count n):
cdef object buf = PyBytes_FromStringAndSize(NULL, <MPI_Aint>n)
p[0] = PyBytes_AsString(buf)
return buf
cdef object pickle_allocv(void **p, int n, MPI_Count cnt[], MPI_Aint dsp[]):
cdef MPI_Count d=0
for i in range(n):
dsp[i] = <MPI_Aint> d
d += cnt[i]
return pickle_alloc(p, d)
cdef inline object allocate_count_displ(int n, MPI_Count **p, MPI_Aint **q):
cdef object mem1 = allocate(n, sizeof(MPI_Count), p)
cdef object mem2 = allocate(n, sizeof(MPI_Aint), q)
return (mem1, mem2)
# -----------------------------------------------------------------------------
cdef object PyMPI_send(object obj, int dest, int tag,
MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
#
cdef object tmps = None
if dest!= MPI_PROC_NULL:
tmps = pickle_dump(pickle, obj, &sbuf, &scount)
with nogil: CHKERR( MPI_Send_c(
sbuf, scount, stype,
dest, tag, comm) )
return None
cdef object PyMPI_bsend(object obj, int dest, int tag,
MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
#
cdef object tmps = None
if dest!= MPI_PROC_NULL:
tmps = pickle_dump(pickle, obj, &sbuf, &scount)
with nogil: CHKERR( MPI_Bsend_c(
sbuf, scount, stype,
dest, tag, comm) )
return None
cdef object PyMPI_ssend(object obj, int dest, int tag,
MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
#
cdef object tmps = None
if dest!= MPI_PROC_NULL:
tmps = pickle_dump(pickle, obj, &sbuf, &scount)
with nogil: CHKERR( MPI_Ssend_c(
sbuf, scount, stype,
dest, tag, comm) )
return None
# -----------------------------------------------------------------------------
cdef object PyMPI_recv_obarg(object obj, int source, int tag,
MPI_Comm comm, MPI_Status *status):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *rbuf = NULL
cdef MPI_Count rcount = 0
cdef MPI_Datatype rtype = MPI_BYTE
cdef MPI_Status rsts
cdef object rmsg = None
cdef MPI_Aint rlen = 0
#
PyErr_WarnFormat(
UserWarning, 1, b"%s",
b"the 'buf' argument is deprecated",
)
#
if source!= MPI_PROC_NULL:
if is_integral(obj):
rcount = <MPI_Count> obj
rmsg = pickle_alloc(&rbuf, rcount)
else:
rmsg = asbuffer_w(obj, &rbuf, &rlen)
rcount = <MPI_Count> rlen
if status == MPI_STATUS_IGNORE:
status = &rsts
<void> rmsg
with nogil:
CHKERR( MPI_Recv_c(
rbuf, rcount, rtype,
source, tag, comm, status) )
if source!= MPI_PROC_NULL:
CHKERR( MPI_Get_count_c(status, rtype, &rcount) )
#
if rcount <= 0: return None
return pickle_load(pickle, rbuf, rcount)
cdef object PyMPI_recv_match(object obj, int source, int tag,
MPI_Comm comm, MPI_Status *status):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *rbuf = NULL
cdef MPI_Count rcount = 0
cdef MPI_Datatype rtype = MPI_BYTE | Cython |
#
cdef MPI_Message match = MPI_MESSAGE_NULL
cdef MPI_Status rsts
<void> obj # unused
#
with nogil:
CHKERR( MPI_Mprobe(source, tag, comm, &match, &rsts) )
CHKERR( MPI_Get_count_c(&rsts, rtype, &rcount) )
cdef object tmpr = pickle_alloc(&rbuf, rcount)
with nogil:
CHKERR( MPI_Mrecv_c(
rbuf, rcount, rtype, &match, status) )
#
if rcount <= 0: return None
return pickle_load(pickle, rbuf, rcount)
cdef object PyMPI_recv_probe(object obj, int source, int tag,
MPI_Comm comm, MPI_Status *status):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *rbuf = NULL
cdef MPI_Count rcount = 0
cdef MPI_Datatype rtype = MPI_BYTE
#
cdef MPI_Status rsts
cdef object tmpr
<void> obj # unused
#
with PyMPI_Lock(comm, "recv"):
with nogil:
CHKERR( MPI_Probe(source, tag, comm, &rsts) )
CHKERR( MPI_Get_count_c(&rsts, rtype, &rcount) )
CHKERR( PyMPI_Status_get_source(&rsts, &source) )
CHKERR( PyMPI_Status_get_tag(&rsts, &tag) )
tmpr = pickle_alloc(&rbuf, rcount)
with nogil:
CHKERR( MPI_Recv_c(
rbuf, rcount, rtype,
source, tag, comm, status) )
#
if rcount <= 0: return None
return pickle_load(pickle, rbuf, rcount)
cdef object PyMPI_recv(object obj, int source, int tag,
MPI_Comm comm, MPI_Status *status):
if obj is not None:
return PyMPI_recv_obarg(obj, source, tag, comm, status)
elif options.recv_mprobe:
return PyMPI_recv_match(obj, source, tag, comm, status)
else:
return PyMPI_recv_probe(obj, source, tag, comm, status)
# -----------------------------------------------------------------------------
cdef object PyMPI_isend(object obj, int dest, int tag,
MPI_Comm comm, MPI_Request *request):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
#
cdef object smsg = None
if dest!= MPI_PROC_NULL:
smsg = pickle_dump(pickle, obj, &sbuf, &scount)
with nogil: CHKERR( MPI_Isend_c(
sbuf, scount, stype,
dest, tag, comm, request) )
return smsg
cdef object PyMPI_ibsend(object obj, int dest, int tag,
MPI_Comm comm, MPI_Request *request):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
#
cdef object smsg = None
if dest!= MPI_PROC_NULL:
smsg = pickle_dump(pickle, obj, &sbuf, &scount)
with nogil: CHKERR( MPI_Ibsend_c(
sbuf, scount, stype,
dest, tag, comm, request) )
return smsg
cdef object PyMPI_issend(object obj, int dest, int tag,
MPI_Comm comm, MPI_Request *request):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
#
cdef object smsg = None
if dest!= MPI_PROC_NULL:
smsg = pickle_dump(pickle, obj, &sbuf, &scount)
with nogil: CHKERR( MPI_Issend_c(
sbuf, scount, stype,
dest, tag, comm, request) )
return smsg
cdef object PyMPI_irecv(object obj, int source, int tag,
MPI_Comm comm, MPI_Request *request):
#
cdef void *rbuf = NULL
cdef MPI_Aint rlen = 0
cdef MPI_Count rcount = 0
cdef MPI_Datatype rtype = MPI_BYTE
#
cdef object rmsg = None
if source!= MPI_PROC_NULL:
if obj is None:
rcount = options.irecv_bufsz
obj = pickle_alloc(&rbuf, rcount)
rmsg = asbuffer_r(obj, NULL, NULL)
elif is_integral(obj):
rcount = <MPI_Count> obj
obj = pickle_alloc(&rbuf, rcount)
rmsg = asbuffer_r(obj, NULL, NULL)
else:
rmsg = asbuffer_w(obj, &rbuf, &rlen)
rcount = <MPI_Count> rlen
with nogil: CHKERR( MPI_Irecv_c(
rbuf, rcount, rtype,
source, tag, comm, request) )
return rmsg
# -----------------------------------------------------------------------------
cdef object PyMPI_sendrecv(object sobj, int dest, int sendtag,
object robj, int source, int recvtag,
MPI_Comm comm, MPI_Status *status):
cdef MPI_Request request = MPI_REQUEST_NULL
sobj = PyMPI_isend(sobj, dest, sendtag, comm, &request)
robj = PyMPI_recv (robj, source, recvtag, comm, status)
with nogil: CHKERR( MPI_Wait(&request, MPI_STATUS_IGNORE) )
return robj
# -----------------------------------------------------------------------------
cdef object PyMPI_load(MPI_Status *status, object ob):
cdef Pickle pickle = PyMPI_PICKLE
cdef MPI_Count rcount = 0
cdef MPI_Datatype rtype = MPI_BYTE
if type(ob) is not memory: return None
CHKERR( MPI_Get_count_c(status, rtype, &rcount) )
if rcount <= 0: return None
cdef void *rbuf = (<memory>ob).view.buf
return pickle_load(pickle, rbuf, rcount)
cdef object PyMPI_wait(Request request, Status status):
cdef object buf
#
cdef MPI_Status rsts
with nogil: CHKERR( MPI_Wait(&request.ob_mpi, &rsts) )
buf = request.ob_buf
if status is not None:
status.ob_mpi = rsts
if request.ob_mpi == MPI_REQUEST_NULL:
request.ob_buf = None
#
return PyMPI_load(&rsts, buf)
cdef object PyMPI_test(Request request, int *flag, Status status):
cdef object buf = None
#
cdef MPI_Status rsts
with nogil: CHKERR( MPI_Test(&request.ob_mpi, flag, &rsts) )
if flag[0]:
buf = request.ob_buf
if status is not None:
status.ob_mpi = rsts
if request.ob_mpi == MPI_REQUEST_NULL:
request.ob_buf = None
#
if not flag[0]: return None
return PyMPI_load(&rsts, buf)
cdef object PyMPI_waitany(requests, int *index, Status status):
cdef object buf = None
#
cdef int count = 0
cdef MPI_Request *irequests = NULL
cdef MPI_Status rsts
#
cdef tmp = acquire_rs(requests, None, &count, &irequests, NULL)
try:
with nogil: CHKERR( MPI_Waitany(count, irequests, index, &rsts) )
if index[0]!= MPI_UNDEFINED:
buf = (<Request>requests[index[0]]).ob_buf
if status is not None:
status.ob_mpi = rsts
finally:
release_rs(requests, None, count, irequests, 0, NULL)
#
if index[0] == MPI_UNDEFINED: return None
return PyMPI_load(&rsts, buf)
cdef object PyMPI_testany(requests, int *index, int *flag, Status status):
cdef object buf = None
#
cdef int count = 0
cdef MPI_Request *irequests = NULL
cdef MPI_Status rsts
#
cdef tmp = acquire_rs(requests, None, &count, &irequests, NULL)
try:
with nogil: CHKERR( MPI_Testany(count, irequests, index, flag, &rsts) )
if index[0]!= MPI_UNDEFINED:
buf = (<Request>requests[index[0]]).ob_buf
if status is not None:
status.ob_mpi = rsts
finally:
release_rs(requests, None, count, irequests, 0, NULL)
#
if index[0] == MPI_UNDEFINED: return None
if not | Cython |
flag[0]: return None
return PyMPI_load(&rsts, buf)
cdef object PyMPI_waitall(requests, statuses):
cdef object bufs = None
#
cdef int count = 0
cdef MPI_Request *irequests = NULL
cdef MPI_Status *istatuses = MPI_STATUSES_IGNORE
#
cdef tmp = acquire_rs(requests, True, &count, &irequests, &istatuses)
try:
with nogil: CHKERR( MPI_Waitall(count, irequests, istatuses) )
bufs = [(<Request>requests[i]).ob_buf for i in range(count)]
finally:
release_rs(requests, statuses, count, irequests, count, istatuses)
#
return [PyMPI_load(&istatuses[i], bufs[i]) for i in range(count)]
cdef object PyMPI_testall(requests, int *flag, statuses):
cdef object bufs = None
#
cdef int count = 0
cdef MPI_Request *irequests = NULL
cdef MPI_Status *istatuses = MPI_STATUSES_IGNORE
#
cdef tmp = acquire_rs(requests, True, &count, &irequests, &istatuses)
try:
with nogil: CHKERR( MPI_Testall(count, irequests, flag, istatuses) )
if flag[0]:
bufs = [(<Request>requests[i]).ob_buf for i in range(count)]
finally:
release_rs(requests, statuses, count, irequests, count, istatuses)
#
if not flag[0]: return None
return [PyMPI_load(&istatuses[i], bufs[i]) for i in range(count)]
cdef object PyMPI_waitsome(requests, statuses):
cdef object bufs = None
cdef object indices = None
cdef object objects = None
#
cdef int incount = 0
cdef MPI_Request *irequests = NULL
cdef int outcount = MPI_UNDEFINED, *iindices = NULL
cdef MPI_Status *istatuses = MPI_STATUSES_IGNORE
#
cdef tmp1 = acquire_rs(requests, True, &incount, &irequests, &istatuses)
cdef tmp2 = newarray(incount, &iindices)
try:
with nogil: CHKERR( MPI_Waitsome(
incount, irequests, &outcount, iindices, istatuses) )
if outcount!= MPI_UNDEFINED:
bufs = [
(<Request>requests[iindices[i]]).ob_buf
for i in range(outcount)
]
finally:
release_rs(requests, statuses, incount, irequests, outcount, istatuses)
#
if outcount!= MPI_UNDEFINED:
indices = [iindices[i] for i in range(outcount)]
objects = [PyMPI_load(&istatuses[i], bufs[i]) for i in range(outcount)]
return (indices, objects)
cdef object PyMPI_testsome(requests, statuses):
cdef object bufs = None
cdef object indices = None
cdef object objects = None
#
cdef int incount = 0
cdef MPI_Request *irequests = NULL
cdef int outcount = MPI_UNDEFINED, *iindices = NULL
cdef MPI_Status *istatuses = MPI_STATUSES_IGNORE
#
cdef tmp1 = acquire_rs(requests, True, &incount, &irequests, &istatuses)
cdef tmp2 = newarray(incount, &iindices)
try:
with nogil: CHKERR( MPI_Testsome(
incount, irequests, &outcount, iindices, istatuses) )
if outcount!= MPI_UNDEFINED:
bufs = [
(<Request>requests[iindices[i]]).ob_buf
for i in range(outcount)
]
finally:
release_rs(requests, statuses, incount, irequests, outcount, istatuses)
#
if outcount!= MPI_UNDEFINED:
indices = [iindices[i] for i in range(outcount)]
objects = [PyMPI_load(&istatuses[i], bufs[i])for i in range(outcount)]
return (indices, objects)
# -----------------------------------------------------------------------------
cdef object PyMPI_probe(int source, int tag,
MPI_Comm comm, MPI_Status *status):
with nogil: CHKERR( MPI_Probe(source, tag, comm, status) )
return True
cdef object PyMPI_iprobe(int source, int tag,
MPI_Comm comm, MPI_Status *status):
cdef int flag = 0
with nogil: CHKERR( MPI_Iprobe(source, tag, comm, &flag, status) )
return <bint>flag
cdef object PyMPI_mprobe(int source, int tag, MPI_Comm comm,
MPI_Message *message, MPI_Status *status):
cdef void* rbuf = NULL
cdef MPI_Count rcount = 0
cdef MPI_Datatype rtype = MPI_BYTE
cdef MPI_Status rsts
if (status == MPI_STATUS_IGNORE): status = &rsts
with nogil: CHKERR( MPI_Mprobe(source, tag, comm, message, status) )
if message[0] == MPI_MESSAGE_NO_PROC: return None
CHKERR( MPI_Get_count_c(status, rtype, &rcount) )
cdef object rmsg = pickle_alloc(&rbuf, rcount)
return rmsg
cdef object PyMPI_improbe(int source, int tag, MPI_Comm comm, int *flag,
MPI_Message *message, MPI_Status *status):
cdef void* rbuf = NULL
cdef MPI_Count rcount = 0
cdef MPI_Datatype rtype = MPI_BYTE
cdef MPI_Status rsts
if (status == MPI_STATUS_IGNORE): status = &rsts
with nogil: CHKERR( MPI_Improbe(source, tag, comm, flag, message, status) )
if flag[0] == 0 or message[0] == MPI_MESSAGE_NO_PROC: return None
CHKERR( MPI_Get_count_c(status, rtype, &rcount) )
cdef object rmsg = pickle_alloc(&rbuf, rcount)
return rmsg
cdef object PyMPI_mrecv(object rmsg,
MPI_Message *message, MPI_Status *status):
cdef Pickle pickle = PyMPI_PICKLE
cdef void* rbuf = NULL
cdef MPI_Aint rlen = 0
cdef MPI_Datatype rtype = MPI_BYTE
if message[0] == MPI_MESSAGE_NO_PROC:
rmsg = None
elif rmsg is None:
pass
elif PyBytes_CheckExact(rmsg):
rmsg = asbuffer_r(rmsg, &rbuf, &rlen)
else:
rmsg = asbuffer_w(rmsg, &rbuf, &rlen) #~> unreachable
cdef MPI_Count rcount = <MPI_Count> rlen
with nogil: CHKERR( MPI_Mrecv_c(
rbuf, rcount, rtype, message, status) )
rmsg = pickle_load(pickle, rbuf, rcount)
return rmsg
cdef object PyMPI_imrecv(object rmsg,
MPI_Message *message, MPI_Request *request):
cdef void* rbuf = NULL
cdef MPI_Aint rlen = 0
cdef MPI_Datatype rtype = MPI_BYTE
if message[0] == MPI_MESSAGE_NO_PROC:
rmsg = None
elif rmsg is None:
pass
elif PyBytes_CheckExact(rmsg):
rmsg = asbuffer_r(rmsg, &rbuf, &rlen)
else:
rmsg = asbuffer_w(rmsg, &rbuf, &rlen) #~> unreachable
cdef MPI_Count rcount = <MPI_Count> rlen
with nogil: CHKERR( MPI_Imrecv_c(
rbuf, rcount, rtype, message, request) )
return rmsg
# -----------------------------------------------------------------------------
cdef object PyMPI_barrier(MPI_Comm comm):
with nogil: CHKERR( MPI_Barrier(comm) )
return None
cdef object PyMPI_bcast(object obj, int root, MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *buf = NULL
cdef MPI_Count count = 0
cdef MPI_Datatype dtype = MPI_BYTE
#
cdef int dosend=0, dorecv=0
cdef int inter=0, rank=0
CHKERR( MPI_Comm_test_inter(comm, &inter) )
if inter:
if root == MPI_PROC_NULL:
dosend=0; dorecv=0;
elif root == MPI_ROOT:
dosend=1; dorecv=0;
else:
dosend=0; dorecv=1;
else:
CHKERR( MPI_Comm_rank(comm, &rank) )
if root == rank:
dosend=1; dorecv=1;
else:
dosend=0; dorecv=1;
#
cdef object | Cython |
smsg = None
cdef object rmsg = None
#
if dosend: smsg = pickle_dump(pickle, obj, &buf, &count)
if dosend and dorecv: rmsg = smsg
with PyMPI_Lock(comm, "bcast"):
with nogil: CHKERR( MPI_Bcast_c(
&count, 1, MPI_COUNT,
root, comm) )
if dorecv and not dosend:
rmsg = pickle_alloc(&buf, count)
with nogil: CHKERR( MPI_Bcast_c(
buf, count, dtype,
root, comm) )
if dorecv: rmsg = pickle_load(pickle, buf, count)
#
return rmsg
cdef object PyMPI_gather(object sendobj, int root, MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
cdef void *rbuf = NULL
cdef MPI_Count *rcounts = NULL
cdef MPI_Aint *rdispls = NULL
cdef MPI_Datatype rtype = MPI_BYTE
#
cdef int dosend=0, dorecv=0
cdef int inter=0, size=0, rank=0
CHKERR( MPI_Comm_test_inter(comm, &inter) )
if inter:
CHKERR( MPI_Comm_remote_size(comm, &size) )
if root == MPI_PROC_NULL:
dosend=0; dorecv=0;
elif root == MPI_ROOT:
dosend=0; dorecv=1;
else:
dosend=1; dorecv=0;
else:
CHKERR( MPI_Comm_size(comm, &size) )
CHKERR( MPI_Comm_rank(comm, &rank) )
if root == rank:
dosend=1; dorecv=1;
else:
dosend=1; dorecv=0;
#
cdef object tmps = None
cdef object rmsg = None
cdef object tmp1
#
if dorecv: tmp1 = allocate_count_displ(size, &rcounts, &rdispls)
if dosend: tmps = pickle_dump(pickle, sendobj, &sbuf, &scount)
with PyMPI_Lock(comm, "gather"):
with nogil: CHKERR( MPI_Gather_c(
&scount, 1, MPI_COUNT,
rcounts, 1, MPI_COUNT,
root, comm) )
if dorecv: rmsg = pickle_allocv(&rbuf, size, rcounts, rdispls)
with nogil: CHKERR( MPI_Gatherv_c(
sbuf, scount, stype,
rbuf, rcounts, rdispls, rtype,
root, comm) )
if dorecv: rmsg = pickle_loadv(pickle, rbuf, size, rcounts, rdispls)
#
return rmsg
cdef object PyMPI_scatter(object sendobj, int root, MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count *scounts = NULL
cdef MPI_Aint *sdispls = NULL
cdef MPI_Datatype stype = MPI_BYTE
cdef void *rbuf = NULL
cdef MPI_Count rcount = 0
cdef MPI_Datatype rtype = MPI_BYTE
#
cdef int dosend=0, dorecv=0
cdef int inter=0, size=0, rank=0
CHKERR( MPI_Comm_test_inter(comm, &inter) )
if inter:
CHKERR( MPI_Comm_remote_size(comm, &size) )
if root == MPI_PROC_NULL:
dosend=0; dorecv=0;
elif root == MPI_ROOT:
dosend=1; dorecv=0;
else:
dosend=0; dorecv=1;
else:
CHKERR( MPI_Comm_size(comm, &size) )
CHKERR( MPI_Comm_rank(comm, &rank) )
if root == rank:
dosend=1; dorecv=1;
else:
dosend=0; dorecv=1;
#
cdef object tmps = None
cdef object rmsg = None
cdef object tmp1
#
if dosend: tmp1 = allocate_count_displ(size, &scounts, &sdispls)
if dosend: tmps = pickle_dumpv(pickle, sendobj, &sbuf, size, scounts, sdispls)
with PyMPI_Lock(comm, "scatter"):
with nogil: CHKERR( MPI_Scatter_c(
scounts, 1, MPI_COUNT,
&rcount, 1, MPI_COUNT,
root, comm) )
if dorecv: rmsg = pickle_alloc(&rbuf, rcount)
with nogil: CHKERR( MPI_Scatterv_c(
sbuf, scounts, sdispls, stype,
rbuf, rcount, rtype,
root, comm) )
if dorecv: rmsg = pickle_load(pickle, rbuf, rcount)
#
return rmsg
cdef object PyMPI_allgather(object sendobj, MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
cdef void *rbuf = NULL
cdef MPI_Count *rcounts = NULL
cdef MPI_Aint *rdispls = NULL
cdef MPI_Datatype rtype = MPI_BYTE
#
cdef int inter=0, size=0
CHKERR( MPI_Comm_test_inter(comm, &inter) )
if inter:
CHKERR( MPI_Comm_remote_size(comm, &size) )
else:
CHKERR( MPI_Comm_size(comm, &size) )
#
cdef object tmps = None
cdef object rmsg = None
cdef object tmp1
#
tmp1 = allocate_count_displ(size, &rcounts, &rdispls)
tmps = pickle_dump(pickle, sendobj, &sbuf, &scount)
with PyMPI_Lock(comm, "allgather"):
with nogil: CHKERR( MPI_Allgather_c(
&scount, 1, MPI_COUNT,
rcounts, 1, MPI_COUNT,
comm) )
rmsg = pickle_allocv(&rbuf, size, rcounts, rdispls)
with nogil: CHKERR( MPI_Allgatherv_c(
sbuf, scount, stype,
rbuf, rcounts, rdispls, rtype,
comm) )
rmsg = pickle_loadv(pickle, rbuf, size, rcounts, rdispls)
#
return rmsg
cdef object PyMPI_alltoall(object sendobj, MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count *scounts = NULL
cdef MPI_Aint *sdispls = NULL
cdef MPI_Datatype stype = MPI_BYTE
cdef void *rbuf = NULL
cdef MPI_Count *rcounts = NULL
cdef MPI_Aint *rdispls = NULL
cdef MPI_Datatype rtype = MPI_BYTE
#
cdef int inter=0, size=0
CHKERR( MPI_Comm_test_inter(comm, &inter) )
if inter:
CHKERR( MPI_Comm_remote_size(comm, &size) )
else:
CHKERR( MPI_Comm_size(comm, &size) )
#
cdef object tmps = None
cdef object rmsg = None
cdef object tmp1, tmp2
#
tmp1 = allocate_count_displ(size, &scounts, &sdispls)
tmp2 = allocate_count_displ(size, &rcounts, &rdispls)
tmps = pickle_dumpv(pickle, sendobj, &sbuf, size, scounts, sdispls)
with PyMPI_Lock(comm, "alltoall"):
with nogil: CHKERR( MPI_Alltoall_c(
scounts, 1, MPI_COUNT,
rcounts, 1, MPI_COUNT,
comm) )
rmsg = pickle_allocv(&rbuf, size, rcounts, rdispls)
with nogil: CHKERR( MPI_Alltoallv_c(
sbuf, scounts, sdispls, stype,
rbuf, rcounts, rdispls, rtype,
comm) )
rmsg = pickle_loadv(pickle, rbuf, size, rcounts, rdispls)
#
return rmsg
cdef object PyMPI_neighbor_allgather(object sendobj, MPI_Comm comm):
| Cython |
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
cdef void *rbuf = NULL
cdef MPI_Count *rcounts = NULL
cdef MPI_Aint *rdispls = NULL
cdef MPI_Datatype rtype = MPI_BYTE
#
cdef int rsize=0
comm_neighbors_count(comm, &rsize, NULL)
#
cdef object tmps = None
cdef object rmsg = None
cdef object tmp1
#
tmp1 = allocate_count_displ(rsize, &rcounts, &rdispls)
for i in range(rsize): rcounts[i] = 0
tmps = pickle_dump(pickle, sendobj, &sbuf, &scount)
with PyMPI_Lock(comm, "neighbor_allgather"):
with nogil: CHKERR( MPI_Neighbor_allgather_c(
&scount, 1, MPI_COUNT,
rcounts, 1, MPI_COUNT,
comm) )
rmsg = pickle_allocv(&rbuf, rsize, rcounts, rdispls)
with nogil: CHKERR( MPI_Neighbor_allgatherv_c(
sbuf, scount, stype,
rbuf, rcounts, rdispls, rtype,
comm) )
rmsg = pickle_loadv(pickle, rbuf, rsize, rcounts, rdispls)
#
return rmsg
cdef object PyMPI_neighbor_alltoall(object sendobj, MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
#
cdef void *sbuf = NULL
cdef MPI_Count *scounts = NULL
cdef MPI_Aint *sdispls = NULL
cdef MPI_Datatype stype = MPI_BYTE
cdef void *rbuf = NULL
cdef MPI_Count *rcounts = NULL
cdef MPI_Aint *rdispls = NULL
cdef MPI_Datatype rtype = MPI_BYTE
#
cdef int ssize=0, rsize=0
comm_neighbors_count(comm, &rsize, &ssize)
#
cdef object tmps = None
cdef object rmsg = None
cdef object tmp1, tmp2
#
tmp1 = allocate_count_displ(ssize, &scounts, &sdispls)
tmp2 = allocate_count_displ(rsize, &rcounts, &rdispls)
for i in range(rsize): rcounts[i] = 0
tmps = pickle_dumpv(pickle, sendobj, &sbuf, ssize, scounts, sdispls)
with PyMPI_Lock(comm, "neighbor_alltoall"):
with nogil: CHKERR( MPI_Neighbor_alltoall_c(
scounts, 1, MPI_COUNT,
rcounts, 1, MPI_COUNT,
comm) )
rmsg = pickle_allocv(&rbuf, rsize, rcounts, rdispls)
with nogil: CHKERR( MPI_Neighbor_alltoallv_c(
sbuf, scounts, sdispls, stype,
rbuf, rcounts, rdispls, rtype,
comm) )
rmsg = pickle_loadv(pickle, rbuf, rsize, rcounts, rdispls)
#
return rmsg
# -----------------------------------------------------------------------------
cdef inline object _py_reduce(object seq, object op):
if seq is None: return None
cdef Py_ssize_t i, n = len(seq)
cdef object res = seq[0]
for i in range(1, n):
res = op(res, seq[i])
return res
cdef inline object _py_scan(object seq, object op):
if seq is None: return None
cdef Py_ssize_t i, n = len(seq)
for i in range(1, n):
seq[i] = op(seq[i-1], seq[i])
return seq
cdef inline object _py_exscan(object seq, object op):
if seq is None: return None
seq = _py_scan(seq, op)
seq.pop(-1)
seq.insert(0, None)
return seq
cdef object PyMPI_reduce_naive(object sendobj, object op,
int root, MPI_Comm comm):
cdef object items = PyMPI_gather(sendobj, root, comm)
return _py_reduce(items, op)
cdef object PyMPI_allreduce_naive(object sendobj, object op, MPI_Comm comm):
cdef object items = PyMPI_allgather(sendobj, comm)
return _py_reduce(items, op)
cdef object PyMPI_scan_naive(object sendobj, object op, MPI_Comm comm):
cdef object items = PyMPI_gather(sendobj, 0, comm)
items = _py_scan(items, op)
return PyMPI_scatter(items, 0, comm)
cdef object PyMPI_exscan_naive(object sendobj, object op, MPI_Comm comm):
cdef object items = PyMPI_gather(sendobj, 0, comm)
items = _py_exscan(items, op)
return PyMPI_scatter(items, 0, comm)
# -----
cdef inline object PyMPI_copy(object obj):
cdef Pickle pickle = PyMPI_PICKLE
cdef void *buf = NULL
cdef MPI_Count count = 0
obj = pickle_dump(pickle, obj, &buf, &count)
return pickle_load(pickle, buf, count)
cdef object PyMPI_send_p2p(object obj, int dst, int tag, MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
cdef void *sbuf = NULL
cdef MPI_Count scount = 0
cdef MPI_Datatype stype = MPI_BYTE
cdef object tmps = pickle_dump(pickle, obj, &sbuf, &scount)
with nogil: CHKERR( MPI_Send_c(&scount, 1, MPI_COUNT, dst, tag, comm) )
with nogil: CHKERR( MPI_Send_c(sbuf, scount, stype, dst, tag, comm) )
return None
cdef object PyMPI_recv_p2p(int src, int tag, MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
cdef void *rbuf = NULL
cdef MPI_Count rcount = 0
cdef MPI_Datatype rtype = MPI_BYTE
cdef MPI_Status *status = MPI_STATUS_IGNORE
with nogil: CHKERR( MPI_Recv_c(&rcount, 1, MPI_COUNT, src, tag, comm, status) )
cdef object tmpr = pickle_alloc(&rbuf, rcount)
with nogil: CHKERR( MPI_Recv_c(rbuf, rcount, rtype, src, tag, comm, status) )
return pickle_load(pickle, rbuf, rcount)
cdef object PyMPI_sendrecv_p2p(object obj,
int dst, int stag,
int src, int rtag,
MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
cdef void *sbuf = NULL, *rbuf = NULL
cdef MPI_Count scount = 0, rcount = 0
cdef MPI_Datatype dtype = MPI_BYTE
cdef object tmps = pickle_dump(pickle, obj, &sbuf, &scount)
with nogil: CHKERR( MPI_Sendrecv_c(
&scount, 1, MPI_COUNT, dst, stag,
&rcount, 1, MPI_COUNT, src, rtag,
comm, MPI_STATUS_IGNORE) )
cdef object tmpr = pickle_alloc(&rbuf, rcount)
with nogil: CHKERR( MPI_Sendrecv_c(
sbuf, scount, dtype, dst, stag,
rbuf, rcount, dtype, src, rtag,
comm, MPI_STATUS_IGNORE) )
return pickle_load(pickle, rbuf, rcount)
cdef object PyMPI_bcast_p2p(object obj, int root, MPI_Comm comm):
cdef Pickle pickle = PyMPI_PICKLE
cdef void *buf = NULL
cdef MPI_Count count = 0
cdef MPI_Datatype dtype = MPI_BYTE
cdef int rank = MPI_PROC_NULL
CHKERR( MPI_Comm_rank(comm, &rank) )
if root == rank: obj = pickle_dump(pickle, obj, &buf, &count)
with PyMPI_Lock(comm, "@bcast_p2p@"):
with nogil: CHKERR( MPI_Bcast_c(&count, 1, MPI_COUNT, root, comm) )
if root!= rank: obj = pickle_alloc(&buf, count)
with nogil: CHKERR( MPI_Bcast_c(buf, count, dtype, root, comm) )
return pickle_load(pickle, buf, count)
cdef object PyMPI_reduce_p2p(object sendobj, object op, int root,
MPI_Comm comm, int tag):
# Get communicator size and rank
cdef int size = | Cython |
MPI_UNDEFINED
cdef int rank = MPI_PROC_NULL
CHKERR( MPI_Comm_size(comm, &size) )
CHKERR( MPI_Comm_rank(comm, &rank) )
# Check root argument
if root < 0 or root >= size:
<void>MPI_Comm_call_errhandler(comm, MPI_ERR_ROOT)
raise MPIException(MPI_ERR_ROOT)
#
cdef object result = PyMPI_copy(sendobj)
cdef object tmp
# Compute reduction at process 0
cdef unsigned int umask = <unsigned int> 1
cdef unsigned int usize = <unsigned int> size
cdef unsigned int urank = <unsigned int> rank
cdef int target = 0
while umask < usize:
if (umask & urank)!= 0:
target = <int> ((urank & ~umask) % usize)
PyMPI_send_p2p(result, target, tag, comm)
else:
target = <int> (urank | umask)
if target < size:
tmp = PyMPI_recv_p2p(target, tag, comm)
result = op(result, tmp)
umask <<= 1
# Send reduction to root
if root!= 0:
if rank == 0:
PyMPI_send_p2p(result, root, tag, comm)
elif rank == root:
result = PyMPI_recv_p2p(0, tag, comm)
if rank!= root:
result = None
#
return result
cdef object PyMPI_scan_p2p(object sendobj, object op,
MPI_Comm comm, int tag):
# Get communicator size and rank
cdef int size = MPI_UNDEFINED
cdef int rank = MPI_PROC_NULL
CHKERR( MPI_Comm_size(comm, &size) )
CHKERR( MPI_Comm_rank(comm, &rank) )
#
cdef object result = PyMPI_copy(sendobj)
cdef object partial = result
cdef object tmp
# Compute prefix reduction
cdef unsigned int umask = <unsigned int> 1
cdef unsigned int usize = <unsigned int> size
cdef unsigned int urank = <unsigned int> rank
cdef int target = 0
while umask < usize:
target = <int> (urank ^ umask)
if target < size:
tmp = PyMPI_sendrecv_p2p(partial, target, tag,
target, tag, comm)
if rank > target:
partial = op(tmp, partial)
result = op(tmp, result)
else:
tmp = op(partial, tmp)
partial = tmp
umask <<= 1
#
return result
cdef object PyMPI_exscan_p2p(object sendobj, object op,
MPI_Comm comm, int tag):
# Get communicator size and rank
cdef int size = MPI_UNDEFINED
cdef int rank = MPI_PROC_NULL
CHKERR( MPI_Comm_size(comm, &size) )
CHKERR( MPI_Comm_rank(comm, &rank) )
#
cdef object result = PyMPI_copy(sendobj)
cdef object partial = result
cdef object tmp
# Compute prefix reduction
cdef unsigned int umask = <unsigned int> 1
cdef unsigned int usize = <unsigned int> size
cdef unsigned int urank = <unsigned int> rank
cdef unsigned int uflag = <unsigned int> 0
cdef int target = 0
while umask < usize:
target = <int> (urank ^ umask)
if target < size:
tmp = PyMPI_sendrecv_p2p(partial, target, tag,
target, tag, comm)
if rank > target:
partial = op(tmp, partial)
if uflag == 0:
result = tmp; uflag = 1
else:
result = op(tmp, result)
else:
tmp = op(partial, tmp)
partial = tmp
umask <<= 1
#
if rank == 0:
result = None
return result
# -----
cdef extern from * nogil:
int PyMPI_Commctx_intra(MPI_Comm,MPI_Comm*,int*)
int PyMPI_Commctx_inter(MPI_Comm,MPI_Comm*,int*,MPI_Comm*,int*)
cdef int PyMPI_Commctx_INTRA(MPI_Comm comm,
MPI_Comm *dupcomm, int *tag) except -1:
with PyMPI_Lock(comm, "@commctx_intra"):
CHKERR( PyMPI_Commctx_intra(comm, dupcomm, tag) )
return 0
cdef int PyMPI_Commctx_INTER(MPI_Comm comm,
MPI_Comm *dupcomm, int *tag,
MPI_Comm *localcomm, int *low_group) except -1:
with PyMPI_Lock(comm, "@commctx_inter"):
CHKERR( PyMPI_Commctx_inter(comm, dupcomm, tag,
localcomm, low_group) )
return 0
def _commctx_intra(
Intracomm comm: Intracomm,
) -> tuple[Intracomm, int]:
"""
Create/get intracommunicator duplicate.
"""
cdef int tag = MPI_UNDEFINED
cdef Intracomm dupcomm = <Intracomm>New(Intracomm)
PyMPI_Commctx_INTRA(comm.ob_mpi, &dupcomm.ob_mpi, &tag)
return (dupcomm, tag)
def _commctx_inter(
Intercomm comm: Intercomm,
) -> tuple[Intercomm, int, Intracomm, bool]:
"""
Create/get intercommunicator duplicate.
"""
cdef int tag = MPI_UNDEFINED, low_group = 0
cdef Intercomm dupcomm = <Intercomm>New(Intercomm)
cdef Intracomm localcomm = <Intracomm>New(Intracomm)
PyMPI_Commctx_INTER(comm.ob_mpi, &dupcomm.ob_mpi, &tag,
&localcomm.ob_mpi, &low_group)
return (dupcomm, tag, localcomm, <bint>low_group)
# -----
cdef object PyMPI_reduce_intra(object sendobj, object op,
int root, MPI_Comm comm):
cdef int tag = MPI_UNDEFINED
PyMPI_Commctx_INTRA(comm, &comm, &tag)
return PyMPI_reduce_p2p(sendobj, op, root, comm, tag)
cdef object PyMPI_reduce_inter(object sendobj, object op,
int root, MPI_Comm comm):
cdef int tag = MPI_UNDEFINED
cdef MPI_Comm localcomm = MPI_COMM_NULL
PyMPI_Commctx_INTER(comm, &comm, &tag, &localcomm, NULL)
# Get communicator remote size and rank
cdef int size = MPI_UNDEFINED
cdef int rank = MPI_PROC_NULL
CHKERR( MPI_Comm_remote_size(comm, &size) )
CHKERR( MPI_Comm_rank(comm, &rank) )
if root >= 0 and root < size:
# Reduce in local group and send to remote root
sendobj = PyMPI_reduce_p2p(sendobj, op, 0, localcomm, tag)
if rank == 0: PyMPI_send_p2p(sendobj, root, tag, comm)
return None
elif root == MPI_ROOT: # Receive from remote group
return PyMPI_recv_p2p(0, tag, comm)
elif root == MPI_PROC_NULL: # This process does nothing
return None
else: # Wrong root argument
<void>MPI_Comm_call_errhandler(comm, MPI_ERR_ROOT)
raise MPIException(MPI_ERR_ROOT)
cdef object PyMPI_allreduce_intra(object sendobj, object op, MPI_Comm comm):
cdef int tag = MPI_UNDEFINED
PyMPI_Commctx_INTRA(comm, &comm, &tag)
sendobj = PyMPI_reduce_p2p(sendobj, op, 0, comm, tag)
return PyMPI_bcast_p2p(sendobj, 0, comm)
cdef object PyMPI_allreduce_inter(object sendobj, object op, MPI_Comm comm):
cdef int tag = MPI_UNDEFINED
cdef int rank = MPI_PROC_NULL
cdef MPI_Comm localcomm = MPI_COMM_NULL
PyMPI_Commctx_INTER(comm, &comm, &tag, &localcomm, NULL)
CHKERR( MPI_Comm_rank(comm, &rank) )
# Reduce in local group, exchange, and broadcast in local group
sendobj = PyMPI_reduce_p2p(sendobj, op, 0, localcomm, tag)
if rank == 0:
sendobj = PyMPI_sendrecv_p2p(sendobj, 0, tag, 0, tag, comm)
return PyMPI_bcast_p2p(sendobj, 0, localcomm)
cdef object PyMPI_scan_intra(object sendobj, object op, MPI_Comm comm):
cdef int tag = MPI_UNDEFINED
PyMPI_Commctx_INTRA(comm, &comm, &tag)
return PyMPI_scan_p2p(sendobj, op, comm, tag)
cdef object PyMPI_exscan_intra(object sendobj, object op, MPI_Comm comm):
cdef int tag = MPI_UNDEFINED
PyMPI_Commctx_INTRA(comm, &comm, &tag)
return Py | Cython |
MPI_exscan_p2p(sendobj, op, comm, tag)
# -----
cdef inline bint comm_is_intra(MPI_Comm comm) except -1 nogil:
cdef int inter = 0
CHKERR( MPI_Comm_test_inter(comm, &inter) )
if inter: return 0
else: return 1
cdef object PyMPI_reduce(object sendobj, object op, int root, MPI_Comm comm):
if not options.fast_reduce:
return PyMPI_reduce_naive(sendobj, op, root, comm)
elif comm_is_intra(comm):
return PyMPI_reduce_intra(sendobj, op, root, comm)
else:
return PyMPI_reduce_inter(sendobj, op, root, comm)
cdef object PyMPI_allreduce(object sendobj, object op, MPI_Comm comm):
if not options.fast_reduce:
return PyMPI_allreduce_naive(sendobj, op, comm)
elif comm_is_intra(comm):
return PyMPI_allreduce_intra(sendobj, op, comm)
else:
return PyMPI_allreduce_inter(sendobj, op, comm)
cdef object PyMPI_scan(object sendobj, object op, MPI_Comm comm):
if not options.fast_reduce:
return PyMPI_scan_naive(sendobj, op, comm)
else:
return PyMPI_scan_intra(sendobj, op, comm)
cdef object PyMPI_exscan(object sendobj, object op, MPI_Comm comm):
if not options.fast_reduce:
return PyMPI_exscan_naive(sendobj, op, comm)
else:
return PyMPI_exscan_intra(sendobj, op, comm)
# -----------------------------------------------------------------------------
<|end_of_text|># -----------------------------------------------------------------------------
class MFNType(object):
"""
MFN type
Action of a matrix function on a vector.
- `KRYLOV`: Restarted Krylov solver.
- `EXPOKIT`: Implementation of the method in Expokit.
"""
KRYLOV = S_(MFNKRYLOV)
EXPOKIT = S_(MFNEXPOKIT)
class MFNConvergedReason(object):
CONVERGED_TOL = MFN_CONVERGED_TOL
CONVERGED_ITS = MFN_CONVERGED_ITS
DIVERGED_ITS = MFN_DIVERGED_ITS
DIVERGED_BREAKDOWN = MFN_DIVERGED_BREAKDOWN
CONVERGED_ITERATING = MFN_CONVERGED_ITERATING
ITERATING = MFN_CONVERGED_ITERATING
# -----------------------------------------------------------------------------
cdef class MFN(Object):
"""
MFN
"""
Type = MFNType
ConvergedReason = MFNConvergedReason
def __cinit__(self):
self.obj = <PetscObject*> &self.mfn
self.mfn = NULL
def view(self, Viewer viewer=None):
"""
Prints the MFN data structure.
Parameters
----------
viewer: Viewer, optional.
Visualization context; if not provided, the standard
output is used.
"""
cdef PetscViewer vwr = def_Viewer(viewer)
CHKERR( MFNView(self.mfn, vwr) )
def destroy(self):
"""
Destroys the MFN object.
"""
CHKERR( MFNDestroy(&self.mfn) )
self.mfn = NULL
return self
def reset(self):
"""
Resets the MFN object.
"""
CHKERR( MFNReset(self.mfn) )
def create(self, comm=None):
"""
Creates the MFN object.
Parameters
----------
comm: Comm, optional.
MPI communicator. If not provided, it defaults to all
processes.
"""
cdef MPI_Comm ccomm = def_Comm(comm, SLEPC_COMM_DEFAULT())
cdef SlepcMFN newmfn = NULL
CHKERR( MFNCreate(ccomm, &newmfn) )
SlepcCLEAR(self.obj); self.mfn = newmfn
return self
def setType(self, mfn_type):
"""
Selects the particular solver to be used in the MFN object.
Parameters
----------
mfn_type: `MFN.Type` enumerate
The solver to be used.
"""
cdef SlepcMFNType cval = NULL
mfn_type = str2bytes(mfn_type, &cval)
CHKERR( MFNSetType(self.mfn, cval) )
def getType(self):
"""
Gets the MFN type of this object.
Returns
-------
type: `MFN.Type` enumerate
The solver currently being used.
"""
cdef SlepcMFNType mfn_type = NULL
CHKERR( MFNGetType(self.mfn, &mfn_type) )
return bytes2str(mfn_type)
def getOptionsPrefix(self):
"""
Gets the prefix used for searching for all MFN options in the
database.
Returns
-------
prefix: string
The prefix string set for this MFN object.
"""
cdef const_char *prefix = NULL
CHKERR( MFNGetOptionsPrefix(self.mfn, &prefix) )
return bytes2str(prefix)
def setOptionsPrefix(self, prefix):
"""
Sets the prefix used for searching for all MFN options in the
database.
Parameters
----------
prefix: string
The prefix string to prepend to all MFN option requests.
"""
cdef const_char *cval = NULL
prefix = str2bytes(prefix, &cval)
CHKERR( MFNSetOptionsPrefix(self.mfn, cval) )
def appendOptionsPrefix(self, prefix):
"""
Appends to the prefix used for searching for all MFN options
in the database.
Parameters
----------
prefix: string
The prefix string to prepend to all MFN option requests.
"""
cdef const_char *cval = NULL
prefix = str2bytes(prefix, &cval)
CHKERR( MFNAppendOptionsPrefix(self.mfn, cval) )
def setFromOptions(self):
"""
Sets MFN options from the options database. This routine must
be called before `setUp()` if the user is to be allowed to set
the solver type.
"""
CHKERR( MFNSetFromOptions(self.mfn) )
def getTolerances(self):
"""
Gets the tolerance and maximum iteration count used by the
default MFN convergence tests.
Returns
-------
tol: float
The convergence tolerance.
max_it: int
The maximum number of iterations
"""
cdef PetscReal rval = 0
cdef PetscInt ival = 0
CHKERR( MFNGetTolerances(self.mfn, &rval, &ival) )
return (toReal(rval), toInt(ival))
def setTolerances(self, tol=None, max_it=None):
"""
Sets the tolerance and maximum iteration count used by the
default MFN convergence tests.
Parameters
----------
tol: float, optional
The convergence tolerance.
max_it: int, optional
The maximum number of iterations
"""
cdef PetscReal rval = PETSC_DEFAULT
cdef PetscInt ival = PETSC_DEFAULT
if tol is not None: rval = asReal(tol)
if max_it is not None: ival = asInt(max_it)
CHKERR( MFNSetTolerances(self.mfn, rval, ival) )
def getDimensions(self):
"""
Gets the dimension of the subspace used by the solver.
Returns
-------
ncv: int
Maximum dimension of the subspace to be used by the solver.
"""
cdef PetscInt ival = 0
CHKERR( MFNGetDimensions(self.mfn, &ival) )
return toInt(ival)
def setDimensions(self, ncv):
"""
Sets the dimension of the subspace to be used by the solver.
Parameters
----------
ncv: int
Maximum dimension of the subspace to be used by the
solver.
"""
cdef PetscInt ival = asInt(ncv)
CHKERR( MFNSetDimensions(self.mfn, ival) )
def getFN(self):
"""
Obtain the math function object associated to the MFN object.
Returns
-------
fn: FN
The math function context.
"""
cdef FN fn = FN()
CHKERR( MFNGetFN(self.mfn, &fn.fn) )
PetscINCREF(fn.obj)
return fn
def setFN(self, FN fn):
"""
Associates a math function object to the MFN object.
Parameters
----------
fn: FN
The math function context.
"""
CHKERR( MFNSetFN(self.mfn, fn.fn) )
def getBV(self):
"""
Obtain the basis vector object associated to the MFN object.
Returns
-------
bv: BV
The basis vectors context.
"""
cdef BV bv = BV()
CHKERR( MFNGetBV(self.mfn, &bv.bv) )
PetscINCREF(bv.obj)
return bv
def setBV(self, BV bv):
"""
Associates a basis vector object to the MFN object.
Parameters
| Cython |
----------
bv: BV
The basis vectors context.
"""
CHKERR( MFNSetBV(self.mfn, bv.bv) )
def getOperator(self):
"""
Gets the matrix associated with the MFN object.
Returns
-------
A: Mat
The matrix for which the matrix function is to be computed.
"""
cdef Mat A = Mat()
CHKERR( MFNGetOperator(self.mfn, &A.mat) )
PetscINCREF(A.obj)
return A
def setOperator(self, Mat A):
"""
Sets the matrix associated with the MFN object.
Parameters
----------
A: Mat
The problem matrix.
"""
CHKERR( MFNSetOperator(self.mfn, A.mat) )
#
def setMonitor(self, monitor, args=None, kargs=None):
"""
Appends a monitor function to the list of monitors.
"""
if monitor is None: return
cdef object monitorlist = self.get_attr('__monitor__')
if monitorlist is None:
monitorlist = []
self.set_attr('__monitor__', monitorlist)
CHKERR( MFNMonitorSet(self.mfn, MFN_Monitor, NULL, NULL) )
if args is None: args = ()
if kargs is None: kargs = {}
monitorlist.append((monitor, args, kargs))
def getMonitor(self):
"""
Gets the list of monitor functions.
"""
return self.get_attr('__monitor__')
def cancelMonitor(self):
"""
Clears all monitors for an `MFN` object.
"""
CHKERR( MFNMonitorCancel(self.mfn) )
self.set_attr('__monitor__', None)
#
def setUp(self):
"""
Sets up all the internal data structures necessary for the
execution of the eigensolver.
"""
CHKERR( MFNSetUp(self.mfn) )
def solve(self, Vec b, Vec x):
"""
Solves the matrix function problem. Given a vector b, the
vector x = f(A)*b is returned.
Parameters
----------
b: Vec
The right hand side vector.
x: Vec
The solution.
"""
CHKERR( MFNSolve(self.mfn, b.vec, x.vec) )
def solveTranspose(self, Vec b, Vec x):
"""
Solves the transpose matrix function problem. Given a vector b, the
vector x = f(A^T)*b is returned.
Parameters
----------
b: Vec
The right hand side vector.
x: Vec
The solution.
"""
CHKERR( MFNSolveTranspose(self.mfn, b.vec, x.vec) )
def getIterationNumber(self):
"""
Gets the current iteration number. If the call to `solve()` is
complete, then it returns the number of iterations carried out
by the solution method.
Returns
-------
its: int
Iteration number.
"""
cdef PetscInt ival = 0
CHKERR( MFNGetIterationNumber(self.mfn, &ival) )
return toInt(ival)
def getConvergedReason(self):
"""
Gets the reason why the `solve()` iteration was stopped.
Returns
-------
reason: `MFN.ConvergedReason` enumerate
Negative value indicates diverged, positive value
converged.
"""
cdef SlepcMFNConvergedReason val = MFN_CONVERGED_ITERATING
CHKERR( MFNGetConvergedReason(self.mfn, &val) )
return val
def setErrorIfNotConverged(self, flg=True):
"""
Causes `solve()` to generate an error if the solver has not converged.
Parameters
----------
flg: bool
True indicates you want the error generated.
"""
cdef PetscBool tval = flg
CHKERR( MFNSetErrorIfNotConverged(self.mfn, tval) )
def getErrorIfNotConverged(self):
"""
Return a flag indicating whether `solve()` will generate an
error if the solver does not converge.
Returns
-------
flg: bool
True indicates you want the error generated.
"""
cdef PetscBool tval = PETSC_FALSE
CHKERR( MFNGetErrorIfNotConverged(self.mfn, &tval) )
return toBool(tval)
#
property tol:
def __get__(self):
return self.getTolerances()[0]
def __set__(self, value):
self.setTolerances(tol=value)
property max_it:
def __get__(self):
return self.getTolerances()[1]
def __set__(self, value):
self.setTolerances(max_it=value)
property fn:
def __get__(self):
return self.getFN()
def __set__(self, value):
self.setBV(value)
property bv:
def __get__(self):
return self.getFN()
def __set__(self, value):
self.setBV(value)
# -----------------------------------------------------------------------------
del MFNType
del MFNConvergedReason
# -----------------------------------------------------------------------------
<|end_of_text|>#cython: c_string_type=unicode, c_string_encoding=utf8
'''
TODO:
- ensure that we correctly check allocation
- remove compat sdl usage (like SDL_SetAlpha must be replaced with sdl 1.3
call, not 1.2)
'''
include '../../lib/sdl2.pxi'
from kivy.core.image import ImageData
from kivy.compat import PY2
cdef dict sdl2_cache = {}
cdef list sdl2_cache_order = []
cdef class _TTFContainer:
cdef TTF_Font* font
def __cinit__(self):
self.font = NULL
def __dealloc__(self):
if self.font!= NULL:
TTF_CloseFont(self.font)
self.font = NULL
cdef class _SurfaceContainer:
cdef SDL_Surface* surface
cdef int w, h
def __cinit__(self, w, h):
self.surface = NULL
self.w = w
self.h = h
def __init__(self, w, h):
# XXX check on OSX to see if little endian/big endian make a difference
# here.
self.surface = SDL_CreateRGBSurface(0,
w, h, 32,
0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)
def __dealloc__(self):
if self.surface!= NULL:
SDL_FreeSurface(self.surface)
self.surface = NULL
def render(self, container, text, x, y):
cdef TTF_Font *font = _get_font(container)
cdef SDL_Color c
cdef SDL_Color oc
cdef SDL_Surface *st
cdef SDL_Surface *fgst
cdef SDL_Rect r
cdef SDL_Rect fgr
cdef list color = list(container.options['color'])
cdef list outline_color = list(container.options['outline_color'])
outline_width = container.options['outline_width']
if font == NULL:
return
c.a = oc.a = 255
c.r = <int>(color[0] * 255)
c.g = <int>(color[1] * 255)
c.b = <int>(color[2] * 255)
bytes_text = <bytes>text.encode('utf-8')
hinting = container.options['font_hinting']
if hinting == 'normal':
if TTF_GetFontHinting(font)!= TTF_HINTING_NORMAL:
TTF_SetFontHinting(font, TTF_HINTING_NORMAL)
elif hinting == 'light':
if TTF_GetFontHinting(font)!= TTF_HINTING_LIGHT:
TTF_SetFontHinting(font, TTF_HINTING_LIGHT)
elif hinting =='mono':
if TTF_GetFontHinting(font)!= TTF_HINTING_MONO:
TTF_SetFontHinting(font, TTF_HINTING_MONO)
elif hinting is None:
if TTF_GetFontHinting(font)!= TTF_HINTING_NONE:
TTF_SetFontHinting(font, TTF_HINTING_NONE)
if container.options['font_kerning']:
if TTF_GetFontKerning(font) == 0:
TTF_SetFontKerning(font, 1)
else:
if TTF_GetFontKerning(font)!= 0:
TTF_SetFontKerning(font, 0)
direction = container.options['font_direction']
if direction == 'ltr':
TTF_SetFontDirection(font, TTF_DIRECTION_LTR)
elif direction == 'rtl':
TTF_SetFontDirection(font, TTF_DIRECTION_RTL)
elif direction == 'ttb':
TTF_SetFontDirection(font, TTF_DIRECTION_TTB)
elif direction == 'btt':
TTF_SetFontDirection(font, TTF_DIRECTION_BTT)
fontscript = container.options['font_script_name']
TTF_SetFontScriptName(font, fontscript)
if outline_width:
TTF_SetFontOutline(font, outline_width)
oc.r = <int>(outline_color[0] * 255)
oc.g = <int>(outline_color[1] * 255 | Cython |
)
oc.b = <int>(outline_color[2] * 255)
st = (
TTF_RenderUTF8_Blended(font, <char *>bytes_text, oc)
if container.options['font_blended']
else TTF_RenderUTF8_Solid(font, <char *>bytes_text, oc)
)
TTF_SetFontOutline(font, 0)
else:
st = (
TTF_RenderUTF8_Blended(font, <char *>bytes_text, c)
if container.options['font_blended']
else TTF_RenderUTF8_Solid(font, <char *>bytes_text, c)
)
if st == NULL:
return
if outline_width:
fgst = (
TTF_RenderUTF8_Blended(font, <char *>bytes_text, c)
if container.options['font_blended']
else TTF_RenderUTF8_Solid(font, <char *>bytes_text, c)
)
if fgst == NULL:
SDL_FreeSurface(st)
return
fgr.x = outline_width
fgr.y = outline_width
fgr.w = fgst.w
fgr.h = fgst.h
SDL_SetSurfaceBlendMode(fgst, SDL_BLENDMODE_BLEND)
SDL_BlitSurface(fgst, NULL, st, &fgr)
SDL_FreeSurface(fgst)
r.x = x
r.y = y
r.w = st.w
r.h = st.h
SDL_SetSurfaceAlphaMod(st, <int>(color[3] * 255))
if container.options['line_height'] < 1:
"""
We are using SDL_BLENDMODE_BLEND only when line_height < 1 as a workaround.
Previously, We enabled SDL_BLENDMODE_BLEND also for text w/ line_height >= 1,
but created an unexpected behavior (See PR #6507 and issue #6508).
"""
SDL_SetSurfaceBlendMode(st, SDL_BLENDMODE_BLEND)
else:
SDL_SetSurfaceBlendMode(st, SDL_BLENDMODE_NONE)
SDL_BlitSurface(st, NULL, self.surface, &r)
SDL_FreeSurface(st)
def get_data(self):
cdef int datalen = self.surface.w * self.surface.h * 4
cdef bytes pixels = (<char *>self.surface.pixels)[:datalen]
data = ImageData(self.w, self.h, 'rgba', pixels)
return data
cdef TTF_Font *_get_font(self) except *:
cdef TTF_Font *fontobject = NULL
cdef _TTFContainer ttfc
cdef char *error
cdef str s_error
cdef bytes bytes_fontname
# fast path
fontid = self._get_font_id()
if fontid in sdl2_cache:
ttfc = sdl2_cache[fontid]
return ttfc.font
# ensure ttf is init.
if not TTF_WasInit():
TTF_Init()
# try first the file if it's a filename
fontname = self.options['font_name_r']
bytes_fontname = <bytes>fontname.encode('utf-8')
ext = fontname.rsplit('.', 1)
if len(ext) == 2:
# try to open the font if it has an extension
fontobject = TTF_OpenFont(bytes_fontname,
int(self.options['font_size']))
# fallback to search a system font
if fontobject == NULL:
s_error = SDL_GetError()
raise ValueError('{}: for font {}'.format(s_error, fontname))
# set underline and strikethrough style
style = TTF_STYLE_NORMAL
if self.options['underline']:
style = style | TTF_STYLE_UNDERLINE
if self.options['strikethrough']:
style = style | TTF_STYLE_STRIKETHROUGH
TTF_SetFontStyle(fontobject, style)
sdl2_cache[fontid] = ttfc = _TTFContainer()
ttfc.font = fontobject
sdl2_cache_order.append(fontid)
# to prevent too much file open, limit the number of opened fonts to 64
while len(sdl2_cache_order) > 64:
popid = sdl2_cache_order.pop(0)
ttfc = sdl2_cache[popid]
del sdl2_cache[popid]
ttfc = sdl2_cache[fontid]
return ttfc.font
def _get_extents(container, text):
cdef TTF_Font *font = _get_font(container)
cdef int w, h
outline_width = container.options['outline_width']
if font == NULL:
return 0, 0
if not PY2:
text = text.encode('utf-8')
bytes_text = <bytes>text
if outline_width:
TTF_SetFontOutline(font, outline_width)
TTF_SizeUTF8(font, <char *>bytes_text, &w, &h)
if outline_width:
TTF_SetFontOutline(font, 0)
return w, h
def _get_fontdescent(container):
return TTF_FontDescent(_get_font(container))
def _get_fontascent(container):
return TTF_FontAscent(_get_font(container))
<|end_of_text|># cython wrapper for libstuff
cimport cstuff
def do_fast_stuff(a, b):
return int(cstuff.doFastStuff(int(a), int(b)))
<|end_of_text|>#
# Copyright (c) 2021 by Kristoffer Paulsson <[email protected]>.
#
# This software is available under the terms of the MIT license. Parts are licensed under
# different terms if stated. The legal terms are attached to the LICENSE file and are
# made available on:
#
# https://opensource.org/licenses/MIT
#
# SPDX-License-Identifier: MIT
#
# Contributors:
# Kristoffer Paulsson - initial implementation
#
"""Support classes for the ctl."""
import datetime
import uuid
from pathlib import Path
from types import SimpleNamespace
from angelos.bin.nacl import Signer
from angelos.facade.facade import Facade
from angelos.lib.const import Const
from angelos.lib.policy.crypto import Crypto
from angelos.portfolio.collection import PrivatePortfolio
from angelos.portfolio.portfolio.setup import SetupPersonPortfolio, PersonData
ADMIN_ENTITY = PersonData(**{
"given_name": "John",
"names": ["John", "Admin"],
"family_name": "Roe",
"sex": "man",
"born": datetime.date(1970, 1, 1)
})
class AdminFacade(Facade):
"""Client admin facade to be used with the network authentication protocol."""
@classmethod
def setup(cls, signer: Signer):
"""Setup the admin facade using a signer."""
portfolio = SetupPersonPortfolio().perform(ADMIN_ENTITY, role=Const.A_ROLE_PRIMARY, server=False)
portfolio.privkeys.seed = signer.seed
list(portfolio.keys)[0].verify = signer.vk
for doc in portfolio.documents():
doc._fields["signature"].redo = True
doc.signature = None
if doc._fields["signature"].multiple:
Crypto.sign(doc, portfolio, multiple=True)
else:
Crypto.sign(doc, portfolio)
return cls(Path("~/"), None, portfolio=portfolio, role=Const.A_ROLE_PRIMARY, server=False)
@classmethod
def _setup(
cls, home_dir: Path, secret: bytes, portfolio: PrivatePortfolio,
vault_type: int, vault_role: int
) -> "VaultStorage":
return SimpleNamespace(
facade=None,
close=lambda: None,
archive=SimpleNamespace(
stats=lambda: SimpleNamespace(
node=uuid.UUID(int=0),
)
)
)
@classmethod
def _check_type(cls, portfolio: PrivatePortfolio, server: bool) -> None:
return Const.A_TYPE_ADMIN_CLIENT
<|end_of_text|>from quantlib.types cimport Real, Spread
from libcpp cimport bool
from libcpp.vector cimport vector
from cython.operator cimport dereference as deref, preincrement as preinc
from quantlib.handle cimport make_shared, shared_ptr, static_pointer_cast
from quantlib.time.date cimport Date, date_from_qldate
from quantlib.time.daycounter cimport DayCounter
from quantlib.indexes.ibor_index cimport OvernightIndex
cimport quantlib.indexes._ibor_index as _ii
cimport quantlib._cashflow as _cf
from.rateaveraging cimport RateAveraging
from. cimport _overnight_indexed_coupon as _oic
cdef class OvernightIndexedCoupon(FloatingRateCoupon):
def __init__(self, Date payment_date not None, Real nominal,
Date start_date not None, Date end_date not None,
OvernightIndex index not None, Real gearing=1., Spread spread=0.,
Date ref_period_start=Date(), Date ref_period_end=Date(),
DayCounter day_counter=DayCounter(), bool telescopic_values= False,
RateAveraging averaging_method=RateAveraging.Compound):
self._thisptr = make_shared[_oic.OvernightIndexedCoupon](
deref(payment_date._thisptr), nominal,
deref(start_date._thisptr), deref(end_date._thisptr),
static_pointer_cast[_ii.OvernightIndex](index._thisptr),
gearing, spread,
deref(ref_period_start._thisptr), deref(ref_period_end._thisptr),
deref(day_counter._ | Cython |
thisptr), telescopic_values, averaging_method
)
cdef class OvernightLeg(Leg):
def __iter__(self):
cdef OvernightIndexedCoupon oic
cdef vector[shared_ptr[_cf.CashFlow]].iterator it = self._thisptr.begin()
while it!= self._thisptr.end():
oic = OvernightIndexedCoupon.__new__(OvernightIndexedCoupon)
oic._thisptr = deref(it)
yield oic
preinc(it)
def __repr__(self):
""" Pretty print cash flow schedule. """
header = "Cash Flow Schedule:\n"
values = ("{0!s} {1:f}".format(ic.date, ic.amount) for ic in self)
return header + '\n'.join(values)
<|end_of_text|>
from kivy.uix.widget import Widget
from kivy.properties import (StringProperty, ListProperty,
NumericProperty, DictProperty, BooleanProperty, ObjectProperty)
from kivy.clock import Clock
from math import fabs
from kivy.core.window import Window
class Component(object):
pass
cdef class RotateComponent:
cdef float _r
def __cinit__(self, float r):
self._r = r
property r:
def __get__(self):
return self._r
def __set__(self, float value):
self._r = value
cdef class ScaleComponent:
cdef float _s
def __cinit__(self, float s):
self._s = s
property s:
def __get__(self):
return self._s
def __set__(self, float value):
self._s = value
cdef class PositionComponent:
cdef float _x
cdef float _y
def __cinit__(self, float x, float y):
self._x = x
self._y = y
property x:
def __get__(self):
return self._x
def __set__(self, float value):
self._x = value
property y:
def __get__(self):
return self._y
def __set__(self, float value):
self._y = value
cdef class ColorComponent:
cdef float _r
cdef float _g
cdef float _b
cdef float _a
def __cinit__(self, float r, float g, float b, float a):
self._r = r
self._g = g
self._b = b
self._a = a
property r:
def __get__(self):
return self._r
def __set__(self, float value):
self._r = value
property g:
def __get__(self):
return self._g
def __set__(self, float value):
self._g = value
property b:
def __get__(self):
return self._b
def __set__(self, float value):
self._b = value
property a:
def __get__(self):
return self._a
def __set__(self, float value):
self._a = value
class GameSystem(Widget):
'''GameSystem is the part of your game that holds the logic to operate
on the data of your Entity's components. They keep track of the entity_id
of each entity that has a component for the system. The GameSystem is
responsible for the creation and deletion of its corresponding components.
**Attributes:**
**system_id** (StringProperty): Name of this gamesystem, used to name
entity component attribute, and refer to system.
**updateable** (BooleanProperty): Boolean to let gameworld know
whether or not to run an update tick on this gamesystem. Defaults to
False
**paused** (BooleanProperty): Boolean used to determine whether or not
this system should be updated on the current tickif updateable is True
**gameworld** (ObjectProperty): Reference to the gameworld object,
usually bound in kv
**viewport** (StringProperty): Name of the GameView this system will
be rendered too.
**update_time** (NumericProperty): The 'tick' rate of this system's
update. Defaults to 1./60. or 60 FPS
**entity_ids** (list): a list of entities that have an active
component for this GameSystem
'''
system_id = StringProperty('default_id')
updateable = BooleanProperty(False)
paused = BooleanProperty(False)
gameworld = ObjectProperty(None)
viewport = StringProperty('default_gameview')
update_time = NumericProperty(1./60.)
def __init__(self, **kwargs):
cdef list entity_ids
cdef float frame_time
super(GameSystem, self).__init__(**kwargs)
self.entity_ids = list()
self.frame_time = 0.0
def update(self, dt):
'''
Args:
dt (float): time argument passed in by Clock. Should be
equivalent to update_time.
Override this function to create your gamesystems update logic
typically looks like:
.. code-block:: python
gameworld = self.gameworld
entities = gameworld.entities
for entity_id in self.entity_ids:
entity = entities[entity_id]
#Do your system logic per entity here
'''
pass
def _update(self, dt):
'''
This function is called internally in order to ensure that no time
is lost, excess time that is not quite another update_time
is added to frame_time and consumed next tick.
'''
self.frame_time += dt
update_time = self.update_time
while self.frame_time >= update_time:
self.update(update_time)
self.frame_time -= update_time
def generate_component(self, args):
'''This function is called to generate a component. The default
behavior is to take in a dict and turn all the keys, val pairs to
attributes of an Entity object. Override this to create a custom
component or take in a different args format.
'''
new_component = Component()
for each in args:
setattr(new_component, each, args[each])
return new_component
def create_component(self, object entity, args):
setattr(entity, self.system_id, self.generate_component(args))
self.entity_ids.append(entity.entity_id)
def remove_entity(self, int entity_id):
'''
Args:
entity_id (int): the entity_id for the entity being removed
from the GameSystem
Function used by GameWorld to remove an entity, you should ensure
all data related to your component is cleaned up or recycled here'''
self.entity_ids.remove(entity_id)
def on_remove_system(self):
'''Function called when a system is removed during a gameworld state
change
'''
pass
def on_add_system(self):
'''Function called when a system is added during a gameworld state
change'''
pass
def on_delete_system(self):
'''Function called when a system is deleted by gameworld'''
pass
class PositionSystem(GameSystem):
'''PositionSystem is optimized to hold 2d location data for your entities.
The rendering systems will be able to interact with this data using the
underlying C structures rather than the Python objects.'''
def generate_component(self, tuple pos):
'''
Args:
pos (tuple): (float x, float y)
Position system takes in a tuple: (x, y) and creates a component
with x, y properties (_x, _y to access from cython)
'''
x = pos[0]
y = pos[1]
new_component = PositionComponent.__new__(PositionComponent, x, y)
return new_component
class ScaleSystem(GameSystem):
'''ScaleSystem is optimized to hold a single scale float for your entities.
The rendering systems will be able to interact with this data using the
underlying C structures rather than the Python objects. This object will
potentially change in the future to support scaling at different
rates in different directions.'''
def generate_component(self, float s):
'''
Args:
s (float): scaling factor for the Entity
Scale system takes in a float: s and creates a component with
s property (_s to access from cython)'''
new_component = ScaleComponent.__new__(ScaleComponent, s)
return new_component
class RotateSystem(GameSystem):
'''RotateSystem is optimized to hold a single rotate float for your
entities. The CymunkPhysics System and Renderers expect this to be an
angle in radians.
The rendering systems will be able to interact with this data using the
underlying C structures rather than the Python objects. This object will
potentially change in the future to support rotating around arbitrary axes
'''
def generate_component(self, float r):
'''
Args:
r (float): rotation in radians for the Entity
Rotate system takes in a float: r and creates a component with
r property (_r to access from cython)'''
new_component = RotateComponent.__new__(RotateComponent, r)
return new_component
class ColorSystem(GameSystem):
'''ColorSystem is optimized to hold rgba data for your entities.
Renderers expect this data to be between 0.0 and 1.0 for each float.
| Cython |
The rendering systems will be able to interact with this data using the
underlying C structures rather than the Python objects.'''
def generate_component(self, tuple color):
'''
Args:
color (tuple): color for entity (r, g, b, a) in 0.0 to 1.0
Color system takes in a 4 tuple of floats 0.0 to 1.0 (r, g, b, a)
and creates r, g, b, a properties (_r, _g, _b, _a to access
from cython)'''
r = color[0]
g = color[1]
b = color[2]
a = color[3]
new_component = ColorComponent.__new__(ColorComponent, r, g, b, a)
return new_component
class GameMap(GameSystem):
'''GameMap is a basic implementation of a map size for your GameWorld that
limits the scrolling of GameView typically a GameMap does not actually
have any entities, it simply holds some data and logic for use by
other GameSystems
**Attributes:**
**map_size** (ListProperty): Sets the size of this map, used to
determine scrolling bounds. If the map size is smaller than the
window it will be centered inside the window.
**margins** (ListProperty): The amount of scrolling beyond the size of
the map in x, y directions to be allowed. If the map is smaller than
the window. This value is calculated automatically.
**default_margins** (ListProperty): The amount of margin if the map is
larger than the window, defaults to (0, 0) which means no scrolling
beyond edge of GameMap.
'''
system_id = StringProperty('default_map')
map_size = ListProperty((2000., 2000.))
window_size = ListProperty((0., 0.))
margins = ListProperty((0., 0.))
map_color = ListProperty((1., 1., 1., 1.))
default_margins = ListProperty((0., 0.))
def on_map_size(self, instance, value):
self.check_margins()
def on_size(self, instance, value):
self.check_margins()
def check_margins(self):
map_size = self.map_size
window_size = Window.size
window_larger_x = False
window_larger_y = False
if window_size[0] > map_size[0]:
margin_x = (window_size[0] - map_size[0])/2.
window_larger_x = True
if window_size[1] > map_size[1]:
margin_y = (window_size[1] - map_size[1])/2.
window_larger_y = True
if window_larger_x:
self.margins[0] = margin_x
if window_larger_y:
self.margins[1] = margin_y
if not window_larger_x and not window_larger_y:
self.margins = self.default_margins
def on_add_system(self):
super(GameMap, self).on_add_system()
if self.gameworld:
self.gameworld.currentmap = self
def on_remove_system(self):
super(GameMap, self).on_remove_system()
if self.gameworld.currentmap == self:
self.gameworld.currentmap = None
class GameView(GameSystem):
'''GameView is another entity-less system. It is intended to work with
other systems in order to provide camera functionally.
**The implementation for GameView is very messy at the moment,
expect changes in the future to clean up the API and add functionality**
**Attributes:**
**do_scroll_lock** (BooleanProperty): If True the scrolling will be
locked to the bounds of the GameWorld's currentmap.
**camera_pos** (ListProperty): Current position of the camera
**focus_entity** (BooleanProperty): If True the camera will follow the
entity set in entity_to_focus
**do_scroll** (BooleanProperty): If True touches will scroll the camera
**entity_to_focus** (NumericProperty): Entity entity_id for the camera
to focus on if focus_entity is True.
**camera_speed_multiplier** (NumericProperty): Time it will take camera
to reach focused entity, Speed will be 1.0/camera_speed_multiplier
seconds to close the distance
'''
system_id = StringProperty('default_gameview')
do_scroll_lock = BooleanProperty(True)
camera_pos = ListProperty((0, 0))
focus_entity = BooleanProperty(False)
do_scroll = BooleanProperty(True)
entity_to_focus = NumericProperty(None, allownone=True)
updateable = BooleanProperty(True)
camera_speed_multiplier = NumericProperty(1.0)
def on_entity_to_focus(self, instance, value):
if value == None:
self.focus_entity = False
else:
self.focus_entity = True
def update(self, dt):
cdef int entity_to_focus
cdef float dist_x
cdef float dist_y
cdef object entity
cdef float camera_speed_multiplier
cdef PositionComponent position_data
gameworld = self.gameworld
if self.focus_entity:
entity_to_focus = self.entity_to_focus
entity = gameworld.entities[entity_to_focus]
position_data = entity.position
camera_pos = self.camera_pos
camera_speed_multiplier = self.camera_speed_multiplier
size = self.size
dist_x = -camera_pos[0] - position_data._x + size[0]*.5
dist_y = -camera_pos[1] - position_data._y + size[1]*.5
if self.do_scroll_lock:
dist_x, dist_y = self.lock_scroll(dist_x, dist_y)
self.camera_pos[0] += dist_x*camera_speed_multiplier*dt
self.camera_pos[1] += dist_y*camera_speed_multiplier*dt
gameworld.update_render_state(self)
def on_size(self, instance, value):
if self.do_scroll_lock and self.gameworld.currentmap:
dist_x, dist_y = self.lock_scroll(0, 0)
self.camera_pos[0] += dist_x
self.camera_pos[1] += dist_y
self.gameworld.update_render_state(self)
def on_touch_move(self, touch):
if not self.focus_entity and self.do_scroll:
dist_x = touch.dx
dist_y = touch.dy
if fabs(dist_x) + fabs(dist_y) > 2:
if self.do_scroll_lock and self.gameworld.currentmap:
dist_x, dist_y = self.lock_scroll(dist_x, dist_y)
self.camera_pos[0] += dist_x
self.camera_pos[1] += dist_y
def lock_scroll(self, float distance_x, float distance_y):
currentmap = self.gameworld.currentmap
size = self.size
pos = self.pos
map_size = currentmap.map_size
margins = currentmap.margins
camera_pos = self.camera_pos
cdef float x= pos[0]
cdef float y = pos[1]
cdef float w = size[0]
cdef float h = size[1]
cdef float mw = map_size[0]
cdef float mh = map_size[1]
cdef float marg_x = margins[0]
cdef float marg_y = margins[1]
cdef float cx = camera_pos[0]
cdef float cy = camera_pos[1]
if cx + distance_x > x + marg_x:
distance_x = x - cx + marg_x
elif cx + mw + distance_x <= x + w - marg_x:
distance_x = x + w - marg_x - cx - mw
if cy + distance_y > y + marg_y:
distance_y = y - cy + marg_y
elif cy + mh + distance_y <= y + h - marg_y:
distance_y = y + h - cy - mh - marg_y
return distance_x, distance_y
<|end_of_text|>
cdef extern from 'git2/repository.h':
ctypedef struct git_repository
int git_repository_open(git_repository** repo_out, const char* path)
void git_repository_free(git_repository* repo)
cdef extern from'memcached_backend_adapter.h':
int attach_memcached_to_repo(git_repository* repo, const char *host, int port)
int give_me_five()
def say_hello():
print "Hello World!"
cdef int hand = give_me_five()
class _Backend:
def __init__(self,
str host: str,
int port: int,
str str_path: str) -> None:
"""
Create a backend object
:param host: The memcached host to connect to
:type host: str
:param port: The port on the host where memcached is running
:type port: int
:param str_path: path to the refs for this git repo
:type str_path: str
"""
# Convert python string to ctype const char*
py_byte_string = str_path.encode('UTF-8')
cdef const char* path = py_byte_string
print "repo path is at " + str_path
print "init NULL repo object"
c | Cython |
def git_repository *repository = NULL;
print "open repo object at " + str_path
cdef int err = git_repository_open(&repository, path)
if err < 0:
print "error free"
git_repository_free(repository)
raise Exception("could not open the repo error {}".format(err))
print "attach backend"
cdef int backend_err = attach_memcached_to_repo(repository, "localhost", 5000)
if backend_err < 0:
print "error free"
git_repository_free(repository)
raise Exception("got {}".format(backend_err))
<|end_of_text|># -*- coding: utf-8 -*-
"""
Created on Wed Jan 13 17:06:15 2021
@author: angus
"""
import numpy as np
cimport numpy as np
from libc.math cimport exp
from libc.stdlib cimport rand
import matplotlib.pyplot as plt
import time
cdef extern from "limits.h":
int RAND_MAX
cdef create_cells(int x_size, int y_size):
# Creates array of given size filled with random distribution of
# either +1 or -1
cdef long int[:, :] cells = np.random.choice([-1, 1], size = (y_size, x_size))
return cells
cdef create_image(long[:, :] cells):
# Takes the final array and converts it to an image
plt.imshow(cells, aspect = 'equal', origin = 'lower', cmap = 'binary')
plt.savefig('2D.png')
cdef energy_diff(long int[:, :] cells, double inverse_temp):
# Iterates over all the cells in the array, carrying out the energy
# calculation on each one
cdef:
int row, column
int y_size = cells.shape[0]
int x_size = cells.shape[1]
double energy
for row in range(y_size):
for column in range(x_size):
energy = 2 * cells[row][column] * (cells[(row - 1) % y_size][column] +
cells[(row + 1) % y_size][column] +
cells[row][(column - 1) % x_size] +
cells[row][(column + 1) % x_size])
if energy < 0 or exp(-energy * inverse_temp) * RAND_MAX > rand():
cells[row][column] *= -1
return cells
def main(int array_size, float inverse_temp, int iterations):
# Does any calculations
# This is the function imported in the run file
cdef:
int count = 0
double start_time = time.time()
long[:, :] cells = create_cells(array_size, array_size)
while count < iterations:
cells = energy_diff(cells, inverse_temp)
count += 1
print(time.time() - start_time)
create_image(cells)<|end_of_text|>import errno
import logging
import socket
import gevent
from gevent.event import AsyncResult, Event
from libc.stdint cimport uint32_t, uint8_t
from loqui.exceptions import NoEncoderAvailable, ConnectionTerminated, LoquiDecoderError, StreamDefunct, \
NotClientException, NotServerException, LoquiErrorReceived
from opcodes cimport Request, Response, Ping, Pong, Push, Hello, GoAway, HelloAck, Error
from socket_watcher cimport SocketWatcher
from stream_handler cimport LoquiStreamHandler
cdef size_t OUTBUF_MAX = 65535
class CloseReasons(object):
NORMAL = 0
PING_TIMEOUT = 1
UNKNOWN_ENCODER = 2
NO_MUTUAL_ENCODERS = 3
DIDNT_STOP_IN_TIME = 4
DECODER_ERROR = 5
cdef class LoquiSocketSession:
def __cinit__(self, object sock, object encoders, bint is_client=True, object on_request=None, object on_push=None):
self._is_client = is_client
self._stream_handler = LoquiStreamHandler()
self._sock = sock
self._watcher = SocketWatcher(self._sock.fileno())
self._inflight_requests = {}
self._available_encoders = encoders
self._available_compressors = {}
self._shutdown_event = Event()
self._close_event = Event()
self._ready_event = Event()
self._ping_interval = 5
self._is_ready = False
self._shutting_down = False
if not self._is_client:
self._on_request = on_request
self._on_push = on_push
gevent.spawn(self._ping_loop)
gevent.spawn(self._run_loop)
if is_client:
self._send_hello()
cpdef set_push_handler(self, object push_handler):
self._on_push = None
cdef _resume_sending(self):
if self._sock is None:
return
if self._stream_handler.write_buffer_len() == 0:
return
self._watcher.switch_if_write_unblocked()
cdef shutdown(self):
if self._shutting_down:
return
self._shutting_down = True
cdef void _cleanup_socket(self):
sock = self._sock
self._sock = None
if sock:
sock.close()
# Request a switch so that the socket event loop will exit.
if sock:
self._watcher.request_switch()
self._cleanup_inflight_requests(ConnectionTerminated())
# Unblock anything waiting on ready event.
if not self._ready_event.is_set():
self._ready_event.set()
# Unblock anything waiting on stop event.
if not self._shutdown_event.is_set():
self._shutdown_event.set()
# Unblock anything waiting on the close event.
if not self._close_event.is_set():
self._close_event.set()
cpdef close(self, uint8_t code=CloseReasons.NORMAL, bytes reason=None,
block=False, block_timeout=None, close_timeout=None, bint via_remote_goaway=False):
if not self._shutting_down:
self._shutting_down = True
# Unblock anything waiting on ready event.
if not self._ready_event.is_set():
self._ready_event.set()
# Unblock anything waiting on stop event.
if not self._shutdown_event.is_set():
self._shutdown_event.set()
# Send goaway to the remote node.
if not via_remote_goaway and self._sock:
self._stream_handler.send_goaway(0, code, reason)
# Spawn a greenlet that will wait
gevent.spawn(self._close_timeout)
# If we are blocking, wait on close event to succeed.
if block:
self.join(block_timeout)
cpdef _close_timeout(self):
if self._close_event.wait(self._ping_interval):
return
self._cleanup_socket()
cpdef join(self, timeout=None):
self._close_event.wait(timeout=timeout)
cpdef terminate(self):
self._cleanup_socket()
cdef _cleanup_inflight_requests(self, close_exception):
requests = self._inflight_requests.values()
self._inflight_requests.clear()
for request in requests:
if isinstance(request, AsyncResult):
request.set_exception(close_exception)
cdef bint await_ready(self) except 1:
if not self._is_ready:
self._ready_event.wait()
cdef bint is_ready(self):
return self._is_ready
cdef _encode_data(self, object data):
if not self._is_ready:
self._ready_event.wait()
if not self._encoder_dumps:
raise NoEncoderAvailable()
return 0, self._encoder_dumps(data)
cdef _decode_data(self, uint8_t flags, object data):
if not self._is_ready:
self._ready_event.wait()
if not self._encoder_loads:
raise NoEncoderAvailable()
return self._encoder_loads(data)
cpdef object send_request(self, object data):
if not self._is_client:
raise NotClientException()
if self.defunct():
raise StreamDefunct
cdef bytes encoded_data
cdef uint8_t flags
flags, encoded_data = self._encode_data(data)
result = AsyncResult()
cdef uint32_t seq = self._stream_handler.send_request(flags, encoded_data)
self._inflight_requests[seq] = result
self._resume_sending()
return result
cpdef object send_push(self, object data):
if self.defunct():
raise StreamDefunct()
cdef bytes encoded_data
cdef uint8_t flags
flags, encoded_data = self._encode_data(data)
self._stream_handler.send_push(flags, encoded_data)
self._resume_sending()
cpdef object send_response(self, uint32_t seq, object data):
if self._is_client:
raise NotServerException()
if self.defunct():
return
cdef bytes encoded_data
cdef uint8_t flags
request = self._inflight_requests.pop(seq, None)
if request:
flags, encoded_data = self._encode_data(data)
self._stream_handler.send_response(flags, seq, encoded_data)
self._resume_sending()
else:
logging.error('Sending response for unknown seq %s', seq)
return None
cpdef object send_ping(self):
if self.defunct():
raise StreamDefunct()
result = AsyncResult()
| Cython |
cdef uint32_t seq = self._stream_handler.send_ping(0)
self._inflight_requests[seq] = result
self._resume_sending()
return result
cpdef object _send_hello_ack(self, bytes selected_encoding, bytes selected_compressor):
if self._is_client:
raise NotServerException()
if self.defunct():
raise StreamDefunct()
self._stream_handler.send_hello_ack(0, int(self._ping_interval * 1000), selected_encoding, selected_compressor)
cpdef object _send_hello(self):
if not self._is_client:
raise NotClientException()
self._stream_handler.send_hello(0, list(self._available_encoders.keys()), list(self._available_compressors.keys()))
cdef _handle_ping_timeout(self):
self.close(code=CloseReasons.PING_TIMEOUT)
cdef _handle_data_received(self, data):
try:
events = self._stream_handler.on_bytes_received(data)
except LoquiDecoderError as e:
print e
return self.close(code=CloseReasons.DECODER_ERROR)
if not events:
return
if self._is_client:
self._handle_client_events(events)
else:
self._handle_server_events(events)
self._resume_sending()
cdef _handle_client_events(self, list events):
for event in events:
if isinstance(event, Response):
self._handle_response(event)
elif isinstance(event, Push):
self._handle_push(event)
elif isinstance(event, Ping):
self._handle_ping(event)
elif isinstance(event, Pong):
self._handle_pong(event)
elif isinstance(event, GoAway):
self._handle_go_away(event)
elif isinstance(event, HelloAck):
self._handle_hello_ack(event)
elif isinstance(event, Error):
self._handle_error(event)
cdef _handle_server_events(self, list events):
for event in events:
if isinstance(event, Request):
self._handle_request(event)
elif isinstance(event, Push):
self._handle_push(event)
elif isinstance(event, Ping):
self._handle_ping(event)
elif isinstance(event, Pong):
self._handle_pong(event)
elif isinstance(event, GoAway):
self._handle_go_away(event)
elif isinstance(event, Hello):
self._handle_hello(event)
cdef _handle_request(self, Request request):
if self._on_request:
# In this case, we set the inflight requests to the given request. That way send_response
# will know if the seq is valid or not.
request.data = self._decode_data(request.flags, request.data)
self._inflight_requests[request.seq] = request
response = self._on_request(request, self)
# If a response is given, we can return it to the sender right away.
# Otherwise, it's the responsibility of the `_on_request` handler to eventually
# call `send_response`.
if response is not None:
self.send_response(request.seq, response)
cdef _handle_response(self, Response response):
request = self._inflight_requests.pop(response.seq, None)
if request:
try:
# If we've gotten a response for a request we've made.
request.set(self._decode_data(response.flags, response.data))
except Exception as e:
request.set_exception(e)
cdef _handle_push(self, Push push):
if self._on_push:
push.data = self._decode_data(push.flags, push.data)
self._on_push(push, self)
cdef _handle_ping(self, Ping ping):
# Nothing to do here - the stream handler handles sending pongs back for us.
pass
cdef _handle_pong(self, Pong pong):
ping_request = self._inflight_requests.pop(pong.seq, None)
if ping_request:
ping_request.set(pong)
cdef _handle_hello(self, Hello hello):
encoding, encoder = self._pick_best_encoding(hello.supported_encodings)
if not encoding:
self.close(reason=CloseReasons.NO_MUTUAL_ENCODERS)
else:
self._encoder_dumps = encoder.dumps
self._encoder_loads = encoder.loads
self._encoding = encoding
self._send_hello_ack(encoding, None)
self._is_ready = True
self._ready_event.set()
cdef _handle_hello_ack(self, HelloAck hello_ack):
encoder = self._available_encoders.get(hello_ack.selected_encoding)
if not encoder:
self.close(code=CloseReasons.UNKNOWN_ENCODER, reason=b'Unknown encoding %s' % hello_ack.selected_encoding)
else:
self._ping_interval = int(hello_ack.ping_interval / 1000)
self._encoder_dumps = encoder.dumps
self._encoder_loads = encoder.loads
self._encoding = hello_ack.selected_encoding
self._is_ready = True
self._ready_event.set()
cdef _handle_go_away(self, GoAway go_away):
print "Got goaway on seq", self._stream_handler.current_seq(), go_away.code
self.close(via_remote_goaway=True, reason=go_away.reason, code=go_away.code)
cdef _handle_error(self, Error error):
request = self._inflight_requests.pop(error.seq, None)
if request:
request.set_exception(LoquiErrorReceived(error.code, error.data))
cdef _pick_best_encoding(self, list encodings):
for encoding in encodings:
encoder = self._available_encoders.get(encoding)
if encoder:
return encoding, encoder
return None, None
cpdef _ping_loop(self):
while self._sock:
ping_result = self.send_ping()
if self._shutdown_event.wait(self._ping_interval):
return
if not ping_result.ready():
self._handle_ping_timeout()
return
cpdef _run_loop(self):
loop = gevent.get_hub().loop
io = loop.io
cdef int MAXPRI = loop.MAXPRI
cdef int READ = 1
cdef int WRITE = 2
cdef bint write_watcher_started = False
cdef bint sock_should_write = False
cdef bint did_empty_buffer = False
cdef object sock_recv = self._sock.recv
cdef object sock_send = self._sock.send
cdef object watcher_mark_ready = (<object> self._watcher).mark_ready
cdef size_t write_bytes_remaining
sock_read_watcher = io(self._watcher.sock_fileno, READ)
sock_write_watcher = io(self._watcher.sock_fileno, WRITE)
try:
sock_read_watcher.start(watcher_mark_ready, self._watcher.sock_fileno, True)
while self._sock:
if write_watcher_started == False and self._stream_handler.write_buffer_len() > 0:
sock_write_watcher.start(watcher_mark_ready, self._watcher.sock_fileno, False)
self._watcher.wait()
if not self._sock:
return
if self._watcher.sock_read_ready:
try:
data = sock_recv(65536)
except socket.error as e:
if e.errno in (errno.EAGAIN, errno.EINPROGRESS):
continue
data = None
if not data:
self.close()
self._cleanup_socket()
return
else:
self._handle_data_received(data)
# We should attempt to write, if the watcher has notified us that the socket is ready
# to accept more data, or we aren't write blocked yet - and we have a write buffer.
sock_should_write = self._watcher.sock_write_ready or (
not self._watcher.sock_write_blocked and self._stream_handler.write_buffer_len() > 0
)
if sock_should_write:
try:
bytes_written = sock_send(self._stream_handler.write_buffer_get_bytes(OUTBUF_MAX, False))
except socket.error as e:
if e.errno in (errno.EAGAIN, errno.EINPROGRESS):
bytes_written = 0
else:
self.close()
self._cleanup_socket()
# No bytes have been written. It's safe to assume the socket is still (somehow) blocked
# and we don't need to do anything.
if not bytes_written:
self._watcher.sock_write_blocked = True
continue
write_bytes_remaining = self._stream_handler.write_buffer_consume_bytes(bytes_written)
# Did we completely write the buffer? If so - the socket isn't blocked anymore.
self._watcher.sock_write_blocked = write_bytes_remaining > 0
# If no data is available to send - we can stop the watcher. Otherwise,
# we will leave the watcher open, so the data filled into the buffer
# will attempt to be written upon the next tick of the event loop.
if write_bytes_remaining == 0:
sock_write_watcher.stop()
write_watcher_started = False
# If we are shutting down, have an empty write buffer, and no more in-flight requests,
# it's safe to terminate the socket.
if self._shutting_down and self._stream_handler.write_buffer_len() == 0 and not self._inflight_requests:
print 'cleaning up socket because we are drained'
self._cleanup_socket()
self._watcher.reset()
finally:
sock_read_watcher.stop()
| Cython |
sock_write_watcher.stop()
cdef bint defunct(self):
if self._sock is None:
return True
if self._shutting_down:
return True
return False<|end_of_text|>cdef float Nsr, clearSkySolarRadiation, averageT, surfaceEmissivity, cloudCoverFactor, Nolr
Nsr = (1 - albedoCoefficient) * solarRadiation
clearSkySolarRadiation = (0.75 + 2 * pow(10, -5) * elevation) * extraSolarRadiation
averageT = (pow(maxTair + 273.16, 4) + pow(minTair + 273.16, 4)) / 2
surfaceEmissivity = (0.34 - 0.14 * sqrt(vaporPressure / 10))
cloudCoverFactor = (1.35 * (solarRadiation / clearSkySolarRadiation) - 0.35)
Nolr = stefanBoltzman * averageT * surfaceEmissivity * cloudCoverFactor
netRadiation= Nsr - Nolr
netOutGoingLongWaveRadiation = Nolr
<|end_of_text|>from _memray.records cimport Allocation
from libcpp cimport bool
cdef extern from "hooks.h" namespace "memray::hooks":
cdef cppclass Allocator:
pass
bool isDeallocator(const Allocator& allocator)
<|end_of_text|>from numpy.lib.histograms import _ravel_and_check_weights
from scipy.special import expit as sigmoid
import numpy as np
import util
import copy
import json
import math
import array
class RandomlyTrue:
def __bool__(self):
return util.flipCoin(0.5)
instance = None
cdef class Connection:
cdef unsigned int in_node, out_node
cdef float weight
cdef int enabled
cdef unsigned int innov_number
def __init__(self, unsigned int in_node, unsigned int out_node, float weight, int enabled, unsigned int innov):
self.in_node = in_node
self.out_node = out_node
self.weight = weight
self.enabled = enabled
self.innov_number = innov
def to_json(self):
return [self.in_node, self.out_node, self.weight, self.enabled, self.innov_number]
def get_innov(self):
return self.innov_number
RandomlyTrue.instance = RandomlyTrue()
def random_uniform0(double half_range):
# return np.random.normal(0, half_range)
return np.random.uniform(-half_range, half_range)
class Genes:
class Metaparameters:
def __init__(self,
c1=1, c2=1, c3=3,
perturbation_chance=0.8,
perturbation_stdev=0.1,
reset_weight_chance=0.1,
new_link_chance=0.3,
bias_link_chance=0.01,
new_link_weight_stdev=1,
new_node_chance=0.03,
disable_mutation_chance=0.1,
enable_mutation_chance=0.25,
allow_recurrent=True,
mutate_loop=1):
self.innovation_number = 0
def none_or(value, default_value):
return default_value if value is None else value
self.c1 = none_or(c1, 0.1)
self.c2 = none_or(c2, 0.1)
self.c3 = none_or(c3, 0.1)
self.new_link_chance = none_or(new_link_chance, 0.1)
self.bias_link_chance = none_or(bias_link_chance, 0.1)
self.new_link_weight_stdev = none_or(new_link_weight_stdev, 1)
self.new_node_chance = none_or(new_node_chance, 0.1)
self.perturbation_chance = none_or(perturbation_chance, 0.1)
self.reset_weight_chance = none_or(reset_weight_chance, 0.5)
self.perturbation_stdev = none_or(perturbation_stdev, 0.1)
self.disable_mutation_chance = none_or(disable_mutation_chance, 0.1)
self.enable_mutation_chance = none_or(enable_mutation_chance, 0.1)
self.allow_recurrent = none_or(allow_recurrent, True)
self.mutate_loop = none_or(mutate_loop, 1)
self._connections = {}
self._node_splits = {}
def _increment_innovation(self):
self.innovation_number += 1
return self.innovation_number
def reset_tracking(self):
self._connections = {}
self._node_splits = {}
def register_connection(self, in_node, out_node):
pair = (in_node, out_node)
innovation_number = self._connections.get(pair, None)
if innovation_number is None:
innovation_number = self._increment_innovation()
self._connections[pair] = innovation_number
return innovation_number
def register_node_split(self, in_node, out_node, between_node):
tuple = (in_node, out_node, between_node)
innovation_numbers = self._node_splits.get(tuple, None)
if innovation_numbers is None:
leading = self._increment_innovation()
trailing = self._increment_innovation()
innovation_numbers = (leading, trailing)
self._node_splits[tuple] = innovation_numbers
return innovation_numbers
def load_from_json(as_json):
ret = Genes.Metaparameters(
c1=as_json.get("c1"),
c2=as_json.get("c2"),
c3=as_json.get("c3"),
perturbation_chance=as_json.get("perturbation_chance"),
perturbation_stdev=as_json.get("perturbation_stdev"),
reset_weight_chance=as_json.get("reset_weight_chance"),
new_link_chance=as_json.get("new_link_chance"),
bias_link_chance=as_json.get("bias_link_chance"),
new_link_weight_stdev=as_json.get("new_link_weight_stdev"),
new_node_chance=as_json.get("new_node_chance"),
disable_mutation_chance=as_json.get("disable_mutation_chance"),
enable_mutation_chance=as_json.get("enable_mutation_chance"),
allow_recurrent=as_json.get("allow_recurrent"),
mutate_loop=as_json.get("mutate_loop")
)
if "innovation_number" in as_json:
ret.innovation_number = as_json["innovation_number"]
return ret
def load(in_stream, decoder=json):
as_json = decoder.load(in_stream)
return Genes.Metaparameters.load_from_json(as_json)
def as_json(self):
return {
"innovation_number": self.innovation_number,
"c1": self.c1,
"c2": self.c2,
"c3": self.c3,
"new_link_chance": self.new_link_chance,
"bias_link_chance": self.bias_link_chance,
"new_link_weight_stdev": self.new_link_weight_stdev,
"new_node_chance": self.new_node_chance,
"perturbation_chance": self.perturbation_chance,
"perturbation_stdev": self.perturbation_stdev,
"reset_weight_chance": self.reset_weight_chance,
"disable_mutation_chance": self.disable_mutation_chance,
"enable_mutation_chance": self.enable_mutation_chance,
"allow_recurrent": self.allow_recurrent,
"mutate_loop": self.mutate_loop
}
def save(self, out_stream, encoder=json):
out = self.as_json()
out_stream.write(encoder.dumps(out))
out_stream.flush()
BIAS_INDEX = 0
def __init__(self, num_sensors_or_copy, num_outputs=None, metaparameters=None):
if isinstance(num_sensors_or_copy, Genes):
to_copy = num_sensors_or_copy
self._num_sensors = to_copy._num_sensors
self._num_outputs = to_copy._num_outputs
self._dynamic_nodes = copy.deepcopy(to_copy._dynamic_nodes)
self._connections = copy.deepcopy(to_copy._connections)
self._metaparameters = to_copy._metaparameters
self._connections_sorted = to_copy._connections_sorted
self.fitness = copy.deepcopy(to_copy.fitness)
else:
self._num_sensors = num_sensors_or_copy
self._num_outputs = num_outputs
self._dynamic_nodes = []
for _ in range(num_outputs):
self._dynamic_nodes.append(array.array("I"))
self._connections = []
self._metaparameters = metaparameters
self._connections_sorted = True
self.fitness = 0
def feed_sensor_values(self, values, neurons=None):
""" Run the network with the given input through the given neurons (creates them if not given), returns neuron values """
if neurons is None:
neurons = [0 for _ in range(self.total_nodes() + 1)]
assert len(values) == self._num_sensors, "invalid number of inputs"
neurons[0] = 1.0 # BIAS node
for i in range(self._num_sensors):
neurons[i + 1] = values[i]
def feed(unsigned long long node_index):
node = self._dynamic_nodes[node_index]
neuron_index = node_index + self._num_sensors + 1
has_connections = False
cdef double sum = 0
| Cython |
cdef Connection connection = None
for connection_index in node:
connection = <Connection>self._connections[connection_index]
# assert out_node = neuron_index
if connection.enabled:
has_connections = True
sum += neurons[connection.in_node] * connection.weight
if has_connections:
neurons[neuron_index] = math.tanh(sum)
cdef unsigned long long num_outputs = self._num_outputs
cdef unsigned long long total_dynamic = len(self._dynamic_nodes)
for hidden_node_index in range(num_outputs, total_dynamic):
feed(hidden_node_index)
for output_node_index in range(num_outputs):
feed(output_node_index)
return neurons
def extract_output_values(self, neuron_values):
""" Extracts the output values from the result of feed_sensor_values """
return neuron_values[self._num_sensors + 1:self._num_sensors + self._num_outputs + 1]
def _node_by_index(self, index):
return self._dynamic_nodes[index - self._num_sensors - 1]
def total_nodes(self):
return 1 + self._num_sensors + len(self._dynamic_nodes)
def input_node_index(self, input_index):
return 1 + input_index
def output_node_index(self, index):
return 1 + self._num_sensors + index
def _is_hidden_node_index(self, index):
return index >= 1 + self._num_sensors + self._num_outputs
def _is_output_node_index(self, index):
return index > self._num_sensors and index < 1 + self._num_sensors + self._num_outputs
def add_connection(self, input_index, output_index):
if not self._metaparameters.allow_recurrent:
def swap():
return output_index, input_index
if input_index == output_index:
return
if self._is_output_node_index(input_index):
if output_index < input_index or self._is_hidden_node_index(output_index):
input_index, output_index = swap()
elif self._is_hidden_node_index(output_index) and output_index < input_index: # both hidden and output is earlier
input_index, output_index = swap()
incoming = self._node_by_index(output_index)
cdef Connection connection
for connection_index in incoming:
connection = <Connection>self._connections[connection_index]
if connection.in_node == input_index:
return self
innovation_number = self._metaparameters.register_connection(input_index, output_index)
connection = Connection(input_index, output_index, random_uniform0(self._metaparameters.new_link_weight_stdev), True, innovation_number)
incoming.append(len(self._connections))
cdef Connection last_connection
if len(self._connections) > 0:
last_connection = <Connection>self._connections[-1]
if innovation_number < last_connection.innov_number:
self._connections_sorted = False
self._connections.append(connection)
return self
def _add_connection(self):
total_nodes = self.total_nodes()
input_index = 0 if util.flipCoin(self._metaparameters.bias_link_chance) else util.random.randint(0, total_nodes - 1)
output_index = util.random.randint(self._num_sensors + 1, total_nodes - 1)
self.add_connection(input_index, output_index)
def _add_node(self):
if len(self._connections) == 0:
return
cdef Connection connection
if self._metaparameters.allow_recurrent:
connection = <Connection>util.random.choice(self._connections)
else:
choices = []
for i in range(self._num_outputs):
choices.extend(self._dynamic_nodes[i])
connection = <Connection>self._connections[util.random.choice(choices)]
connection.enabled = False
new_node = array.array("I")
self._dynamic_nodes.append(new_node)
leading_innov, trailing_innov = self._metaparameters.register_node_split(connection.in_node, connection.out_node, self.total_nodes() - 1)
leading = Connection(connection.in_node, self.total_nodes() - 1, 1, True, leading_innov)
trailing = Connection(self.total_nodes() - 1, connection.out_node, connection.weight, True, trailing_innov)
cdef Connection last_connection
if len(self._connections) > 0:
last_connection = <Connection>(self._connections[-1])
if leading_innov < last_connection.innov_number:
self._connections_sorted = False
self._connections.append(leading)
self._connections.append(trailing)
new_node.append(len(self._connections) - 2)
self._node_by_index(connection.out_node).append(len(self._connections) - 1)
def perturb(self):
cdef double reset_chance = self._metaparameters.reset_weight_chance
cdef double new_link_weight_stdev = self._metaparameters.new_link_weight_stdev
cdef double perturbation_stdev = self._metaparameters.perturbation_stdev
cdef Connection connection
for _connection in self._connections:
connection = <Connection>_connection
if util.flipCoin(reset_chance):
connection.weight = random_uniform0(new_link_weight_stdev)
else:
connection.weight += random_uniform0(perturbation_stdev)
return self
def _enable_mutation(self, enable):
if len(self._connections) == 0:
return
cdef Connection connection = <Connection>util.random.choice(self._connections)
connection.enabled = enable
def mutate(self):
""" Mutate the genes in this genome, returns self """
for _ in range(self._metaparameters.mutate_loop):
if util.flipCoin(self._metaparameters.new_link_chance):
self._add_connection()
if util.flipCoin(self._metaparameters.new_node_chance):
self._add_node()
if util.flipCoin(self._metaparameters.perturbation_chance):
self.perturb()
# if util.flipCoin(self._metaparameters.disable_mutation_chance):
# self._enable_mutation(False)
# if util.flipCoin(self._metaparameters.enable_mutation_chance):
# self._enable_mutation(True)
return self
def _sorted_connections(self):
if self._connections_sorted:
return self._connections
return sorted(self._connections, key=Connection.get_innov)
def breed(self, other, self_more_fit=RandomlyTrue.instance):
""" Creates a child from the result of breeding self and other genes, returns new child """
ret = Genes(self._num_sensors, self._num_outputs, self._metaparameters)
sconnections = self._sorted_connections()
oconnections = other._sorted_connections()
slen = len(sconnections)
olen = len(oconnections)
i = 0
j = 0
def turn_on_maybe(Connection connection):
if not connection.enabled and util.flipCoin(self._metaparameters.enable_mutation_chance):
connection.enabled = True
cdef Connection sc = None
cdef Connection so = None
while i < slen and j < olen:
sc = <Connection>sconnections[i]
so = <Connection>oconnections[j]
sci = sc.innov_number
soi = so.innov_number
if sci == soi:
ret._connections.append(copy.copy(sc if util.flipCoin(0.5) else so))
turn_on_maybe(ret._connections[-1])
i += 1
j += 1
elif sci < soi:
i += 1
if self_more_fit:
ret._connections.append(copy.copy(sc))
turn_on_maybe(ret._connections[-1])
else:
j += 1
if not self_more_fit:
ret._connections.append(copy.copy(so))
turn_on_maybe(ret._connections[-1])
while i < slen:
if self_more_fit:
ret._connections.append(copy.copy(sconnections[i]))
turn_on_maybe(ret._connections[-1])
i += 1
while j < olen:
if not self_more_fit:
ret._connections.append(copy.copy(oconnections[j]))
turn_on_maybe(ret._connections[-1])
j += 1
max_node = 0
cdef Connection connection
for _connection in ret._connections:
connection = <Connection>_connection
max_node = max(max_node, connection.in_node, connection.out_node)
i = ret.total_nodes()
while i <= max_node:
ret._dynamic_nodes.append(array.array("I"))
i += 1
for index, _connection in enumerate(ret._connections):
connection = <Connection>_connection
ret._node_by_index(connection.out_node).append(index)
return ret
def distance(self, other):
assert self._metaparameters is other._metaparameters
c1 = self._metaparameters.c1
c2 = self._metaparameters.c2
c3 = self._metaparameters.c3
sconnections = self._sorted_connections()
oconnections = other._sorted_connections()
slen = len(sconnections)
olen = len(oconnections)
n = max(olen, slen)
if n == 0:
return 0
disjoint = 0
weight_difference = 0
shared | Cython |
= 0
i = 0
j = 0
cdef Connection sc, so
while i < slen and j < olen:
sc = <Connection>sconnections[i]
so = <Connection>oconnections[j]
sci = sc.innov_number
soi = so.innov_number
if sci == soi:
weight_difference += abs(sc.weight - so.weight)
shared += 1
i += 1
j += 1
else:
disjoint += 1
if sci < soi:
i += 1
else:
j += 1
excess = olen - j + slen - i
return (c1 * excess / n) + (c2 * disjoint / n) + (0 if shared == 0 else c3 * weight_difference / shared)
def clone(self):
return Genes(self)
def as_json(self):
""" returns self as a dict """
return {"nodeCount": self.total_nodes(), "inputCount": self._num_sensors, "outputCount": self._num_outputs, "connections": [(<Connection>c).to_json() for c in self._connections], "fitness": self.fitness}
def save(self, out_stream, encoder=json):
""" save to the stream using the given encoder, encoder must define dumps function that takes in a JSON-like object"""
as_json = self.as_json()
out_stream.write(encoder.dumps(as_json))
out_stream.flush()
def load_from_json(json_object, metaparameters):
""" loads from a dict-like object """
ret = Genes(json_object["inputCount"], json_object["outputCount"], metaparameters)
to_add = json_object["nodeCount"] - ret.total_nodes()
for _ in range(to_add):
ret._dynamic_nodes.append([])
connections = [Connection(c[0], c[1], c[2], c[3], c[4]) for c in json_object["connections"]]
count = 0
ret._connections = connections
connections.sort(key=Connection.get_innov)
cdef Connection connection
for _connection in connections:
connection = <Connection>_connection
ret._node_by_index(connection.out_node).append(count)
count += 1
ret.fitness = json_object.get("fitness", 0)
return ret
def load(in_stream, metaparameters, decoder=json):
""" load from stream using given decoder, decoder must define load function that takes in a stream and returns a dict-like object"""
as_json = decoder.load(in_stream)
return Genes.load_from_json(as_json, metaparameters)
def setFitness(self, fitness):
self.fitness = fitness
def getFitness(self):
return self.fitness
<|end_of_text|>from Types cimport *
from Param cimport *
from TransformationModel cimport *
from String cimport *
from StringList cimport *
from TransformationModel cimport TM_DataPoint
cdef extern from "<OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>" namespace "OpenMS::TransformationDescription":
cdef cppclass TransformationStatistics "OpenMS::TransformationDescription::TransformationStatistics":
TransformationStatistics() nogil except +
TransformationStatistics(TransformationStatistics &) nogil except +
# libcpp_vector[ size_t ] percents # const
double xmin
double xmax
double ymin
double ymax
libcpp_map[size_t, double ] percentiles_before
libcpp_map[size_t, double ] percentiles_after
cdef extern from "<OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>" namespace "OpenMS":
cdef cppclass TransformationDescription:
TransformationDescription() nogil except +
TransformationDescription(TransformationDescription &) nogil except +
libcpp_vector[TM_DataPoint] getDataPoints() nogil except + # wrap-doc:Returns the data points
void setDataPoints(libcpp_vector[TM_DataPoint]& data) nogil except + # wrap-doc:Sets the data points. Removes the model that was previously fitted to the data (if any)
void setDataPoints(libcpp_vector[libcpp_pair[double,double]]& data) nogil except + # wrap-doc:Sets the data points (backwards-compatible overload). Removes the model that was previously fitted to the data (if any)
double apply(double) nogil except + # wrap-doc:Applies the transformation to `value`
void fitModel(String model_type, Param params) nogil except + # wrap-doc:Fits a model to the data
void fitModel(String model_type) nogil except + # wrap-doc:Fits a model to the data
String getModelType() nogil except + # wrap-doc:Gets the type of the fitted model
Param getModelParameters() nogil except + # wrap-doc:Returns the model parameters
void invert() nogil except + # wrap-doc:Computes an (approximate) inverse of the transformation
void getDeviations(libcpp_vector[double]& diffs, bool do_apply, bool do_sort) nogil except +
# wrap-doc:
# Get the deviations between the data pairs
# -----
# :param diffs: Output
# :param do_apply: Get deviations after applying the model?
# :param do_sort: Sort `diffs` before returning?
TransformationStatistics getStatistics() nogil except +
# NAMESPACE # void printSummary(std::ostream & os) nogil except +
cdef extern from "<OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>" namespace "OpenMS::TransformationDescription":
void getModelTypes(StringList result) nogil except + # wrap-attach:TransformationDescription
<|end_of_text|>cimport cspdylay
from libc.stdlib cimport malloc, free
from libc.string cimport memcpy, memset
from libc.stdint cimport uint8_t, uint16_t, uint32_t, int32_t
# Also update version in setup.py
__version__ = '0.1.2'
class EOFError(Exception):
pass
class CallbackFailureError(Exception):
pass
class TemporalCallbackFailureError(Exception):
pass
class InvalidArgumentError(Exception):
pass
class ZlibError(Exception):
pass
class UnsupportedVersionError(Exception):
pass
class StreamClosedError(Exception):
pass
class DataProvider:
def __init__(self, source, read_cb):
self.source = source
self.read_cb = read_cb
cdef class CtrlFrame:
cdef uint16_t version
cdef uint16_t frame_type
cdef uint8_t flags
cdef int32_t length
cdef void fillhd(self, cspdylay.spdylay_ctrl_hd *hd):
self.version = hd.version
self.frame_type = hd.type
self.flags = hd.flags
self.length = hd.length
property version:
def __get__(self):
return self.version
property frame_type:
def __get__(self):
return self.frame_type
property flags:
def __get__(self):
return self.flags
property length:
def __get__(self):
return self.length
cdef class SynStreamFrame(CtrlFrame):
cdef int32_t stream_id
cdef int32_t assoc_stream_id
cdef uint8_t pri
cdef uint8_t slot
cdef object nv
cdef fill(self, cspdylay.spdylay_syn_stream *frame):
self.fillhd(&frame.hd)
self.stream_id = frame.stream_id
self.assoc_stream_id = frame.assoc_stream_id
self.pri = frame.pri
self.slot = frame.slot
self.nv = cnv2pynv(frame.nv)
property stream_id:
def __get__(self):
return self.stream_id
property assoc_stream_id:
def __get__(self):
return self.assoc_stream_id
property pri:
def __get__(self):
return self.pri
property nv:
def __get__(self):
return self.nv
cdef class SynReplyFrame(CtrlFrame):
cdef int32_t stream_id
cdef object nv
cdef fill(self, cspdylay.spdylay_syn_reply *frame):
self.fillhd(&frame.hd)
self.stream_id = frame.stream_id
self.nv = cnv2pynv(frame.nv)
property stream_id:
def __get__(self):
return self.stream_id
property nv:
def __get__(self):
return self.nv
cdef class HeadersFrame(CtrlFrame):
cdef int32_t stream_id
cdef object nv
cdef fill(self, cspdylay.spdylay_headers *frame):
self.fillhd(&frame.hd)
self.stream_id = frame.stream_id
self.nv = cnv2pynv(frame.nv)
property stream_id:
def __get__(self):
return self.stream_id
property nv:
def __get__(self):
return self.nv
cdef class RstStreamFrame(CtrlFrame):
cdef int32_t stream_id
cdef uint32_t status_code
cdef fill(self, cspdylay.spdylay_rst_stream *frame):
self.fillhd(&frame.hd)
self.stream_id = frame.stream_id
self.status_code = frame.status_code
property stream_id:
| Cython |
def __get__(self):
return self.stream_id
property status_code:
def __get__(self):
return self.status_code
cdef class SettingsFrame(CtrlFrame):
cdef object iv
cdef fill(self, cspdylay.spdylay_settings *frame):
self.fillhd(&frame.hd)
self.iv = csettings2pysettings(frame.niv, frame.iv)
property iv:
def __get__(self):
return self.iv
cdef class PingFrame(CtrlFrame):
cdef uint32_t unique_id
cdef fill(self, cspdylay.spdylay_ping *frame):
self.fillhd(&frame.hd)
self.unique_id = frame.unique_id
property unique_id:
def __get__(self):
return self.unique_id
cdef class GoawayFrame(CtrlFrame):
cdef int32_t last_good_stream_id
cdef uint32_t status_code
cdef fill(self, cspdylay.spdylay_goaway *frame):
self.fillhd(&frame.hd)
self.last_good_stream_id = frame.last_good_stream_id
self.status_code = frame.status_code
property last_good_stream_id:
def __get__(self):
return self.last_good_stream_id
property status_code:
def __get__(self):
return self.status_code
cdef class WindowUpdateFrame(CtrlFrame):
cdef int32_t stream_id
cdef int32_t delta_window_size
cdef fill(self, cspdylay.spdylay_window_update *frame):
self.fillhd(&frame.hd)
self.stream_id = frame.stream_id
self.delta_window_size = frame.delta_window_size
property stream_id:
def __get__(self):
return self.stream_id
property delta_window_size:
def __get__(self):
return self.delta_window_size
cdef cnv2pynv(char **nv):
''' Convert C-style name/value pairs ``nv`` to Python style
pairs. We assume that strings in nv is UTF-8 encoded as per SPDY
spec. In Python pairs, we use unicode string.'''
cdef size_t i
pynv = []
i = 0
while nv[i]!= NULL:
pynv.append((nv[i].decode('UTF-8'), nv[i+1].decode('UTF-8')))
i += 2
return pynv
cdef char** pynv2cnv(object nv) except *:
''' Convert Python style UTF-8 name/value pairs ``nv`` to C-style
pairs. Python style name/value pairs are list of tuple (key,
value).'''
cdef char **cnv = <char**>malloc((len(nv)*2+1)*sizeof(char*))
cdef size_t i
if cnv == NULL:
raise MemoryError()
i = 0
for n, v in nv:
cnv[i] = n
i += 1
cnv[i] = v
i += 1
cnv[i] = NULL
return cnv
cdef pynv_encode(nv):
res = []
for k, v in nv:
res.append((k.encode('UTF-8'), v.encode('UTF-8')))
return res
cdef object csettings2pysettings(size_t niv,
cspdylay.spdylay_settings_entry *iv):
cdef size_t i = 0
cdef cspdylay.spdylay_settings_entry *ent
res = []
while i < niv:
ent = &iv[i]
res.append((ent.settings_id, ent.flags, ent.value))
i += 1
return res
cdef cspdylay.spdylay_settings_entry* pysettings2csettings(object iv) except *:
cdef size_t i
cdef cspdylay.spdylay_settings_entry *civ =\
<cspdylay.spdylay_settings_entry*>malloc(\
len(iv)*sizeof(cspdylay.spdylay_settings_entry))
if civ == NULL:
raise MemoryError()
i = 0
for settings_id, flags, value in iv:
civ[i].settings_id = settings_id
civ[i].flags = flags
civ[i].value = value
i += 1
return civ
cdef cspdylay.spdylay_data_provider create_c_data_prd\
(cspdylay.spdylay_data_provider *cdata_prd, object pydata_prd):
cdata_prd.source.ptr = <void*>pydata_prd
cdata_prd.read_callback = read_callback
cdef object cframe2pyframe(cspdylay.spdylay_frame_type frame_type,
cspdylay.spdylay_frame *frame):
cdef SynStreamFrame syn_stream
cdef SynReplyFrame syn_reply
cdef HeadersFrame headers
cdef RstStreamFrame rst_stream
cdef SettingsFrame settings
cdef PingFrame ping
cdef GoawayFrame goaway
cdef WindowUpdateFrame window_update
cdef object pyframe = None
if frame_type == cspdylay.SPDYLAY_SYN_STREAM:
syn_stream = SynStreamFrame()
syn_stream.fill(&frame.syn_stream)
pyframe = syn_stream
elif frame_type == cspdylay.SPDYLAY_SYN_REPLY:
syn_reply = SynReplyFrame()
syn_reply.fill(&frame.syn_reply)
pyframe = syn_reply
elif frame_type == cspdylay.SPDYLAY_HEADERS:
headers = HeadersFrame()
headers.fill(&frame.headers)
pyframe = headers
elif frame_type == cspdylay.SPDYLAY_RST_STREAM:
rst_stream = RstStreamFrame()
rst_stream.fill(&frame.rst_stream)
pyframe = rst_stream
elif frame_type == cspdylay.SPDYLAY_SETTINGS:
settings = SettingsFrame()
settings.fill(&frame.settings)
pyframe = settings
elif frame_type == cspdylay.SPDYLAY_PING:
ping = PingFrame()
ping.fill(&frame.ping)
pyframe = ping
elif frame_type == cspdylay.SPDYLAY_GOAWAY:
goaway = GoawayFrame()
goaway.fill(&frame.goaway)
pyframe = goaway
elif frame_type == cspdylay.SPDYLAY_WINDOW_UPDATE:
window_update = WindowUpdateFrame()
window_update.fill(&frame.window_update)
pyframe = window_update
return pyframe
cdef void _call_frame_callback(Session pysession,
cspdylay.spdylay_frame_type frame_type,
cspdylay.spdylay_frame *frame,
object callback):
if not callback:
return
try:
pyframe = cframe2pyframe(frame_type, frame)
if pyframe:
callback(pysession, pyframe)
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef void on_ctrl_recv_callback(cspdylay.spdylay_session *session,
cspdylay.spdylay_frame_type frame_type,
cspdylay.spdylay_frame *frame,
void *user_data):
cdef Session pysession = <Session>user_data
_call_frame_callback(pysession, frame_type, frame,
pysession.on_ctrl_recv_cb)
cdef void on_invalid_ctrl_recv_callback(cspdylay.spdylay_session *session,
cspdylay.spdylay_frame_type frame_type,
cspdylay.spdylay_frame *frame,
uint32_t status_code,
void *user_data):
cdef Session pysession = <Session>user_data
if not pysession.on_invalid_ctrl_recv_cb:
return
try:
pyframe = cframe2pyframe(frame_type, frame)
if pyframe:
pysession.on_invalid_ctrl_recv_cb(pysession, pyframe, status_code)
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef void before_ctrl_send_callback(cspdylay.spdylay_session *session,
cspdylay.spdylay_frame_type frame_type,
cspdylay.spdylay_frame *frame,
void *user_data):
cdef Session pysession = <Session>user_data
_call_frame_callback(pysession, frame_type, frame,
pysession.before_ctrl_send_cb)
cdef void on_ctrl_send_callback(cspdylay.spdylay_session *session,
cspdylay.spdylay_frame_type frame_type,
cspdylay.spdylay_frame *frame,
void *user_data):
cdef Session pysession = <Session>user_data
_call_frame_callback(pysession, frame_type, frame,
pysession.on_ctrl_send_cb)
cdef void on_ctrl_not_send_callback(cspdylay.spdylay_session *session,
cspdylay.spdylay_frame_type frame_type,
cspdylay.spdylay_frame *frame,
int error_code,
void *user_data):
cdef Session pysession = <Session> | Cython |
user_data
if not pysession.on_ctrl_not_send_cb:
return
try:
pyframe = cframe2pyframe(frame_type, frame)
if pyframe:
pysession.on_ctrl_not_send_cb(pysession, pyframe, error_code)
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef void on_ctrl_recv_parse_error_callback(\
cspdylay.spdylay_session *session,
cspdylay.spdylay_frame_type frame_type,
uint8_t *head, size_t headlen,
uint8_t *payload, size_t payloadlen,
int error_code, void *user_data):
cdef Session pysession = <Session>user_data
if not pysession.on_ctrl_recv_parse_error_cb:
return
try:
pysession.on_ctrl_recv_parse_error_cb(pysession, frame_type,
(<char*>head)[:headlen],
(<char*>payload)[:payloadlen],
error_code)
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef void on_unknown_ctrl_recv_callback(cspdylay.spdylay_session *session,
uint8_t *head, size_t headlen,
uint8_t *payload, size_t payloadlen,
void *user_data):
cdef Session pysession = <Session>user_data
if not pysession.on_unknown_ctrl_recv_cb:
return
try:
pysession.on_unknown_ctrl_recv_cb(pysession,
(<char*>head)[:headlen],
(<char*>payload)[:payloadlen])
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef ssize_t recv_callback(cspdylay.spdylay_session *session,
uint8_t *buf, size_t length,
int flags, void *user_data):
cdef Session pysession = <Session>user_data
if pysession.recv_callback:
try:
data = pysession.recv_callback(pysession, length)
except EOFError as e:
pysession.error = e
return cspdylay.SPDYLAY_ERR_EOF
except CallbackFailureError as e:
pysession.error = e
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
except Exception as e:
pysession.error = e
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
except BaseException as e:
pysession.base_error = e
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
if data:
if len(data) > length:
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
memcpy(buf, <char*>data, len(data))
return len(data)
else:
return cspdylay.SPDYLAY_ERR_WOULDBLOCK
else:
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
cdef ssize_t send_callback(cspdylay.spdylay_session *session,
uint8_t *data, size_t length, int flags,
void *user_data):
cdef Session pysession = <Session>user_data
if pysession.send_callback:
try:
rv = pysession.send_callback(pysession, (<char*>data)[:length])
except CallbackFailureError as e:
pysession.error = e
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
except Exception as e:
pysession.error = e
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
except BaseException as e:
pysession.base_error = e
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
if rv:
return rv
else:
return cspdylay.SPDYLAY_ERR_WOULDBLOCK
else:
# If no send_callback is given, pretend all data were sent and
# just return length
return length
cdef void on_data_chunk_recv_callback(cspdylay.spdylay_session *session,
uint8_t flags, int32_t stream_id,
uint8_t *data, size_t length,
void *user_data):
cdef Session pysession = <Session>user_data
if pysession.on_data_chunk_recv_cb:
try:
pysession.on_data_chunk_recv_cb(pysession, flags, stream_id,
(<char*>data)[:length])
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef void on_data_recv_callback(cspdylay.spdylay_session *session,
uint8_t flags, int32_t stream_id,
int32_t length, void *user_data):
cdef Session pysession = <Session>user_data
if pysession.on_data_recv_cb:
try:
pysession.on_data_recv_cb(pysession, flags, stream_id, length)
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef void on_data_send_callback(cspdylay.spdylay_session *session,
uint8_t flags, int32_t stream_id,
int32_t length, void *user_data):
cdef Session pysession = <Session>user_data
if pysession.on_data_send_cb:
try:
pysession.on_data_send_cb(pysession, flags, stream_id, length)
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef void on_stream_close_callback(cspdylay.spdylay_session *session,
int32_t stream_id,
cspdylay.spdylay_status_code status_code,
void *user_data):
cdef Session pysession = <Session>user_data
if pysession.on_stream_close_cb:
try:
pysession.on_stream_close_cb(pysession, stream_id, status_code)
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef void on_request_recv_callback(cspdylay.spdylay_session *session,
int32_t stream_id,
void *user_data):
cdef Session pysession = <Session>user_data
if pysession.on_request_recv_cb:
try:
pysession.on_request_recv_cb(pysession, stream_id)
except Exception as e:
pysession.error = e
except BaseException as e:
pysession.base_error = e
cdef class ReadCtrl:
cdef int flags
def __cinit__(self):
self.flags = 0
property flags:
def __set__(self, value):
self.flags = value
cdef ssize_t read_callback(cspdylay.spdylay_session *session,
int32_t stream_id, uint8_t *buf, size_t length,
int *eof, cspdylay.spdylay_data_source *source,
void *user_data):
cdef Session pysession = <Session>user_data
cdef ReadCtrl read_ctrl = ReadCtrl()
data_prd = <object>source.ptr
try:
res = data_prd.read_cb(pysession, stream_id, length, read_ctrl,
data_prd.source)
except TemporalCallbackFailureError as e:
return cspdylay.SPDYLAY_ERR_TEMPORAL_CALLBACK_FAILURE
except CallbackFailureError as e:
pysession.error = e
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
except Exception as e:
pysession.error = e
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
except BaseException as e:
pysession.base_error = e
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
if read_ctrl.flags & READ_EOF:
eof[0] = 1
if res == cspdylay.SPDYLAY_ERR_DEFERRED:
return res
elif res:
if len(res) > length:
return cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
memcpy(buf, <char*>res, len(res))
return len(res)
else:
return 0
cdef class Session:
cdef cspdylay.spdylay_session *_c_session
cdef object recv_callback
cdef object send_callback
cdef object on_ctrl_recv_cb
cdef object on_invalid_ctrl_recv_cb
cdef object on_data_chunk_recv_cb
cdef object on_data_recv_cb
cdef object before_ctrl_send_cb
cdef object on_ctrl_send_cb
cdef object on_ctrl_not_send_cb
cdef object on_data_send_cb
cdef object on_stream_close_cb
cdef object on_request_recv_cb
cdef object on_ctrl_recv_parse_error_cb
cdef object on_unknown_ctrl_recv_cb
cdef object user_data
cdef object error
cdef object base_error
property user_data:
def __get__(self):
return self.user_data
def __cinit__(self, side, version, config=None,
send_cb=None, recv_cb=None,
on_ctrl_recv_cb=None,
on_invalid_ctrl_recv_cb=None,
on_data | Cython |
_chunk_recv_cb=None,
on_data_recv_cb=None,
before_ctrl_send_cb=None,
on_ctrl_send_cb=None,
on_ctrl_not_send_cb=None,
on_data_send_cb=None,
on_stream_close_cb=None,
on_request_recv_cb=None,
on_ctrl_recv_parse_error_cb=None,
on_unknown_ctrl_recv_cb=None,
user_data=None):
cdef cspdylay.spdylay_session_callbacks c_session_callbacks
cdef int rv
self._c_session = NULL
memset(&c_session_callbacks, 0, sizeof(c_session_callbacks))
c_session_callbacks.recv_callback = \
<cspdylay.spdylay_recv_callback>recv_callback
c_session_callbacks.send_callback = \
<cspdylay.spdylay_send_callback>send_callback
c_session_callbacks.on_ctrl_recv_callback = \
<cspdylay.spdylay_on_ctrl_recv_callback>on_ctrl_recv_callback
c_session_callbacks.on_invalid_ctrl_recv_callback = \
<cspdylay.spdylay_on_invalid_ctrl_recv_callback>\
on_invalid_ctrl_recv_callback
c_session_callbacks.on_data_chunk_recv_callback = \
<cspdylay.spdylay_on_data_chunk_recv_callback>\
on_data_chunk_recv_callback
c_session_callbacks.on_data_recv_callback = \
<cspdylay.spdylay_on_data_recv_callback>on_data_recv_callback
c_session_callbacks.before_ctrl_send_callback = \
<cspdylay.spdylay_before_ctrl_send_callback>\
before_ctrl_send_callback
c_session_callbacks.on_ctrl_send_callback = \
<cspdylay.spdylay_on_ctrl_send_callback>on_ctrl_send_callback
c_session_callbacks.on_ctrl_not_send_callback = \
<cspdylay.spdylay_on_ctrl_not_send_callback>\
on_ctrl_not_send_callback
c_session_callbacks.on_data_send_callback = \
<cspdylay.spdylay_on_data_send_callback>on_data_send_callback
c_session_callbacks.on_stream_close_callback = \
<cspdylay.spdylay_on_stream_close_callback>on_stream_close_callback
c_session_callbacks.on_request_recv_callback = \
<cspdylay.spdylay_on_request_recv_callback>on_request_recv_callback
# c_session_callbacks.get_credential_proof = NULL
# c_session_callbacks.get_credential_ncerts = NULL
# c_session_callbacks.get_credential_cert = NULL
c_session_callbacks.on_ctrl_recv_parse_error_callback = \
<cspdylay.spdylay_on_ctrl_recv_parse_error_callback>\
on_ctrl_recv_parse_error_callback
c_session_callbacks.on_unknown_ctrl_recv_callback = \
<cspdylay.spdylay_on_unknown_ctrl_recv_callback>\
on_unknown_ctrl_recv_callback
self.recv_callback = recv_cb
self.send_callback = send_cb
self.on_ctrl_recv_cb = on_ctrl_recv_cb
self.on_invalid_ctrl_recv_cb = on_invalid_ctrl_recv_cb
self.on_data_chunk_recv_cb = on_data_chunk_recv_cb
self.on_data_recv_cb = on_data_recv_cb
self.before_ctrl_send_cb = before_ctrl_send_cb
self.on_ctrl_send_cb = on_ctrl_send_cb
self.on_ctrl_not_send_cb = on_ctrl_not_send_cb
self.on_data_send_cb = on_data_send_cb
self.on_stream_close_cb = on_stream_close_cb
self.on_request_recv_cb = on_request_recv_cb
self.on_ctrl_recv_parse_error_cb = on_ctrl_recv_parse_error_cb
self.on_unknown_ctrl_recv_cb = on_unknown_ctrl_recv_cb
self.user_data = user_data
if side == CLIENT:
rv = cspdylay.spdylay_session_client_new(&self._c_session,
version,
&c_session_callbacks,
<void*>self)
elif side == SERVER:
rv = cspdylay.spdylay_session_server_new(&self._c_session,
version,
&c_session_callbacks,
<void*>self)
else:
raise InvalidArgumentError('side must be either CLIENT or SERVER')
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
elif rv == cspdylay.SPDYLAY_ERR_ZLIB:
raise ZlibError(_strerror(rv))
elif rv == cspdylay.SPDYLAY_ERR_UNSUPPORTED_VERSION:
raise UnsupportedVersionError(_strerror(rv))
def __init__(self, side, version, config=None,
send_cb=None, recv_cb=None,
on_ctrl_recv_cb=None,
on_invalid_ctrl_recv_cb=None,
on_data_chunk_recv_cb=None,
on_data_recv_cb=None,
before_ctrl_send_cb=None,
on_ctrl_send_cb=None,
on_ctrl_not_send_cb=None,
on_data_send_cb=None,
on_stream_close_cb=None,
on_request_recv_cb=None,
on_ctrl_recv_parse_error_cb=None,
user_data=None):
pass
def __dealloc__(self):
cspdylay.spdylay_session_del(self._c_session)
cpdef recv(self, data=None):
cdef int rv
cdef char *c_data
self.error = self.base_error = None
if data is None:
rv = cspdylay.spdylay_session_recv(self._c_session)
else:
c_data = data
rv = cspdylay.spdylay_session_mem_recv(self._c_session,
<uint8_t*>c_data, len(data))
if self.base_error:
raise self.base_error
if self.error:
raise self.error
if rv >= 0:
return
elif rv == cspdylay.SPDYLAY_ERR_EOF:
raise EOFError()
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
elif rv == cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE:
raise CallbackFailureError()
cpdef send(self):
cdef int rv
self.error = self.base_error = None
rv = cspdylay.spdylay_session_send(self._c_session)
if self.base_error:
raise self.base_error
elif self.error:
raise self.error
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
elif rv == cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE:
raise CallbackFailureError()
cpdef resume_data(self, stream_id):
cpdef int rv
rv = cspdylay.spdylay_session_resume_data(self._c_session, stream_id)
if rv == 0:
return True
elif rv == cspdylay.SPDYLAY_ERR_INVALID_ARGUMENT:
return False
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef want_read(self):
return cspdylay.spdylay_session_want_read(self._c_session)
cpdef want_write(self):
return cspdylay.spdylay_session_want_write(self._c_session)
cpdef get_stream_user_data(self, stream_id):
return <object>cspdylay.spdylay_session_get_stream_user_data(\
self._c_session, stream_id)
cpdef get_outbound_queue_size(self):
return cspdylay.spdylay_session_get_outbound_queue_size(\
self._c_session)
cpdef get_pri_lowest(self):
return cspdylay.spdylay_session_get_pri_lowest(self._c_session)
cpdef fail_session(self, status_code):
cdef int rv
rv = cspdylay.spdylay_session_fail_session(self._c_session,
status_code)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_request(self, pri, nv, data_prd=None, stream_user_data=None):
cdef cspdylay.spdylay_data_provider c_data_prd
cdef cspdylay.spdylay_data_provider *c_data_prd_ptr
cpdef int rv
cdef char **cnv
nv = pynv_encode(nv)
cnv = pynv2cnv(nv)
if data_prd:
create_c_data_prd(&c_data_prd, data_prd)
c_data_prd_ptr = &c_data_prd
else:
c_data_prd_ptr = NULL
rv = cspdylay.spdylay_submit_request(self._c_session, pri, cnv,
c_data_prd_ptr,
<void*>stream_user_data)
free(cnv)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_INVALID_ARGUMENT:
raise InvalidArgumentError(_strerror(rv))
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_response(self, stream_id, nv, data_prd=None):
cdef cspdylay.spdylay_data_provider c_data_prd
cdef cspdylay.spdylay_data_provider *c_data_prd_ptr
cpdef int rv
cdef char **cnv
nv = pynv_encode(nv)
cnv = pynv2cnv(nv)
| Cython |
if data_prd:
create_c_data_prd(&c_data_prd, data_prd)
c_data_prd_ptr = &c_data_prd
else:
c_data_prd_ptr = NULL
rv = cspdylay.spdylay_submit_response(self._c_session, stream_id,
cnv, c_data_prd_ptr)
free(cnv)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_INVALID_ARGUMENT:
raise InvalidArgumentError(_strerror(rv))
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_syn_stream(self, flags, pri, nv, assoc_stream_id=0,
stream_user_data=None):
cdef int rv
cdef char **cnv
nv = pynv_encode(nv)
cnv = pynv2cnv(nv)
rv = cspdylay.spdylay_submit_syn_stream(self._c_session,
flags,
assoc_stream_id,
pri,
cnv,
<void*>stream_user_data)
free(cnv)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_INVALID_ARGUMENT:
raise InvalidArgumentError(_strerror(rv))
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_syn_reply(self, flags, stream_id, nv):
cdef int rv
cdef char **cnv
nv = pynv_encode(nv)
cnv = pynv2cnv(nv)
rv = cspdylay.spdylay_submit_syn_reply(self._c_session,
flags, stream_id, cnv)
free(cnv)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_INVALID_ARGUMENT:
raise InvalidArgumentError(_strerror(rv))
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_headers(self, flags, stream_id, nv):
cdef int rv
cdef char **cnv
nv = pynv_encode(nv)
cnv = pynv2cnv(nv)
rv = cspdylay.spdylay_submit_headers(self._c_session,
flags, stream_id, cnv)
free(cnv)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_INVALID_ARGUMENT:
raise InvalidArgumentError(_strerror(rv))
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_data(self, stream_id, flags, data_prd):
cdef cspdylay.spdylay_data_provider c_data_prd
cdef cspdylay.spdylay_data_provider *c_data_prd_ptr
cpdef int rv
if data_prd:
create_c_data_prd(&c_data_prd, data_prd)
c_data_prd_ptr = &c_data_prd
else:
c_data_prd_ptr = NULL
rv = cspdylay.spdylay_submit_data(self._c_session, stream_id,
flags, c_data_prd_ptr)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_rst_stream(self, stream_id, status_code):
cdef int rv
rv = cspdylay.spdylay_submit_rst_stream(self._c_session, stream_id,
status_code)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_ping(self):
cdef int rv
rv = cspdylay.spdylay_submit_ping(self._c_session)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_goaway(self, status_code):
cdef int rv
rv = cspdylay.spdylay_submit_goaway(self._c_session, status_code)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_window_update(self, stream_id, delta_window_size):
cdef int rv
rv = cspdylay.spdylay_submit_window_update(self._c_session, stream_id,
delta_window_size)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_INVALID_ARGUMENT:
raise InvalidArgumentError()
elif rv == cspdylay.SPDYLAY_ERR_STREAM_CLOSED:
raise StreamClosedError()
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cpdef submit_settings(self, flags, iv):
''' Submit SETTINGS frame. iv is list of tuple (settings_id,
flag, value)
'''
cdef int rv
cdef cspdylay.spdylay_settings_entry *civ = pysettings2csettings(iv)
rv = cspdylay.spdylay_submit_settings(self._c_session, flags,
civ, len(iv))
free(civ)
if rv == 0:
return
elif rv == cspdylay.SPDYLAY_ERR_INVALID_ARGUMENT:
raise InvalidArgumentError(_strerror(rv))
elif rv == cspdylay.SPDYLAY_ERR_NOMEM:
raise MemoryError()
cdef _strerror(int error_code):
return cspdylay.spdylay_strerror(error_code).decode('UTF-8')
cpdef get_npn_protocols():
cdef size_t proto_list_len
cdef cspdylay.spdylay_npn_proto *proto_list
proto_list = cspdylay.spdylay_npn_get_proto_list(&proto_list_len)
res = []
for i in range(proto_list_len):
res.append((<char*>proto_list[i].proto)[:proto_list[i].len]\
.decode('UTF-8'))
return res
cpdef int npn_get_version(proto):
cdef char *cproto
if proto == None:
return 0
proto = proto.encode('UTF-8')
cproto = proto
return cspdylay.spdylay_npn_get_version(<unsigned char*>cproto, len(proto))
# Side
CLIENT = 1
SERVER = 2
# SPDY protocol version
PROTO_SPDY2 = cspdylay.SPDYLAY_PROTO_SPDY2
PROTO_SPDY3 = cspdylay.SPDYLAY_PROTO_SPDY3
# Control frame flags
CTRL_FLAG_NONE = cspdylay.SPDYLAY_CTRL_FLAG_NONE
CTRL_FLAG_FIN = cspdylay.SPDYLAY_CTRL_FLAG_FIN
CTRL_FLAG_UNIDIRECTIONAL = cspdylay.SPDYLAY_CTRL_FLAG_UNIDIRECTIONAL
# Data frame flags
DATA_FLAG_NONE = cspdylay.SPDYLAY_DATA_FLAG_NONE
DATA_FLAG_FIN = cspdylay.SPDYLAY_DATA_FLAG_FIN
# Error codes
ERR_INVALID_ARGUMENT = cspdylay.SPDYLAY_ERR_INVALID_ARGUMENT
ERR_ZLIB = cspdylay.SPDYLAY_ERR_ZLIB
ERR_UNSUPPORTED_VERSION = cspdylay.SPDYLAY_ERR_UNSUPPORTED_VERSION
ERR_WOULDBLOCK = cspdylay.SPDYLAY_ERR_WOULDBLOCK
ERR_PROTO = cspdylay.SPDYLAY_ERR_PROTO
ERR_INVALID_FRAME = cspdylay.SPDYLAY_ERR_INVALID_FRAME
ERR_EOF = cspdylay.SPDYLAY_ERR_EOF
ERR_DEFERRED = cspdylay.SPDYLAY_ERR_DEFERRED
ERR_STREAM_ID_NOT_AVAILABLE = cspdylay.SPDYLAY_ERR_STREAM_ID_NOT_AVAILABLE
ERR_STREAM_CLOSED = cspdylay.SPDYLAY_ERR_STREAM_CLOSED
ERR_STREAM_CLOSING = cspdylay.SPDYLAY_ERR_STREAM_CLOSING
ERR_STREAM_SHUT_WR = cspdylay.SPDYLAY_ERR_STREAM_SHUT_WR
ERR_INVALID_STREAM_ID = cspdylay.SPDYLAY_ERR_INVALID_STREAM_ID
ERR_INVALID_STREAM_STATE = cspdylay.SPDYLAY_ERR_INVALID_STREAM_STATE
ERR_DEFERRED_DATA_EXIST = cspdylay.SPDYLAY_ERR_DEFERRED_DATA_EXIST
ERR_SYN_STREAM_NOT_ALLOWED = cspdylay.SPDYLAY_ERR_SYN_STREAM_NOT_ALLOWED
ERR_GOAWAY_ALREADY_SENT = cspdylay.SPDYLAY_ERR_GOAWAY_ALREADY_SENT
ERR_INVALID_HEADER_BLOCK = cspdylay.SPDYLAY_ERR_INVALID_HEADER_BLOCK
ERR_INVALID_STATE = cspdylay.SPDYLAY_ERR_INVALID_STATE
ERR_GZIP = cspdylay.SPDYLAY_ERR_GZIP
ERR_TEMPORAL_CALLBACK_FAILURE = cspdylay.SPDYLAY_ERR_TEMPORAL_CALLBACK_FAILURE
ERR_FATAL = cspdylay.SPDYLAY_ERR_FATAL
ERR_NOMEM = cspdylay.SPDYLAY_ERR_NOMEM
ERR_CALLBACK_FAILURE = cspdylay.SPDYLAY_ERR_CALLBACK_FAILURE
# Read Callback Flags
READ_EOF = 1
# The status code for RST_STREAM
OK = cspdylay.S | Cython |
PDYLAY_OK
PROTOCOL_ERROR = cspdylay.SPDYLAY_PROTOCOL_ERROR
INVALID_STREAM = cspdylay.SPDYLAY_INVALID_STREAM
REFUSED_STREAM = cspdylay.SPDYLAY_REFUSED_STREAM
UNSUPPORTED_VERSION = cspdylay.SPDYLAY_UNSUPPORTED_VERSION
CANCEL = cspdylay.SPDYLAY_CANCEL
INTERNAL_ERROR = cspdylay.SPDYLAY_INTERNAL_ERROR
FLOW_CONTROL_ERROR = cspdylay.SPDYLAY_FLOW_CONTROL_ERROR
# Following status codes were introduced in SPDY/3
STREAM_IN_USE = cspdylay.SPDYLAY_STREAM_IN_USE
STREAM_ALREADY_CLOSED = cspdylay.SPDYLAY_STREAM_ALREADY_CLOSED
INVALID_CREDENTIALS = cspdylay.SPDYLAY_INVALID_CREDENTIALS
FRAME_TOO_LARGE = cspdylay.SPDYLAY_FRAME_TOO_LARGE
# The status codes for GOAWAY, introduced in SPDY/3.
GOAWAY_OK = cspdylay.SPDYLAY_GOAWAY_OK
GOAWAY_PROTOCOL_ERROR = cspdylay.SPDYLAY_GOAWAY_PROTOCOL_ERROR
GOAWAY_INTERNAL_ERROR = cspdylay.SPDYLAY_GOAWAY_INTERNAL_ERROR
# Frame types
SYN_STREAM = cspdylay.SPDYLAY_SYN_STREAM
SYN_REPLY = cspdylay.SPDYLAY_SYN_REPLY
RST_STREAM = cspdylay.SPDYLAY_RST_STREAM
SETTINGS = cspdylay.SPDYLAY_SETTINGS
NOOP = cspdylay.SPDYLAY_NOOP
PING = cspdylay.SPDYLAY_PING
GOAWAY = cspdylay.SPDYLAY_GOAWAY
HEADERS = cspdylay.SPDYLAY_HEADERS
WINDOW_UPDATE = cspdylay.SPDYLAY_WINDOW_UPDATE
CREDENTIAL = cspdylay.SPDYLAY_CREDENTIAL
# The flags for the SETTINGS control frame.
FLAG_SETTINGS_NONE = cspdylay.SPDYLAY_FLAG_SETTINGS_NONE
FLAG_SETTINGS_CLEAR_SETTINGS = cspdylay.SPDYLAY_FLAG_SETTINGS_CLEAR_SETTINGS
# The flags for SETTINGS ID/value pair.
ID_FLAG_SETTINGS_NONE = cspdylay.SPDYLAY_ID_FLAG_SETTINGS_NONE
ID_FLAG_SETTINGS_PERSIST_VALUE = cspdylay.SPDYLAY_ID_FLAG_SETTINGS_PERSIST_VALUE
ID_FLAG_SETTINGS_PERSISTED = cspdylay.SPDYLAY_ID_FLAG_SETTINGS_PERSISTED
# The SETTINGS ID.
SETTINGS_UPLOAD_BANDWIDTH = cspdylay.SPDYLAY_SETTINGS_UPLOAD_BANDWIDTH
SETTINGS_DOWNLOAD_BANDWIDTH = cspdylay.SPDYLAY_SETTINGS_DOWNLOAD_BANDWIDTH
SETTINGS_ROUND_TRIP_TIME = cspdylay.SPDYLAY_SETTINGS_ROUND_TRIP_TIME
SETTINGS_MAX_CONCURRENT_STREAMS = \
cspdylay.SPDYLAY_SETTINGS_MAX_CONCURRENT_STREAMS
SETTINGS_CURRENT_CWND = cspdylay.SPDYLAY_SETTINGS_CURRENT_CWND
SETTINGS_DOWNLOAD_RETRANS_RATE = \
cspdylay.SPDYLAY_SETTINGS_DOWNLOAD_RETRANS_RATE
SETTINGS_INITIAL_WINDOW_SIZE = cspdylay.SPDYLAY_SETTINGS_INITIAL_WINDOW_SIZE
SETTINGS_CLIENT_CERTIFICATE_VECTOR_SIZE = \
cspdylay.SPDYLAY_SETTINGS_CLIENT_CERTIFICATE_VECTOR_SIZE
SETTINGS_MAX = cspdylay.SPDYLAY_SETTINGS_MAX
try:
# Simple SPDY Server implementation. We mimics the methods and
# attributes of http.server.BaseHTTPRequestHandler. Since this
# implementation uses TLS NPN, Python 3.3.0 or later is required.
import socket
import threading
import socketserver
import ssl
import io
import select
import sys
import time
from xml.sax.saxutils import escape
class Stream:
def __init__(self, stream_id):
self.stream_id = stream_id
self.data_prd = None
self.method = None
self.path = None
self.version = None
self.scheme = None
self.host = None
self.headers = []
self.rfile = None
self.wfile = None
def process_headers(self, headers):
for k, v in headers:
if k == ':method':
self.method = v
elif k == ':scheme':
self.scheme = v
elif k == ':path':
self.path = v
elif k == ':version':
self.version = v
elif k == ':host':
self.host = v
else:
self.headers.append((k, v))
class SessionCtrl:
def __init__(self):
self.streams = {}
class BaseSPDYRequestHandler(socketserver.BaseRequestHandler):
server_version = 'Python-spdylay'
error_content_type = 'text/html; charset=UTF-8'
# Same HTML from Apache error page
error_message_format = '''\
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>{code} {reason}</title>
</head><body>
<h1>{reason}</h1>
<p>{explain}</p>
<hr>
<address>{server} at {hostname} Port {port}</address>
</body></html>
'''
def send_error(self, code, message=None):
# Make sure that code is really int
code = int(code)
try:
shortmsg, longmsg = self.responses[code]
except KeyError:
shortmsg, longmsg = '???', '???'
if message is None:
message = shortmsg
explain = longmsg
content = self.error_message_format.format(\
code=code,
reason = escape(message),
explain=escape(explain),
server=escape(self.server_version),
hostname=escape(socket.getfqdn()),
port=self.server.server_address[1]).encode('UTF-8')
self.send_response(code, message)
self.send_header('content-type', self.error_content_type)
self.send_header('content-length', str(len(content)))
self.wfile.write(content)
def send_response(self, code, message=None):
if message is None:
try:
shortmsg, _ = self.responses[code]
except KeyError:
shortmsg = '???'
message = shortmsg
self._response_headers.append((':status',
'{} {}'.format(code, message)))
def send_header(self, keyword, value):
self._response_headers.append((keyword, value))
def version_string(self):
return self.server_version +'' + self.sys_version
def handle_one_request(self, stream):
self.stream = stream
stream.wfile = io.BytesIO()
self.command = stream.method
self.path = stream.path
self.request_version = stream.version
self.headers = stream.headers
self.rfile = stream.rfile
self.wfile = stream.wfile
self._response_headers = []
if stream.method is None:
self.send_error(400)
else:
mname = 'do_' + stream.method
if hasattr(self, mname):
method = getattr(self, mname)
if self.rfile is not None:
self.rfile.seek(0)
method()
else:
self.send_error(501, 'Unsupported method ({})'\
.format(stream.method))
self.wfile.seek(0)
data_prd = DataProvider(self.wfile, self.read_cb)
stream.data_prd = data_prd
self.send_header(':version', 'HTTP/1.1')
self.send_header('server', self.version_string())
self.send_header('date', self.date_time_string())
self.session.submit_response(stream.stream_id,
self._response_headers, data_prd)
def send_cb(self, session, data):
return self.request.send(data)
def read_cb(self, session, stream_id, length, read_ctrl, source):
data = source.read(length)
if not data:
read_ctrl.flags = READ_EOF
return data
def on_ctrl_recv_cb(self, session, frame):
if frame.frame_type == SYN_STREAM:
stream = Stream(frame.stream_id)
self.ssctrl.streams[frame.stream_id] = stream
stream.process_headers(frame.nv)
elif frame.frame_type == HEADERS:
if frame.stream_id in self.ssctrl.streams:
stream = self.ssctrl.streams[frame.stream_id]
stream.process_headers(frame.nv)
def on_data_chunk_recv_cb(self, session, flags, stream_id, data):
if stream_id in self.ssctrl.streams:
stream = self.ssctrl.streams[stream_id]
if stream.method == 'POST':
if not stream.rfile:
stream.rfile = io.BytesIO()
stream.rfile.write(data)
else:
# We don't allow request body if method is not POST
session.submit_rst_stream(stream_id, PROTOCOL_ERROR)
def on_stream_close_cb(self, session, stream_id, status_code):
if stream_id in self.ssctrl.streams:
del self.ssctrl.streams[stream_id]
def on_request_recv_cb(self, session, stream_id):
if stream_id in self.ssctrl.streams:
stream = self.ssctrl.streams[stream_id]
self.handle_one_request(stream)
def handle(self):
self.request.setsockopt(socket.IPPROTO_TCP,
socket.TCP_NODELAY, True)
try:
self.request.do_handshake()
self.request.setblocking(False)
version = npn_get_version(self.request.selected_npn_protocol())
if version == 0:
return
self.ssctrl = Session | Cython |
Ctrl()
self.session = Session(\
SERVER, version,
send_cb=self.send_cb,
on_ctrl_recv_cb=self.on_ctrl_recv_cb,
on_data_chunk_recv_cb=self.on_data_chunk_recv_cb,
on_stream_close_cb=self.on_stream_close_cb,
on_request_recv_cb=self.on_request_recv_cb)
self.session.submit_settings(\
FLAG_SETTINGS_NONE,
[(SETTINGS_MAX_CONCURRENT_STREAMS, ID_FLAG_SETTINGS_NONE,
100)]
)
while self.session.want_read() or self.session.want_write():
want_read = want_write = False
try:
data = self.request.recv(4096)
if data:
self.session.recv(data)
else:
break
except ssl.SSLWantReadError:
want_read = True
except ssl.SSLWantWriteError:
want_write = True
try:
self.session.send()
except ssl.SSLWantReadError:
want_read = True
except ssl.SSLWantWriteError:
want_write = True
if want_read or want_write:
select.select([self.request] if want_read else [],
[self.request] if want_write else [],
[])
finally:
self.request.setblocking(True)
# The following methods and attributes are copied from
# Lib/http/server.py of cpython source code
def date_time_string(self, timestamp=None):
"""Return the current date and time formatted for a
message header."""
if timestamp is None:
timestamp = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
self.weekdayname[wd],
day, self.monthname[month], year,
hh, mm, ss)
return s
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
monthname = [None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# The Python system version, truncated to its first component.
sys_version = "Python/" + sys.version.split()[0]
# Table mapping response codes to messages; entries have the
# form {code: (shortmessage, longmessage)}.
# See RFC 2616 and 6585.
responses = {
100: ('Continue', 'Request received, please continue'),
101: ('Switching Protocols',
'Switching to new protocol; obey Upgrade header'),
200: ('OK', 'Request fulfilled, document follows'),
201: ('Created', 'Document created, URL follows'),
202: ('Accepted',
'Request accepted, processing continues off-line'),
203: ('Non-Authoritative Information',
'Request fulfilled from cache'),
204: ('No Content', 'Request fulfilled, nothing follows'),
205: ('Reset Content', 'Clear input form for further input.'),
206: ('Partial Content', 'Partial content follows.'),
300: ('Multiple Choices',
'Object has several resources -- see URI list'),
301: ('Moved Permanently',
'Object moved permanently -- see URI list'),
302: ('Found', 'Object moved temporarily -- see URI list'),
303: ('See Other', 'Object moved -- see Method and URL list'),
304: ('Not Modified',
'Document has not changed since given time'),
305: ('Use Proxy',
'You must use proxy specified in Location to access this '
'resource.'),
307: ('Temporary Redirect',
'Object moved temporarily -- see URI list'),
400: ('Bad Request',
'Bad request syntax or unsupported method'),
401: ('Unauthorized',
'No permission -- see authorization schemes'),
402: ('Payment Required',
'No payment -- see charging schemes'),
403: ('Forbidden',
'Request forbidden -- authorization will not help'),
404: ('Not Found', 'Nothing matches the given URI'),
405: ('Method Not Allowed',
'Specified method is invalid for this resource.'),
406: ('Not Acceptable', 'URI not available in preferred format.'),
407: ('Proxy Authentication Required', 'You must authenticate with '
'this proxy before proceeding.'),
408: ('Request Timeout', 'Request timed out; try again later.'),
409: ('Conflict', 'Request conflict.'),
410: ('Gone',
'URI no longer exists and has been permanently removed.'),
411: ('Length Required', 'Client must specify Content-Length.'),
412: ('Precondition Failed', 'Precondition in headers is false.'),
413: ('Request Entity Too Large', 'Entity is too large.'),
414: ('Request-URI Too Long', 'URI is too long.'),
415: ('Unsupported Media Type',
'Entity body in unsupported format.'),
416: ('Requested Range Not Satisfiable',
'Cannot satisfy request range.'),
417: ('Expectation Failed',
'Expect condition could not be satisfied.'),
428: ('Precondition Required',
'The origin server requires the request to be conditional.'),
429: ('Too Many Requests', 'The user has sent too many requests '
'in a given amount of time ("rate limiting").'),
431: ('Request Header Fields Too Large',
'The server is unwilling to process '
'the request because its header fields are too large.'),
500: ('Internal Server Error', 'Server got itself in trouble'),
501: ('Not Implemented',
'Server does not support this operation'),
502: ('Bad Gateway',
'Invalid responses from another server/proxy.'),
503: ('Service Unavailable',
'The server cannot process the request due to a high load'),
504: ('Gateway Timeout',
'The gateway server did not receive a timely response'),
505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
511: ('Network Authentication Required',
'The client needs to authenticate to gain network access.'),
}
class ThreadedSPDYServer(socketserver.ThreadingMixIn,
socketserver.TCPServer):
def __init__(self, server_address, RequestHandlerCalss,
cert_file, key_file):
self.allow_reuse_address = True
self.ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
self.ctx.options = ssl.OP_ALL | ssl.OP_NO_SSLv2 | \
ssl.OP_NO_COMPRESSION
self.ctx.load_cert_chain(cert_file, key_file)
self.ctx.set_npn_protocols(get_npn_protocols())
socketserver.TCPServer.__init__(self, server_address,
RequestHandlerCalss)
def start(self, daemon=False):
server_thread = threading.Thread(target=self.serve_forever)
server_thread.daemon = daemon
server_thread.start()
def process_request(self, request, client_address):
# ThreadingMixIn.process_request() dispatches request and
# client_address to separate thread. To cleanly shutdown
# SSL/TLS wrapped socket, we wrap socket here.
# SSL/TLS handshake is postponed to each thread.
request = self.ctx.wrap_socket(\
request, server_side=True, do_handshake_on_connect=False)
socketserver.ThreadingMixIn.process_request(self,
request, client_address)
# Simple SPDY client implementation. Since this implementation
# uses TLS NPN, Python 3.3.0 or later is required.
from urllib.parse import urlsplit
class BaseSPDYStreamHandler:
def __init__(self, url, fetcher):
self.url = url
self.fetcher = fetcher
self.stream_id = None
def on_header(self, nv):
pass
def on_data(self, data):
pass
def on_close(self, status_code):
pass
class UrlFetchError(Exception):
pass
class UrlFetcher:
def __init__(self, server_address, urls, StreamHandlerClass):
self.server_address = server_address
self.handlers = [StreamHandlerClass(url, self) for url in urls]
self.streams = {}
self.finished = []
self.ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
self.ctx.options = ssl.OP_ALL | ssl.OP_NO_SSLv2 | \
ssl.OP_NO_COMPRESSION
self.ctx.set_npn_protocols(get_npn_protocols())
def send_cb(self, session, data):
return self.sock.send(data)
def before_ctrl_send_cb(self, session, frame):
if frame.frame_type == SYN_STREAM:
handler = session.get_stream_user_data(frame.stream_id)
if handler:
handler.stream_id = frame.stream_id
self.streams[handler.stream_id] = handler
def on_ctrl_recv_cb(self, session, frame):
if frame.frame_type == SYN_REPLY or frame.frame_type == HEADERS:
if frame.stream_id in self.streams:
handler = self.streams[frame.stream_id]
handler.on_header(frame.nv)
def on_data_chunk_recv_cb(self, session, flags, stream_id, data):
if stream_id in self.streams:
handler = self.streams[stream_id]
handler.on_data(data)
def on_stream_close_cb(self, session, stream_id, status_code):
if stream | Cython |
_id in self.streams:
handler = self.streams[stream_id]
handler.on_close(status_code)
del self.streams[stream_id]
self.finished.append(handler)
def connect(self, server_address):
self.sock = None
for res in socket.getaddrinfo(server_address[0], server_address[1],
socket.AF_UNSPEC,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
except OSError as msg:
self.sock = None
continue
try:
self.sock.connect(sa)
except OSError as msg:
self.sock.close()
self.sock = None
continue
break
else:
raise UrlFetchError('Could not connect to {}'\
.format(server_address))
def tls_handshake(self):
self.sock = self.ctx.wrap_socket(self.sock, server_side=False,
do_handshake_on_connect=False)
self.sock.do_handshake()
self.version = npn_get_version(self.sock.selected_npn_protocol())
if self.version == 0:
raise UrlFetchError('NPN failed')
def loop(self):
self.connect(self.server_address)
try:
self._loop()
finally:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
def _loop(self):
self.tls_handshake()
self.sock.setblocking(False)
session = Session(CLIENT,
self.version,
send_cb=self.send_cb,
on_ctrl_recv_cb=self.on_ctrl_recv_cb,
on_data_chunk_recv_cb=self.on_data_chunk_recv_cb,
before_ctrl_send_cb=self.before_ctrl_send_cb,
on_stream_close_cb=self.on_stream_close_cb)
session.submit_settings(\
FLAG_SETTINGS_NONE,
[(SETTINGS_MAX_CONCURRENT_STREAMS, ID_FLAG_SETTINGS_NONE, 100)]
)
if self.server_address[1] == 443:
hostport = self.server_address[0]
else:
hostport = '{}:{}'.format(self.server_address[0],
self.server_address[1])
for handler in self.handlers:
res = urlsplit(handler.url)
if res.path:
path = res.path
else:
path = '/'
if res.query:
path = '?'.join([path, res.query])
session.submit_request(0,
[(':method', 'GET'),
(':scheme', 'https'),
(':path', path),
(':version', 'HTTP/1.1'),
(':host', hostport),
('accept', '*/*'),
('user-agent', 'python-spdylay')],
stream_user_data=handler)
while (session.want_read() or session.want_write()) \
and not len(self.finished) == len(self.handlers):
want_read = want_write = False
try:
data = self.sock.recv(4096)
if data:
session.recv(data)
else:
break
except ssl.SSLWantReadError:
want_read = True
except ssl.SSLWantWriteError:
want_write = True
try:
session.send()
except ssl.SSLWantReadError:
want_read = True
except ssl.SSLWantWriteError:
want_write = True
if want_read or want_write:
select.select([self.sock] if want_read else [],
[self.sock] if want_write else [],
[])
def _urlfetch_session_one(urls, StreamHandlerClass):
res = urlsplit(urls[0])
if res.scheme!= 'https':
raise UrlFetchError('Unsupported scheme {}'.format(res.scheme))
hostname = res.hostname
port = res.port if res.port else 443
f = UrlFetcher((hostname, port), urls, StreamHandlerClass)
f.loop()
def urlfetch(url_or_urls, StreamHandlerClass):
if isinstance(url_or_urls, str):
_urlfetch_session_one([url_or_urls], StreamHandlerClass)
else:
urls = []
prev_addr = (None, None)
for url in url_or_urls:
res = urlsplit(url)
port = res.port if res.port else 443
if prev_addr!= (res.hostname, port):
if urls:
_urlfetch_session_one(urls, StreamHandlerClass)
urls = []
prev_addr = (res.hostname, port)
urls.append(url)
if urls:
_urlfetch_session_one(urls, StreamHandlerClass)
except ImportError:
# No server for 2.x because they lack TLS NPN.
pass
<|end_of_text|>__author__ = 'denislavrov'
from action.jitrswitch.switch import SwitchLogic, Packet
import struct
from cpython cimport array
IP_MF = 0x2000 # more fragments (not last frag)
IP_OFFMASK = 0x1fff # mask for fragment offset
cdef extern from "netinet/in.h":
short ntohs(short netshort)
short htons(short hostshort)
cdef struct pshdr:
unsigned int srcip
unsigned int dstip
char rsrv
char proto
unsigned short tcp_len
cdef unsigned short checksumcy(array.array msg):
cdef unsigned int s = 0
cdef unsigned int w = 0
cdef unsigned int i = 0
for i in range(0, len(msg), 2):
w = msg[i] + (msg[i + 1] << 8)
s += w
s = (s >> 16) + (s & 0xffff)
s += s >> 16
return ~s & 0xffff
cdef unsigned short tcp_checksumcy(packet):
cdef array.array pktdata = array.array("B", packet.pktdata)
cdef unsigned char* data = pktdata.data.as_uchars
cdef unsigned int* source_address = <unsigned int*> (data + 14 + 12)
cdef unsigned int ihl = (<int>(data[14] & 0xf)) * 4
cdef unsigned short tcp_length = ntohs((<unsigned short *> (data + 14 + 2))[0]) - ihl
tcp = <unsigned char*>(data + 14 + ihl)
tcp[16] = 0
tcp[17] = 0
cdef pshdr phdr
phdr.srcip = source_address[0]
phdr.dstip = source_address[1]
phdr.rsrv = 0
phdr.proto = 0x06
phdr.tcp_len = htons(tcp_length)
cdef array.array tmp = array.array("B", [])
array.extend_buffer(tmp, <char *>&phdr, sizeof(phdr))
array.extend_buffer(tmp, <char *>tcp, tcp_length)
sum = checksumcy(tmp)
data[14 + ihl + 16] = sum & 0xff
data[14 + ihl + 17] = sum >> 8
packet.pktdata = bytes(pktdata)
return sum
class TCPChecksum(SwitchLogic):
def process_packet(self, packet):
if packet.srcport in self.interfaces and packet.pktdata[14 + 9] == 0x06: # check if TCP
off = struct.unpack(">H", packet.pktdata[14 + 6: 14 + 8])[0]
if (off & (IP_MF | IP_OFFMASK)) == 0:
tcp_checksumcy(packet)
def __init__(self, switch, interfaces):
super().__init__(switch)
self.interfaces = interfaces
<|end_of_text|># cython: profile = True
from libc.stdint cimport int8_t, int32_t, uint64_t
from libc.string cimport memcpy
from cpython.mem cimport PyMem_Malloc, PyMem_Free
from cpython.array cimport array
cimport cython
from cython.parallel import prange, threadid
import numpy as np
cimport containers
cdef int EMPTY = 0
cdef int WHITE = 1
cdef int BLACK = 2
cdef int FUTURE_MOVE = -1
cdef int PASS_MOVE = -2
cdef uint64_t rcol = 72340172838076673ULL
cdef uint64_t lcol = 9259542123273814144ULL
cdef uint64_t not_rcol = 18374403900871474942Ull
cdef uint64_t not_lcol = 9187201950435737471ULL
# Game Data
# turn
# WHITE (1) or BLACK (2)
# board
# 3 64-bit integers
# 1-bits in "empties" indicate EMPTY squares
# 1-bits in "whites" indicate WHITE squares
# 1-bits in "blacks" indicate BLACK squares
#
# Data Structures
# buckets of game states
# search tree:
# root node contains the current game state
# each child node represents one of the possible valid moves
cdef struct State:
uint64_t empties
uint64_t whites
uint64_t blacks
uint64_t turn
cdef struct Search:
containers.BucketList* l1
containers.BucketList* l2
containers.BucketList* last
cdef void print_bits(uint64_t num, as_square=True):
cdef uint64_t i
b = [1 if ((num >> i) & 1) else 0 for i in range(64)]
b = b[::-1]
| Cython |
if as_square:
print(np.array(b).reshape((8,8)))
else:
print(np.array(b))
cdef void print_state(State* state):
cdef uint64_t e, w, b
print('board:')
e = state.empties
w = state.whites
b = state.blacks
board = []
for i in range(64):
if (e >> i) % 2 == 1:
board.append(EMPTY)
elif (w >> i) % 2 == 1:
board.append(WHITE)
elif (b >> i) % 2 == 1:
board.append(BLACK)
board = board[::-1]
print(np.array(board).reshape((8, 8)))
print('turn: {}'.format(state.turn))
cdef void set_opening(State* state):
state.empties = 18446743970227683327ULL
state.whites = 68853694464ULL
state.blacks = 34628173824ULL
state.turn = BLACK
cdef void add_child_states_of(containers.BucketList *bl, State *state) nogil:
cdef uint64_t up_moves, dn_moves, lf_moves, rt_moves, ur_moves, ul_moves, dr_moves, dl_moves
cdef uint64_t moves
cdef uint64_t e, w, b
cdef uint64_t mv, flip, tmp
cdef int i, s
cdef State *child
e = state.empties
w = state.whites
b = state.blacks
cdef uint64_t c1, c2, c1_mv, c2_mv, c2_run
if state.turn == WHITE:
c1 = w
c2 = b
else:
c1 = b
c2 = w
c1_mv = (c1 << 56)
c2_mv = (c2 << 48)
up_moves = c2_mv & c1_mv
for i in range(5, 0, -1):
c1_mv = (c1 << (8 * (i + 1)))
c2_mv = (c2 << (8 * i))
up_moves = c2_mv & (c1_mv | up_moves)
up_moves = up_moves & e
c1_mv = (c1 >> 56)
c2_mv = (c2 >> 48)
dn_moves = c2_mv & c1_mv
for i in range(5, 0, -1):
c1_mv = (c1 >> (8 * (i + 1)))
c2_mv = (c2 >> (8 * i))
dn_moves = c2_mv & (c1_mv | dn_moves)
dn_moves = dn_moves & e
c1_mv = not_rcol & (c1 << 1)
c1_mv = not_rcol & (c1_mv << 1)
c2_run = not_rcol & (c2 << 1)
lf_moves = c2_run & c1_mv
for i in range(1, 7):
c2_run = c2_run & not_rcol & (c2_run << 1)
c1_mv = not_rcol & (c1_mv << 1)
lf_moves = lf_moves | c2_run & c1_mv
lf_moves = lf_moves & e
c1_mv = not_lcol & (c1 >> 1)
c1_mv = not_lcol & (c1_mv >> 1)
c2_run = not_lcol & (c2 >> 1)
rt_moves = c2_run & c1_mv
for i in range(1, 7):
c2_run = c2_run & not_lcol & (c2_run >> 1)
c1_mv = not_lcol & (c1_mv >> 1)
rt_moves = rt_moves | c2_run & c1_mv
rt_moves = rt_moves & e
c1_mv = not_lcol & (c1 << 7)
c1_mv = not_lcol & (c1_mv << 7)
c2_run = not_lcol & (c2 << 7)
ur_moves = c2_run & c1_mv
for i in range(1, 7):
c2_run = c2_run & not_lcol & (c2_run << 7)
c1_mv = not_lcol & (c1_mv << 7)
ur_moves = ur_moves | c2_run & c1_mv
ur_moves = ur_moves & e
c1_mv = not_rcol & (c1 << 9)
c1_mv = not_rcol & (c1_mv << 9)
c2_run = not_rcol & (c2 << 9)
ul_moves = c2_run & c1_mv
for i in range(1, 7):
c2_run = c2_run & not_rcol & (c2_run << 9)
c1_mv = not_rcol & (c1_mv << 9)
ul_moves = ul_moves | c2_run & c1_mv
ul_moves = ul_moves & e
c1_mv = not_lcol & (c1 >> 9)
c1_mv = not_lcol & (c1_mv >> 9)
c2_run = not_lcol & (c2 >> 9)
dr_moves = c2_run & c1_mv
for i in range(1, 7):
c2_run = c2_run & not_lcol & (c2_run >> 9)
c1_mv = not_lcol & (c1_mv >> 9)
dr_moves = dr_moves | c2_run & c1_mv
dr_moves = dr_moves & e
c1_mv = not_rcol & (c1 >> 7)
c1_mv = not_rcol & (c1_mv >> 7)
c2_run = not_rcol & (c2 >> 7)
dl_moves = c2_run & c1_mv
for i in range(1, 7):
c2_run = c2_run & not_rcol & (c2_run >> 7)
c1_mv = not_rcol & (c1_mv >> 7)
dl_moves = dl_moves | c2_run & c1_mv
dl_moves = dl_moves & e
moves = up_moves | dn_moves | lf_moves | rt_moves | ur_moves | ul_moves | dr_moves | dl_moves
if moves == 0:
child = <State *>containers.bucket_list_add_item(bl)
child[0] = state[0] # OR memcpy(child, state, sizeof(State))
if child.turn == WHITE:
child.turn = BLACK
else:
child.turn = WHITE
return
for i in range(64):
mv = (1ULL << i)
if (moves & mv) == 0:
continue
flip = mv
if mv & up_moves:
tmp = mv >> 8
while tmp & c2:
flip = flip | tmp
tmp = tmp >> 8
if mv & dn_moves:
tmp = mv << 8
while tmp & c2:
flip = flip | tmp
tmp = tmp << 8
if mv & lf_moves:
tmp = mv >> 1
while tmp & c2:
flip = flip | tmp
tmp = tmp >> 1
if mv & rt_moves:
tmp = mv << 1
while tmp & c2:
flip = flip | tmp
tmp = tmp << 1
if mv & ur_moves:
tmp = mv >> 7
while tmp & c2:
flip = flip | tmp
tmp = tmp >> 7
if mv & ul_moves:
tmp = mv >> 9
while tmp & c2:
flip = flip | tmp
tmp = tmp >> 9
if mv & dr_moves:
tmp = mv << 9
while tmp & c2:
flip = flip | tmp
tmp = tmp << 9
if mv & dl_moves:
tmp = mv << 7
while tmp & c2:
flip = flip | tmp
tmp = tmp << 7
child = <State *>containers.bucket_list_add_item(bl)
child[0] = state[0] # OR memcpy(child, state, sizeof(State))
child.empties = state.empties & ~mv
if state.turn == WHITE:
child.whites = state.whites | flip
child.blacks = state.blacks & ~flip
child.turn = BLACK
else:
child.whites = state.whites & ~flip
child.blacks = state.blacks | flip
child.turn = WHITE
cdef Search* make_search():
cdef Search *search = <Search *>PyMem_Malloc(1 * sizeof(Search))
search.l1 = containers.bucket_list_make(sizeof(State))
search.l2 = containers.bucket_list_make(sizeof(State))
search.last = NULL
return search
cdef void del_search(Search* search):
if search == NULL:
return | Cython |
containers.bucket_list_del(search.l1)
containers.bucket_list_del(search.l2)
search.last = NULL
PyMem_Free(search)
cdef void seed_search(Search* search, State* state=NULL):
if search.l1.size!= 0:
return
cdef State *tmp = <State *>containers.bucket_list_add_item(search.l1)
if state == NULL:
set_opening(tmp)
else:
tmp[0] = state[0] # OR memcpy(tmp, state, sizeof(State))
search.last = search.l1
cdef int search_generations(Search* search, int num, int num_threads=4):
if num <= 0 or search.last == NULL:
return 1
if not (1 <= num_threads <= 16):
return 2
cdef int i, n
cdef long tid
cdef containers.BucketList *prev
cdef containers.BucketList *curr
cdef containers.BucketList *thread_bl[16]
cdef State *s
if num_threads == 1:
print(search.last.size)
for n in range(num):
prev = search.last
curr = search.l2 if search.l1 == search.last else search.l1
containers.bucket_list_clear(curr)
for i in range(prev.size):
add_child_states_of(curr, <State *>containers.bucket_list_get_item(prev, i))
search.last = curr
print(search.last.size)
else:
for i in range(num_threads):
thread_bl[i] = containers.bucket_list_make(sizeof(State))
print(search.last.size)
for n in range(num):
prev = search.last
curr = search.l2 if search.l1 == search.last else search.l1
containers.bucket_list_clear(curr)
for i in range(num_threads):
containers.bucket_list_clear(thread_bl[i])
for i in prange(prev.size, nogil=True, num_threads=num_threads):
tid = threadid()
add_child_states_of(thread_bl[tid], <State *>containers.bucket_list_get_item(prev, i))
for i in range(num_threads):
containers.bucket_list_transfer_data(curr, thread_bl[i])
search.last = curr
print(search.last.size)
for i in range(num_threads):
containers.bucket_list_del(thread_bl[i])
import time
# TODO: there is a segfault that happens when the ITEMS_PER_BUCKET is too low and
# multithreading is being used.
#
# NOTE: for single-threads a large ITEMS_PER_BUCKET really helps speed things up,
# but for multi-threading a lower ITEMS_PER_BUCKET is better.
cdef Search *search = make_search()
seed_search(search)
start = time.time()
search_generations(search, 11, num_threads=16)
print(time.time() - start)
#cdef State s
#cdef containers.BucketList *bl = containers.bucket_list_make(sizeof(State))
#set_opening(&s)
#print_state(&s)
#print(bl.size)
#add_child_states_of(bl, &s)
#print(bl.size)
#cdef Search *search = make_search()
#seed_search(search)
<|end_of_text|>cdef extern from "yajl/yajl_common.h":
ctypedef struct yajl_alloc_funcs:
pass
<|end_of_text|>from libc.stdlib cimport calloc
from libc.stdlib cimport free
from libc.string cimport memcpy
from libc.string cimport memset
from libc.math cimport fabs
import numpy as np
cimport numpy as np
np.import_array()
cimport _utils as ut
from _utils cimport log
from _utils cimport safe_realloc
from _utils cimport sizet_ptr_to_ndarray
#from _utils cimport WeightMedianCalculator
cdef class Criterion:
def __dealloc__(self):
free(self.sum_total)
free(self.sum_left)
free(self.sum_right)
def __getstate__(self):
return()
def __setstate__(self, d):
pass
cdef int init(self, const DOUBLE_t[:, ::1] y, DOUBLE_t* sample_weight,
double weighted_n_samples, SIZE_t* samples, SIZE_t start,
SIZE_t end) nogil except -1:
pass
cdef int reset(self) nogil except -1:
pass
cdef int reverse_reset(self) nogil except -1:
pass
cdef int update(self, SIZE_t new_pos) nogil except -1:
pass
cdef double node_impurity(self) nogil:
pass
cdef void children_impurity(self, double* impurity_left,
double* impurity_right) nogil:
pass
cdef void node_value(self, double* dest) nogil:
pass
cdef double proxy_impurity_improvement(self) nogil:
cdef double impurity_left
cdef double impurity_right
self.children_impurity(&impurity_left, &impurity_right)
return (- self.weighted_n_right * impurity_right
- self.weighted_n_left * impurity_left)
cdef double impurity_improvement(self, double impurity) nogil:
cdef double impurity_left
cdef double impurity_right
self.children_impurity(&impurity_left, &impurity_right)
return ((self.weighted_n_node_samples / self.weighted_n_samples) *
(impurity - (self.weighted_n_right /
self.weighted_n_node_samples * impurity_right)
- (self.weighted_n_left /
self.weighted_n_node_samples * impurity_left)))
cdef class ClassificationCriterion(Criterion):
def __cinit__(self, SIZE_t n_outputs,
np.ndarray[SIZE_t, ndim=1] n_classes):
self.sample_weight = NULL
self.samples = NULL
self.start = 0
self.pos = 0
self.end = 0
self.n_outputs = n_outputs
self.n_samples = 0
self.n_node_samples = 0
self.weighted_n_node_samples = 0.0
self.weighted_n_left = 0.0
self.weighted_n_right = 0.0
self.sum_total = NULL
self.sum_left = NULL
self.sum_right = NULL
self.n_classes = NULL
safe_realloc(&self.n_classes, n_outputs)
cdef SIZE_t k = 0
cdef SIZE_t sum_stride = 0
for k in range(n_outputs):
self.n_classes[k] = n_classes[k]
if n_classes[k] > sum_stride:
sum_stride = n_classes[k]
self.sum_stride = sum_stride
cdef SIZE_t n_elements = n_outputs * sum_stride
self.sum_total = <double*> calloc(n_elements, sizeof(double))
self.sum_left = <double*> calloc(n_elements, sizeof(double))
self.sum_right = <double*> calloc(n_elements, sizeof(double))
if (self.sum_total == NULL or
self.sum_left == NULL or
self.sum_right == NULL):
raise MemoryError()
def __dealloc__(self):
free(self.n_classes)
def __reduce__(self):
return (type(self),
(self.n_outputs,
sizet_ptr_to_ndarray(self.n_classes, self.n_outputs)),
self.__getstate__())
cdef int init(self, const ut.DOUBLE_t[:, ::1] y, ut.DOUBLE_t* sample_weight,
double weighted_n_samples, ut.SIZE_t* samples, ut.SIZE_t start,
ut.SIZE_t end) nogil except -1:
self.y = y
self.sample_weight = sample_weight
self.samples = samples
self.start = start
self.end = end
self.n_node_samples = end - start
self.weighted_n_samples = weighted_n_samples
self.weighted_n_node_samples = 0.0
cdef SIZE_t* n_classes = self.n_classes
cdef double* sum_total = self.sum_total
cdef SIZE_t i
cdef SIZE_t p
cdef SIZE_t k
cdef SIZE_t c
cdef DOUBLE_t w = 1.0
cdef SIZE_t offset = 0
for k in range(self.n_outputs):
memset(sum_total + offset, 0, n_classes[k] * sizeof(double))
offset += self.sum_stride
for p in range(start, end):
i = samples[p]
if sample_weight!= NULL:
w = sample_weight[i]
for k in range(self.n_outputs):
c = <SIZE_t> self.y[i, k]
sum_total[k * self.sum_stride + c] += w
self.weighted_n_node_samples += w
self.reset()
return 0
cdef int reset(self) nogil except -1:
self.pos = self.start
self.weighted_n_left = 0.0
self.weighted_n_right = self.weighted_n_node_samples
cdef double* sum_total = self.sum_total
cdef double* sum_left = self.sum_left
cdef double* sum_right = self.sum_right
cdef SIZE_t* n_classes = self.n_classes
cdef SIZE_t k
for k in range(self.n_outputs):
memset(sum_left, 0, n_classes[k] * sizeof(double))
memcpy(sum_right, sum_total, n_classes[k] * sizeof(double))
sum_total += self.sum_stride
sum_left | Cython |
+= self.sum_stride
sum_right += self.sum_stride
return 0
cdef int reverse_reset(self) nogil except -1:
"""Reset the criterion at pos=end
Returns -1 in case of failure to allocate memory (and raise MemoryError)
or 0 otherwise.
"""
self.pos = self.end
self.weighted_n_left = self.weighted_n_node_samples
self.weighted_n_right = 0.0
cdef double* sum_total = self.sum_total
cdef double* sum_left = self.sum_left
cdef double* sum_right = self.sum_right
cdef SIZE_t* n_classes = self.n_classes
cdef SIZE_t k
for k in range(self.n_outputs):
memset(sum_right, 0, n_classes[k] * sizeof(double))
memcpy(sum_left, sum_total, n_classes[k] * sizeof(double))
sum_total += self.sum_stride
sum_left += self.sum_stride
sum_right += self.sum_stride
return 0
cdef int update(self, ut.SIZE_t new_pos) nogil except -1:
cdef SIZE_t pos = self.pos
cdef SIZE_t end = self.end
cdef double* sum_left = self.sum_left
cdef double* sum_right = self.sum_right
cdef double* sum_total = self.sum_total
cdef SIZE_t* n_classes = self.n_classes
cdef SIZE_t* samples = self.samples
cdef DOUBLE_t* sample_weight = self.sample_weight
cdef SIZE_t i
cdef SIZE_t p
cdef SIZE_t k
cdef SIZE_t c
cdef SIZE_t label_index
cdef DOUBLE_t w = 1.0
if (new_pos - pos) <= (end - new_pos):
for p in range(pos, new_pos):
i = samples[p]
if sample_weight!= NULL:
w = sample_weight[i]
for k in range(self.n_outputs):
label_index = k * self.sum_stride + <SIZE_t> self.y[i, k]
sum_left[label_index] += w
self.weighted_n_left += w
else:
self.reverse_reset()
for p in range(end - 1, new_pos - 1, -1):
i = samples[p]
if sample_weight!= NULL:
w = sample_weight[i]
for k in range(self.n_outputs):
label_index = k * self.sum_stride + <SIZE_t> self.y[i, k]
sum_left[label_index] -= w
self.weighted_n_left -= w
# Update right part statistics
self.weighted_n_right = self.weighted_n_node_samples - self.weighted_n_left
for k in range(self.n_outputs):
for c in range(n_classes[k]):
sum_right[c] = sum_total[c] - sum_left[c]
sum_right += self.sum_stride
sum_left += self.sum_stride
sum_total += self.sum_stride
self.pos = new_pos
return 0
cdef double node_impurity(self) nogil:
pass
cdef void children_impurity(self, double* impurity_left,
double* impurity_right) nogil:
pass
cdef void node_value(self, double* dest) nogil:
cdef double* sum_total = self.sum_total
cdef SIZE_t* n_classes = self.n_classes
cdef SIZE_t k
for k in range(self.n_outputs):
memcpy(dest, sum_total, n_classes[k] * sizeof(double))
dest += self.sum_stride
sum_total += self.sum_stride
cdef class Entropy(ClassificationCriterion):
cdef double node_impurity(self) nogil:
cdef SIZE_t* n_classes = self.n_classes
cdef double* sum_total = self.sum_total
cdef double entropy = 0.0
cdef double count_k
cdef SIZE_t k
cdef SIZE_t c
for k in range(self.n_outputs):
for c in range(n_classes[k]):
count_k = sum_total[c]
if count_k > 0.0:
count_k /= self.weighted_n_node_samples
entropy -= count_k * log(count_k)
sum_total += self.sum_stride
return entropy / self.n_outputs
cdef void children_impurity(self, double* impurity_left,
double* impurity_right) nogil:
cdef SIZE_t* n_classes = self.n_classes
cdef double* sum_left = self.sum_left
cdef double* sum_right = self.sum_right
cdef double entropy_left = 0.0
cdef double entropy_right = 0.0
cdef double count_k
cdef SIZE_t k
cdef SIZE_t c
for k in range(self.n_outputs):
for c in range(n_classes[k]):
count_k = sum_left[c]
if count_k > 0.0:
count_k /= self.weighted_n_left
entropy_left -= count_k * log(count_k)
count_k = sum_right[c]
if count_k > 0.0:
count_k /= self.weighted_n_right
entropy_right -= count_k * log(count_k)
sum_left += self.sum_stride
sum_right += self.sum_stride
impurity_left[0] = entropy_left / self.n_outputs
impurity_right[0] = entropy_right / self.n_outputs
cdef class Gini(ClassificationCriterion):
cdef double node_impurity(self) nogil:
cdef SIZE_t* n_classes = self.n_classes
cdef double* sum_total = self.sum_total
cdef double gini = 0.0
cdef double sq_count
cdef double count_k
cdef SIZE_t k
cdef SIZE_t c
for k in range(self.n_outputs):
sq_count = 0.0
for c in range(n_classes[k]):
count_k = sum_total[c]
sq_count += count_k * count_k
gini += 1.0 - sq_count / (self.weighted_n_node_samples *
self.weighted_n_node_samples)
sum_total += self.sum_stride
return gini / self.n_outputs
cdef void children_impurity(self, double* impurity_left,
double* impurity_right) nogil:
cdef SIZE_t* n_classes = self.n_classes
cdef double* sum_left = self.sum_left
cdef double* sum_right = self.sum_right
cdef double gini_left = 0.0
cdef double gini_right = 0.0
cdef double sq_count_left
cdef double sq_count_right
cdef double count_k
cdef SIZE_t k
cdef SIZE_t c
for k in range(self.n_outputs):
sq_count_left = 0.0
sq_count_right = 0.0
for c in range(n_classes[k]):
count_k = sum_left[c]
sq_count_left += count_k * count_k
count_k = sum_right[c]
sq_count_right += count_k * count_k
gini_left += 1.0 - sq_count_left/(self.weighted_n_left *
self.weighted_n_left)
gini_right += 1.0 - sq_count_right/(self.weighted_n_right *
self.weighted_n_right)
sum_left += self.sum_stride
sum_right += self.sum_stride
impurity_left[0] = gini_left/self.n_outputs
impurity_right[0] = gini_right/self.n_outputs
<|end_of_text|>
#??? Surface
#??? Boundary Conditions
# Statistical Output: make different grouops of variables for Mean Var and Second Order Momenta
import time
import numpy as np
cimport numpy as np
import os # for self.outpath
from Grid cimport Grid
cimport TimeStepping
cimport ReferenceState
from Initialization import InitializationFactory
cimport PrognosticVariables
cimport MomentumAdvection
cimport ScalarAdvection
# from SGS_variante2 import SGSFactory
from SGS import SGSFactory
cimport MomentumDiffusion
cimport ScalarDiffusion
cimport NetCDFIO
from Thermodynamics import ThermodynamicsFactory
from TurbulenceScheme import TurbulenceFactory
# cimport TurbulenceScheme
class Simulation1d:
def __init__(self, namelist):
self.Gr = Grid(namelist)
self.TS = TimeStepping.TimeStepping()
self.Ref = ReferenceState.ReferenceState(self.Gr)
self.Init = InitializationFactory(namelist)
self.PV = PrognosticVariables.PrognosticVariables(self.Gr)
self.M1 = PrognosticVariables.MeanVariables(self.Gr)
self.M2 = PrognosticVariables.SecondOrderMomenta(self.Gr)
self.Th = ThermodynamicsFactory(namelist)
self.MA = MomentumAdvection.MomentumAdvection(namelist)
self.SA = ScalarAdvection.ScalarAdvection(namelist)
self.Turb = TurbulenceFactory(namelist)
self.SGS = SGSFactory(namelist)
self.MD = MomentumDiffusion.MomentumDiffusion()
self.SD = ScalarDiffusion.ScalarDiffusion(nam | Cython |
elist)
self.StatsIO = NetCDFIO.NetCDFIO_Stats()
return
def initialize(self, namelist):
uuid = str(namelist['meta']['uuid'])
self.outpath = str(os.path.join(namelist['output']['output_root'] + 'Output.' + namelist['meta']['simname'] + '.' + uuid[-5:]))
self.StatsIO.initialize(namelist, self.Gr)
self.TS.initialize(namelist)
# Add new prognostic variables
self.PV.add_variable('phi','m/s', "velocity") # self.PV.add_variable('phi','m/s', "sym", "velocity")
# cdef:
# PV_ = self.PV
# print(PV_.nv) #not accessible (also not as # print(self.PV.nv))
self.M1.add_variable('u','m/s', "velocity")
self.M1.add_variable('v','m/s', "velocity")
self.M1.add_variable('w','m/s', "velocity")
self.M2.add_variable('uu', '(m/s)^2', "velocity")
self.M2.add_variable('vv', '(m/s)^2', "velocity")
self.M2.add_variable('wu', '(m/s)^2', "velocity")
self.M2.add_variable('wv', '(m/s)^2', "velocity")
self.M2.add_variable('ww', '(m/s)^2', "velocity")
self.M2.add_variable('pu', '(m/s)^2', "velocity")
self.M2.add_variable('pv', '(m/s)^2', "velocity")
self.M2.add_variable('pw', '(m/s)^2', "velocity")
# AuxillaryVariables(namelist, self.PV, self.DV, self.Pa)
self.Th.initialize(self.Gr, self.M1, self.M2) # adding prognostic thermodynamic variables
self.PV.initialize(self.Gr, self.StatsIO)
self.M1.initialize(self.Gr, self.StatsIO)
self.M2.initialize(self.Gr, self.StatsIO)
self.Init.initialize_reference(self.Gr, self.Ref, self.StatsIO)
self.Init.initialize_profiles(self.Gr, self.Ref, self.M1, self.M2, self.StatsIO)
self.MA.initialize(self.Gr, self.M1)
self.SA.initialize(self.Gr, self.M1)
self.SGS.initialize(self.Gr, self.M1, self.M2)
self.MD.initialize(self.Gr, self.M1)
self.SD.initialize(self.Gr, self.M1)
print('Initialization completed!')
# self.plot()
return
def run(self):
print('Sim: start run')
while(self.TS.t < self.TS.t_max):
# (0) update auxiliary fields
self.SGS.update(self.Gr) # --> compute diffusivity / viscosity for M1 and M2 (being the same at the moment)
self.M1.plot('beginning of timestep', self.Gr, self.TS)
# (1) update mean field (M1) tendencies
# self.Th.update()
self.MA.update_M1_2nd(self.Gr, self.Ref, self.M1) # self.MA.update(self.Gr, self.Ref, self.M1)
self.SA.update_M1_2nd(self.Gr, self.Ref, self.M1) # self.SA.update(self.Gr, self.Ref, self.M1)
self.MD.update(self.Gr, self.Ref, self.M1, self.SGS)
self.SD.update(self.Gr, self.Ref, self.M1, self.SGS)
# self.M1.plot('after SD update', self.Gr, self.TS)
self.Turb.update_M1(self.Gr, self.M1, self.M2) # --> add turbulent flux divergence to mean field tendencies: dz<w'phi'>
#??? surface fluxes??? (--> in SGS or MD/SD scheme?)
#??? update boundary conditions???
#??? pressure solver???
self.M1.plot('without tendency update', self.Gr, self.TS)
# (2) update second order momenta (M2) tendencies
# self.MA.update # --> self.MA.update_M2(): advection of M2
# self.SA.update # --> self.SA.update_M2(): advection of M2
# self.MD.update()
# self.SD.update()
# self.Turb.update_M2() # update higher order terms in M2 tendencies
print('Sim: Turb update')
self.Turb.update(self.Gr, self.M1, self.M2)
# Turb.advect_M2_local(Gr, M1, M2)
#??? update boundary conditions???
#??? pressure correlations???
#??? surface fluxes??? (--> in SGS or MD/SD scheme?)
self.M1.update(self.Gr, self.TS) # --> updating values by adding tendencies
self.M2.update(self.Gr, self.TS) # --> updating values by adding tendencies
self.TS.update()
return
# def plot(self):
#
# plt.figure(1)
# plt.plot()
# plt.title(var + ','+ message)
# # plt.show()
# plt.savefig(self.outpath + '/' + var + '_' + message + '.png')
# plt.close()
def io(self):
print('calling io')
cdef:
double stats_dt = 0.0
double condstats_dt = 0.0
double restart_dt = 0.0
double vis_dt = 0.0
double min_dt = 0.0
if self.TS.t > 0 and self.TS.rk_step == self.TS.n_rk_steps - 1:
print('doing io:'+ str(self.TS.t) + ','+ str(self.TS.rk_step))
# Adjust time step for output if necessary
stats_dt = self.StatsIO.last_output_time + self.StatsIO.frequency - self.TS.t
condstats_dt = self.CondStatsIO.last_output_time + self.CondStatsIO.frequency - self.TS.t
restart_dt = self.Restart.last_restart_time + self.Restart.frequency - self.TS.t
vis_dt = self.VO.last_vis_time + self.VO.frequency - self.TS.t
# dts = np.array([fields_dt, stats_dt, condstats_dt, restart_dt, vis_dt,
# self.TS.dt, self.TS.dt_max, self.VO.frequency, self.Restart.frequency,
# self.StatsIO.frequency, self.CondStatsIO.frequency, self.FieldsIO.frequency])
dts = np.array([stats_dt, condstats_dt, restart_dt, vis_dt,
self.TS.dt, self.TS.dt_max, self.VO.frequency, self.Restart.frequency,
self.StatsIO.frequency, self.CondStatsIO.frequency])
self.TS.dt = np.amin(dts[dts > 0.0])
# If time to ouput stats do output
# self.Pa.root_print('StatsIO freq:'+ str(self.StatsIO.frequency) + ','+ str(self.StatsIO.last_output_time) + ','+ str(self.TS.t))
if self.StatsIO.last_output_time + self.StatsIO.frequency == self.TS.t:
#if self.StatsIO.last_output_time + self.StatsIO.frequency == self.TS.t or self.StatsIO.last_output_time + self.StatsIO.frequency + 10.0 == self.TS.t:
#if (1==1):
self.Pa.root_print('Doing StatsIO')
self.StatsIO.last_output_time = self.TS.t
self.StatsIO.open_files(self.Pa)
self.StatsIO.write_simulation_time(self.TS.t, self.Pa)
self.Micro.stats_io(self.Gr, self.Ref, self.PV, self.DV, self.StatsIO, self.Pa) # do Micro.stats_io prior to DV.stats_io to get sedimentation velocity only in output
self.PV.stats_io(self.Gr, self.Ref, self.StatsIO, self.Pa)
self.DV.stats_io(self.Gr, self.StatsIO, self.Pa)
self.Fo.stats_io(self.Gr, self.Ref, self.PV, self.DV, self.StatsIO, self.Pa)
self.Th.stats_io(self.Gr, self.Ref, self.PV, self.DV, self.StatsIO, self.Pa)
self.Sur.stats_io(self.Gr, self.StatsIO, self.Pa)
self.SGS.stats_io(self.Gr,self.DV,self.PV,self.Ke,self.StatsIO,self.Pa)
self.SA.stats_io(self.Gr, self.PV, self.StatsIO, self.Pa)
self.MA.stats_io(self.Gr, self.PV, self.StatsIO, self.Pa)
self.SD.stats_io(self.Gr, self.Ref,self.PV, self.DV, self.StatsIO, self.Pa)
self.MD.stats_io(self.Gr, self.PV, self.DV, self.Ke, self.StatsIO, self.Pa)
self.Ke.stats_io(self.Gr,self.Ref,self.PV,self.StatsIO,self.Pa)
self.Tr.stats_io | Cython |
( self.Gr, self.StatsIO, self.Pa)
self.Ra.stats_io(self.Gr, self.DV, self.StatsIO, self.Pa)
self.Budg.stats_io(self.Sur, self.StatsIO, self.Pa)
self.Aux.stats_io(self.Gr, self.Ref, self.PV, self.DV, self.MA, self.MD, self.StatsIO, self.Pa)
self.StatsIO.close_files(self.Pa)
self.Pa.root_print('Finished Doing StatsIO')
return
<|end_of_text|>cimport cython
from cpython.object cimport PyObject
from cpython.dict cimport PyDict_GetItem, PyDict_SetItem
from glycan_profiling._c.tandem.spectrum_match cimport ScoreSet
DEF NUM_SCORES = 15
cdef class ModelScoreSet(ScoreSet):
def __init__(self, glycopeptide_score=0., peptide_score=0., glycan_score=0., glycan_coverage=0.,
stub_glycopeptide_intensity_utilization=0., oxonium_ion_intensity_utilization=0.,
n_stub_glycopeptide_matches=0, peptide_coverage=0.0, total_signal_utilization=0.0,
peptide_correlation=0.0, peptide_backbone_count=0,
glycan_correlation=0.0, peptide_reliability_total=0.0, glycan_reliability_total=0.0,
partition_label=0):
self.glycopeptide_score = glycopeptide_score
self.peptide_score = peptide_score
self.glycan_score = glycan_score
self.glycan_coverage = glycan_coverage
self.stub_glycopeptide_intensity_utilization = stub_glycopeptide_intensity_utilization
self.oxonium_ion_intensity_utilization = oxonium_ion_intensity_utilization
self.n_stub_glycopeptide_matches = n_stub_glycopeptide_matches
self.peptide_coverage = peptide_coverage
self.total_signal_utilization = total_signal_utilization
self.peptide_correlation = peptide_correlation
self.peptide_backbone_count = peptide_backbone_count
self.glycan_correlation = glycan_correlation
self.peptide_reliability_total = peptide_reliability_total
self.glycan_reliability_total = glycan_reliability_total
self.partition_label = partition_label
cpdef bytearray pack(self):
cdef:
float[NUM_SCORES] data
data[0] = self.glycopeptide_score
data[1] = self.peptide_score
data[2] = self.glycan_score
data[3] = self.glycan_coverage
data[4] = self.stub_glycopeptide_intensity_utilization
data[5] = self.oxonium_ion_intensity_utilization
data[6] = <int>self.n_stub_glycopeptide_matches
data[7] = self.peptide_coverage
data[8] = self.total_signal_utilization
data[9] = self.peptide_correlation
data[10] = <int>self.peptide_backbone_count
data[11] = self.glycan_correlation
data[12] = self.peptide_reliability_total
data[13] = self.glycan_reliability_total
data[14] = <int>self.partition_label
return ((<char*>data)[:sizeof(float) * NUM_SCORES])
@staticmethod
def unpack(bytearray data):
cdef:
float* buff
char* temp
int n_stub_glycopeptide_matches
float stub_utilization
float oxonium_utilization
float peptide_coverage
float peptide_correlation
int peptide_backbone_count
float total_signal_utilization
float glycan_correlation
float peptide_reliability_total
float glycan_reliability_total
int partition_label
temp = data
buff = <float*>(temp)
stub_utilization = buff[4]
oxonium_utilization = buff[5]
n_stub_glycopeptide_matches = <int>buff[6]
peptide_coverage = buff[7]
total_signal_utilization = buff[8]
peptide_correlation = buff[9]
peptide_backbone_count = <int>buff[10]
glycan_correlation = buff[11]
peptide_reliability_total = buff[12]
glycan_reliability_total = buff[13]
partition_label = <int>buff[14]
return ModelScoreSet._create_model_score_set(
buff[0], buff[1], buff[2], buff[3], stub_utilization,
oxonium_utilization, n_stub_glycopeptide_matches, peptide_coverage,
total_signal_utilization, peptide_correlation, peptide_backbone_count,
glycan_correlation, peptide_reliability_total, glycan_reliability_total,
partition_label)
@staticmethod
cdef ModelScoreSet _create_model_score_set(float glycopeptide_score, float peptide_score, float glycan_score, float glycan_coverage,
float stub_glycopeptide_intensity_utilization, float oxonium_ion_intensity_utilization,
int n_stub_glycopeptide_matches, float peptide_coverage, float total_signal_utilization,
float peptide_correlation, int peptide_backbone_count, float glycan_correlation,
float peptide_reliability_total, float glycan_reliability_total, int partition_label):
cdef:
ModelScoreSet self
self = ModelScoreSet.__new__(ModelScoreSet)
self.glycopeptide_score = glycopeptide_score
self.peptide_score = peptide_score
self.glycan_score = glycan_score
self.glycan_coverage = glycan_coverage
self.stub_glycopeptide_intensity_utilization = stub_glycopeptide_intensity_utilization
self.oxonium_ion_intensity_utilization = oxonium_ion_intensity_utilization
self.n_stub_glycopeptide_matches = n_stub_glycopeptide_matches
self.peptide_coverage = peptide_coverage
self.total_signal_utilization = total_signal_utilization
self.peptide_correlation = peptide_correlation
self.peptide_backbone_count = peptide_backbone_count
self.glycan_correlation = glycan_correlation
self.peptide_reliability_total = peptide_reliability_total
self.glycan_reliability_total = glycan_reliability_total
self.partition_label = partition_label
return self
def __repr__(self):
template = (
"{self.__class__.__name__}({self.glycopeptide_score}, {self.peptide_score},"
" {self.glycan_score}, {self.glycan_coverage}, {self.stub_glycopeptide_intensity_utilization},"
" {self.oxonium_ion_intensity_utilization}, {self.n_stub_glycopeptide_matches}, {self.peptide_coverage},"
" {self.total_signal_utilization}, {self.peptide_correlation}, {self.peptide_backbone_count},"
" {self.glycan_correlation}, {self.peptide_reliability_total}, {self.glycan_reliability_total},"
" {self.partition_label}"
")")
return template.format(self=self)
def __len__(self):
return NUM_SCORES
def __getitem__(self, int i):
if i == 0:
return self.glycopeptide_score
elif i == 1:
return self.peptide_score
elif i == 2:
return self.glycan_score
elif i == 3:
return self.glycan_coverage
elif i == 4:
return self.stub_glycopeptide_intensity_utilization
elif i == 5:
return self.oxonium_ion_intensity_utilization
elif i == 6:
return self.n_stub_glycopeptide_matches
elif i == 7:
return self.peptide_coverage
elif i == 8:
return self.total_signal_utilization
elif i == 9:
return self.peptide_correlation
elif i == 10:
return self.peptide_backbone_count
elif i == 11:
return self.glycan_correlation
elif i == 12:
return self.peptide_reliability_total
elif i == 13:
return self.glycan_reliability_total
elif i == 14:
return self.partition_label
else:
raise IndexError(i)
def __iter__(self):
yield self.glycopeptide_score
yield self.peptide_score
yield self.glycan_score
yield self.glycan_coverage
yield self.stub_glycopeptide_intensity_utilization
yield self.oxonium_ion_intensity_utilization
yield self.n_stub_glycopeptide_matches
yield self.peptide_coverage
yield self.total_signal_utilization
yield self.peptide_correlation
yield self.peptide_backbone_count
yield self.glycan_correlation
yield self.peptide_reliability_total
yield self.glycan_reliability_total
yield self.partition_label
def __reduce__(self):
return self.__class__, (self.glycopeptide_score, self.peptide_score,
self.glycan_score, self.glycan_coverage, self.stub_glycopeptide_intensity_utilization,
self.oxonium_ | Cython |
ion_intensity_utilization, self.n_stub_glycopeptide_matches,
self.peptide_coverage, self.total_signal_utilization,
self.peptide_correlation, self.peptide_backbone_count,
self.glycan_correlation, self.peptide_reliability_total,
self.glycan_reliability_total, self.partition_label)
@classmethod
def from_spectrum_matcher(cls, match):
stub_utilization, stub_count, peptide_count, total_signal_utilization = match.count_peptide_Y_ion_utilization()
oxonium_utilization = match.oxonium_ion_utilization()
return cls(match.score,
match.peptide_score(),
match.glycan_score(),
match.glycan_coverage(),
stub_utilization,
oxonium_utilization,
stub_count,
match.peptide_coverage(),
total_signal_utilization,
match.peptide_correlation(),
peptide_count,
match.glycan_correlation(),
match.peptide_reliability().sum(),
match.glycan_reliability().sum(),
match.partition_key,
)
@classmethod
def field_names(cls):
cdef list field_names = super(ModelScoreSet, cls).field_names()
field_names.extend([
"peptide_correlation",
"peptide_backbone_count",
"glycan_correlation",
"peptide_reliability_total",
"glycan_reliability_total",
"partition_label"
])
return field_names
cpdef list values(self):
cdef list values = super(ModelScoreSet, self).values()
values.append(self.peptide_correlation)
values.append(self.peptide_backbone_count)
values.append(self.glycan_correlation)
values.append(self.peptide_reliability_total)
values.append(self.glycan_reliability_total)
values.append(self.partition_label)
return values<|end_of_text|># mode: error
cimport cython
@cython.autotestdict(False)
def foo():
pass
_ERRORS = u"""
5:0: The autotestdict compiler directive is not allowed in function scope
"""
<|end_of_text|>#cython: language_level=3
from pippi cimport defaults
from pippi cimport dsp
from pippi cimport fx
from pippi cimport grains
from pippi cimport interpolation
from pippi cimport soundbuffer
from pippi cimport soundpipe
from pippi cimport wavetables
<|end_of_text|>################################################
# WARNING! #
# This file has been auto-generated by xdress. #
# Do not modify!!! #
# #
# #
# Come on, guys. I mean it! #
################################################
cimport _cproblem
cimport dtypes
cimport numpy as np
cimport stlcontainers
from cyclopts cimport cpp_exchange_instance
from libcpp.map cimport map as cpp_map
from libcpp.vector cimport vector as cpp_vector
cdef class ExArc:
cdef void * _inst
cdef public bint _free_inst
cdef public np.ndarray _ucaps
cdef public np.ndarray _vcaps
pass
cdef class ExGroup:
cdef void * _inst
cdef public bint _free_inst
cdef public np.ndarray _cap_dirs
cdef public np.ndarray _caps
pass
cdef class ExNode:
cdef void * _inst
cdef public bint _free_inst
pass
cdef class ExSolution(_cproblem.ProbSolution):
cdef public stlcontainers._MapIntDouble _flows
pass
{'cpppxd_footer': '', 'pyx_header': '', 'pxd_header': '', 'pxd_footer': '', 'cpppxd_header': '', 'pyx_footer': ''}<|end_of_text|># imagecodecs/_blosc.pyx
# distutils: language = c
# cython: language_level = 3
# cython: boundscheck=False
# cython: wraparound=False
# cython: cdivision=True
# cython: nonecheck=False
# Copyright (c) 2019-2023, Christoph Gohlke
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Blosc codec for the imagecodecs package."""
__version__ = '2023.3.16'
include '_shared.pxi'
from blosc cimport *
class BLOSC:
"""BLOSC codec constants."""
available = True
class SHUFFLE(enum.IntEnum):
"""BLOSC codec shuffle types."""
NOSHUFFLE = BLOSC_NOSHUFFLE
SHUFFLE = BLOSC_SHUFFLE
BITSHUFFLE = BLOSC_BITSHUFFLE
class COMPRESSOR(enum.IntEnum):
"""BLOSC codec compressors."""
BLOSCLZ = BLOSC_BLOSCLZ
LZ4 = BLOSC_LZ4
LZ4HC = BLOSC_LZ4HC
SNAPPY = BLOSC_SNAPPY
ZLIB = BLOSC_ZLIB
ZSTD = BLOSC_ZSTD
class BloscError(RuntimeError):
"""BLOSC codec exceptions."""
def blosc_version():
"""Return C-Blosc library version string."""
return 'c-blosc'+ BLOSC_VERSION_STRING.decode()
def blosc_check(data):
"""Return whether data is BLOSC encoded."""
def blosc_encode(
data,
level=None,
compressor=None,
shuffle=None,
typesize=None,
blocksize=None,
numthreads=None,
out=None
):
"""Return BLOSC encoded data."""
cdef:
const uint8_t[::1] src
const uint8_t[::1] dst # must be const to write to bytes
ssize_t srcsize
ssize_t dstsize
size_t cblocksize
size_t ctypesize
char* compname = NULL
int clevel = _default_value(level, 9, 0, 9)
int numinternalthreads = <int> _default_threads(numthreads)
int doshuffle
int ret
if data is out:
raise ValueError('cannot encode in-place')
try:
src = data # common case: contiguous bytes
ctypesize = 1
except Exception:
view = memoryview(data)
if view.contiguous:
src = view.cast('B') # view as bytes
else:
src = view.tobytes() # copy non-contiguous
ctypesize = view.itemsize
srcsize = src.size
if srcsize > 2147483647 - BLOSC_MAX_OVERHEAD:
raise ValueError('data size larger than 2 GB')
if blocksize is None:
cblocksize = 0
else:
cblocksize = blocksize
if compressor is None:
compname = BLOSC_BLOSCLZ_COMPNAME
elif compressor == BLOSC_BLOSCLZ:
compname = BLOSC_BLOSCLZ_COMPNAME
elif compressor == BLOSC_LZ4:
compname = BLOSC_LZ4_COMPNAME
elif compressor == BLOSC_LZ4HC:
compname = BLOSC_LZ4HC_COMPNAME
elif compressor == BLOSC_SNAPPY:
compname = BLOSC_SNAPPY_COMPNAME
elif compressor == BLOSC_ZLIB:
compname = BLOSC_ZLIB_COMPNAME
elif compressor == BLOSC_ZSTD:
compname = BLOSC_ZSTD_COMPNAME
else:
compressor = compressor.lower().encode()
compname = compressor
if shuffle is None:
doshuffle = BLOSC_SHUFFLE
elif not shuffle:
doshuffle = BLOSC_NOSHUFFLE
elif shuffle == BLOSC_NOSHUFFLE or shuffle == 'noshuffle':
doshuffle = BLOSC_NOSHUFFLE
elif shuffle == BLOSC_BITSHUFFLE or shuffle == 'bitshuffle':
doshuffle = B | Cython |
LOSC_BITSHUFFLE
else:
doshuffle = BLOSC_SHUFFLE
out, dstsize, outgiven, outtype = _parse_output(out)
if out is None:
if dstsize < 0:
dstsize = srcsize + BLOSC_MAX_OVERHEAD
if dstsize < 17:
dstsize = 17
out = _create_output(outtype, dstsize)
dst = out
dstsize = dst.size
with nogil:
if numinternalthreads == 0:
numinternalthreads = blosc_get_nthreads()
ret = blosc_compress_ctx(
clevel,
doshuffle,
ctypesize,
<size_t> srcsize,
<const void*> &src[0],
<void*> &dst[0],
<size_t> dstsize,
<const char*> compname,
cblocksize,
numinternalthreads
)
if ret <= 0:
raise BloscError(f'blosc_compress_ctx returned {ret}')
del dst
return _return_output(out, dstsize, ret, outgiven)
def blosc_decode(data, numthreads=None, out=None):
"""Return decoded BLOSC data."""
cdef:
const uint8_t[::1] src = data
const uint8_t[::1] dst # must be const to write to bytes
ssize_t dstsize
ssize_t srcsize = src.size
size_t nbytes, cbytes, blocksize
int numinternalthreads = <int> _default_threads(numthreads)
int ret
if data is out:
raise ValueError('cannot decode in-place')
if src.size > 2147483647:
raise ValueError('data size larger than 2 GB')
out, dstsize, outgiven, outtype = _parse_output(out)
if out is None:
if dstsize < 0:
blosc_cbuffer_sizes(
<const void*> &src[0],
&nbytes,
&cbytes,
&blocksize
)
if nbytes == 0 and blocksize == 0:
raise BloscError(
'blosc_cbuffer_sizes returned invalid blosc data'
)
dstsize = <ssize_t> nbytes
out = _create_output(outtype, dstsize)
dst = out
dstsize = dst.size
if dstsize > 2147483647:
raise ValueError('output size larger than 2 GB')
with nogil:
if numinternalthreads == 0:
numinternalthreads = blosc_get_nthreads()
ret = blosc_decompress_ctx(
<const void*> &src[0],
<void*> &dst[0],
dstsize,
numinternalthreads
)
if ret < 0:
raise BloscError(f'blosc_decompress_ctx returned {ret}')
del dst
return _return_output(out, dstsize, ret, outgiven)
<|end_of_text|>import check_line
def get_val(fileout,param,num,ini,fin,from_stt):
with open(fileout) as fp:
for cnt, line in enumerate(fp):
if cnt == check_line(fileout,param,num,from_stt):
return line[ini:fin]
<|end_of_text|># -*- mode:cython -*-
cdef extern from "Python.h":
ctypedef int Py_ssize_t
int PyObject_AsCharBuffer(object obj, char **buffer, Py_ssize_t *buffer_len) except -1
int PyObject_AsReadBuffer(object obj, char **buffer, Py_ssize_t *buffer_len) except -1
int PyObject_CheckReadBuffer(object o)
int PyObject_AsWriteBuffer(object obj, char **buffer, Py_ssize_t *buffer_len) except -1
object PyBytes_FromStringAndSize(char *v, Py_ssize_t len)
void *PyMem_Malloc(int)
void PyMem_Free(void *p)
cdef extern from "string.h":
ctypedef int size_t
void *memcpy(void *dest, void *src, size_t n)
cdef extern from "math.h":
double log(double x)
double log1p(double x)
double sqrt(double x)
double fabs(double x)
double pow(double x, double y)
double M_LN2
cdef extern from "math_stuff.h":
double inverse_erf(double x)
import numpy
cimport numpy
cimport cython
from libcpp.vector cimport vector
from libcpp.algorithm cimport sort
cdef extern from "cxx_gram.h":
ctypedef unsigned int coordinate_t
ctypedef int *const_int_ptr "const int *"
struct c_CItemI1 "CountItem<1,int> ":
int *addr
int item
ctypedef vector[c_CItemI1] c_VecI1 "std::vector<CountItem<1,int> >"
ctypedef vector[c_CItemI1].iterator c_VecIterI1 "std::vector<CountItem<1,int> >::iterator"
struct c_SmallerAddrI1 "smallerAddr<1,int> ":
pass
c_CItemI1 c_VecI1_get_pointer "get_pointer" (c_VecI1 *v, size_t k)
void c_compactifyI1 "compactify"(c_VecI1 *v)
int c_get_countI1 "get_count_v"(c_VecI1 *v,
c_CItemI1)
struct c_CItemI2 "CountItem<2,int> ":
int *addr
int item
ctypedef vector[c_CItemI2] c_VecI2 "std::vector<CountItem<2,int> >"
ctypedef vector[c_CItemI2].iterator c_VecIterI2 "std::vector<CountItem<2,int> >::iterator"
struct c_SmallerAddrI2 "smallerAddr<2,int> ":
pass
c_CItemI2 c_VecI2_get_pointer "get_pointer" (c_VecI2 *v, size_t k)
void c_compactifyI2 "compactify"(c_VecI2 *v)
int c_get_countI2 "get_count_v"(c_VecI2 *v,
c_CItemI2)
struct c_CItemI3 "CountItem<3,int> ":
int *addr
int item
ctypedef vector[c_CItemI3] c_VecI3 "std::vector<CountItem<3,int> >"
ctypedef vector[c_CItemI3].iterator c_VecIterI3 "std::vector<CountItem<3,int> >::iterator"
struct c_SmallerAddrI3 "smallerAddr<3,int> ":
pass
c_CItemI3 c_VecI3_get_pointer "get_pointer" (c_VecI3 *v, size_t k)
void c_compactifyI3 "compactify"(c_VecI3 *v)
int c_get_countI3 "get_count_v"(c_VecI3 *v,
c_CItemI3)
struct c_CSRMatrixI "CSRMatrix<int>":
coordinate_t num_rows
int *offsets
coordinate_t *rightColumns
int *values
void write_binary(int fileno)
c_CSRMatrixI *transpose()
void compute_left_marginals(int *vec)
void compute_right_marginals(int *vec)
void compute_right_squared_marginals(int *vec)
c_CSRMatrixI *new_CSRMatrixI "new CSRMatrix<int>" ()
c_CSRMatrixI *vec2csrI "vec2csr"(c_VecI2 *v)
c_CSRMatrixI *add_csrI "add_csr"(c_CSRMatrixI *a,c_CSRMatrixI *b)
int csrFromBufferI "csrFromBuffer"(void *buf, c_CSRMatrixI *m)
c_CSRMatrixI *new_csrI "new_csr<int>"(int numRows, int numNonZero)
void print_csrI "print_csr<int>"(c_CSRMatrixI *v)
ctypedef float *const_float_ptr "const float *"
struct c_CItemF1 "CountItem<1,float> ":
int *addr
float item
ctypedef vector[c_CItemF1] c_VecF1 "std::vector<CountItem<1,float> >"
ctypedef vector[c_CItemF1].iterator c_VecIterF1 "std::vector<CountItem<1,float> >::iterator"
struct c_SmallerAddrF1 "smallerAddr<1,float> ":
pass
c_CItemF1 c_VecF1_get_pointer "get_pointer" (c_VecF1 *v, size_t k)
void c_compactifyF1 "compactify"(c_VecF1 *v)
float c_get_countF1 "get_count_v"(c_VecF1 *v,
c_CItemF1)
struct c_CItemF2 "CountItem<2,float> ":
int *addr
float item
ctypedef vector[c_CItemF2] c_VecF2 "std::vector<CountItem< | Cython |