Ejemplo n.º 1
0
                                            struct ndpi_flow_struct *flow,
                                            const unsigned char *packet,
                                            const unsigned short packetlen,
                                            const u_int64_t packet_time_ms);
ndpi_protocol ndpi_detection_giveup(struct ndpi_detection_module_struct *ndpi_struct,
                                    struct ndpi_flow_struct *flow,
                                    u_int8_t enable_guess,
                                    u_int8_t *protocol_was_guessed);
void ndpi_py_setup_detection_module(struct ndpi_detection_module_struct *mod);
struct ndpi_flow_struct * ndpi_py_initialize_flow(void);
char* ndpi_protocol2name(struct ndpi_detection_module_struct *ndpi_mod, ndpi_protocol proto, char *buf, u_int buf_len);
const char* ndpi_category_get_name(struct ndpi_detection_module_struct *ndpi_mod, ndpi_protocol_category_t category);
const char* ndpi_confidence_get_name(ndpi_confidence_t confidence);
"""

ffi_builder = FFI()


INCLUDE_DIR = pathlib.Path(__file__)\
    .parent.resolve().parent.resolve().parent.resolve().\
    joinpath("src").joinpath("include")

LIBRARY_DIR = pathlib.Path(__file__)\
    .parent.resolve().parent.resolve().parent.resolve().\
    joinpath("src").joinpath("lib")


NDPI_CDEF = subprocess.run(["gcc",
                            "-DNDPI_LIB_COMPILATION",
                            "-DNDPI_CFFI_PREPROCESSING",
                            "-DNDPI_CFFI_PREPROCESSING_EXCLUDE_PACKED",
Ejemplo n.º 2
0
 def test_struct_with_typedef(self):
     ffi = FFI()
     ffi.cdef("typedef struct { float x; } foo_t;")
     p = ffi.new("foo_t *", [5.2])
     assert repr(p).startswith("<cdata 'foo_t *' ")
Ejemplo n.º 3
0
from os.path import dirname, join, realpath

from cffi import FFI

ffibuilder = FFI()
ffibuilder.set_unicode(False)

ffibuilder.cdef(r"""
    int read_bed_chunk(char*, uint64_t, uint64_t,
                       uint64_t, uint64_t,
                       uint64_t, uint64_t,
                       uint64_t*, uint64_t*);
""")

dirname(realpath(__file__))
ffibuilder.set_source(
    "pandas_plink.bed_reader",
    r"""
int read_bed_chunk(char*, uint64_t, uint64_t,
                       uint64_t, uint64_t,
                       uint64_t, uint64_t,
                       uint64_t*, uint64_t*);
""",
    sources=[join("pandas_plink", "_bed_reader.c")],
)

if __name__ == "__main__":
    ffibuilder.compile(verbose=True)
Ejemplo n.º 4
0
"""FFI build script."""
from cffi import FFI

FFI_BUILDER = FFI()

HEADER = 'uint32_t murmurhash3_32_x86(const unsigned char* key, int len, int32_t seed);'

FFI_BUILDER.cdef(HEADER)
FFI_BUILDER.set_source(
    'mmh3cffi._cimpl',
    '',
    sources=['csrc/mmh3.c'],
    include_dirs=['./csrc']
)

if __name__ == '__main__':
    FFI_BUILDER.compile()
Ejemplo n.º 5
0
################################################################################
#  THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY  #
#  Read the zproject/README.md for information about making permanent changes. #
################################################################################

from __future__ import print_function
import os
import re
import sys

from cffi import FFI

ffi = FFI()

try:
    # If LD_LIBRARY_PATH or your OSs equivalent is set, this is the only way to
    # load the library.  If we use find_library below, we get the wrong result.
    if os.name == 'posix':
        if sys.platform == 'darwin':
            libpath = 'libzyre.2.dylib'
        else:
            libpath = 'libzyre.so.2'
    elif os.name == 'nt':
        libpath = 'libzyre.dll'
    lib = ffi.dlopen(libpath)
except OSError:
    libpath = find_library("zyre")
    if not libpath:
        raise ImportError("Unable to find libzyre")
    lib = ffi.dlopen(libpath)
Ejemplo n.º 6
0
def setup_module(mod):
    SRC = """
    #include <string.h>
    #define FOOBAR (-42)
    static const int FOOBAZ = -43;
    #define BIGPOS 420000000000L
    #define BIGNEG -420000000000L
    int add42(int x) { return x + 42; }
    int add43(int x, ...) { return x; }
    int globalvar42 = 1234;
    const int globalconst42 = 4321;
    const char *const globalconsthello = "hello";
    struct foo_s;
    typedef struct bar_s { int x; signed char a[]; } bar_t;
    enum foo_e { AA, BB, CC };

    void init_test_re_python(void) { }      /* windows hack */
    void PyInit__test_re_python(void) { }   /* windows hack */
    """
    tmpdir = udir.join('test_re_python')
    tmpdir.ensure(dir=1)
    c_file = tmpdir.join('_test_re_python.c')
    c_file.write(SRC)
    ext = ffiplatform.get_extension(str(c_file),
                                    '_test_re_python',
                                    export_symbols=[
                                        'add42', 'add43', 'globalvar42',
                                        'globalconst42', 'globalconsthello'
                                    ])
    outputfilename = ffiplatform.compile(str(tmpdir), ext)

    # test with a non-ascii char
    ofn, oext = os.path.splitext(outputfilename)
    if sys.platform == "win32":
        unicode_name = ofn + (u + '\u03be') + oext
    else:
        unicode_name = ofn + (u + '\xe9') + oext
        try:
            unicode_name.encode(sys.getfilesystemencoding())
        except UnicodeEncodeError:
            unicode_name = None
    if unicode_name is not None:
        print(repr(outputfilename) + ' ==> ' + repr(unicode_name))
        os.rename(outputfilename, unicode_name)
        outputfilename = unicode_name

    mod.extmod = outputfilename
    mod.tmpdir = tmpdir
    #
    ffi = FFI()
    ffi.cdef("""
    #define FOOBAR -42
    static const int FOOBAZ = -43;
    #define BIGPOS 420000000000L
    #define BIGNEG -420000000000L
    int add42(int);
    int add43(int, ...);
    extern int globalvar42;
    const int globalconst42;
    const char *const globalconsthello;
    int no_such_function(int);
    extern int no_such_globalvar;
    struct foo_s;
    typedef struct bar_s { int x; signed char a[]; } bar_t;
    enum foo_e { AA, BB, CC };
    int strlen(const char *);
    struct with_union { union { int a; char b; }; };
    union with_struct { struct { int a; char b; }; };
    struct NVGcolor { union { float rgba[4]; struct { float r,g,b,a; }; }; };
    typedef struct selfref { struct selfref *next; } *selfref_ptr_t;
    """)
    ffi.set_source('re_python_pysrc', None)
    ffi.emit_python_code(str(tmpdir.join('re_python_pysrc.py')))
    mod.original_ffi = ffi
    #
    sys.path.insert(0, str(tmpdir))
Ejemplo n.º 7
0
 def check(self, source, expected_ofs_y, expected_align, expected_size):
     # NOTE: 'expected_*' is the numbers expected from GCC.
     # The numbers expected from MSVC are not explicitly written
     # in this file, and will just be taken from the compiler.
     ffi = FFI()
     ffi.cdef("struct s1 { %s };" % source)
     ctype = ffi.typeof("struct s1")
     # verify the information with gcc
     ffi1 = FFI()
     ffi1.cdef("""
         static const int Gofs_y, Galign, Gsize;
         struct s1 *try_with_value(int fieldnum, long long value);
     """)
     fnames = [
         name for name, cfield in ctype.fields
         if name and cfield.bitsize > 0
     ]
     setters = [
         'case %d: s.%s = value; break;' % iname
         for iname in enumerate(fnames)
     ]
     lib = ffi1.verify("""
         struct s1 { %s };
         struct sa { char a; struct s1 b; };
         #define Gofs_y  offsetof(struct s1, y)
         #define Galign  offsetof(struct sa, b)
         #define Gsize   sizeof(struct s1)
         struct s1 *try_with_value(int fieldnum, long long value)
         {
             static struct s1 s;
             memset(&s, 0, sizeof(s));
             switch (fieldnum) { %s }
             return &s;
         }
     """ % (source, ' '.join(setters)))
     if sys.platform == 'win32':
         expected_ofs_y = lib.Gofs_y
         expected_align = lib.Galign
         expected_size = lib.Gsize
     else:
         assert (lib.Gofs_y, lib.Galign,
                 lib.Gsize) == (expected_ofs_y, expected_align,
                                expected_size)
     # the real test follows
     assert ffi.offsetof("struct s1", "y") == expected_ofs_y
     assert ffi.alignof("struct s1") == expected_align
     assert ffi.sizeof("struct s1") == expected_size
     # compare the actual storage of the two
     for name, cfield in ctype.fields:
         if cfield.bitsize < 0 or not name:
             continue
         if int(ffi.cast(cfield.type, -1)) == -1:  # signed
             min_value = -(1 << (cfield.bitsize - 1))
             max_value = (1 << (cfield.bitsize - 1)) - 1
         else:
             min_value = 0
             max_value = (1 << cfield.bitsize) - 1
         for t in [
                 1, 2, 4, 8, 16, 128, 2813, 89728, 981729, -1, -2, -4, -8,
                 -16, -128, -2813, -89728, -981729
         ]:
             if min_value <= t <= max_value:
                 self._fieldcheck(ffi, lib, fnames, name, t)
Ejemplo n.º 8
0
    LOGISTIC = 0
    RELU = 1
    RELIE = 2
    LINEAR = 3
    RAMP = 4
    TANH = 5
    PLSE = 6
    LEAKY = 7
    ELU = 8
    LOGGY = 9
    STAIR = 10
    HARDTAN = 11
    LHTAN = 12


__darknetffi__ = FFI()

__darknetffi__.cdef("""
typedef struct network network;
typedef struct layer layer;

typedef struct{
    int *leaf;
    int n;
    int *parent;
    int *child;
    int *group;
    char **name;

    int groups;
    int *group_size;
Ejemplo n.º 9
0
def init_lib():
    if LibEVT.lib is None:
        LibEVT.ffi = FFI()
        LibEVT.ffi.cdef("""
                typedef struct {
                    size_t  sz;
                    char    buf[0];
                } evt_data_t;

                #define EVT_OK                       0
                #define EVT_INTERNAL_ERROR          -1
                #define EVT_INVALID_ARGUMENT        -2
                #define EVT_INVALID_PRIVATE_KEY     -3
                #define EVT_INVALID_PUBLIC_KEY      -4
                #define EVT_INVALID_SIGNATURE       -5
                #define EVT_INVALID_HASH            -6
                #define EVT_INVALID_ACTION          -7
                #define EVT_INVALID_BINARY          -8
                #define EVT_SIZE_NOT_EQUALS         -11
                #define EVT_DATA_NOT_EQUALS         -12

                int evt_free(void*);
                int evt_equals(evt_data_t* rhs, evt_data_t* lhs);


                typedef evt_data_t evt_bin_t;
                typedef evt_data_t evt_chain_id_t;
                typedef evt_data_t evt_block_id_t;
                typedef evt_data_t evt_public_key_t;
                typedef evt_data_t evt_private_key_t;
                typedef evt_data_t evt_signature_t;
                typedef evt_data_t evt_checksum_t;


                void* evt_abi();
                void evt_free_abi(void* abi);
                int evt_abi_json_to_bin(void* evt_abi, const char* action, const char* json, evt_bin_t** bin /* out */);
                int evt_abi_bin_to_json(void* evt_abi, const char* action, evt_bin_t* bin, char** json /* out */);
                int evt_trx_json_to_digest(void* evt_abi, const char* json, evt_chain_id_t* chain_id, evt_checksum_t** digest /* out */);
                int evt_chain_id_from_string(const char* str, evt_chain_id_t** chain_id /* out */);


                int evt_generate_new_pair(evt_public_key_t** pub_key /* out */, evt_private_key_t** priv_key /* out */);
                int evt_get_public_key(evt_private_key_t* priv_key, evt_public_key_t** pub_key /* out */);
                int evt_sign_hash(evt_private_key_t* priv_key, evt_checksum_t* hash, evt_signature_t** sign /* out */);
                int evt_recover(evt_signature_t* sign, evt_checksum_t* hash, evt_public_key_t** pub_key /* out */);
                int evt_hash(const char* buf, size_t sz, evt_checksum_t** hash /* out */);

                int evt_public_key_string(evt_public_key_t* pub_key, char** str /* out */);
                int evt_private_key_string(evt_private_key_t* priv_key, char** str /* out */);
                int evt_signature_string(evt_signature_t* sign, char** str /* out */);
                int evt_checksum_string(evt_checksum_t* hash, char** str /* out */);

                int evt_public_key_from_string(const char* str, evt_public_key_t** pub_key /* out */);
                int evt_private_key_from_string(const char* str, evt_private_key_t** priv_key /* out */);
                int evt_signature_from_string(const char* str, evt_signature_t** sign /* out */);
                int evt_checksum_from_string(const char* str, evt_checksum_t** hash /* out */);

                int evt_block_id_from_string(const char* str, evt_block_id_t** block_id /* out */);
                int evt_ref_block_num(evt_block_id_t* block_id, uint16_t* ref_block_num);
                int evt_ref_block_prefix(evt_block_id_t* block_id, uint32_t* ref_block_prefix);
                """)

        if "LIBEVT_PATH" in os.environ:
            LibEVT.lib = LibEVT.ffi.dlopen(os.environ["LIBEVT_PATH"] +
                                           '/libevt.so')
        else:
            LibEVT.lib = LibEVT.ffi.dlopen('libevt.so')

        LibEVT.abi = LibEVT.lib.evt_abi()
Ejemplo n.º 10
0
def generate_wrapper():
    """Force the (re-)generation of the wrapper module for the current LLVM
    installation"""
    global ffi
    global cached_module
    output_path = cached_module
    ffi = FFI()

    libs, ffi_code, enums = parse_headers()

    if len(libs) == 0:
        raise ValueError("No valid LLVM libraries found' \
            ', LLVM must be built with BUILD_SHARED_LIBS")

    classes = defaultdict(list)
    global_functions = []
    constants = []

    # Loop over all the LLVM libraries
    for _, library_name, library in libs:
        # Loop over all the methods we identified with cffi, not all of them
        # will actually be available
        for name in dir(library):
            # A library contains only some methods, find out which ones
            fail = False
            try:
                field = getattr(library, name)
            except AttributeError:
                fail = True

            if not fail and type(field) is int:
                constants.append((name, field))

            # Is this a usable function?
            if not fail and isinstance(field, FFI.CData):
                # Is the first argument an LLVM object? Did we ever see it
                # before?
                prototype = ffi.typeof(field)
                args = prototype.args
                if len(args) > 0 and args[0].kind == "pointer":
                    arg0_type = args[0].item
                    if (arg0_type.kind == "struct"
                            and is_llvm_type(arg0_type.cname)):

                        if not [
                                1 for x in classes[arg0_type.cname]
                                if x[1] == name
                        ]:
                            # Associate to the name of the LLVM object a tuple
                            # containing the library name, the method name and
                            # the function prototype
                            classes[arg0_type.cname].append(
                                (library_name, name, prototype))
                        continue

                # It doesn't fit any class
                if not [1 for x in global_functions if x[1] == name]:
                    global_functions.append((library_name, name, prototype))

    with open(output_path, "w") as output_file:

        def write(string):
            output_file.write(string + "\n")

        # Print file header
        write(ffi_code)
        write("from cffi import FFI")
        write("""
class LLVMException(Exception):
    pass
""")
        for library_path, library_name, library in libs:
            write("""{} = ffi.dlopen("{}")""".format(library_name,
                                                     library_path))

        # Create all the classes
        for key, value in classes.items():
            class_name = remove_llvm_prefix(key)

            # Each class is a wrapper for a pointer to a pointer to an LLVM
            # object: when a pointer is passed to a function use `in_ptr` (which
            # dereferences it), when you want to use it as an out argument using
            # `out_ptr` instead (which returns a **)
            write("""
class {class_name}(object):
    def __new__(cls, value=None):
        if value == ffi.NULL:
            return None
        return super({class_name}, cls).__new__(cls)

    def __init__(self, value=None):
        self.ptr = ffi.new("{key} **")
        if value is not None:
            self.ptr[0] = value

    def __hash__(self):
        return hash(self.ptr[0])

    def __eq__(self, other):
        return self.__hash__() == other.__hash__()

    def in_ptr(self):
        if self.ptr[0] == ffi.NULL:
            raise RuntimeError("in_ptr called on uninitialized object")
        return self.ptr[0]

    def out_ptr(self):
        if self.ptr[0] != ffi.NULL:
            raise RuntimeError(("Passing an already initialized object as an " +
                                "out parameter"))
        return self.ptr""".format(class_name=class_name, key=key))

            # Create a dictionary for properties create function will populate
            # it
            properties = defaultdict(lambda: (("", "None"), ("", "None")))

            for library, name, prototype in value:
                write(
                    create_function(library, name, prototype, class_name,
                                    properties, classes))

            # Create the properties
            write("")
            for name, ((getter_llvm, getter), (setter_llvm,
                                               setter)) in properties.items():
                if keyword.iskeyword(name):
                    name += "_"

                docstring = "\"\"\"See "
                docstring += getter_llvm
                if getter_llvm and setter_llvm:
                    docstring += " and "
                docstring += setter_llvm
                docstring += "\"\"\""

                write("""    {} = property({}, {}, doc={})""".format(
                    name, getter, setter, docstring))

        # Print global functions
        write("\nif True:")
        for library, name, prototype in global_functions:
            write(create_function(library, name, prototype))

        # Print numeric constants
        for name, value in constants:
            if name.startswith("LLVM") and not name.startswith("LLVM_"):
                name = name[4:]
            write("{} = {}".format(name, str(value)))

        # Print enum conversion methods
        for name, values in enums.items():
            write("""
{} = {}
""".format(name, values))
Ejemplo n.º 11
0
import os
import platform
import subprocess

from cffi import FFI

mpc_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))

if platform.machine() == "x86_64":
    try:
        FFI().dlopen(os.path.join(mpc_dir, "libmpc1.so"))
    except OSError:
        # libmpc1.so is likely built for aarch64. cleaning...
        subprocess.check_call(["make", "clean"], cwd=mpc_dir)

subprocess.check_call(["make", "-j4"], cwd=mpc_dir)


def _get_libmpc(mpc_id):
    libmpc_fn = os.path.join(mpc_dir, "libmpc%d.so" % mpc_id)

    ffi = FFI()
    ffi.cdef("""
    typedef struct {
    double x_ego, v_ego, a_ego, x_l, v_l, a_l;
    } state_t;


    typedef struct {
    double x_ego[21];
    double v_ego[21];
Ejemplo n.º 12
0
def build_callback_fn(function_string, userdata_names=[]):
    '''
    Builds a C callback function and returns a function pointer int.

        function_string : str
            This is a string of the C function to be compiled
        userdata_names : list or tuple
            This is an optional list to defince convenience names

    We compile and link and load the function, and return a function pointer.
    See `MjSim.set_substep_callback()` for an example use of these callbacks.

    The callback function should match the signature:
        void fun(const mjModel *m, mjData *d);

    Here's an example function_string:
        ```
        """
        #include <stdio.h>
        void fun(const mjModel* m, mjData* d) {
            printf("hello");
        }
        """
        ```

    Input and output for the function pass through userdata in the data struct:
        ```
        """
        void fun(const mjModel* m, mjData* d) {
            d->userdata[0] += 1;
        }
        """
        ```

    `userdata_names` is expected to match the model where the callback is used.
    These can bet set on a model with:
        `model.set_userdata_names([...])`

    If `userdata_names` is supplied, convenience `#define`s are added for each.
    For example:
        `userdata_names = ['my_sum']`
    Will get gerenerated into the extra line:
        `#define my_sum d->userdata[0]`
    And prepended to the top of the function before compilation.
    Here's an example that takes advantage of this:
        ```
        """
        void fun(const mjModel* m, mjData* d) {
            for (int i = 0; i < m->nu; i++) {
                my_sum += d->ctrl[i];
            }
        }
        """
        ```
    Note these are just C `#define`s and are limited in how they can be used.

    After compilation, the built library containing the function is loaded
    into memory and all of the files (including the library) are deleted.
    To retain these for debugging set the `MUJOCO_PY_DEBUG_FN_BUILDER` envvar.

    To save time compiling, these function pointers may be re-used by many
    different consumers.  They are thread-safe and don't acquire the GIL.

    See the file `tests/test_substep.py` for additional examples,
    including an example which iterates over contacts to compute penetrations.
    '''
    assert isinstance(userdata_names, (list, tuple)), \
        'invalid userdata_names: {}'.format(userdata_names)
    ffibuilder = FFI()
    ffibuilder.cdef('extern uintptr_t __fun;')
    name = '_fn_' + ''.join(choice(ascii_lowercase) for _ in range(15))
    source_string = '#include <mujoco.h>\n'
    # Add defines for each userdata to make setting them easier
    for i, data_name in enumerate(userdata_names):
        source_string += '#define {} d->userdata[{}]\n'.format(data_name, i)
    source_string += function_string
    source_string += '\nuintptr_t __fun = (uintptr_t) fun;'
    # Link against mujoco so we can call mujoco functions from within callback
    ffibuilder.set_source(name,
                          source_string,
                          include_dirs=[join(mujoco_path, 'include')],
                          library_dirs=[join(mujoco_path, 'bin')],
                          libraries=['mujoco200'])
    # Catch compilation exceptions so we can cleanup partial files in that case
    try:
        library_path = ffibuilder.compile(verbose=True)
    except Exception as e:
        build_fn_cleanup(name)
        raise e
    # On Mac the MuJoCo library is linked strangely, so we have to fix it here
    if sys.platform == 'darwin':
        fixed_library_path = manually_link_libraries(mujoco_path, library_path)
        move(fixed_library_path, library_path)  # Overwrite with fixed library
    module = load_dynamic_ext(name, library_path)
    # Now that the module is loaded into memory, we can actually delete it
    build_fn_cleanup(name)
    return module.lib.__fun
Ejemplo n.º 13
0
def test_typeof():
    ffi = FFI(backend=FakeBackend())
    clong = ffi.typeof("signed long int")
    assert isinstance(clong, FakeType)
    assert clong.cdecl == 'primitive long'
Ejemplo n.º 14
0
 def test_inspecttype(self):
     ffi = FFI(backend=self.Backend())
     assert ffi.typeof("long").kind == "primitive"
     assert ffi.typeof("long(*)(long, long**, ...)").cname == (
         "long(*)(long, long * *, ...)")
     assert ffi.typeof("long(*)(long, long**, ...)").ellipsis is True
Ejemplo n.º 15
0
def xtest_cffi_assembly():
    mesh = UnitSquareMesh(MPI.comm_world, 13, 13)
    V = FunctionSpace(mesh, ("Lagrange", 1))

    if MPI.rank(mesh.mpi_comm()) == 0:
        from cffi import FFI
        ffibuilder = FFI()
        ffibuilder.set_source(
            "_cffi_kernelA", r"""
        #include <math.h>
        #include <stdalign.h>
        void tabulate_tensor_poissonA(double* restrict A, const double* w,
                                    const double* restrict coordinate_dofs,
                                    int cell_orientation)
        {
        // Precomputed values of basis functions and precomputations
        // FE* dimensions: [entities][points][dofs]
        // PI* dimensions: [entities][dofs][dofs] or [entities][dofs]
        // PM* dimensions: [entities][dofs][dofs]
        alignas(32) static const double FE3_C0_D01_Q1[1][1][2] = { { { -1.0, 1.0 } } };
        // Unstructured piecewise computations
        const double J_c0 = coordinate_dofs[0] * FE3_C0_D01_Q1[0][0][0] + coordinate_dofs[2] * FE3_C0_D01_Q1[0][0][1];
        const double J_c3 = coordinate_dofs[1] * FE3_C0_D01_Q1[0][0][0] + coordinate_dofs[5] * FE3_C0_D01_Q1[0][0][1];
        const double J_c1 = coordinate_dofs[0] * FE3_C0_D01_Q1[0][0][0] + coordinate_dofs[4] * FE3_C0_D01_Q1[0][0][1];
        const double J_c2 = coordinate_dofs[1] * FE3_C0_D01_Q1[0][0][0] + coordinate_dofs[3] * FE3_C0_D01_Q1[0][0][1];
        alignas(32) double sp[20];
        sp[0] = J_c0 * J_c3;
        sp[1] = J_c1 * J_c2;
        sp[2] = sp[0] + -1 * sp[1];
        sp[3] = J_c0 / sp[2];
        sp[4] = -1 * J_c1 / sp[2];
        sp[5] = sp[3] * sp[3];
        sp[6] = sp[3] * sp[4];
        sp[7] = sp[4] * sp[4];
        sp[8] = J_c3 / sp[2];
        sp[9] = -1 * J_c2 / sp[2];
        sp[10] = sp[9] * sp[9];
        sp[11] = sp[8] * sp[9];
        sp[12] = sp[8] * sp[8];
        sp[13] = sp[5] + sp[10];
        sp[14] = sp[6] + sp[11];
        sp[15] = sp[12] + sp[7];
        sp[16] = fabs(sp[2]);
        sp[17] = sp[13] * sp[16];
        sp[18] = sp[14] * sp[16];
        sp[19] = sp[15] * sp[16];
        // UFLACS block mode: preintegrated
        A[0] = 0.5 * sp[19] + 0.5 * sp[18] + 0.5 * sp[18] + 0.5 * sp[17];
        A[1] = -0.5 * sp[19] + -0.5 * sp[18];
        A[2] = -0.5 * sp[18] + -0.5 * sp[17];
        A[3] = -0.5 * sp[19] + -0.5 * sp[18];
        A[4] = 0.5 * sp[19];
        A[5] = 0.5 * sp[18];
        A[6] = -0.5 * sp[18] + -0.5 * sp[17];
        A[7] = 0.5 * sp[18];
        A[8] = 0.5 * sp[17];
        }

        void tabulate_tensor_poissonL(double* restrict A, const double* w,
                                     const double* restrict coordinate_dofs,
                                     int cell_orientation)
        {
        // Precomputed values of basis functions and precomputations
        // FE* dimensions: [entities][points][dofs]
        // PI* dimensions: [entities][dofs][dofs] or [entities][dofs]
        // PM* dimensions: [entities][dofs][dofs]
        alignas(32) static const double FE4_C0_D01_Q1[1][1][2] = { { { -1.0, 1.0 } } };
        // Unstructured piecewise computations
        const double J_c0 = coordinate_dofs[0] * FE4_C0_D01_Q1[0][0][0] + coordinate_dofs[2] * FE4_C0_D01_Q1[0][0][1];
        const double J_c3 = coordinate_dofs[1] * FE4_C0_D01_Q1[0][0][0] + coordinate_dofs[5] * FE4_C0_D01_Q1[0][0][1];
        const double J_c1 = coordinate_dofs[0] * FE4_C0_D01_Q1[0][0][0] + coordinate_dofs[4] * FE4_C0_D01_Q1[0][0][1];
        const double J_c2 = coordinate_dofs[1] * FE4_C0_D01_Q1[0][0][0] + coordinate_dofs[3] * FE4_C0_D01_Q1[0][0][1];
        alignas(32) double sp[4];
        sp[0] = J_c0 * J_c3;
        sp[1] = J_c1 * J_c2;
        sp[2] = sp[0] + -1 * sp[1];
        sp[3] = fabs(sp[2]);
        // UFLACS block mode: preintegrated
        A[0] = 0.1666666666666667 * sp[3];
        A[1] = 0.1666666666666667 * sp[3];
        A[2] = 0.1666666666666667 * sp[3];
        }
        """)
        ffibuilder.cdef("""
        void tabulate_tensor_poissonA(double* restrict A, const double* w,
                                    const double* restrict coordinate_dofs,
                                    int cell_orientation);
        void tabulate_tensor_poissonL(double* restrict A, const double* w,
                                    const double* restrict coordinate_dofs,
                                    int cell_orientation);
        """)

        ffibuilder.compile(verbose=True)

    MPI.barrier(mesh.mpi_comm())
    from _cffi_kernelA import ffi, lib

    a = cpp.fem.Form([V._cpp_object, V._cpp_object])
    ptrA = ffi.cast("intptr_t", ffi.addressof(lib, "tabulate_tensor_poissonA"))
    a.set_cell_tabulate(0, ptrA)

    L = cpp.fem.Form([V._cpp_object])
    ptrL = ffi.cast("intptr_t", ffi.addressof(lib, "tabulate_tensor_poissonL"))
    L.set_cell_tabulate(0, ptrL)

    assembler = cpp.fem.Assembler([[a]], [L], [])
    A = assembler.assemble_matrix(cpp.fem.Assembler.BlockType.monolithic)
    b = assembler.assemble_vector(cpp.fem.Assembler.BlockType.monolithic)

    Anorm = A.norm(cpp.la.Norm.frobenius)
    bnorm = b.norm(cpp.la.Norm.l2)
    assert (np.isclose(Anorm, 56.124860801609124))
    assert (np.isclose(bnorm, 0.0739710713711999))

    list_timings([TimingType.wall])
Ejemplo n.º 16
0
from pathlib import Path
from cffi import FFI

flex_motion_ffi = FFI()
LIB_PATH = Path(__file__).parent.absolute() / 'lib'
INC_PATH = LIB_PATH

with open(str(INC_PATH / 'flexmotn_flat.h')) as f:
    flex_motion_ffi.cdef(f.read())

flex_motion_ffi.set_source('_flex_motion_cffi',
                           f'#include "flexmotn_flat.h"',
                           libraries=[str(INC_PATH / 'FlexMS32')],
                           include_dirs=[str(INC_PATH)])

if __name__ == '__main__':
    flex_motion_ffi.compile(verbose=True)
Ejemplo n.º 17
0
def test_partial_enum():
    ffi = FFI()
    ffi.cdef("enum foo { A, B, ... };")
    ffi.set_source('test_partial_enum', None)
    py.test.raises(VerificationMissing, ffi.emit_python_code,
                   str(tmpdir.join('test_partial_enum.py')))
Ejemplo n.º 18
0
# You should have received a copy of the GNU General Public License
# along with bedup.  If not, see <http://www.gnu.org/licenses/>.

from cffi import FFI
import fcntl

from . import cffi_support


__all__ = (
    'getflags',
    'editflags',
    'FS_IMMUTABLE_FL',
)

ffi = FFI()
ffi.cdef('''
#define FS_IOC_GETFLAGS ...
#define FS_IOC_SETFLAGS ...

#define	FS_SECRM_FL ... /* Secure deletion */
#define	FS_UNRM_FL ... /* Undelete */
#define	FS_COMPR_FL ... /* Compress file */
#define FS_SYNC_FL ... /* Synchronous updates */
#define FS_IMMUTABLE_FL ... /* Immutable file */
#define FS_APPEND_FL ... /* writes to file may only append */
#define FS_NODUMP_FL ... /* do not dump file */
#define FS_NOATIME_FL ... /* do not update atime */
/* Reserved for compression usage... */
#define FS_DIRTY_FL ...
#define FS_COMPRBLK_FL ... /* One or more compressed clusters */
Ejemplo n.º 19
0
import os

from types import TracebackType
from typing import Optional, Type, Union

from cffi import FFI

from tartiflette.language.parsers.libgraphqlparser.transformers import (
    document_from_ast_json, )
from tartiflette.types.exceptions.tartiflette import GraphQLSyntaxError

__all__ = ("parse_to_document", )

# TODO: automatize read from headers files
_FFI = FFI()
_FFI.cdef("""
struct GraphQLAstNode *graphql_parse_string(
    const char *text, const char **error);

void graphql_error_free(const char *error);

void graphql_node_free(struct GraphQLAstNode *node);

const char *graphql_ast_to_json(const struct GraphQLAstNode *node);
""")

# TODO: use importlib.resource in Python 3.7
_LIBGRAPHQLPARSER_DIR = os.path.join(os.path.dirname(__file__), "cffi")
try:
    _LIB = _FFI.dlopen(f"{_LIBGRAPHQLPARSER_DIR}/libgraphqlparser.so")
except OSError: