def numpy2vec(array, dtype, shape, syntax, name): # # dtype assert dtype in [bool, int, float, cppad_py.a_double] # ------------------------------------------------------------------------- # if not isinstance(array, numpy.ndarray): msg = syntax + ': ' + name + ' is not an numpy.ndarray' raise NotImplementedError(msg) if not array.dtype == dtype: msg = syntax + ': ' + name + '.dtype is not ' + str(dtype) raise NotImplementedError(msg) # # vector, nr, nc if isinstance(shape, int): vector = True nr = shape nc = 1 elif len(shape) == 1: vector = True nr = shape[0] nc = 1 else: assert len(shape) == 2 vector = False nr = shape[0] nc = shape[1] # if vector and len(array.shape) != 1: msg = syntax + ': ' + name + ' is not a vector' elif len(array.shape) != 2: msg = syntax + ': ' + name + ' is not a matrix' # if array.shape[0] != nr: msg = syntax + ': ' + name + '.shape[0] is not ' + str(nr) # if dtype == bool: vec = cppad_py.vec_bool(nr * nc) if dtype == int: vec = cppad_py.vec_int(nr * nc) if dtype == float: vec = cppad_py.vec_double(nr * nc) if dtype == cppad_py.a_double: vec = cppad_py.vec_a_double(nr * nc) # if vector: for i in range(nr): # must copy data so vec can manage its own memory vec[i] = dtype(array[i]) else: if array.shape[1] != nc: msg = syntax + ': ' + name + '.shape[1] is not ' + str(nc) # for i in range(nr): for j in range(nc): # must copy data so vec can manage its own memory vec[i * nc + j] = dtype(array[i, j]) # return vec
def vector_size_xam(): # import numpy import cppad_py # # initialize return variable ok = True # --------------------------------------------------------------------- # create vectors bv = cppad_py.vec_bool() iv = cppad_py.vec_int(1) dv = cppad_py.vec_double(2) av = cppad_py.vec_a_double(3) # # check size of vectors ok = ok and bv.size() == 0 ok = ok and iv.size() == 1 ok = ok and dv.size() == 2 ok = ok and av.size() == 3 # return (ok)
def vector_set_get_xam(): # import numpy import cppad_py # # initialize return variable ok = True # --------------------------------------------------------------------- n = 4 bv = cppad_py.vec_bool(n) iv = cppad_py.vec_int(n) dv = numpy.empty(n, dtype=float) av = numpy.empty(n, dtype=cppad_py.a_double) # # setting elements for i in range(n): bv[i] = i > n / 2 iv[i] = 2 * i dv[i] = 3.0 * i av[i] = cppad_py.a_double(4.0 * i) # # for i in range(n): be = bv[i] ok = ok and be == (i > n / 2) # ie = iv[i] ok = ok and ie == 2 * i # de = dv[i] ok = ok and de == 3.0 * i # ae = av[i] ok = ok and ae == 4.0 * i # # return (ok)