/* Generated by Cython 0.26 */

/* BEGIN: Cython Metadata
{
    "distutils": {
        "depends": [
            "cpp-btree/btree_set.h",
            "discodop/_containers.h",
            "discodop/bitcount.h",
            "discodop/macros.h"
        ],
        "extra_compile_args": [
            "-Isparsepp/",
            "-Wno-strict-prototypes",
            "-Wno-unused-function",
            "-Wno-unreachable-code",
            "-Wno-sign-compare",
            "-D__STDC_LIMIT_MACROS",
            "-O3",
            "-march=native",
            "-DNDEBUG"
        ],
        "extra_link_args": [
            "-DNDEBUG"
        ],
        "include_dirs": [
            "./discodop",
            "discodop"
        ],
        "language": "c++",
        "name": "discodop.kbest",
        "sources": [
            "discodop/kbest.pyx"
        ]
    },
    "module_name": "discodop.kbest"
}
END: Cython Metadata */

#define PY_SSIZE_T_CLEAN
#include "Python.h"
#ifndef Py_PYTHON_H
    #error Python headers needed to compile C extensions, please install development version of Python.
#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000)
    #error Cython requires Python 2.6+ or Python 3.2+.
#else
#define CYTHON_ABI "0_26"
#include <stddef.h>
#ifndef offsetof
  #define offsetof(type, member) ( (size_t) & ((type*)0) -> member )
#endif
#if !defined(WIN32) && !defined(MS_WINDOWS)
  #ifndef __stdcall
    #define __stdcall
  #endif
  #ifndef __cdecl
    #define __cdecl
  #endif
  #ifndef __fastcall
    #define __fastcall
  #endif
#endif
#ifndef DL_IMPORT
  #define DL_IMPORT(t) t
#endif
#ifndef DL_EXPORT
  #define DL_EXPORT(t) t
#endif
#define __PYX_COMMA ,
#ifndef HAVE_LONG_LONG
  #if PY_VERSION_HEX >= 0x03030000 || (PY_MAJOR_VERSION == 2 && PY_VERSION_HEX >= 0x02070000)
    #define HAVE_LONG_LONG
  #endif
#endif
#ifndef PY_LONG_LONG
  #define PY_LONG_LONG LONG_LONG
#endif
#ifndef Py_HUGE_VAL
  #define Py_HUGE_VAL HUGE_VAL
#endif
#ifdef PYPY_VERSION
  #define CYTHON_COMPILING_IN_PYPY 1
  #define CYTHON_COMPILING_IN_PYSTON 0
  #define CYTHON_COMPILING_IN_CPYTHON 0
  #undef CYTHON_USE_TYPE_SLOTS
  #define CYTHON_USE_TYPE_SLOTS 0
  #undef CYTHON_USE_ASYNC_SLOTS
  #define CYTHON_USE_ASYNC_SLOTS 0
  #undef CYTHON_USE_PYLIST_INTERNALS
  #define CYTHON_USE_PYLIST_INTERNALS 0
  #undef CYTHON_USE_UNICODE_INTERNALS
  #define CYTHON_USE_UNICODE_INTERNALS 0
  #undef CYTHON_USE_UNICODE_WRITER
  #define CYTHON_USE_UNICODE_WRITER 0
  #undef CYTHON_USE_PYLONG_INTERNALS
  #define CYTHON_USE_PYLONG_INTERNALS 0
  #undef CYTHON_AVOID_BORROWED_REFS
  #define CYTHON_AVOID_BORROWED_REFS 1
  #undef CYTHON_ASSUME_SAFE_MACROS
  #define CYTHON_ASSUME_SAFE_MACROS 0
  #undef CYTHON_UNPACK_METHODS
  #define CYTHON_UNPACK_METHODS 0
  #undef CYTHON_FAST_THREAD_STATE
  #define CYTHON_FAST_THREAD_STATE 0
  #undef CYTHON_FAST_PYCALL
  #define CYTHON_FAST_PYCALL 0
#elif defined(PYSTON_VERSION)
  #define CYTHON_COMPILING_IN_PYPY 0
  #define CYTHON_COMPILING_IN_PYSTON 1
  #define CYTHON_COMPILING_IN_CPYTHON 0
  #ifndef CYTHON_USE_TYPE_SLOTS
    #define CYTHON_USE_TYPE_SLOTS 1
  #endif
  #undef CYTHON_USE_ASYNC_SLOTS
  #define CYTHON_USE_ASYNC_SLOTS 0
  #undef CYTHON_USE_PYLIST_INTERNALS
  #define CYTHON_USE_PYLIST_INTERNALS 0
  #ifndef CYTHON_USE_UNICODE_INTERNALS
    #define CYTHON_USE_UNICODE_INTERNALS 1
  #endif
  #undef CYTHON_USE_UNICODE_WRITER
  #define CYTHON_USE_UNICODE_WRITER 0
  #undef CYTHON_USE_PYLONG_INTERNALS
  #define CYTHON_USE_PYLONG_INTERNALS 0
  #ifndef CYTHON_AVOID_BORROWED_REFS
    #define CYTHON_AVOID_BORROWED_REFS 0
  #endif
  #ifndef CYTHON_ASSUME_SAFE_MACROS
    #define CYTHON_ASSUME_SAFE_MACROS 1
  #endif
  #ifndef CYTHON_UNPACK_METHODS
    #define CYTHON_UNPACK_METHODS 1
  #endif
  #undef CYTHON_FAST_THREAD_STATE
  #define CYTHON_FAST_THREAD_STATE 0
  #undef CYTHON_FAST_PYCALL
  #define CYTHON_FAST_PYCALL 0
#else
  #define CYTHON_COMPILING_IN_PYPY 0
  #define CYTHON_COMPILING_IN_PYSTON 0
  #define CYTHON_COMPILING_IN_CPYTHON 1
  #ifndef CYTHON_USE_TYPE_SLOTS
    #define CYTHON_USE_TYPE_SLOTS 1
  #endif
  #if PY_MAJOR_VERSION < 3
    #undef CYTHON_USE_ASYNC_SLOTS
    #define CYTHON_USE_ASYNC_SLOTS 0
  #elif !defined(CYTHON_USE_ASYNC_SLOTS)
    #define CYTHON_USE_ASYNC_SLOTS 1
  #endif
  #if PY_VERSION_HEX < 0x02070000
    #undef CYTHON_USE_PYLONG_INTERNALS
    #define CYTHON_USE_PYLONG_INTERNALS 0
  #elif !defined(CYTHON_USE_PYLONG_INTERNALS)
    #define CYTHON_USE_PYLONG_INTERNALS 1
  #endif
  #ifndef CYTHON_USE_PYLIST_INTERNALS
    #define CYTHON_USE_PYLIST_INTERNALS 1
  #endif
  #ifndef CYTHON_USE_UNICODE_INTERNALS
    #define CYTHON_USE_UNICODE_INTERNALS 1
  #endif
  #if PY_VERSION_HEX < 0x030300F0
    #undef CYTHON_USE_UNICODE_WRITER
    #define CYTHON_USE_UNICODE_WRITER 0
  #elif !defined(CYTHON_USE_UNICODE_WRITER)
    #define CYTHON_USE_UNICODE_WRITER 1
  #endif
  #ifndef CYTHON_AVOID_BORROWED_REFS
    #define CYTHON_AVOID_BORROWED_REFS 0
  #endif
  #ifndef CYTHON_ASSUME_SAFE_MACROS
    #define CYTHON_ASSUME_SAFE_MACROS 1
  #endif
  #ifndef CYTHON_UNPACK_METHODS
    #define CYTHON_UNPACK_METHODS 1
  #endif
  #ifndef CYTHON_FAST_THREAD_STATE
    #define CYTHON_FAST_THREAD_STATE 1
  #endif
  #ifndef CYTHON_FAST_PYCALL
    #define CYTHON_FAST_PYCALL 1
  #endif
#endif
#if !defined(CYTHON_FAST_PYCCALL)
#define CYTHON_FAST_PYCCALL  (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1)
#endif
#if CYTHON_USE_PYLONG_INTERNALS
  #include "longintrepr.h"
  #undef SHIFT
  #undef BASE
  #undef MASK
#endif
#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag)
  #define Py_OptimizeFlag 0
#endif
#define __PYX_BUILD_PY_SSIZE_T "n"
#define CYTHON_FORMAT_SSIZE_T "z"
#if PY_MAJOR_VERSION < 3
  #define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
  #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
          PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
  #define __Pyx_DefaultClassType PyClass_Type
#else
  #define __Pyx_BUILTIN_MODULE_NAME "builtins"
  #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
          PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
  #define __Pyx_DefaultClassType PyType_Type
#endif
#ifndef Py_TPFLAGS_CHECKTYPES
  #define Py_TPFLAGS_CHECKTYPES 0
#endif
#ifndef Py_TPFLAGS_HAVE_INDEX
  #define Py_TPFLAGS_HAVE_INDEX 0
#endif
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
  #define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#ifndef Py_TPFLAGS_HAVE_FINALIZE
  #define Py_TPFLAGS_HAVE_FINALIZE 0
#endif
#if PY_VERSION_HEX < 0x030700A0 || !defined(METH_FASTCALL)
  #ifndef METH_FASTCALL
     #define METH_FASTCALL 0x80
  #endif
  typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args, Py_ssize_t nargs);
  typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject **args,
                                                          Py_ssize_t nargs, PyObject *kwnames);
#else
  #define __Pyx_PyCFunctionFast _PyCFunctionFast
  #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords
#endif
#if CYTHON_FAST_PYCCALL
#define __Pyx_PyFastCFunction_Check(func)\
    ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS)))))
#else
#define __Pyx_PyFastCFunction_Check(func) 0
#endif
#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND)
  #define CYTHON_PEP393_ENABLED 1
  #define __Pyx_PyUnicode_READY(op)       (likely(PyUnicode_IS_READY(op)) ?\
                                              0 : _PyUnicode_Ready((PyObject *)(op)))
  #define __Pyx_PyUnicode_GET_LENGTH(u)   PyUnicode_GET_LENGTH(u)
  #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i)
  #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u)   PyUnicode_MAX_CHAR_VALUE(u)
  #define __Pyx_PyUnicode_KIND(u)         PyUnicode_KIND(u)
  #define __Pyx_PyUnicode_DATA(u)         PyUnicode_DATA(u)
  #define __Pyx_PyUnicode_READ(k, d, i)   PyUnicode_READ(k, d, i)
  #define __Pyx_PyUnicode_WRITE(k, d, i, ch)  PyUnicode_WRITE(k, d, i, ch)
  #define __Pyx_PyUnicode_IS_TRUE(u)      (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u)))
#else
  #define CYTHON_PEP393_ENABLED 0
  #define PyUnicode_1BYTE_KIND  1
  #define PyUnicode_2BYTE_KIND  2
  #define PyUnicode_4BYTE_KIND  4
  #define __Pyx_PyUnicode_READY(op)       (0)
  #define __Pyx_PyUnicode_GET_LENGTH(u)   PyUnicode_GET_SIZE(u)
  #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i]))
  #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u)   ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111)
  #define __Pyx_PyUnicode_KIND(u)         (sizeof(Py_UNICODE))
  #define __Pyx_PyUnicode_DATA(u)         ((void*)PyUnicode_AS_UNICODE(u))
  #define __Pyx_PyUnicode_READ(k, d, i)   ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i]))
  #define __Pyx_PyUnicode_WRITE(k, d, i, ch)  (((void)(k)), ((Py_UNICODE*)d)[i] = ch)
  #define __Pyx_PyUnicode_IS_TRUE(u)      (0 != PyUnicode_GET_SIZE(u))
#endif
#if CYTHON_COMPILING_IN_PYPY
  #define __Pyx_PyUnicode_Concat(a, b)      PyNumber_Add(a, b)
  #define __Pyx_PyUnicode_ConcatSafe(a, b)  PyNumber_Add(a, b)
#else
  #define __Pyx_PyUnicode_Concat(a, b)      PyUnicode_Concat(a, b)
  #define __Pyx_PyUnicode_ConcatSafe(a, b)  ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\
      PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b))
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains)
  #define PyUnicode_Contains(u, s)  PySequence_Contains(u, s)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check)
  #define PyByteArray_Check(obj)  PyObject_TypeCheck(obj, &PyByteArray_Type)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format)
  #define PyObject_Format(obj, fmt)  PyObject_CallMethod(obj, "__format__", "O", fmt)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc)
  #define PyObject_Malloc(s)   PyMem_Malloc(s)
  #define PyObject_Free(p)     PyMem_Free(p)
  #define PyObject_Realloc(p)  PyMem_Realloc(p)
#endif
#if CYTHON_COMPILING_IN_PYSTON
  #define __Pyx_PyCode_HasFreeVars(co)  PyCode_HasFreeVars(co)
  #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno)
#else
  #define __Pyx_PyCode_HasFreeVars(co)  (PyCode_GetNumFree(co) > 0)
  #define __Pyx_PyFrame_SetLineNumber(frame, lineno)  (frame)->f_lineno = (lineno)
#endif
#define __Pyx_PyString_FormatSafe(a, b)   ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b))
#define __Pyx_PyUnicode_FormatSafe(a, b)  ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b))
#if PY_MAJOR_VERSION >= 3
  #define __Pyx_PyString_Format(a, b)  PyUnicode_Format(a, b)
#else
  #define __Pyx_PyString_Format(a, b)  PyString_Format(a, b)
#endif
#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII)
  #define PyObject_ASCII(o)            PyObject_Repr(o)
#endif
#if PY_MAJOR_VERSION >= 3
  #define PyBaseString_Type            PyUnicode_Type
  #define PyStringObject               PyUnicodeObject
  #define PyString_Type                PyUnicode_Type
  #define PyString_Check               PyUnicode_Check
  #define PyString_CheckExact          PyUnicode_CheckExact
#endif
#if PY_MAJOR_VERSION >= 3
  #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj)
  #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj)
#else
  #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj))
  #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj))
#endif
#ifndef PySet_CheckExact
  #define PySet_CheckExact(obj)        (Py_TYPE(obj) == &PySet_Type)
#endif
#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type)
#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception)
#if PY_MAJOR_VERSION >= 3
  #define PyIntObject                  PyLongObject
  #define PyInt_Type                   PyLong_Type
  #define PyInt_Check(op)              PyLong_Check(op)
  #define PyInt_CheckExact(op)         PyLong_CheckExact(op)
  #define PyInt_FromString             PyLong_FromString
  #define PyInt_FromUnicode            PyLong_FromUnicode
  #define PyInt_FromLong               PyLong_FromLong
  #define PyInt_FromSize_t             PyLong_FromSize_t
  #define PyInt_FromSsize_t            PyLong_FromSsize_t
  #define PyInt_AsLong                 PyLong_AsLong
  #define PyInt_AS_LONG                PyLong_AS_LONG
  #define PyInt_AsSsize_t              PyLong_AsSsize_t
  #define PyInt_AsUnsignedLongMask     PyLong_AsUnsignedLongMask
  #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
  #define PyNumber_Int                 PyNumber_Long
#endif
#if PY_MAJOR_VERSION >= 3
  #define PyBoolObject                 PyLongObject
#endif
#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY
  #ifndef PyUnicode_InternFromString
    #define PyUnicode_InternFromString(s) PyUnicode_FromString(s)
  #endif
#endif
#if PY_VERSION_HEX < 0x030200A4
  typedef long Py_hash_t;
  #define __Pyx_PyInt_FromHash_t PyInt_FromLong
  #define __Pyx_PyInt_AsHash_t   PyInt_AsLong
#else
  #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t
  #define __Pyx_PyInt_AsHash_t   PyInt_AsSsize_t
#endif
#if PY_MAJOR_VERSION >= 3
  #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func))
#else
  #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass)
#endif
#ifndef __has_attribute
  #define __has_attribute(x) 0
#endif
#ifndef __has_cpp_attribute
  #define __has_cpp_attribute(x) 0
#endif
#if CYTHON_USE_ASYNC_SLOTS
  #if PY_VERSION_HEX >= 0x030500B1
    #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods
    #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async)
  #else
    typedef struct {
        unaryfunc am_await;
        unaryfunc am_aiter;
        unaryfunc am_anext;
    } __Pyx_PyAsyncMethodsStruct;
    #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved))
  #endif
#else
  #define __Pyx_PyType_AsAsync(obj) NULL
#endif
#ifndef CYTHON_RESTRICT
  #if defined(__GNUC__)
    #define CYTHON_RESTRICT __restrict__
  #elif defined(_MSC_VER) && _MSC_VER >= 1400
    #define CYTHON_RESTRICT __restrict
  #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    #define CYTHON_RESTRICT restrict
  #else
    #define CYTHON_RESTRICT
  #endif
#endif
#ifndef CYTHON_UNUSED
# if defined(__GNUC__)
#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
#     define CYTHON_UNUSED __attribute__ ((__unused__))
#   else
#     define CYTHON_UNUSED
#   endif
# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER))
#   define CYTHON_UNUSED __attribute__ ((__unused__))
# else
#   define CYTHON_UNUSED
# endif
#endif
#ifndef CYTHON_MAYBE_UNUSED_VAR
#  if defined(__cplusplus)
     template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { }
#  else
#    define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x)
#  endif
#endif
#ifndef CYTHON_NCP_UNUSED
# if CYTHON_COMPILING_IN_CPYTHON
#  define CYTHON_NCP_UNUSED
# else
#  define CYTHON_NCP_UNUSED CYTHON_UNUSED
# endif
#endif
#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None)
#ifdef _MSC_VER
    #ifndef _MSC_STDINT_H_
        #if _MSC_VER < 1300
           typedef unsigned char     uint8_t;
           typedef unsigned int      uint32_t;
        #else
           typedef unsigned __int8   uint8_t;
           typedef unsigned __int32  uint32_t;
        #endif
    #endif
#else
   #include <stdint.h>
#endif
#ifndef CYTHON_FALLTHROUGH
  #ifdef __cplusplus
    #if __has_cpp_attribute(fallthrough)
      #define CYTHON_FALLTHROUGH [[fallthrough]]
    #elif __has_cpp_attribute(clang::fallthrough)
      #define CYTHON_FALLTHROUGH [[clang::fallthrough]]
    #endif
  #endif
  #ifndef CYTHON_FALLTHROUGH
    #if __has_attribute(fallthrough) || (defined(__GNUC__) && defined(__attribute__))
      #define CYTHON_FALLTHROUGH __attribute__((fallthrough))
    #else
      #define CYTHON_FALLTHROUGH
    #endif
  #endif
#endif

#ifndef __cplusplus
  #error "Cython files generated with the C++ option must be compiled with a C++ compiler."
#endif
#ifndef CYTHON_INLINE
  #if defined(__clang__)
    #define CYTHON_INLINE __inline__ __attribute__ ((__unused__))
  #else
    #define CYTHON_INLINE inline
  #endif
#endif
template<typename T>
void __Pyx_call_destructor(T& x) {
    x.~T();
}
template<typename T>
class __Pyx_FakeReference {
  public:
    __Pyx_FakeReference() : ptr(NULL) { }
    __Pyx_FakeReference(const T& ref) : ptr(const_cast<T*>(&ref)) { }
    T *operator->() { return ptr; }
    T *operator&() { return ptr; }
    operator T&() { return *ptr; }
    template<typename U> bool operator ==(U other) { return *ptr == other; }
    template<typename U> bool operator !=(U other) { return *ptr != other; }
  private:
    T *ptr;
};

#if defined(WIN32) || defined(MS_WINDOWS)
  #define _USE_MATH_DEFINES
#endif
#include <math.h>
#ifdef NAN
#define __PYX_NAN() ((float) NAN)
#else
static CYTHON_INLINE float __PYX_NAN() {
  float value;
  memset(&value, 0xFF, sizeof(value));
  return value;
}
#endif
#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL)
#define __Pyx_truncl trunc
#else
#define __Pyx_truncl truncl
#endif


#define __PYX_ERR(f_index, lineno, Ln_error) \
{ \
  __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \
}

#if PY_MAJOR_VERSION >= 3
  #define __Pyx_PyNumber_Divide(x,y)         PyNumber_TrueDivide(x,y)
  #define __Pyx_PyNumber_InPlaceDivide(x,y)  PyNumber_InPlaceTrueDivide(x,y)
#else
  #define __Pyx_PyNumber_Divide(x,y)         PyNumber_TrueDivide(x,y)
  #define __Pyx_PyNumber_InPlaceDivide(x,y)  PyNumber_InPlaceTrueDivide(x,y)
#endif

#ifndef __PYX_EXTERN_C
  #ifdef __cplusplus
    #define __PYX_EXTERN_C extern "C"
  #else
    #define __PYX_EXTERN_C extern
  #endif
#endif

#define __PYX_HAVE__discodop__kbest
#define __PYX_HAVE_API__discodop__kbest
#include <utility>
#include "ios"
#include "new"
#include "stdexcept"
#include "typeinfo"
#include <vector>
#include <string.h>
#include <string>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include "macros.h"
#include "bitcount.h"
#include "_containers.h"
#include "../cpp-btree/btree_set.h"
#ifdef _OPENMP
#include <omp.h>
#endif /* _OPENMP */

#ifdef PYREX_WITHOUT_ASSERTIONS
#define CYTHON_WITHOUT_ASSERTIONS
#endif

typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding;
                const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry;

#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0
#define __PYX_DEFAULT_STRING_ENCODING ""
#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#define __Pyx_uchar_cast(c) ((unsigned char)c)
#define __Pyx_long_cast(x) ((long)x)
#define __Pyx_fits_Py_ssize_t(v, type, is_signed)  (\
    (sizeof(type) < sizeof(Py_ssize_t))  ||\
    (sizeof(type) > sizeof(Py_ssize_t) &&\
          likely(v < (type)PY_SSIZE_T_MAX ||\
                 v == (type)PY_SSIZE_T_MAX)  &&\
          (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\
                                v == (type)PY_SSIZE_T_MIN)))  ||\
    (sizeof(type) == sizeof(Py_ssize_t) &&\
          (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\
                               v == (type)PY_SSIZE_T_MAX)))  )
#if defined (__cplusplus) && __cplusplus >= 201103L
    #include <cstdlib>
    #define __Pyx_sst_abs(value) std::abs(value)
#elif SIZEOF_INT >= SIZEOF_SIZE_T
    #define __Pyx_sst_abs(value) abs(value)
#elif SIZEOF_LONG >= SIZEOF_SIZE_T
    #define __Pyx_sst_abs(value) labs(value)
#elif defined (_MSC_VER) && defined (_M_X64)
    #define __Pyx_sst_abs(value) _abs64(value)
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    #define __Pyx_sst_abs(value) llabs(value)
#elif defined (__GNUC__)
    #define __Pyx_sst_abs(value) __builtin_llabs(value)
#else
    #define __Pyx_sst_abs(value) ((value<0) ? -value : value)
#endif
static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*);
static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length);
#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s))
#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l)
#define __Pyx_PyBytes_FromString        PyBytes_FromString
#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*);
#if PY_MAJOR_VERSION < 3
    #define __Pyx_PyStr_FromString        __Pyx_PyBytes_FromString
    #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#else
    #define __Pyx_PyStr_FromString        __Pyx_PyUnicode_FromString
    #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize
#endif
#define __Pyx_PyObject_AsWritableString(s)    ((char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsWritableSString(s)    ((signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsWritableUString(s)    ((unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsSString(s)    ((const signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsUString(s)    ((const unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_FromCString(s)  __Pyx_PyObject_FromString((const char*)s)
#define __Pyx_PyBytes_FromCString(s)   __Pyx_PyBytes_FromString((const char*)s)
#define __Pyx_PyByteArray_FromCString(s)   __Pyx_PyByteArray_FromString((const char*)s)
#define __Pyx_PyStr_FromCString(s)     __Pyx_PyStr_FromString((const char*)s)
#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s)
#if PY_MAJOR_VERSION < 3
static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u)
{
    const Py_UNICODE *u_end = u;
    while (*u_end++) ;
    return (size_t)(u_end - u - 1);
}
#else
#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen
#endif
#define __Pyx_PyUnicode_FromUnicode(u)       PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u))
#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode
#define __Pyx_PyUnicode_AsUnicode            PyUnicode_AsUnicode
#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj)
#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None)
#define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False))
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x);
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
#if CYTHON_ASSUME_SAFE_MACROS
#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
#else
#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x)
#endif
#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x))
#else
#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x))
#endif
#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x))
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
static int __Pyx_sys_getdefaultencoding_not_ascii;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
    PyObject* sys;
    PyObject* default_encoding = NULL;
    PyObject* ascii_chars_u = NULL;
    PyObject* ascii_chars_b = NULL;
    const char* default_encoding_c;
    sys = PyImport_ImportModule("sys");
    if (!sys) goto bad;
    default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL);
    Py_DECREF(sys);
    if (!default_encoding) goto bad;
    default_encoding_c = PyBytes_AsString(default_encoding);
    if (!default_encoding_c) goto bad;
    if (strcmp(default_encoding_c, "ascii") == 0) {
        __Pyx_sys_getdefaultencoding_not_ascii = 0;
    } else {
        char ascii_chars[128];
        int c;
        for (c = 0; c < 128; c++) {
            ascii_chars[c] = c;
        }
        __Pyx_sys_getdefaultencoding_not_ascii = 1;
        ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL);
        if (!ascii_chars_u) goto bad;
        ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL);
        if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) {
            PyErr_Format(
                PyExc_ValueError,
                "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.",
                default_encoding_c);
            goto bad;
        }
        Py_DECREF(ascii_chars_u);
        Py_DECREF(ascii_chars_b);
    }
    Py_DECREF(default_encoding);
    return 0;
bad:
    Py_XDECREF(default_encoding);
    Py_XDECREF(ascii_chars_u);
    Py_XDECREF(ascii_chars_b);
    return -1;
}
#endif
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL)
#else
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL)
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
static char* __PYX_DEFAULT_STRING_ENCODING;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
    PyObject* sys;
    PyObject* default_encoding = NULL;
    char* default_encoding_c;
    sys = PyImport_ImportModule("sys");
    if (!sys) goto bad;
    default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL);
    Py_DECREF(sys);
    if (!default_encoding) goto bad;
    default_encoding_c = PyBytes_AsString(default_encoding);
    if (!default_encoding_c) goto bad;
    __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c));
    if (!__PYX_DEFAULT_STRING_ENCODING) goto bad;
    strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c);
    Py_DECREF(default_encoding);
    return 0;
bad:
    Py_XDECREF(default_encoding);
    return -1;
}
#endif
#endif


/* Test for GCC > 2.95 */
#if defined(__GNUC__)     && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))
  #define likely(x)   __builtin_expect(!!(x), 1)
  #define unlikely(x) __builtin_expect(!!(x), 0)
#else /* !__GNUC__ or GCC < 2.95 */
  #define likely(x)   (x)
  #define unlikely(x) (x)
#endif /* __GNUC__ */
static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; }

static PyObject *__pyx_m;
static PyObject *__pyx_d;
static PyObject *__pyx_b;
static PyObject *__pyx_cython_runtime;
static PyObject *__pyx_empty_tuple;
static PyObject *__pyx_empty_bytes;
static PyObject *__pyx_empty_unicode;
static int __pyx_lineno;
static int __pyx_clineno = 0;
static const char * __pyx_cfilenm= __FILE__;
static const char *__pyx_filename;


static const char *__pyx_f[] = {
  "discodop/kbest.pyx",
  "array.pxd",
  "discodop/containers.pxd",
  "stringsource",
  "type.pxd",
  "discodop/pcfg.pxd",
  "discodop/plcfrs.pxd",
};
/* None.proto */
#if defined(__GNUC__)
#define __Pyx_PACKED __attribute__((__packed__))
#else
#define __Pyx_PACKED
#endif


/* "containers.pxd":21
 * include "constants.pxi"
 * 
 * ctypedef uint16_t Idx  # PCFG chart indices; max 16 bits.             # <<<<<<<<<<<<<<
 * 
 * cdef extern from "_containers.h":
 */
typedef uint16_t __pyx_t_8discodop_10containers_Idx;

/*--- Type declarations ---*/
#ifndef _ARRAYARRAY_H
struct arrayobject;
typedef struct arrayobject arrayobject;
#endif
struct __pyx_obj_8discodop_10containers_StringList;
struct __pyx_obj_8discodop_10containers_StringIntDict;
struct __pyx_obj_8discodop_10containers_Grammar;
struct __pyx_obj_8discodop_10containers_Chart;
struct __pyx_obj_8discodop_10containers_Whitelist;
struct __pyx_obj_8discodop_10containers_Ctrees;
struct __pyx_obj_8discodop_10containers_Vocabulary;
struct __pyx_obj_8discodop_10containers_FixedVocabulary;
struct __pyx_obj_8discodop_4pcfg_CFGChart;
struct __pyx_obj_8discodop_4pcfg_DenseCFGChart;
struct __pyx_obj_8discodop_4pcfg_SparseCFGChart;
struct __pyx_obj_8discodop_6plcfrs_LCFRSChart;
struct __pyx_obj_8discodop_6plcfrs_SmallLCFRSChart;
struct __pyx_obj_8discodop_6plcfrs_FatLCFRSChart;
struct __pyx_t_8discodop_10containers_Node;
struct __pyx_t_8discodop_10containers_NodeArray;
union __pyx_t_8discodop_10containers_ItemType;
struct __pyx_t_8discodop_10containers_DArray;

/* "containers.pxd":638
 * # start fragments stuff
 * 
 * cdef packed struct Node:  # a node of a binary tree             # <<<<<<<<<<<<<<
 * 	int32_t prod # >= 0: production ID; -1: unseen production
 * 	int16_t left  # >= 0: array idx to child Node; <0: idx sent[-left - 1];
 */
#if defined(__SUNPRO_C)
  #pragma pack(1)
#elif !defined(__GNUC__)
  #pragma pack(push, 1)
#endif
struct __Pyx_PACKED __pyx_t_8discodop_10containers_Node {
  int32_t prod;
  int16_t left;
  int16_t right;
};
#if defined(__SUNPRO_C)
  #pragma pack()
#elif !defined(__GNUC__)
  #pragma pack(pop)
#endif

/* "containers.pxd":644
 * 
 * 
 * cdef packed struct NodeArray:  # a tree as an array of Node structs             # <<<<<<<<<<<<<<
 * 	uint32_t offset  # index to Node array where this tree starts
 * 	int16_t len, root  # number of nodes, index to root node
 */
#if defined(__SUNPRO_C)
  #pragma pack(1)
#elif !defined(__GNUC__)
  #pragma pack(push, 1)
#endif
struct __Pyx_PACKED __pyx_t_8discodop_10containers_NodeArray {
  uint32_t offset;
  int16_t len;
  int16_t root;
};
#if defined(__SUNPRO_C)
  #pragma pack()
#elif !defined(__GNUC__)
  #pragma pack(pop)
#endif

/* "containers.pxd":664
 * 
 * 
 * cdef union ItemType:             # <<<<<<<<<<<<<<
 * 	void *ptr
 * 	char *aschar
 */
union __pyx_t_8discodop_10containers_ItemType {
  void *ptr;
  char *aschar;
  uint32_t *asint;
};

/* "containers.pxd":670
 * 
 * 
 * cdef struct DArray:             # <<<<<<<<<<<<<<
 * 	uint8_t itemsize
 * 	uint32_t len
 */
struct __pyx_t_8discodop_10containers_DArray {
  uint8_t itemsize;
  uint32_t len;
  uint32_t capacity;
  union __pyx_t_8discodop_10containers_ItemType d;
};
struct __pyx_t_8discodop_4pcfg_MidFilter;
struct __pyx_t_8discodop_4pcfg_SparseCFGItem;
union __pyx_t_8discodop_4pcfg_CFGItem;

/* "pcfg.pxd":19
 * 
 * # Records the minimum and maximum mid points for (left/right index, label)
 * cdef struct MidFilter:             # <<<<<<<<<<<<<<
 * 	vector[short] minleft, maxleft, minright, maxright
 * 
 */
struct __pyx_t_8discodop_4pcfg_MidFilter {
  std::vector<short>  minleft;
  std::vector<short>  maxleft;
  std::vector<short>  minright;
  std::vector<short>  maxright;
};

/* "pcfg.pxd":37
 * # in both cases, an item can be constructed from a cell (an item with label 0)
 * # by adding the label to it.
 * cdef packed struct SparseCFGItem:             # <<<<<<<<<<<<<<
 * 		Label label
 * 		Idx start
 */
#if defined(__SUNPRO_C)
  #pragma pack(1)
#elif !defined(__GNUC__)
  #pragma pack(push, 1)
#endif
struct __Pyx_PACKED __pyx_t_8discodop_4pcfg_SparseCFGItem {
  Label label;
  __pyx_t_8discodop_10containers_Idx start;
  __pyx_t_8discodop_10containers_Idx end;
};
#if defined(__SUNPRO_C)
  #pragma pack()
#elif !defined(__GNUC__)
  #pragma pack(pop)
#endif

/* "pcfg.pxd":43
 * 
 * 
 * cdef union CFGItem:             # <<<<<<<<<<<<<<
 * 	uint64_t dt
 * 	SparseCFGItem st
 */
union __pyx_t_8discodop_4pcfg_CFGItem {
  uint64_t dt;
  struct __pyx_t_8discodop_4pcfg_SparseCFGItem st;
};

/* "discodop/kbest.pxd":11
 * from .plcfrs cimport LCFRSChart, SmallLCFRSChart, FatLCFRSChart
 * 
 * ctypedef sparse_hash_map[ItemNo, RankedEdgeAgenda[Prob]] agendas_type             # <<<<<<<<<<<<<<
 * 
 * cdef string getderiv(ItemNo v, RankedEdge ej, Chart chart)
 */
typedef spp::sparse_hash_map<ItemNo,RankedEdgeAgenda<Prob> >  __pyx_t_8discodop_5kbest_agendas_type;

/* "containers.pxd":509
 * 
 * @cython.final
 * cdef class StringList(object):             # <<<<<<<<<<<<<<
 * 	cdef vector[string] ob
 * 
 */
struct __pyx_obj_8discodop_10containers_StringList {
  PyObject_HEAD
  std::vector<std::string>  ob;
};


/* "containers.pxd":514
 * 
 * @cython.final
 * cdef class StringIntDict(object):             # <<<<<<<<<<<<<<
 * 	cdef sparse_hash_map[string, Label] ob
 * 
 */
struct __pyx_obj_8discodop_10containers_StringIntDict {
  PyObject_HEAD
  spp::sparse_hash_map<std::string,Label>  ob;
};


/* "containers.pxd":519
 * 
 * @cython.final
 * cdef class Grammar:             # <<<<<<<<<<<<<<
 * 	cdef ProbRule **bylhs
 * 	cdef ProbRule **unary
 */
struct __pyx_obj_8discodop_10containers_Grammar {
  PyObject_HEAD
  struct __pyx_vtabstruct_8discodop_10containers_Grammar *__pyx_vtab;
  ProbRule **bylhs;
  ProbRule **unary;
  ProbRule **lbinary;
  ProbRule **rbinary;
  std::vector<LexicalRule>  lexical;
  spp::sparse_hash_map<std::string,std::vector<uint32_t> >  lexicalbyword;
  spp::sparse_hash_map<Label,spp::sparse_hash_map<std::string,uint32_t> >  lexicalbylhs;
  Label *mapping;
  Label *selfmapping;
  Label **splitmapping;
  uint32_t *revrulemap;
  uint64_t *mask;
  std::vector<std::vector<Label> >  revmap;
  std::vector<uint8_t>  fanout;
  std::vector<ProbRule>  buf;
  RuleHashMap<uint32_t>  rulenos;
  size_t nonterminals;
  size_t phrasalnonterminals;
  size_t numrules;
  size_t numunary;
  size_t numbinary;
  size_t maxfanout;
  int logprob;
  int bitpar;
  PyObject *start;
  PyObject *rulesfile;
  PyObject *lexiconfile;
  PyObject *altweightsfile;
  PyObject *ruletuples;
  struct __pyx_obj_8discodop_10containers_StringList *tolabel;
  struct __pyx_obj_8discodop_10containers_StringIntDict *toid;
  PyObject *rulemapping;
  PyObject *selfrulemapping;
  PyObject *currentmodel;
  std::vector<Prob>  defaultmodel;
  PyObject *models;
};


/* "containers.pxd":560
 * # [ ] can we exploit bottom-up order of parser or previous CTF stages
 * # 		to pack the parse forest?
 * cdef class Chart:             # <<<<<<<<<<<<<<
 * 	cdef vector[Prob] probs
 * 	cdef vector[Prob] inside
 */
struct __pyx_obj_8discodop_10containers_Chart {
  PyObject_HEAD
  struct __pyx_vtabstruct_8discodop_10containers_Chart *__pyx_vtab;
  std::vector<Prob>  probs;
  std::vector<Prob>  inside;
  std::vector<Prob>  outside;
  std::vector<std::vector<Edge> >  parseforest;
  std::vector<std::vector<std::pair<RankedEdge,Prob> > >  rankededges;
  PyObject *derivations;
  struct __pyx_obj_8discodop_10containers_Grammar *grammar;
  PyObject *sent;
  short lensent;
  Label start;
  int logprob;
  int viterbi;
};


/* "containers.pxd":591
 * 
 * @cython.final
 * cdef class Whitelist:             # <<<<<<<<<<<<<<
 * 	cdef vector[sparse_hash_set[Label]] cfg  # span -> set of labels
 * 	# cdef vector[vector[Label]] cfg  # span -> sorted array of fine labels
 */
struct __pyx_obj_8discodop_10containers_Whitelist {
  PyObject_HEAD
  std::vector<spp::sparse_hash_set<Label> >  cfg;
  std::vector<SmallChartItemSet>  small;
  std::vector<FatChartItemSet>  fat;
  Label *mapping;
  Label **splitmapping;
};


/* "containers.pxd":650
 * 
 * @cython.final
 * cdef class Ctrees:             # <<<<<<<<<<<<<<
 * 	cdef Node *nodes
 * 	cdef NodeArray *trees
 */
struct __pyx_obj_8discodop_10containers_Ctrees {
  PyObject_HEAD
  struct __pyx_vtabstruct_8discodop_10containers_Ctrees *__pyx_vtab;
  struct __pyx_t_8discodop_10containers_Node *nodes;
  struct __pyx_t_8discodop_10containers_NodeArray *trees;
  long nodesleft;
  long max;
  size_t numnodes;
  size_t numwords;
  short maxnodes;
  int len;
  PyObject *prodindex;
  PyObject *_state;
};


/* "containers.pxd":677
 * 
 * 
 * cdef class Vocabulary:             # <<<<<<<<<<<<<<
 * 	cdef readonly dict prods  # production str. => int
 * 	cdef readonly dict labels  # label/word str => int
 */
struct __pyx_obj_8discodop_10containers_Vocabulary {
  PyObject_HEAD
  struct __pyx_vtabstruct_8discodop_10containers_Vocabulary *__pyx_vtab;
  PyObject *prods;
  PyObject *labels;
  struct __pyx_t_8discodop_10containers_DArray prodbuf;
  struct __pyx_t_8discodop_10containers_DArray labelbuf;
  struct __pyx_t_8discodop_10containers_DArray labelidx;
};


/* "containers.pxd":692
 * 
 * 
 * cdef class FixedVocabulary(Vocabulary):             # <<<<<<<<<<<<<<
 * 	cdef object state  # to keep buffer alive
 * 
 */
struct __pyx_obj_8discodop_10containers_FixedVocabulary {
  struct __pyx_obj_8discodop_10containers_Vocabulary __pyx_base;
  PyObject *state;
};


/* "pcfg.pxd":48
 * 
 * 
 * cdef class CFGChart(Chart):             # <<<<<<<<<<<<<<
 * 	cdef vector[uint64_t] items
 * 	cdef vector[Prob] beambuckets
 */
struct __pyx_obj_8discodop_4pcfg_CFGChart {
  struct __pyx_obj_8discodop_10containers_Chart __pyx_base;
  std::vector<uint64_t>  items;
  std::vector<Prob>  beambuckets;
};


/* "pcfg.pxd":55
 * 
 * @cython.final
 * cdef class DenseCFGChart(CFGChart):             # <<<<<<<<<<<<<<
 * 	cdef void addedge(self, uint64_t item, Idx mid, ProbRule *rule)
 * 	cdef bint updateprob(self, uint64_t item, Prob prob, Prob beam)
 */
struct __pyx_obj_8discodop_4pcfg_DenseCFGChart {
  struct __pyx_obj_8discodop_4pcfg_CFGChart __pyx_base;
};


/* "pcfg.pxd":64
 * 
 * @cython.final
 * cdef class SparseCFGChart(CFGChart):             # <<<<<<<<<<<<<<
 * 	cdef sparse_hash_map[uint64_t, ItemNo] itemindex
 * 	cdef void addedge(self, uint64_t item, Idx mid, ProbRule *rule)
 */
struct __pyx_obj_8discodop_4pcfg_SparseCFGChart {
  struct __pyx_obj_8discodop_4pcfg_CFGChart __pyx_base;
  spp::sparse_hash_map<uint64_t,ItemNo>  itemindex;
};


/* "plcfrs.pxd":30
 * 	FatChartItem
 * 
 * cdef class LCFRSChart(Chart):             # <<<<<<<<<<<<<<
 * 	cdef void addlexedge(self, ItemNo itemidx, short wordidx)
 * 	cdef void updateprob(self, ItemNo itemidx, Prob prob)
 */
struct __pyx_obj_8discodop_6plcfrs_LCFRSChart {
  struct __pyx_obj_8discodop_10containers_Chart __pyx_base;
};


/* "plcfrs.pxd":38
 * 
 * @cython.final
 * cdef class SmallLCFRSChart(LCFRSChart):             # <<<<<<<<<<<<<<
 * 	cdef vector[SmallChartItem] items
 * 	cdef SmallChartItemBtreeMap[ItemNo] itemindex
 */
struct __pyx_obj_8discodop_6plcfrs_SmallLCFRSChart {
  struct __pyx_obj_8discodop_6plcfrs_LCFRSChart __pyx_base;
  std::vector<SmallChartItem>  items;
  SmallChartItemBtreeMap<ItemNo>  itemindex;
  SmallChartItemBtreeMap<Prob>  beambuckets;
};


/* "plcfrs.pxd":49
 * 
 * @cython.final
 * cdef class FatLCFRSChart(LCFRSChart):             # <<<<<<<<<<<<<<
 * 	cdef vector[FatChartItem] items
 * 	cdef FatChartItemBtreeMap[ItemNo] itemindex
 */
struct __pyx_obj_8discodop_6plcfrs_FatLCFRSChart {
  struct __pyx_obj_8discodop_6plcfrs_LCFRSChart __pyx_base;
  std::vector<FatChartItem>  items;
  FatChartItemBtreeMap<ItemNo>  itemindex;
  FatChartItemBtreeMap<Prob>  beambuckets;
};



/* "containers.pxd":519
 * 
 * @cython.final
 * cdef class Grammar:             # <<<<<<<<<<<<<<
 * 	cdef ProbRule **bylhs
 * 	cdef ProbRule **unary
 */

struct __pyx_vtabstruct_8discodop_10containers_Grammar {
  PyObject *(*_indexrules)(struct __pyx_obj_8discodop_10containers_Grammar *, ProbRule **, int, int);
  PyObject *(*rulestr)(struct __pyx_obj_8discodop_10containers_Grammar *, int, int __pyx_skip_dispatch);
  PyObject *(*noderuleno)(struct __pyx_obj_8discodop_10containers_Grammar *, PyObject *, int __pyx_skip_dispatch);
  PyObject *(*getruleno)(struct __pyx_obj_8discodop_10containers_Grammar *, PyObject *, PyObject *, int __pyx_skip_dispatch);
  PyObject *(*yfstr)(struct __pyx_obj_8discodop_10containers_Grammar *, ProbRule);
};
static struct __pyx_vtabstruct_8discodop_10containers_Grammar *__pyx_vtabptr_8discodop_10containers_Grammar;


/* "containers.pxd":560
 * # [ ] can we exploit bottom-up order of parser or previous CTF stages
 * # 		to pack the parse forest?
 * cdef class Chart:             # <<<<<<<<<<<<<<
 * 	cdef vector[Prob] probs
 * 	cdef vector[Prob] inside
 */

struct __pyx_vtabstruct_8discodop_10containers_Chart {
  int (*lexidx)(struct __pyx_obj_8discodop_10containers_Chart *, Edge);
  Prob (*subtreeprob)(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo);
  Prob (*lexprob)(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo, Edge);
  PyObject *(*edgestr)(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo, Edge);
  ItemNo (*_left)(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo, Edge);
  ItemNo (*_right)(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo, Edge);
  ItemNo (*left)(struct __pyx_obj_8discodop_10containers_Chart *, RankedEdge);
  ItemNo (*right)(struct __pyx_obj_8discodop_10containers_Chart *, RankedEdge);
  Label (*label)(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo);
  ItemNo (*getitemidx)(struct __pyx_obj_8discodop_10containers_Chart *, uint64_t);
  SmallChartItem (*asSmallChartItem)(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo);
  FatChartItem (*asFatChartItem)(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo);
  size_t (*asCFGspan)(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo);
};
static struct __pyx_vtabstruct_8discodop_10containers_Chart *__pyx_vtabptr_8discodop_10containers_Chart;


/* "containers.pxd":650
 * 
 * @cython.final
 * cdef class Ctrees:             # <<<<<<<<<<<<<<
 * 	cdef Node *nodes
 * 	cdef NodeArray *trees
 */

struct __pyx_vtabstruct_8discodop_10containers_Ctrees {
  PyObject *(*alloc)(struct __pyx_obj_8discodop_10containers_Ctrees *, int, long, int __pyx_skip_dispatch);
  PyObject *(*realloc)(struct __pyx_obj_8discodop_10containers_Ctrees *, int, int);
  PyObject *(*addnodes)(struct __pyx_obj_8discodop_10containers_Ctrees *, struct __pyx_t_8discodop_10containers_Node *, int, int);
};
static struct __pyx_vtabstruct_8discodop_10containers_Ctrees *__pyx_vtabptr_8discodop_10containers_Ctrees;


/* "containers.pxd":677
 * 
 * 
 * cdef class Vocabulary:             # <<<<<<<<<<<<<<
 * 	cdef readonly dict prods  # production str. => int
 * 	cdef readonly dict labels  # label/word str => int
 */

struct __pyx_vtabstruct_8discodop_10containers_Vocabulary {
  PyObject *(*idtolabel)(struct __pyx_obj_8discodop_10containers_Vocabulary *, uint32_t);
  PyObject *(*getlabel)(struct __pyx_obj_8discodop_10containers_Vocabulary *, int);
  PyObject *(*getword)(struct __pyx_obj_8discodop_10containers_Vocabulary *, int);
  int (*islexical)(struct __pyx_obj_8discodop_10containers_Vocabulary *, int);
  int (*getprod)(struct __pyx_obj_8discodop_10containers_Vocabulary *, PyObject *, PyObject *);
  int (*_getprodid)(struct __pyx_obj_8discodop_10containers_Vocabulary *, PyObject *);
  int (*_getlabelid)(struct __pyx_obj_8discodop_10containers_Vocabulary *, PyObject *);
};
static struct __pyx_vtabstruct_8discodop_10containers_Vocabulary *__pyx_vtabptr_8discodop_10containers_Vocabulary;


/* "containers.pxd":692
 * 
 * 
 * cdef class FixedVocabulary(Vocabulary):             # <<<<<<<<<<<<<<
 * 	cdef object state  # to keep buffer alive
 * 
 */

struct __pyx_vtabstruct_8discodop_10containers_FixedVocabulary {
  struct __pyx_vtabstruct_8discodop_10containers_Vocabulary __pyx_base;
};
static struct __pyx_vtabstruct_8discodop_10containers_FixedVocabulary *__pyx_vtabptr_8discodop_10containers_FixedVocabulary;


/* "pcfg.pxd":48
 * 
 * 
 * cdef class CFGChart(Chart):             # <<<<<<<<<<<<<<
 * 	cdef vector[uint64_t] items
 * 	cdef vector[Prob] beambuckets
 */

struct __pyx_vtabstruct_8discodop_4pcfg_CFGChart {
  struct __pyx_vtabstruct_8discodop_10containers_Chart __pyx_base;
};
static struct __pyx_vtabstruct_8discodop_4pcfg_CFGChart *__pyx_vtabptr_8discodop_4pcfg_CFGChart;


/* "pcfg.pxd":55
 * 
 * @cython.final
 * cdef class DenseCFGChart(CFGChart):             # <<<<<<<<<<<<<<
 * 	cdef void addedge(self, uint64_t item, Idx mid, ProbRule *rule)
 * 	cdef bint updateprob(self, uint64_t item, Prob prob, Prob beam)
 */

struct __pyx_vtabstruct_8discodop_4pcfg_DenseCFGChart {
  struct __pyx_vtabstruct_8discodop_4pcfg_CFGChart __pyx_base;
  void (*addedge)(struct __pyx_obj_8discodop_4pcfg_DenseCFGChart *, uint64_t, __pyx_t_8discodop_10containers_Idx, ProbRule *);
  int (*updateprob)(struct __pyx_obj_8discodop_4pcfg_DenseCFGChart *, uint64_t, Prob, Prob);
  Label (*_label)(struct __pyx_obj_8discodop_4pcfg_DenseCFGChart *, uint64_t);
  Prob (*_subtreeprob)(struct __pyx_obj_8discodop_4pcfg_DenseCFGChart *, uint64_t);
  int (*_hasitem)(struct __pyx_obj_8discodop_4pcfg_DenseCFGChart *, uint64_t);
};
static struct __pyx_vtabstruct_8discodop_4pcfg_DenseCFGChart *__pyx_vtabptr_8discodop_4pcfg_DenseCFGChart;


/* "pcfg.pxd":64
 * 
 * @cython.final
 * cdef class SparseCFGChart(CFGChart):             # <<<<<<<<<<<<<<
 * 	cdef sparse_hash_map[uint64_t, ItemNo] itemindex
 * 	cdef void addedge(self, uint64_t item, Idx mid, ProbRule *rule)
 */

struct __pyx_vtabstruct_8discodop_4pcfg_SparseCFGChart {
  struct __pyx_vtabstruct_8discodop_4pcfg_CFGChart __pyx_base;
  void (*addedge)(struct __pyx_obj_8discodop_4pcfg_SparseCFGChart *, uint64_t, __pyx_t_8discodop_10containers_Idx, ProbRule *);
  int (*updateprob)(struct __pyx_obj_8discodop_4pcfg_SparseCFGChart *, uint64_t, Prob, Prob);
  Label (*_label)(struct __pyx_obj_8discodop_4pcfg_SparseCFGChart *, uint64_t);
  Prob (*_subtreeprob)(struct __pyx_obj_8discodop_4pcfg_SparseCFGChart *, uint64_t);
  int (*_hasitem)(struct __pyx_obj_8discodop_4pcfg_SparseCFGChart *, uint64_t);
};
static struct __pyx_vtabstruct_8discodop_4pcfg_SparseCFGChart *__pyx_vtabptr_8discodop_4pcfg_SparseCFGChart;


/* "plcfrs.pxd":30
 * 	FatChartItem
 * 
 * cdef class LCFRSChart(Chart):             # <<<<<<<<<<<<<<
 * 	cdef void addlexedge(self, ItemNo itemidx, short wordidx)
 * 	cdef void updateprob(self, ItemNo itemidx, Prob prob)
 */

struct __pyx_vtabstruct_8discodop_6plcfrs_LCFRSChart {
  struct __pyx_vtabstruct_8discodop_10containers_Chart __pyx_base;
  void (*addlexedge)(struct __pyx_obj_8discodop_6plcfrs_LCFRSChart *, ItemNo, short);
  void (*updateprob)(struct __pyx_obj_8discodop_6plcfrs_LCFRSChart *, ItemNo, Prob);
  void (*addprob)(struct __pyx_obj_8discodop_6plcfrs_LCFRSChart *, ItemNo, Prob);
  Prob (*_subtreeprob)(struct __pyx_obj_8discodop_6plcfrs_LCFRSChart *, ItemNo);
};
static struct __pyx_vtabstruct_8discodop_6plcfrs_LCFRSChart *__pyx_vtabptr_8discodop_6plcfrs_LCFRSChart;


/* "plcfrs.pxd":38
 * 
 * @cython.final
 * cdef class SmallLCFRSChart(LCFRSChart):             # <<<<<<<<<<<<<<
 * 	cdef vector[SmallChartItem] items
 * 	cdef SmallChartItemBtreeMap[ItemNo] itemindex
 */

struct __pyx_vtabstruct_8discodop_6plcfrs_SmallLCFRSChart {
  struct __pyx_vtabstruct_8discodop_6plcfrs_LCFRSChart __pyx_base;
  SmallChartItem (*_root)(struct __pyx_obj_8discodop_6plcfrs_SmallLCFRSChart *);
  Label (*_label)(struct __pyx_obj_8discodop_6plcfrs_SmallLCFRSChart *, ItemNo);
  void (*addedge)(struct __pyx_obj_8discodop_6plcfrs_SmallLCFRSChart *, ItemNo, ItemNo, SmallChartItem &, ProbRule *);
};
static struct __pyx_vtabstruct_8discodop_6plcfrs_SmallLCFRSChart *__pyx_vtabptr_8discodop_6plcfrs_SmallLCFRSChart;


/* "plcfrs.pxd":49
 * 
 * @cython.final
 * cdef class FatLCFRSChart(LCFRSChart):             # <<<<<<<<<<<<<<
 * 	cdef vector[FatChartItem] items
 * 	cdef FatChartItemBtreeMap[ItemNo] itemindex
 */

struct __pyx_vtabstruct_8discodop_6plcfrs_FatLCFRSChart {
  struct __pyx_vtabstruct_8discodop_6plcfrs_LCFRSChart __pyx_base;
  FatChartItem (*_root)(struct __pyx_obj_8discodop_6plcfrs_FatLCFRSChart *);
  Label (*_label)(struct __pyx_obj_8discodop_6plcfrs_FatLCFRSChart *, ItemNo);
  void (*addedge)(struct __pyx_obj_8discodop_6plcfrs_FatLCFRSChart *, ItemNo, ItemNo, FatChartItem &, ProbRule *);
};
static struct __pyx_vtabstruct_8discodop_6plcfrs_FatLCFRSChart *__pyx_vtabptr_8discodop_6plcfrs_FatLCFRSChart;

/* --- Runtime support code (head) --- */
/* Refnanny.proto */
#ifndef CYTHON_REFNANNY
  #define CYTHON_REFNANNY 0
#endif
#if CYTHON_REFNANNY
  typedef struct {
    void (*INCREF)(void*, PyObject*, int);
    void (*DECREF)(void*, PyObject*, int);
    void (*GOTREF)(void*, PyObject*, int);
    void (*GIVEREF)(void*, PyObject*, int);
    void* (*SetupContext)(const char*, int, const char*);
    void (*FinishContext)(void**);
  } __Pyx_RefNannyAPIStruct;
  static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL;
  static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname);
  #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL;
#ifdef WITH_THREAD
  #define __Pyx_RefNannySetupContext(name, acquire_gil)\
          if (acquire_gil) {\
              PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\
              __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
              PyGILState_Release(__pyx_gilstate_save);\
          } else {\
              __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
          }
#else
  #define __Pyx_RefNannySetupContext(name, acquire_gil)\
          __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
#endif
  #define __Pyx_RefNannyFinishContext()\
          __Pyx_RefNanny->FinishContext(&__pyx_refnanny)
  #define __Pyx_INCREF(r)  __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
  #define __Pyx_DECREF(r)  __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
  #define __Pyx_GOTREF(r)  __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
  #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
  #define __Pyx_XINCREF(r)  do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0)
  #define __Pyx_XDECREF(r)  do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0)
  #define __Pyx_XGOTREF(r)  do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0)
  #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0)
#else
  #define __Pyx_RefNannyDeclarations
  #define __Pyx_RefNannySetupContext(name, acquire_gil)
  #define __Pyx_RefNannyFinishContext()
  #define __Pyx_INCREF(r) Py_INCREF(r)
  #define __Pyx_DECREF(r) Py_DECREF(r)
  #define __Pyx_GOTREF(r)
  #define __Pyx_GIVEREF(r)
  #define __Pyx_XINCREF(r) Py_XINCREF(r)
  #define __Pyx_XDECREF(r) Py_XDECREF(r)
  #define __Pyx_XGOTREF(r)
  #define __Pyx_XGIVEREF(r)
#endif
#define __Pyx_XDECREF_SET(r, v) do {\
        PyObject *tmp = (PyObject *) r;\
        r = v; __Pyx_XDECREF(tmp);\
    } while (0)
#define __Pyx_DECREF_SET(r, v) do {\
        PyObject *tmp = (PyObject *) r;\
        r = v; __Pyx_DECREF(tmp);\
    } while (0)
#define __Pyx_CLEAR(r)    do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0)
#define __Pyx_XCLEAR(r)   do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0)

/* PyObjectGetAttrStr.proto */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) {
    PyTypeObject* tp = Py_TYPE(obj);
    if (likely(tp->tp_getattro))
        return tp->tp_getattro(obj, attr_name);
#if PY_MAJOR_VERSION < 3
    if (likely(tp->tp_getattr))
        return tp->tp_getattr(obj, PyString_AS_STRING(attr_name));
#endif
    return PyObject_GetAttr(obj, attr_name);
}
#else
#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n)
#endif

/* GetBuiltinName.proto */
static PyObject *__Pyx_GetBuiltinName(PyObject *name);

/* PyThreadStateGet.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyThreadState_declare  PyThreadState *__pyx_tstate;
#define __Pyx_PyThreadState_assign  __pyx_tstate = PyThreadState_GET();
#else
#define __Pyx_PyThreadState_declare
#define __Pyx_PyThreadState_assign
#endif

/* PyErrFetchRestore.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_ErrRestoreWithState(type, value, tb)  __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb)
#define __Pyx_ErrFetchWithState(type, value, tb)    __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb)
#define __Pyx_ErrRestore(type, value, tb)  __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb)
#define __Pyx_ErrFetch(type, value, tb)    __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb)
static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb);
static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
#else
#define __Pyx_ErrRestoreWithState(type, value, tb)  PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetchWithState(type, value, tb)  PyErr_Fetch(type, value, tb)
#define __Pyx_ErrRestore(type, value, tb)  PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetch(type, value, tb)  PyErr_Fetch(type, value, tb)
#endif

/* WriteUnraisableException.proto */
static void __Pyx_WriteUnraisable(const char *name, int clineno,
                                  int lineno, const char *filename,
                                  int full_traceback, int nogil);

/* PyCFunctionFastCall.proto */
#if CYTHON_FAST_PYCCALL
static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs);
#else
#define __Pyx_PyCFunction_FastCall(func, args, nargs)  (assert(0), NULL)
#endif

/* PyFunctionFastCall.proto */
#if CYTHON_FAST_PYCALL
#define __Pyx_PyFunction_FastCall(func, args, nargs)\
    __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL)
#if 1 || PY_VERSION_HEX < 0x030600B1
static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs);
#else
#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs)
#endif
#endif

/* PyObjectCall.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw);
#else
#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw)
#endif

/* PyObjectCallMethO.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg);
#endif

/* PyObjectCallOneArg.proto */
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg);

/* RaiseException.proto */
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause);

/* RaiseArgTupleInvalid.proto */
static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
    Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found);

/* RaiseDoubleKeywords.proto */
static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name);

/* ParseKeywords.proto */
static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\
    PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\
    const char* function_name);

/* ArgTypeTest.proto */
static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
    const char *name, int exact);

/* PyObjectCallNoArg.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func);
#else
#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL)
#endif

/* ListCompAppend.proto */
#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) {
    PyListObject* L = (PyListObject*) list;
    Py_ssize_t len = Py_SIZE(list);
    if (likely(L->allocated > len)) {
        Py_INCREF(x);
        PyList_SET_ITEM(list, len, x);
        Py_SIZE(list) = len+1;
        return 0;
    }
    return PyList_Append(list, x);
}
#else
#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x)
#endif

/* IncludeCppStringH.proto */
#include <string>

/* decode_c_string_utf16.proto */
static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) {
    int byteorder = 0;
    return PyUnicode_DecodeUTF16(s, size, errors, &byteorder);
}
static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) {
    int byteorder = -1;
    return PyUnicode_DecodeUTF16(s, size, errors, &byteorder);
}
static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) {
    int byteorder = 1;
    return PyUnicode_DecodeUTF16(s, size, errors, &byteorder);
}

/* decode_c_bytes.proto */
static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes(
         const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop,
         const char* encoding, const char* errors,
         PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors));

/* decode_cpp_string.proto */
static CYTHON_INLINE PyObject* __Pyx_decode_cpp_string(
         std::string cppstring, Py_ssize_t start, Py_ssize_t stop,
         const char* encoding, const char* errors,
         PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) {
    return __Pyx_decode_c_bytes(
        cppstring.data(), cppstring.size(), start, stop, encoding, errors, decode_func);
}

/* GetModuleGlobalName.proto */
static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name);

/* PyIntBinop.proto */
#if !CYTHON_COMPILING_IN_PYPY
static PyObject* __Pyx_PyInt_SubtractObjC(PyObject *op1, PyObject *op2, long intval, int inplace);
#else
#define __Pyx_PyInt_SubtractObjC(op1, op2, intval, inplace)\
    (inplace ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2))
#endif

/* ListAppend.proto */
#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) {
    PyListObject* L = (PyListObject*) list;
    Py_ssize_t len = Py_SIZE(list);
    if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) {
        Py_INCREF(x);
        PyList_SET_ITEM(list, len, x);
        Py_SIZE(list) = len+1;
        return 0;
    }
    return PyList_Append(list, x);
}
#else
#define __Pyx_PyList_Append(L,x) PyList_Append(L,x)
#endif

/* GetVTable.proto */
static void* __Pyx_GetVtable(PyObject *dict);

/* Import.proto */
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level);

/* ImportFrom.proto */
static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name);

/* CLineInTraceback.proto */
static int __Pyx_CLineForTraceback(int c_line);

/* CodeObjectCache.proto */
typedef struct {
    PyCodeObject* code_object;
    int code_line;
} __Pyx_CodeObjectCacheEntry;
struct __Pyx_CodeObjectCache {
    int count;
    int max_count;
    __Pyx_CodeObjectCacheEntry* entries;
};
static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL};
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line);
static PyCodeObject *__pyx_find_code_object(int code_line);
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object);

/* AddTraceback.proto */
static void __Pyx_AddTraceback(const char *funcname, int c_line,
                               int py_line, const char *filename);

/* CppExceptionConversion.proto */
#ifndef __Pyx_CppExn2PyErr
#include <new>
#include <typeinfo>
#include <stdexcept>
#include <ios>
static void __Pyx_CppExn2PyErr() {
  try {
    if (PyErr_Occurred())
      ; // let the latest Python exn pass through and ignore the current one
    else
      throw;
  } catch (const std::bad_alloc& exn) {
    PyErr_SetString(PyExc_MemoryError, exn.what());
  } catch (const std::bad_cast& exn) {
    PyErr_SetString(PyExc_TypeError, exn.what());
  } catch (const std::bad_typeid& exn) {
    PyErr_SetString(PyExc_TypeError, exn.what());
  } catch (const std::domain_error& exn) {
    PyErr_SetString(PyExc_ValueError, exn.what());
  } catch (const std::invalid_argument& exn) {
    PyErr_SetString(PyExc_ValueError, exn.what());
  } catch (const std::ios_base::failure& exn) {
    PyErr_SetString(PyExc_IOError, exn.what());
  } catch (const std::out_of_range& exn) {
    PyErr_SetString(PyExc_IndexError, exn.what());
  } catch (const std::overflow_error& exn) {
    PyErr_SetString(PyExc_OverflowError, exn.what());
  } catch (const std::range_error& exn) {
    PyErr_SetString(PyExc_ArithmeticError, exn.what());
  } catch (const std::underflow_error& exn) {
    PyErr_SetString(PyExc_ArithmeticError, exn.what());
  } catch (const std::exception& exn) {
    PyErr_SetString(PyExc_RuntimeError, exn.what());
  }
  catch (...)
  {
    PyErr_SetString(PyExc_RuntimeError, "Unknown exception");
  }
}
#endif

/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint32_t(uint32_t value);

/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value);

/* None.proto */
#include <new>

/* ArrayAPI.proto */
#ifndef _ARRAYARRAY_H
#define _ARRAYARRAY_H
typedef struct arraydescr {
    int typecode;
    int itemsize;
    PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
    int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
#if PY_MAJOR_VERSION >= 3
    char *formats;
#endif
} arraydescr;
struct arrayobject {
    PyObject_HEAD
    Py_ssize_t ob_size;
    union {
        char *ob_item;
        float *as_floats;
        double *as_doubles;
        int *as_ints;
        unsigned int *as_uints;
        unsigned char *as_uchars;
        signed char *as_schars;
        char *as_chars;
        unsigned long *as_ulongs;
        long *as_longs;
#if PY_MAJOR_VERSION >= 3
        unsigned long long *as_ulonglongs;
        long long *as_longlongs;
#endif
        short *as_shorts;
        unsigned short *as_ushorts;
        Py_UNICODE *as_pyunicodes;
        void *as_voidptr;
    } data;
    Py_ssize_t allocated;
    struct arraydescr *ob_descr;
    PyObject *weakreflist;
#if PY_MAJOR_VERSION >= 3
        int ob_exports;
#endif
};
#ifndef NO_NEWARRAY_INLINE
static CYTHON_INLINE PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size,
    struct arraydescr *descr) {
    arrayobject *op;
    size_t nbytes;
    if (size < 0) {
        PyErr_BadInternalCall();
        return NULL;
    }
    nbytes = size * descr->itemsize;
    if (nbytes / descr->itemsize != (size_t)size) {
        return PyErr_NoMemory();
    }
    op = (arrayobject *) type->tp_alloc(type, 0);
    if (op == NULL) {
        return NULL;
    }
    op->ob_descr = descr;
    op->allocated = size;
    op->weakreflist = NULL;
    op->ob_size = size;
    if (size <= 0) {
        op->data.ob_item = NULL;
    }
    else {
        op->data.ob_item = PyMem_NEW(char, nbytes);
        if (op->data.ob_item == NULL) {
            Py_DECREF(op);
            return PyErr_NoMemory();
        }
    }
    return (PyObject *) op;
}
#else
PyObject* newarrayobject(PyTypeObject *type, Py_ssize_t size,
    struct arraydescr *descr);
#endif
static CYTHON_INLINE int resize(arrayobject *self, Py_ssize_t n) {
    void *items = (void*) self->data.ob_item;
    PyMem_Resize(items, char, (size_t)(n * self->ob_descr->itemsize));
    if (items == NULL) {
        PyErr_NoMemory();
        return -1;
    }
    self->data.ob_item = (char*) items;
    self->ob_size = n;
    self->allocated = n;
    return 0;
}
static CYTHON_INLINE int resize_smart(arrayobject *self, Py_ssize_t n) {
    void *items = (void*) self->data.ob_item;
    Py_ssize_t newsize;
    if (n < self->allocated && n*4 > self->allocated) {
        self->ob_size = n;
        return 0;
    }
    newsize = n + (n / 2) + 1;
    if (newsize <= n) {
        PyErr_NoMemory();
        return -1;
    }
    PyMem_Resize(items, char, (size_t)(newsize * self->ob_descr->itemsize));
    if (items == NULL) {
        PyErr_NoMemory();
        return -1;
    }
    self->data.ob_item = (char*) items;
    self->ob_size = n;
    self->allocated = newsize;
    return 0;
}
#endif

/* CIntFromPy.proto */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *);

/* CIntFromPy.proto */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *);

/* CIntFromPy.proto */
static CYTHON_INLINE uint32_t __Pyx_PyInt_As_uint32_t(PyObject *);

/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value);

/* CheckBinaryVersion.proto */
static int __Pyx_check_binary_version(void);

/* FunctionExport.proto */
static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig);

/* PyIdentifierFromString.proto */
#if !defined(__Pyx_PyIdentifier_FromString)
#if PY_MAJOR_VERSION < 3
  #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s)
#else
  #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s)
#endif
#endif

/* ModuleImport.proto */
static PyObject *__Pyx_ImportModule(const char *name);

/* TypeImport.proto */
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict);

/* VoidPtrImport.proto */
static int __Pyx_ImportVoidPtr(PyObject *module, const char *name, void **p, const char *sig);

/* FunctionImport.proto */
static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig);

/* InitStrings.proto */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t);


/* Module declarations from 'libcpp.utility' */

/* Module declarations from 'libcpp.vector' */

/* Module declarations from 'libc.string' */

/* Module declarations from 'libcpp.string' */

/* Module declarations from 'libc.stdlib' */

/* Module declarations from 'libc.math' */

/* Module declarations from 'libc.stdint' */

/* Module declarations from 'libc.stdio' */

/* Module declarations from '__builtin__' */

/* Module declarations from 'cpython.type' */
static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0;

/* Module declarations from 'cpython' */

/* Module declarations from 'cpython.object' */

/* Module declarations from 'cpython.ref' */

/* Module declarations from 'cpython.exc' */

/* Module declarations from 'cpython.mem' */

/* Module declarations from 'array' */

/* Module declarations from 'cpython.array' */
static PyTypeObject *__pyx_ptype_7cpython_5array_array = 0;
static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_clone(arrayobject *, Py_ssize_t, int); /*proto*/
static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *, char *, Py_ssize_t); /*proto*/

/* Module declarations from 'cpython.buffer' */

/* Module declarations from 'cython' */

/* Module declarations from 'discodop.bit' */
static int (*__pyx_f_8discodop_3bit_bitcount)(uint64_t, int __pyx_skip_dispatch); /*proto*/
static CYTHON_INLINE int __pyx_f_8discodop_3bit_nextset(uint64_t, uint32_t); /*proto*/
static CYTHON_INLINE int __pyx_f_8discodop_3bit_nextunset(uint64_t, uint32_t); /*proto*/
static CYTHON_INLINE int __pyx_f_8discodop_3bit_bitlength(uint64_t); /*proto*/
static CYTHON_INLINE int __pyx_f_8discodop_3bit_abitcount(uint64_t *, int); /*proto*/
static CYTHON_INLINE int __pyx_f_8discodop_3bit_abitlength(uint64_t *, int); /*proto*/
static CYTHON_INLINE int __pyx_f_8discodop_3bit_anextset(uint64_t *, uint32_t, int); /*proto*/
static CYTHON_INLINE int __pyx_f_8discodop_3bit_anextunset(uint64_t *, uint32_t, int); /*proto*/
static CYTHON_INLINE void __pyx_f_8discodop_3bit_setunion(uint64_t *, uint64_t *, uint64_t *, int); /*proto*/

/* Module declarations from 'discodop.containers' */
static PyTypeObject *__pyx_ptype_8discodop_10containers_StringList = 0;
static PyTypeObject *__pyx_ptype_8discodop_10containers_StringIntDict = 0;
static PyTypeObject *__pyx_ptype_8discodop_10containers_Grammar = 0;
static PyTypeObject *__pyx_ptype_8discodop_10containers_Chart = 0;
static PyTypeObject *__pyx_ptype_8discodop_10containers_Whitelist = 0;
static PyTypeObject *__pyx_ptype_8discodop_10containers_Ctrees = 0;
static PyTypeObject *__pyx_ptype_8discodop_10containers_Vocabulary = 0;
static PyTypeObject *__pyx_ptype_8discodop_10containers_FixedVocabulary = 0;
static PyObject **__pyx_vp_8discodop_10containers_log1e200 = 0;
#define __pyx_v_8discodop_10containers_log1e200 (*__pyx_vp_8discodop_10containers_log1e200)
static SmallChartItem (*__pyx_f_8discodop_10containers_CFGtoSmallChartItem)(Label, __pyx_t_8discodop_10containers_Idx, __pyx_t_8discodop_10containers_Idx); /*proto*/
static FatChartItem (*__pyx_f_8discodop_10containers_CFGtoFatChartItem)(Label, __pyx_t_8discodop_10containers_Idx, __pyx_t_8discodop_10containers_Idx); /*proto*/
static CYTHON_INLINE size_t __pyx_f_8discodop_10containers_cellidx(short, short, short, Label); /*proto*/
static CYTHON_INLINE size_t __pyx_f_8discodop_10containers_compactcellidx(short, short, short, Label); /*proto*/

/* Module declarations from 'cpython.dict' */

/* Module declarations from 'cpython.float' */

/* Module declarations from 'discodop.pcfg' */
static PyTypeObject *__pyx_ptype_8discodop_4pcfg_CFGChart = 0;
static PyTypeObject *__pyx_ptype_8discodop_4pcfg_DenseCFGChart = 0;
static PyTypeObject *__pyx_ptype_8discodop_4pcfg_SparseCFGChart = 0;

/* Module declarations from 'cpython.set' */

/* Module declarations from 'discodop.plcfrs' */
static PyTypeObject *__pyx_ptype_8discodop_6plcfrs_LCFRSChart = 0;
static PyTypeObject *__pyx_ptype_8discodop_6plcfrs_SmallLCFRSChart = 0;
static PyTypeObject *__pyx_ptype_8discodop_6plcfrs_FatLCFRSChart = 0;

/* Module declarations from 'discodop.kbest' */
static std::string __pyx_f_8discodop_5kbest_getderiv(ItemNo, RankedEdge, struct __pyx_obj_8discodop_10containers_Chart *); /*proto*/
static RankedEdgeAgenda<Prob>  __pyx_f_8discodop_5kbest_getcandidates(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo, int); /*proto*/
static PyObject *__pyx_f_8discodop_5kbest_lazykthbest(ItemNo, int, int, __pyx_t_8discodop_5kbest_agendas_type &, struct __pyx_obj_8discodop_10containers_Chart *, RankedEdgeSet &, int); /*proto*/
static CYTHON_INLINE Prob __pyx_f_8discodop_5kbest_getprob(struct __pyx_obj_8discodop_10containers_Chart *, ItemNo, RankedEdge &); /*proto*/
static int __pyx_f_8discodop_5kbest_explorederivation(ItemNo, RankedEdge &, struct __pyx_obj_8discodop_10containers_Chart *, RankedEdgeSet &, int); /*proto*/
static CYTHON_INLINE PyObject *__pyx_f_8discodop_5kbest__getderiv(std::string &, ItemNo, RankedEdge &, struct __pyx_obj_8discodop_10containers_Chart *); /*proto*/
static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &); /*proto*/
static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &); /*proto*/
static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &); /*proto*/
static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &); /*proto*/
static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &); /*proto*/
#define __Pyx_MODULE_NAME "discodop.kbest"
int __pyx_module_is_main_discodop__kbest = 0;

/* Implementation of 'discodop.kbest' */
static PyObject *__pyx_builtin_range;
static PyObject *__pyx_builtin_ValueError;
static PyObject *__pyx_builtin_MemoryError;
static const char __pyx_k_k[] = "k";
static const char __pyx_k_n[] = "n";
static const char __pyx_k__2[] = " ";
static const char __pyx_k_all[] = "__all__";
static const char __pyx_k_d_d[] = "%d:%d";
static const char __pyx_k_tmp[] = "tmp";
static const char __pyx_k_cand[] = "cand";
static const char __pyx_k_main[] = "__main__";
static const char __pyx_k_root[] = "root";
static const char __pyx_k_test[] = "__test__";
static const char __pyx_k_chart[] = "chart";
static const char __pyx_k_entry[] = "entry";
static const char __pyx_k_isinf[] = "isinf";
static const char __pyx_k_range[] = "range";
static const char __pyx_k_derivs[] = "derivs";
static const char __pyx_k_import[] = "__import__";
static const char __pyx_k_Grammar[] = "Grammar";
static const char __pyx_k_itemstr[] = "itemstr";
static const char __pyx_k_explored[] = "explored";
static const char __pyx_k_getderiv[] = "getderiv";
static const char __pyx_k_operator[] = "operator";
static const char __pyx_k_lazykbest[] = "lazykbest";
static const char __pyx_k_ValueError[] = "ValueError";
static const char __pyx_k_containers[] = "containers";
static const char __pyx_k_itemgetter[] = "itemgetter";
static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__";
static const char __pyx_k_MemoryError[] = "MemoryError";
static const char __pyx_k_discodop_kbest[] = "discodop.kbest";
static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback";
static const char __pyx_k_discodop_kbest_pyx[] = "discodop/kbest.pyx";
static const char __pyx_k_sprintf_error_return_value_d[] = "sprintf error; return value %d";
static const char __pyx_k_d_best_edge_for_right_child_of[] = "%d-best edge for right child of %s missing";
static const char __pyx_k_d_best_edge_for_s_of_left_item[] = "%d-best edge for %s of left item missing";
static const char __pyx_k_kbest_no_complete_derivation_in[] = "kbest: no complete derivation in chart";
static const char __pyx_k_Extract_the_k_best_derivations_f[] = "Extract the k-best derivations from a probabilistic parse forest.\n\nImplementation of Huang & Chiang (2005): Better k-best parsing.\nhttp://www.cis.upenn.edu/~lhuang3/huang-iwpt-correct.pdf";
static const char __pyx_k_non_zero_rank_vector_d_not_in_ex[] = "non-zero rank vector %d not in explored derivations for %s";
static PyObject *__pyx_n_s_Grammar;
static PyObject *__pyx_n_s_MemoryError;
static PyObject *__pyx_n_s_ValueError;
static PyObject *__pyx_kp_u__2;
static PyObject *__pyx_n_s_all;
static PyObject *__pyx_n_s_cand;
static PyObject *__pyx_n_s_chart;
static PyObject *__pyx_n_s_cline_in_traceback;
static PyObject *__pyx_n_s_containers;
static PyObject *__pyx_kp_u_d_best_edge_for_right_child_of;
static PyObject *__pyx_kp_u_d_best_edge_for_s_of_left_item;
static PyObject *__pyx_kp_u_d_d;
static PyObject *__pyx_n_s_derivs;
static PyObject *__pyx_n_s_discodop_kbest;
static PyObject *__pyx_kp_s_discodop_kbest_pyx;
static PyObject *__pyx_n_s_entry;
static PyObject *__pyx_n_s_explored;
static PyObject *__pyx_n_u_getderiv;
static PyObject *__pyx_n_s_import;
static PyObject *__pyx_n_s_isinf;
static PyObject *__pyx_n_s_itemgetter;
static PyObject *__pyx_n_s_itemstr;
static PyObject *__pyx_n_s_k;
static PyObject *__pyx_kp_u_kbest_no_complete_derivation_in;
static PyObject *__pyx_n_s_lazykbest;
static PyObject *__pyx_n_u_lazykbest;
static PyObject *__pyx_n_s_main;
static PyObject *__pyx_n_s_n;
static PyObject *__pyx_kp_u_non_zero_rank_vector_d_not_in_ex;
static PyObject *__pyx_n_s_operator;
static PyObject *__pyx_n_s_pyx_vtable;
static PyObject *__pyx_n_s_range;
static PyObject *__pyx_n_s_root;
static PyObject *__pyx_kp_u_sprintf_error_return_value_d;
static PyObject *__pyx_n_s_test;
static PyObject *__pyx_n_s_tmp;
static PyObject *__pyx_pf_8discodop_5kbest_lazykbest(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_8discodop_10containers_Chart *__pyx_v_chart, int __pyx_v_k, int __pyx_v_derivs); /* proto */
static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags); /* proto */
static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */
static PyObject *__pyx_int_460;
static PyObject *__pyx_tuple_;
static PyObject *__pyx_tuple__3;
static PyObject *__pyx_codeobj__4;

/* "discodop/kbest.pyx":15
 * include "constants.pxi"
 * 
 * cdef RankedEdgeAgenda[Prob] getcandidates(Chart chart, ItemNo v, int k):             # <<<<<<<<<<<<<<
 * 	""":returns: a heap with up to k candidate arcs starting from vertex v."""
 * 	# NB: the priority queue should either do a stable sort, or should
 */

static RankedEdgeAgenda<Prob>  __pyx_f_8discodop_5kbest_getcandidates(struct __pyx_obj_8discodop_10containers_Chart *__pyx_v_chart, ItemNo __pyx_v_v, int __pyx_v_k) {
  RankedEdgeAgenda<Prob>  __pyx_v_agenda;
  std::vector<std::pair<RankedEdge,Prob> >  __pyx_v_entries;
  std::pair<RankedEdge,Prob>  __pyx_v_entry;
  RankedEdge __pyx_v_re;
  Edge __pyx_v_e;
  Prob __pyx_v_prob;
  long __pyx_v_left;
  long __pyx_v_right;
  RankedEdgeAgenda<Prob>  __pyx_r;
  __Pyx_RefNannyDeclarations
  std::vector<Edge> ::iterator __pyx_t_1;
  std::vector<Edge>  *__pyx_t_2;
  Edge __pyx_t_3;
  int __pyx_t_4;
  Prob __pyx_t_5;
  __Pyx_RefNannySetupContext("getcandidates", 0);

  /* "discodop/kbest.pyx":32
 * 	# loop over edges
 * 	# compute viterbi prob from rule.prob + viterbi probs of children
 * 	for e in chart.parseforest[v]:             # <<<<<<<<<<<<<<
 * 		if e.rule is NULL:
 * 			# there can only be one lexical edge for this combination of
 */
  __pyx_t_2 = &(__pyx_v_chart->parseforest[__pyx_v_v]);
  __pyx_t_1 = __pyx_t_2->begin();
  for (;;) {
    if (!(__pyx_t_1 != __pyx_t_2->end())) break;
    __pyx_t_3 = *__pyx_t_1;
    ++__pyx_t_1;
    __pyx_v_e = __pyx_t_3;

    /* "discodop/kbest.pyx":33
 * 	# compute viterbi prob from rule.prob + viterbi probs of children
 * 	for e in chart.parseforest[v]:
 * 		if e.rule is NULL:             # <<<<<<<<<<<<<<
 * 			# there can only be one lexical edge for this combination of
 * 			# POS tag and terminal, use viterbi probability directly
 */
    __pyx_t_4 = ((__pyx_v_e.rule == NULL) != 0);
    if (__pyx_t_4) {

      /* "discodop/kbest.pyx":36
 * 			# there can only be one lexical edge for this combination of
 * 			# POS tag and terminal, use viterbi probability directly
 * 			prob = chart.subtreeprob(v)             # <<<<<<<<<<<<<<
 * 			left = right = -1
 * 		else:
 */
      __pyx_v_prob = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->subtreeprob(__pyx_v_chart, __pyx_v_v);

      /* "discodop/kbest.pyx":37
 * 			# POS tag and terminal, use viterbi probability directly
 * 			prob = chart.subtreeprob(v)
 * 			left = right = -1             # <<<<<<<<<<<<<<
 * 		else:
 * 			left = right = 0
 */
      __pyx_v_left = -1L;
      __pyx_v_right = -1L;

      /* "discodop/kbest.pyx":33
 * 	# compute viterbi prob from rule.prob + viterbi probs of children
 * 	for e in chart.parseforest[v]:
 * 		if e.rule is NULL:             # <<<<<<<<<<<<<<
 * 			# there can only be one lexical edge for this combination of
 * 			# POS tag and terminal, use viterbi probability directly
 */
      goto __pyx_L5;
    }

    /* "discodop/kbest.pyx":39
 * 			left = right = -1
 * 		else:
 * 			left = right = 0             # <<<<<<<<<<<<<<
 * 			prob = e.rule.prob
 * 			prob += chart.subtreeprob(chart._left(v, e))
 */
    /*else*/ {
      __pyx_v_left = 0;
      __pyx_v_right = 0;

      /* "discodop/kbest.pyx":40
 * 		else:
 * 			left = right = 0
 * 			prob = e.rule.prob             # <<<<<<<<<<<<<<
 * 			prob += chart.subtreeprob(chart._left(v, e))
 * 			if e.rule.rhs2:  # unary rule?
 */
      __pyx_t_5 = __pyx_v_e.rule->prob;
      __pyx_v_prob = __pyx_t_5;

      /* "discodop/kbest.pyx":41
 * 			left = right = 0
 * 			prob = e.rule.prob
 * 			prob += chart.subtreeprob(chart._left(v, e))             # <<<<<<<<<<<<<<
 * 			if e.rule.rhs2:  # unary rule?
 * 				prob += chart.subtreeprob(chart._right(v, e))
 */
      __pyx_v_prob = (__pyx_v_prob + ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->subtreeprob(__pyx_v_chart, ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->_left(__pyx_v_chart, __pyx_v_v, __pyx_v_e)));

      /* "discodop/kbest.pyx":42
 * 			prob = e.rule.prob
 * 			prob += chart.subtreeprob(chart._left(v, e))
 * 			if e.rule.rhs2:  # unary rule?             # <<<<<<<<<<<<<<
 * 				prob += chart.subtreeprob(chart._right(v, e))
 * 			else:
 */
      __pyx_t_4 = (__pyx_v_e.rule->rhs2 != 0);
      if (__pyx_t_4) {

        /* "discodop/kbest.pyx":43
 * 			prob += chart.subtreeprob(chart._left(v, e))
 * 			if e.rule.rhs2:  # unary rule?
 * 				prob += chart.subtreeprob(chart._right(v, e))             # <<<<<<<<<<<<<<
 * 			else:
 * 				right = -1
 */
        __pyx_v_prob = (__pyx_v_prob + ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->subtreeprob(__pyx_v_chart, ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->_right(__pyx_v_chart, __pyx_v_v, __pyx_v_e)));

        /* "discodop/kbest.pyx":42
 * 			prob = e.rule.prob
 * 			prob += chart.subtreeprob(chart._left(v, e))
 * 			if e.rule.rhs2:  # unary rule?             # <<<<<<<<<<<<<<
 * 				prob += chart.subtreeprob(chart._right(v, e))
 * 			else:
 */
        goto __pyx_L6;
      }

      /* "discodop/kbest.pyx":45
 * 				prob += chart.subtreeprob(chart._right(v, e))
 * 			else:
 * 				right = -1             # <<<<<<<<<<<<<<
 * 		re = RankedEdge(v, e, left, right)
 * 		entry.first = re
 */
      /*else*/ {
        __pyx_v_right = -1L;
      }
      __pyx_L6:;
    }
    __pyx_L5:;

    /* "discodop/kbest.pyx":46
 * 			else:
 * 				right = -1
 * 		re = RankedEdge(v, e, left, right)             # <<<<<<<<<<<<<<
 * 		entry.first = re
 * 		entry.second = prob
 */
    __pyx_v_re = RankedEdge(__pyx_v_v, __pyx_v_e, __pyx_v_left, __pyx_v_right);

    /* "discodop/kbest.pyx":47
 * 				right = -1
 * 		re = RankedEdge(v, e, left, right)
 * 		entry.first = re             # <<<<<<<<<<<<<<
 * 		entry.second = prob
 * 		entries.push_back(entry)
 */
    __pyx_v_entry.first = __pyx_v_re;

    /* "discodop/kbest.pyx":48
 * 		re = RankedEdge(v, e, left, right)
 * 		entry.first = re
 * 		entry.second = prob             # <<<<<<<<<<<<<<
 * 		entries.push_back(entry)
 * 	# FIXME: can we guarantee that 'entries' does not have duplicates?
 */
    __pyx_v_entry.second = __pyx_v_prob;

    /* "discodop/kbest.pyx":49
 * 		entry.first = re
 * 		entry.second = prob
 * 		entries.push_back(entry)             # <<<<<<<<<<<<<<
 * 	# FIXME: can we guarantee that 'entries' does not have duplicates?
 * 	agenda.kbest_entries(entries, k)
 */
    try {
      __pyx_v_entries.push_back(__pyx_v_entry);
    } catch(...) {
      __Pyx_CppExn2PyErr();
      __PYX_ERR(0, 49, __pyx_L1_error)
    }

    /* "discodop/kbest.pyx":32
 * 	# loop over edges
 * 	# compute viterbi prob from rule.prob + viterbi probs of children
 * 	for e in chart.parseforest[v]:             # <<<<<<<<<<<<<<
 * 		if e.rule is NULL:
 * 			# there can only be one lexical edge for this combination of
 */
  }

  /* "discodop/kbest.pyx":51
 * 		entries.push_back(entry)
 * 	# FIXME: can we guarantee that 'entries' does not have duplicates?
 * 	agenda.kbest_entries(entries, k)             # <<<<<<<<<<<<<<
 * 	return agenda
 * 
 */
  __pyx_v_agenda.kbest_entries(__pyx_v_entries, __pyx_v_k);

  /* "discodop/kbest.pyx":52
 * 	# FIXME: can we guarantee that 'entries' does not have duplicates?
 * 	agenda.kbest_entries(entries, k)
 * 	return agenda             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = __pyx_v_agenda;
  goto __pyx_L0;

  /* "discodop/kbest.pyx":15
 * include "constants.pxi"
 * 
 * cdef RankedEdgeAgenda[Prob] getcandidates(Chart chart, ItemNo v, int k):             # <<<<<<<<<<<<<<
 * 	""":returns: a heap with up to k candidate arcs starting from vertex v."""
 * 	# NB: the priority queue should either do a stable sort, or should
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_WriteUnraisable("discodop.kbest.getcandidates", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0);
  __Pyx_pretend_to_initialize(&__pyx_r);
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "discodop/kbest.pyx":55
 * 
 * 
 * cdef lazykthbest(ItemNo v, int k, int k1, agendas_type& cand, Chart chart,             # <<<<<<<<<<<<<<
 * 		RankedEdgeSet& explored, int depthlimit):
 * 	""""Explore up to *k*-best derivations headed by vertex *v*.
 */

static PyObject *__pyx_f_8discodop_5kbest_lazykthbest(ItemNo __pyx_v_v, int __pyx_v_k, int __pyx_v_k1, __pyx_t_8discodop_5kbest_agendas_type &__pyx_v_cand, struct __pyx_obj_8discodop_10containers_Chart *__pyx_v_chart, RankedEdgeSet &__pyx_v_explored, int __pyx_v_depthlimit) {
  std::pair<RankedEdge,Prob>  __pyx_v_entry;
  RankedEdge __pyx_v_ej;
  RankedEdge __pyx_v_ej1;
  int __pyx_v_ji;
  int __pyx_v_inrankededges;
  long __pyx_v_i;
  ItemNo __pyx_v_ei;
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  int __pyx_t_2;
  RankedEdge __pyx_t_3;
  long __pyx_t_4;
  int __pyx_t_5;
  PyObject *__pyx_t_6 = NULL;
  Prob __pyx_t_7;
  __Pyx_RefNannySetupContext("lazykthbest", 0);

  /* "discodop/kbest.pyx":65
 * 	cdef RankedEdge ej, ej1
 * 	cdef int ji
 * 	cdef bint inrankededges = chart.rankededges[v].size() != 0             # <<<<<<<<<<<<<<
 * 	# FIXME: cand could be a vector; but need to distinguish first visit from
 * 	# empty agenda.
 */
  __pyx_v_inrankededges = ((__pyx_v_chart->rankededges[__pyx_v_v]).size() != 0);

  /* "discodop/kbest.pyx":69
 * 	# empty agenda.
 * 	# first visit of vertex v?
 * 	if cand.find(v) == cand.end():             # <<<<<<<<<<<<<<
 * 		# initialize the heap
 * 		cand[v] = getcandidates(chart, v, k1)
 */
  __pyx_t_1 = ((__pyx_v_cand.find(__pyx_v_v) == __pyx_v_cand.end()) != 0);
  if (__pyx_t_1) {

    /* "discodop/kbest.pyx":71
 * 	if cand.find(v) == cand.end():
 * 		# initialize the heap
 * 		cand[v] = getcandidates(chart, v, k1)             # <<<<<<<<<<<<<<
 * 	while not inrankededges or <int>chart.rankededges[v].size() < k:
 * 		inrankededges = inrankededges or chart.rankededges[v].size() != 0
 */
    (__pyx_v_cand[__pyx_v_v]) = __pyx_f_8discodop_5kbest_getcandidates(__pyx_v_chart, __pyx_v_v, __pyx_v_k1);

    /* "discodop/kbest.pyx":69
 * 	# empty agenda.
 * 	# first visit of vertex v?
 * 	if cand.find(v) == cand.end():             # <<<<<<<<<<<<<<
 * 		# initialize the heap
 * 		cand[v] = getcandidates(chart, v, k1)
 */
  }

  /* "discodop/kbest.pyx":72
 * 		# initialize the heap
 * 		cand[v] = getcandidates(chart, v, k1)
 * 	while not inrankededges or <int>chart.rankededges[v].size() < k:             # <<<<<<<<<<<<<<
 * 		inrankededges = inrankededges or chart.rankededges[v].size() != 0
 * 		if inrankededges:
 */
  while (1) {
    __pyx_t_2 = ((!(__pyx_v_inrankededges != 0)) != 0);
    if (!__pyx_t_2) {
    } else {
      __pyx_t_1 = __pyx_t_2;
      goto __pyx_L6_bool_binop_done;
    }
    __pyx_t_2 = ((((int)(__pyx_v_chart->rankededges[__pyx_v_v]).size()) < __pyx_v_k) != 0);
    __pyx_t_1 = __pyx_t_2;
    __pyx_L6_bool_binop_done:;
    if (!__pyx_t_1) break;

    /* "discodop/kbest.pyx":73
 * 		cand[v] = getcandidates(chart, v, k1)
 * 	while not inrankededges or <int>chart.rankededges[v].size() < k:
 * 		inrankededges = inrankededges or chart.rankededges[v].size() != 0             # <<<<<<<<<<<<<<
 * 		if inrankededges:
 * 			# last derivation
 */
    __pyx_t_2 = (__pyx_v_inrankededges != 0);
    if (!__pyx_t_2) {
    } else {
      __pyx_t_1 = __pyx_t_2;
      goto __pyx_L8_bool_binop_done;
    }
    __pyx_t_2 = (((__pyx_v_chart->rankededges[__pyx_v_v]).size() != 0) != 0);
    __pyx_t_1 = __pyx_t_2;
    __pyx_L8_bool_binop_done:;
    __pyx_v_inrankededges = __pyx_t_1;

    /* "discodop/kbest.pyx":74
 * 	while not inrankededges or <int>chart.rankededges[v].size() < k:
 * 		inrankededges = inrankededges or chart.rankededges[v].size() != 0
 * 		if inrankededges:             # <<<<<<<<<<<<<<
 * 			# last derivation
 * 			entry = chart.rankededges[v][chart.rankededges[v].size() - 1]
 */
    __pyx_t_1 = (__pyx_v_inrankededges != 0);
    if (__pyx_t_1) {

      /* "discodop/kbest.pyx":76
 * 		if inrankededges:
 * 			# last derivation
 * 			entry = chart.rankededges[v][chart.rankededges[v].size() - 1]             # <<<<<<<<<<<<<<
 * 			ej = entry.first
 * 			# update the heap, adding the successors of last derivation
 */
      __pyx_v_entry = ((__pyx_v_chart->rankededges[__pyx_v_v])[((__pyx_v_chart->rankededges[__pyx_v_v]).size() - 1)]);

      /* "discodop/kbest.pyx":77
 * 			# last derivation
 * 			entry = chart.rankededges[v][chart.rankededges[v].size() - 1]
 * 			ej = entry.first             # <<<<<<<<<<<<<<
 * 			# update the heap, adding the successors of last derivation
 * 			# start of inlined lazynext(v, ej, k1, cand, chart, explored)
 */
      __pyx_t_3 = __pyx_v_entry.first;
      __pyx_v_ej = __pyx_t_3;

      /* "discodop/kbest.pyx":80
 * 			# update the heap, adding the successors of last derivation
 * 			# start of inlined lazynext(v, ej, k1, cand, chart, explored)
 * 			for i in range(2):  # add the |e| neighbors             # <<<<<<<<<<<<<<
 * 				if i == 0 and ej.left >= 0:
 * 					ei = chart.left(ej)
 */
      for (__pyx_t_4 = 0; __pyx_t_4 < 2; __pyx_t_4+=1) {
        __pyx_v_i = __pyx_t_4;

        /* "discodop/kbest.pyx":81
 * 			# start of inlined lazynext(v, ej, k1, cand, chart, explored)
 * 			for i in range(2):  # add the |e| neighbors
 * 				if i == 0 and ej.left >= 0:             # <<<<<<<<<<<<<<
 * 					ei = chart.left(ej)
 * 					ej1 = RankedEdge(v, ej.edge, ej.left + 1, ej.right)
 */
        __pyx_t_2 = ((__pyx_v_i == 0) != 0);
        if (__pyx_t_2) {
        } else {
          __pyx_t_1 = __pyx_t_2;
          goto __pyx_L14_bool_binop_done;
        }
        __pyx_t_2 = ((__pyx_v_ej.left >= 0) != 0);
        __pyx_t_1 = __pyx_t_2;
        __pyx_L14_bool_binop_done:;
        if (__pyx_t_1) {

          /* "discodop/kbest.pyx":82
 * 			for i in range(2):  # add the |e| neighbors
 * 				if i == 0 and ej.left >= 0:
 * 					ei = chart.left(ej)             # <<<<<<<<<<<<<<
 * 					ej1 = RankedEdge(v, ej.edge, ej.left + 1, ej.right)
 * 				elif i == 1 and ej.right >= 0:
 */
          __pyx_v_ei = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->left(__pyx_v_chart, __pyx_v_ej);

          /* "discodop/kbest.pyx":83
 * 				if i == 0 and ej.left >= 0:
 * 					ei = chart.left(ej)
 * 					ej1 = RankedEdge(v, ej.edge, ej.left + 1, ej.right)             # <<<<<<<<<<<<<<
 * 				elif i == 1 and ej.right >= 0:
 * 					ei = chart.right(ej)
 */
          __pyx_v_ej1 = RankedEdge(__pyx_v_v, __pyx_v_ej.edge, (__pyx_v_ej.left + 1), __pyx_v_ej.right);

          /* "discodop/kbest.pyx":81
 * 			# start of inlined lazynext(v, ej, k1, cand, chart, explored)
 * 			for i in range(2):  # add the |e| neighbors
 * 				if i == 0 and ej.left >= 0:             # <<<<<<<<<<<<<<
 * 					ei = chart.left(ej)
 * 					ej1 = RankedEdge(v, ej.edge, ej.left + 1, ej.right)
 */
          goto __pyx_L13;
        }

        /* "discodop/kbest.pyx":84
 * 					ei = chart.left(ej)
 * 					ej1 = RankedEdge(v, ej.edge, ej.left + 1, ej.right)
 * 				elif i == 1 and ej.right >= 0:             # <<<<<<<<<<<<<<
 * 					ei = chart.right(ej)
 * 					ej1 = RankedEdge(v, ej.edge, ej.left, ej.right + 1)
 */
        __pyx_t_2 = ((__pyx_v_i == 1) != 0);
        if (__pyx_t_2) {
        } else {
          __pyx_t_1 = __pyx_t_2;
          goto __pyx_L16_bool_binop_done;
        }
        __pyx_t_2 = ((__pyx_v_ej.right >= 0) != 0);
        __pyx_t_1 = __pyx_t_2;
        __pyx_L16_bool_binop_done:;
        if (__pyx_t_1) {

          /* "discodop/kbest.pyx":85
 * 					ej1 = RankedEdge(v, ej.edge, ej.left + 1, ej.right)
 * 				elif i == 1 and ej.right >= 0:
 * 					ei = chart.right(ej)             # <<<<<<<<<<<<<<
 * 					ej1 = RankedEdge(v, ej.edge, ej.left, ej.right + 1)
 * 				else:
 */
          __pyx_v_ei = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->right(__pyx_v_chart, __pyx_v_ej);

          /* "discodop/kbest.pyx":86
 * 				elif i == 1 and ej.right >= 0:
 * 					ei = chart.right(ej)
 * 					ej1 = RankedEdge(v, ej.edge, ej.left, ej.right + 1)             # <<<<<<<<<<<<<<
 * 				else:
 * 					break
 */
          __pyx_v_ej1 = RankedEdge(__pyx_v_v, __pyx_v_ej.edge, __pyx_v_ej.left, (__pyx_v_ej.right + 1));

          /* "discodop/kbest.pyx":84
 * 					ei = chart.left(ej)
 * 					ej1 = RankedEdge(v, ej.edge, ej.left + 1, ej.right)
 * 				elif i == 1 and ej.right >= 0:             # <<<<<<<<<<<<<<
 * 					ei = chart.right(ej)
 * 					ej1 = RankedEdge(v, ej.edge, ej.left, ej.right + 1)
 */
          goto __pyx_L13;
        }

        /* "discodop/kbest.pyx":88
 * 					ej1 = RankedEdge(v, ej.edge, ej.left, ej.right + 1)
 * 				else:
 * 					break             # <<<<<<<<<<<<<<
 * 				ji = ej1.left if i == 0 else ej1.right
 * 				if depthlimit > 0:
 */
        /*else*/ {
          goto __pyx_L12_break;
        }
        __pyx_L13:;

        /* "discodop/kbest.pyx":89
 * 				else:
 * 					break
 * 				ji = ej1.left if i == 0 else ej1.right             # <<<<<<<<<<<<<<
 * 				if depthlimit > 0:
 * 					# recursively solve a subproblem
 */
        if (((__pyx_v_i == 0) != 0)) {
          __pyx_t_5 = __pyx_v_ej1.left;
        } else {
          __pyx_t_5 = __pyx_v_ej1.right;
        }
        __pyx_v_ji = __pyx_t_5;

        /* "discodop/kbest.pyx":90
 * 					break
 * 				ji = ej1.left if i == 0 else ej1.right
 * 				if depthlimit > 0:             # <<<<<<<<<<<<<<
 * 					# recursively solve a subproblem
 * 					# NB: increment j[i] again, j is zero-based and k is not
 */
        __pyx_t_1 = ((__pyx_v_depthlimit > 0) != 0);
        if (__pyx_t_1) {

          /* "discodop/kbest.pyx":93
 * 					# recursively solve a subproblem
 * 					# NB: increment j[i] again, j is zero-based and k is not
 * 					lazykthbest(ei, ji + 1, k1, cand, chart, explored,             # <<<<<<<<<<<<<<
 * 							depthlimit - 1)
 * 					# if it exists and is not in heap yet
 */
          __pyx_t_6 = __pyx_f_8discodop_5kbest_lazykthbest(__pyx_v_ei, (__pyx_v_ji + 1), __pyx_v_k1, __pyx_v_cand, __pyx_v_chart, __pyx_v_explored, (__pyx_v_depthlimit - 1)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 93, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_6);
          __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;

          /* "discodop/kbest.pyx":96
 * 							depthlimit - 1)
 * 					# if it exists and is not in heap yet
 * 					if (chart.rankededges[ei].size() != 0             # <<<<<<<<<<<<<<
 * 							and ji < <int>chart.rankededges[ei].size()
 * 							and explored.count(ej1) == 0):
 */
          __pyx_t_2 = (((__pyx_v_chart->rankededges[__pyx_v_ei]).size() != 0) != 0);
          if (__pyx_t_2) {
          } else {
            __pyx_t_1 = __pyx_t_2;
            goto __pyx_L20_bool_binop_done;
          }

          /* "discodop/kbest.pyx":97
 * 					# if it exists and is not in heap yet
 * 					if (chart.rankededges[ei].size() != 0
 * 							and ji < <int>chart.rankededges[ei].size()             # <<<<<<<<<<<<<<
 * 							and explored.count(ej1) == 0):
 * 						# 	and cand[ej1.head]): gives duplicates
 */
          __pyx_t_2 = ((__pyx_v_ji < ((int)(__pyx_v_chart->rankededges[__pyx_v_ei]).size())) != 0);
          if (__pyx_t_2) {
          } else {
            __pyx_t_1 = __pyx_t_2;
            goto __pyx_L20_bool_binop_done;
          }

          /* "discodop/kbest.pyx":98
 * 					if (chart.rankededges[ei].size() != 0
 * 							and ji < <int>chart.rankededges[ei].size()
 * 							and explored.count(ej1) == 0):             # <<<<<<<<<<<<<<
 * 						# 	and cand[ej1.head]): gives duplicates
 * 						# add it to the heap
 */
          __pyx_t_2 = ((__pyx_v_explored.count(__pyx_v_ej1) == 0) != 0);
          __pyx_t_1 = __pyx_t_2;
          __pyx_L20_bool_binop_done:;

          /* "discodop/kbest.pyx":96
 * 							depthlimit - 1)
 * 					# if it exists and is not in heap yet
 * 					if (chart.rankededges[ei].size() != 0             # <<<<<<<<<<<<<<
 * 							and ji < <int>chart.rankededges[ei].size()
 * 							and explored.count(ej1) == 0):
 */
          if (__pyx_t_1) {

            /* "discodop/kbest.pyx":101
 * 						# 	and cand[ej1.head]): gives duplicates
 * 						# add it to the heap
 * 						cand[v].setitem(ej1, getprob(chart, v, ej1))             # <<<<<<<<<<<<<<
 * 						explored.insert(ej1)
 * 			# end of lazynext
 */
            __pyx_t_7 = __pyx_f_8discodop_5kbest_getprob(__pyx_v_chart, __pyx_v_v, __pyx_v_ej1); if (unlikely(__pyx_t_7 == -1.0)) __PYX_ERR(0, 101, __pyx_L1_error)
            (__pyx_v_cand[__pyx_v_v]).setitem(__pyx_v_ej1, __pyx_t_7);

            /* "discodop/kbest.pyx":102
 * 						# add it to the heap
 * 						cand[v].setitem(ej1, getprob(chart, v, ej1))
 * 						explored.insert(ej1)             # <<<<<<<<<<<<<<
 * 			# end of lazynext
 * 		if cand[v].empty():
 */
            __pyx_v_explored.insert(__pyx_v_ej1);

            /* "discodop/kbest.pyx":96
 * 							depthlimit - 1)
 * 					# if it exists and is not in heap yet
 * 					if (chart.rankededges[ei].size() != 0             # <<<<<<<<<<<<<<
 * 							and ji < <int>chart.rankededges[ei].size()
 * 							and explored.count(ej1) == 0):
 */
          }

          /* "discodop/kbest.pyx":90
 * 					break
 * 				ji = ej1.left if i == 0 else ej1.right
 * 				if depthlimit > 0:             # <<<<<<<<<<<<<<
 * 					# recursively solve a subproblem
 * 					# NB: increment j[i] again, j is zero-based and k is not
 */
        }
      }
      __pyx_L12_break:;

      /* "discodop/kbest.pyx":74
 * 	while not inrankededges or <int>chart.rankededges[v].size() < k:
 * 		inrankededges = inrankededges or chart.rankededges[v].size() != 0
 * 		if inrankededges:             # <<<<<<<<<<<<<<
 * 			# last derivation
 * 			entry = chart.rankededges[v][chart.rankededges[v].size() - 1]
 */
    }

    /* "discodop/kbest.pyx":104
 * 						explored.insert(ej1)
 * 			# end of lazynext
 * 		if cand[v].empty():             # <<<<<<<<<<<<<<
 * 			break
 * 		# get the next best derivation and delete it from the heap
 */
    __pyx_t_1 = ((__pyx_v_cand[__pyx_v_v]).empty() != 0);
    if (__pyx_t_1) {

      /* "discodop/kbest.pyx":105
 * 			# end of lazynext
 * 		if cand[v].empty():
 * 			break             # <<<<<<<<<<<<<<
 * 		# get the next best derivation and delete it from the heap
 * 		entry = cand[v].pop()
 */
      goto __pyx_L5_break;

      /* "discodop/kbest.pyx":104
 * 						explored.insert(ej1)
 * 			# end of lazynext
 * 		if cand[v].empty():             # <<<<<<<<<<<<<<
 * 			break
 * 		# get the next best derivation and delete it from the heap
 */
    }

    /* "discodop/kbest.pyx":107
 * 			break
 * 		# get the next best derivation and delete it from the heap
 * 		entry = cand[v].pop()             # <<<<<<<<<<<<<<
 * 		chart.rankededges[v].push_back(entry)
 * 
 */
    __pyx_v_entry = (__pyx_v_cand[__pyx_v_v]).pop();

    /* "discodop/kbest.pyx":108
 * 		# get the next best derivation and delete it from the heap
 * 		entry = cand[v].pop()
 * 		chart.rankededges[v].push_back(entry)             # <<<<<<<<<<<<<<
 * 
 * 
 */
    try {
      (__pyx_v_chart->rankededges[__pyx_v_v]).push_back(__pyx_v_entry);
    } catch(...) {
      __Pyx_CppExn2PyErr();
      __PYX_ERR(0, 108, __pyx_L1_error)
    }
  }
  __pyx_L5_break:;

  /* "discodop/kbest.pyx":55
 * 
 * 
 * cdef lazykthbest(ItemNo v, int k, int k1, agendas_type& cand, Chart chart,             # <<<<<<<<<<<<<<
 * 		RankedEdgeSet& explored, int depthlimit):
 * 	""""Explore up to *k*-best derivations headed by vertex *v*.
 */

  /* function exit code */
  __pyx_r = Py_None; __Pyx_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_6);
  __Pyx_AddTraceback("discodop.kbest.lazykthbest", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "discodop/kbest.pyx":111
 * 
 * 
 * cdef inline Prob getprob(Chart chart, ItemNo v, RankedEdge& ej) except -1:             # <<<<<<<<<<<<<<
 * 	"""Get subtree probability of ``ej``.
 * 
 */

static CYTHON_INLINE Prob __pyx_f_8discodop_5kbest_getprob(struct __pyx_obj_8discodop_10containers_Chart *__pyx_v_chart, ItemNo __pyx_v_v, RankedEdge &__pyx_v_ej) {
  Prob __pyx_v_prob;
  ItemNo __pyx_v_ei;
  Prob __pyx_r;
  __Pyx_RefNannyDeclarations
  Prob __pyx_t_1;
  int __pyx_t_2;
  PyObject *__pyx_t_3 = NULL;
  PyObject *__pyx_t_4 = NULL;
  PyObject *__pyx_t_5 = NULL;
  PyObject *__pyx_t_6 = NULL;
  PyObject *__pyx_t_7 = NULL;
  PyObject *__pyx_t_8 = NULL;
  __Pyx_RefNannySetupContext("getprob", 0);

  /* "discodop/kbest.pyx":115
 * 
 * 	Try looking in ``chart.rankededges``, or else use viterbi probability."""
 * 	cdef Prob prob = ej.edge.rule.prob             # <<<<<<<<<<<<<<
 * 	ei = chart.left(ej)
 * 	if ej.left == 0:
 */
  __pyx_t_1 = __pyx_v_ej.edge.rule->prob;
  __pyx_v_prob = __pyx_t_1;

  /* "discodop/kbest.pyx":116
 * 	Try looking in ``chart.rankededges``, or else use viterbi probability."""
 * 	cdef Prob prob = ej.edge.rule.prob
 * 	ei = chart.left(ej)             # <<<<<<<<<<<<<<
 * 	if ej.left == 0:
 * 		prob += chart.subtreeprob(ei)
 */
  __pyx_v_ei = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->left(__pyx_v_chart, __pyx_v_ej);

  /* "discodop/kbest.pyx":117
 * 	cdef Prob prob = ej.edge.rule.prob
 * 	ei = chart.left(ej)
 * 	if ej.left == 0:             # <<<<<<<<<<<<<<
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():
 */
  __pyx_t_2 = ((__pyx_v_ej.left == 0) != 0);
  if (__pyx_t_2) {

    /* "discodop/kbest.pyx":118
 * 	ei = chart.left(ej)
 * 	if ej.left == 0:
 * 		prob += chart.subtreeprob(ei)             # <<<<<<<<<<<<<<
 * 	elif chart.rankededges[ei].size():
 * 		prob += chart.rankededges[ei][ej.left].second
 */
    __pyx_v_prob = (__pyx_v_prob + ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->subtreeprob(__pyx_v_chart, __pyx_v_ei));

    /* "discodop/kbest.pyx":117
 * 	cdef Prob prob = ej.edge.rule.prob
 * 	ei = chart.left(ej)
 * 	if ej.left == 0:             # <<<<<<<<<<<<<<
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():
 */
    goto __pyx_L3;
  }

  /* "discodop/kbest.pyx":119
 * 	if ej.left == 0:
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():             # <<<<<<<<<<<<<<
 * 		prob += chart.rankededges[ei][ej.left].second
 * 	else:
 */
  __pyx_t_2 = ((__pyx_v_chart->rankededges[__pyx_v_ei]).size() != 0);
  if (__pyx_t_2) {

    /* "discodop/kbest.pyx":120
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():
 * 		prob += chart.rankededges[ei][ej.left].second             # <<<<<<<<<<<<<<
 * 	else:
 * 		raise ValueError('non-zero rank vector %d not in explored '
 */
    __pyx_v_prob = (__pyx_v_prob + ((__pyx_v_chart->rankededges[__pyx_v_ei])[__pyx_v_ej.left]).second);

    /* "discodop/kbest.pyx":119
 * 	if ej.left == 0:
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():             # <<<<<<<<<<<<<<
 * 		prob += chart.rankededges[ei][ej.left].second
 * 	else:
 */
    goto __pyx_L3;
  }

  /* "discodop/kbest.pyx":122
 * 		prob += chart.rankededges[ei][ej.left].second
 * 	else:
 * 		raise ValueError('non-zero rank vector %d not in explored '             # <<<<<<<<<<<<<<
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))
 * 	if ej.right == -1:
 */
  /*else*/ {

    /* "discodop/kbest.pyx":123
 * 	else:
 * 		raise ValueError('non-zero rank vector %d not in explored '
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))             # <<<<<<<<<<<<<<
 * 	if ej.right == -1:
 * 		return prob
 */
    __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_ej.right); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 123, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_3);
    __pyx_t_5 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_chart), __pyx_n_s_itemstr); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 123, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_5);
    __pyx_t_6 = __Pyx_PyInt_From_uint32_t(__pyx_v_v); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 123, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_6);
    __pyx_t_7 = NULL;
    if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) {
      __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5);
      if (likely(__pyx_t_7)) {
        PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5);
        __Pyx_INCREF(__pyx_t_7);
        __Pyx_INCREF(function);
        __Pyx_DECREF_SET(__pyx_t_5, function);
      }
    }
    if (!__pyx_t_7) {
      __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 123, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
      __Pyx_GOTREF(__pyx_t_4);
    } else {
      #if CYTHON_FAST_PYCALL
      if (PyFunction_Check(__pyx_t_5)) {
        PyObject *__pyx_temp[2] = {__pyx_t_7, __pyx_t_6};
        __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 123, __pyx_L1_error)
        __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0;
        __Pyx_GOTREF(__pyx_t_4);
        __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
      } else
      #endif
      #if CYTHON_FAST_PYCCALL
      if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) {
        PyObject *__pyx_temp[2] = {__pyx_t_7, __pyx_t_6};
        __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 123, __pyx_L1_error)
        __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0;
        __Pyx_GOTREF(__pyx_t_4);
        __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
      } else
      #endif
      {
        __pyx_t_8 = PyTuple_New(1+1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 123, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_8);
        __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_7); __pyx_t_7 = NULL;
        __Pyx_GIVEREF(__pyx_t_6);
        PyTuple_SET_ITEM(__pyx_t_8, 0+1, __pyx_t_6);
        __pyx_t_6 = 0;
        __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 123, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_4);
        __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
      }
    }
    __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
    __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 123, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_5);
    __Pyx_GIVEREF(__pyx_t_3);
    PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3);
    __Pyx_GIVEREF(__pyx_t_4);
    PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_4);
    __pyx_t_3 = 0;
    __pyx_t_4 = 0;
    __pyx_t_4 = PyUnicode_Format(__pyx_kp_u_non_zero_rank_vector_d_not_in_ex, __pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 123, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_4);
    __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;

    /* "discodop/kbest.pyx":122
 * 		prob += chart.rankededges[ei][ej.left].second
 * 	else:
 * 		raise ValueError('non-zero rank vector %d not in explored '             # <<<<<<<<<<<<<<
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))
 * 	if ej.right == -1:
 */
    __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 122, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_5);
    __Pyx_GIVEREF(__pyx_t_4);
    PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4);
    __pyx_t_4 = 0;
    __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 122, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_4);
    __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
    __Pyx_Raise(__pyx_t_4, 0, 0, 0);
    __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
    __PYX_ERR(0, 122, __pyx_L1_error)
  }
  __pyx_L3:;

  /* "discodop/kbest.pyx":124
 * 		raise ValueError('non-zero rank vector %d not in explored '
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))
 * 	if ej.right == -1:             # <<<<<<<<<<<<<<
 * 		return prob
 * 	ei = chart.right(ej)
 */
  __pyx_t_2 = ((__pyx_v_ej.right == -1L) != 0);
  if (__pyx_t_2) {

    /* "discodop/kbest.pyx":125
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))
 * 	if ej.right == -1:
 * 		return prob             # <<<<<<<<<<<<<<
 * 	ei = chart.right(ej)
 * 	if ej.right == 0:
 */
    __pyx_r = __pyx_v_prob;
    goto __pyx_L0;

    /* "discodop/kbest.pyx":124
 * 		raise ValueError('non-zero rank vector %d not in explored '
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))
 * 	if ej.right == -1:             # <<<<<<<<<<<<<<
 * 		return prob
 * 	ei = chart.right(ej)
 */
  }

  /* "discodop/kbest.pyx":126
 * 	if ej.right == -1:
 * 		return prob
 * 	ei = chart.right(ej)             # <<<<<<<<<<<<<<
 * 	if ej.right == 0:
 * 		prob += chart.subtreeprob(ei)
 */
  __pyx_v_ei = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->right(__pyx_v_chart, __pyx_v_ej);

  /* "discodop/kbest.pyx":127
 * 		return prob
 * 	ei = chart.right(ej)
 * 	if ej.right == 0:             # <<<<<<<<<<<<<<
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():
 */
  __pyx_t_2 = ((__pyx_v_ej.right == 0) != 0);
  if (__pyx_t_2) {

    /* "discodop/kbest.pyx":128
 * 	ei = chart.right(ej)
 * 	if ej.right == 0:
 * 		prob += chart.subtreeprob(ei)             # <<<<<<<<<<<<<<
 * 	elif chart.rankededges[ei].size():
 * 		prob += chart.rankededges[ei][ej.right].second
 */
    __pyx_v_prob = (__pyx_v_prob + ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->subtreeprob(__pyx_v_chart, __pyx_v_ei));

    /* "discodop/kbest.pyx":127
 * 		return prob
 * 	ei = chart.right(ej)
 * 	if ej.right == 0:             # <<<<<<<<<<<<<<
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():
 */
    goto __pyx_L5;
  }

  /* "discodop/kbest.pyx":129
 * 	if ej.right == 0:
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():             # <<<<<<<<<<<<<<
 * 		prob += chart.rankededges[ei][ej.right].second
 * 	else:
 */
  __pyx_t_2 = ((__pyx_v_chart->rankededges[__pyx_v_ei]).size() != 0);
  if (__pyx_t_2) {

    /* "discodop/kbest.pyx":130
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():
 * 		prob += chart.rankededges[ei][ej.right].second             # <<<<<<<<<<<<<<
 * 	else:
 * 		raise ValueError('non-zero rank vector %d not in explored '
 */
    __pyx_v_prob = (__pyx_v_prob + ((__pyx_v_chart->rankededges[__pyx_v_ei])[__pyx_v_ej.right]).second);

    /* "discodop/kbest.pyx":129
 * 	if ej.right == 0:
 * 		prob += chart.subtreeprob(ei)
 * 	elif chart.rankededges[ei].size():             # <<<<<<<<<<<<<<
 * 		prob += chart.rankededges[ei][ej.right].second
 * 	else:
 */
    goto __pyx_L5;
  }

  /* "discodop/kbest.pyx":132
 * 		prob += chart.rankededges[ei][ej.right].second
 * 	else:
 * 		raise ValueError('non-zero rank vector %d not in explored '             # <<<<<<<<<<<<<<
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))
 * 	return prob
 */
  /*else*/ {

    /* "discodop/kbest.pyx":133
 * 	else:
 * 		raise ValueError('non-zero rank vector %d not in explored '
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))             # <<<<<<<<<<<<<<
 * 	return prob
 * 
 */
    __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_ej.right); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 133, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_4);
    __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_chart), __pyx_n_s_itemstr); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 133, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_3);
    __pyx_t_8 = __Pyx_PyInt_From_uint32_t(__pyx_v_v); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 133, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_8);
    __pyx_t_6 = NULL;
    if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_3))) {
      __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_3);
      if (likely(__pyx_t_6)) {
        PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3);
        __Pyx_INCREF(__pyx_t_6);
        __Pyx_INCREF(function);
        __Pyx_DECREF_SET(__pyx_t_3, function);
      }
    }
    if (!__pyx_t_6) {
      __pyx_t_5 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_8); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 133, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
      __Pyx_GOTREF(__pyx_t_5);
    } else {
      #if CYTHON_FAST_PYCALL
      if (PyFunction_Check(__pyx_t_3)) {
        PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_t_8};
        __pyx_t_5 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 133, __pyx_L1_error)
        __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0;
        __Pyx_GOTREF(__pyx_t_5);
        __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
      } else
      #endif
      #if CYTHON_FAST_PYCCALL
      if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) {
        PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_t_8};
        __pyx_t_5 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 133, __pyx_L1_error)
        __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0;
        __Pyx_GOTREF(__pyx_t_5);
        __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
      } else
      #endif
      {
        __pyx_t_7 = PyTuple_New(1+1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 133, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_7);
        __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); __pyx_t_6 = NULL;
        __Pyx_GIVEREF(__pyx_t_8);
        PyTuple_SET_ITEM(__pyx_t_7, 0+1, __pyx_t_8);
        __pyx_t_8 = 0;
        __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 133, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_5);
        __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
      }
    }
    __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
    __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 133, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_3);
    __Pyx_GIVEREF(__pyx_t_4);
    PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4);
    __Pyx_GIVEREF(__pyx_t_5);
    PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_5);
    __pyx_t_4 = 0;
    __pyx_t_5 = 0;
    __pyx_t_5 = PyUnicode_Format(__pyx_kp_u_non_zero_rank_vector_d_not_in_ex, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 133, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_5);
    __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;

    /* "discodop/kbest.pyx":132
 * 		prob += chart.rankededges[ei][ej.right].second
 * 	else:
 * 		raise ValueError('non-zero rank vector %d not in explored '             # <<<<<<<<<<<<<<
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))
 * 	return prob
 */
    __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 132, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_3);
    __Pyx_GIVEREF(__pyx_t_5);
    PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5);
    __pyx_t_5 = 0;
    __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 132, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_5);
    __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
    __Pyx_Raise(__pyx_t_5, 0, 0, 0);
    __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
    __PYX_ERR(0, 132, __pyx_L1_error)
  }
  __pyx_L5:;

  /* "discodop/kbest.pyx":134
 * 		raise ValueError('non-zero rank vector %d not in explored '
 * 				'derivations for %s' % (ej.right, chart.itemstr(v)))
 * 	return prob             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = __pyx_v_prob;
  goto __pyx_L0;

  /* "discodop/kbest.pyx":111
 * 
 * 
 * cdef inline Prob getprob(Chart chart, ItemNo v, RankedEdge& ej) except -1:             # <<<<<<<<<<<<<<
 * 	"""Get subtree probability of ``ej``.
 * 
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_3);
  __Pyx_XDECREF(__pyx_t_4);
  __Pyx_XDECREF(__pyx_t_5);
  __Pyx_XDECREF(__pyx_t_6);
  __Pyx_XDECREF(__pyx_t_7);
  __Pyx_XDECREF(__pyx_t_8);
  __Pyx_AddTraceback("discodop.kbest.getprob", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = -1.0;
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "discodop/kbest.pyx":137
 * 
 * 
 * cdef int explorederivation(ItemNo v, RankedEdge& ej, Chart chart,             # <<<<<<<<<<<<<<
 * 		RankedEdgeSet& explored, int depthlimit) except -2:
 * 	"""Traverse derivation to ensure all 1-best RankedEdges are present.
 */

static int __pyx_f_8discodop_5kbest_explorederivation(ItemNo __pyx_v_v, RankedEdge &__pyx_v_ej, struct __pyx_obj_8discodop_10containers_Chart *__pyx_v_chart, RankedEdgeSet &__pyx_v_explored, int __pyx_v_depthlimit) {
  std::pair<RankedEdge,Prob>  __pyx_v_entry;
  RankedEdgeAgenda<Prob>  __pyx_v_tmp;
  ItemNo __pyx_v_leftitem;
  ItemNo __pyx_v_rightitem;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  PyObject *__pyx_t_2 = NULL;
  PyObject *__pyx_t_3 = NULL;
  PyObject *__pyx_t_4 = NULL;
  PyObject *__pyx_t_5 = NULL;
  PyObject *__pyx_t_6 = NULL;
  PyObject *__pyx_t_7 = NULL;
  int __pyx_t_8;
  __Pyx_RefNannySetupContext("explorederivation", 0);

  /* "discodop/kbest.pyx":144
 * 	cdef pair[RankedEdge, Prob] entry
 * 	cdef RankedEdgeAgenda[Prob] tmp
 * 	if depthlimit <= 0:  # to prevent cycles             # <<<<<<<<<<<<<<
 * 		return False
 * 	if ej.edge.rule is NULL:
 */
  __pyx_t_1 = ((__pyx_v_depthlimit <= 0) != 0);
  if (__pyx_t_1) {

    /* "discodop/kbest.pyx":145
 * 	cdef RankedEdgeAgenda[Prob] tmp
 * 	if depthlimit <= 0:  # to prevent cycles
 * 		return False             # <<<<<<<<<<<<<<
 * 	if ej.edge.rule is NULL:
 * 		return True
 */
    __pyx_r = 0;
    goto __pyx_L0;

    /* "discodop/kbest.pyx":144
 * 	cdef pair[RankedEdge, Prob] entry
 * 	cdef RankedEdgeAgenda[Prob] tmp
 * 	if depthlimit <= 0:  # to prevent cycles             # <<<<<<<<<<<<<<
 * 		return False
 * 	if ej.edge.rule is NULL:
 */
  }

  /* "discodop/kbest.pyx":146
 * 	if depthlimit <= 0:  # to prevent cycles
 * 		return False
 * 	if ej.edge.rule is NULL:             # <<<<<<<<<<<<<<
 * 		return True
 * 	if ej.left != -1:
 */
  __pyx_t_1 = ((__pyx_v_ej.edge.rule == NULL) != 0);
  if (__pyx_t_1) {

    /* "discodop/kbest.pyx":147
 * 		return False
 * 	if ej.edge.rule is NULL:
 * 		return True             # <<<<<<<<<<<<<<
 * 	if ej.left != -1:
 * 		leftitem = chart.left(ej)
 */
    __pyx_r = 1;
    goto __pyx_L0;

    /* "discodop/kbest.pyx":146
 * 	if depthlimit <= 0:  # to prevent cycles
 * 		return False
 * 	if ej.edge.rule is NULL:             # <<<<<<<<<<<<<<
 * 		return True
 * 	if ej.left != -1:
 */
  }

  /* "discodop/kbest.pyx":148
 * 	if ej.edge.rule is NULL:
 * 		return True
 * 	if ej.left != -1:             # <<<<<<<<<<<<<<
 * 		leftitem = chart.left(ej)
 * 		if not chart.rankededges[leftitem].size():
 */
  __pyx_t_1 = ((__pyx_v_ej.left != -1L) != 0);
  if (__pyx_t_1) {

    /* "discodop/kbest.pyx":149
 * 		return True
 * 	if ej.left != -1:
 * 		leftitem = chart.left(ej)             # <<<<<<<<<<<<<<
 * 		if not chart.rankededges[leftitem].size():
 * 			assert ej.left == 0, '%d-best edge for %s of left item missing' % (
 */
    __pyx_v_leftitem = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->left(__pyx_v_chart, __pyx_v_ej);

    /* "discodop/kbest.pyx":150
 * 	if ej.left != -1:
 * 		leftitem = chart.left(ej)
 * 		if not chart.rankededges[leftitem].size():             # <<<<<<<<<<<<<<
 * 			assert ej.left == 0, '%d-best edge for %s of left item missing' % (
 * 						ej.left, chart.itemstr(v))
 */
    __pyx_t_1 = ((!((__pyx_v_chart->rankededges[__pyx_v_leftitem]).size() != 0)) != 0);
    if (__pyx_t_1) {

      /* "discodop/kbest.pyx":151
 * 		leftitem = chart.left(ej)
 * 		if not chart.rankededges[leftitem].size():
 * 			assert ej.left == 0, '%d-best edge for %s of left item missing' % (             # <<<<<<<<<<<<<<
 * 						ej.left, chart.itemstr(v))
 * 			tmp = getcandidates(chart, leftitem, 1)
 */
      #ifndef CYTHON_WITHOUT_ASSERTIONS
      if (unlikely(!Py_OptimizeFlag)) {
        if (unlikely(!((__pyx_v_ej.left == 0) != 0))) {

          /* "discodop/kbest.pyx":152
 * 		if not chart.rankededges[leftitem].size():
 * 			assert ej.left == 0, '%d-best edge for %s of left item missing' % (
 * 						ej.left, chart.itemstr(v))             # <<<<<<<<<<<<<<
 * 			tmp = getcandidates(chart, leftitem, 1)
 * 			if tmp.size() < 1:
 */
          __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_ej.left); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 152, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_2);
          __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_chart), __pyx_n_s_itemstr); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 152, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_4);
          __pyx_t_5 = __Pyx_PyInt_From_uint32_t(__pyx_v_v); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 152, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_5);
          __pyx_t_6 = NULL;
          if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) {
            __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_4);
            if (likely(__pyx_t_6)) {
              PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4);
              __Pyx_INCREF(__pyx_t_6);
              __Pyx_INCREF(function);
              __Pyx_DECREF_SET(__pyx_t_4, function);
            }
          }
          if (!__pyx_t_6) {
            __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 152, __pyx_L1_error)
            __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
            __Pyx_GOTREF(__pyx_t_3);
          } else {
            #if CYTHON_FAST_PYCALL
            if (PyFunction_Check(__pyx_t_4)) {
              PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_t_5};
              __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 152, __pyx_L1_error)
              __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0;
              __Pyx_GOTREF(__pyx_t_3);
              __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
            } else
            #endif
            #if CYTHON_FAST_PYCCALL
            if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) {
              PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_t_5};
              __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 152, __pyx_L1_error)
              __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0;
              __Pyx_GOTREF(__pyx_t_3);
              __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
            } else
            #endif
            {
              __pyx_t_7 = PyTuple_New(1+1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 152, __pyx_L1_error)
              __Pyx_GOTREF(__pyx_t_7);
              __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); __pyx_t_6 = NULL;
              __Pyx_GIVEREF(__pyx_t_5);
              PyTuple_SET_ITEM(__pyx_t_7, 0+1, __pyx_t_5);
              __pyx_t_5 = 0;
              __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_7, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 152, __pyx_L1_error)
              __Pyx_GOTREF(__pyx_t_3);
              __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
            }
          }
          __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
          __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 152, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_4);
          __Pyx_GIVEREF(__pyx_t_2);
          PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2);
          __Pyx_GIVEREF(__pyx_t_3);
          PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3);
          __pyx_t_2 = 0;
          __pyx_t_3 = 0;

          /* "discodop/kbest.pyx":151
 * 		leftitem = chart.left(ej)
 * 		if not chart.rankededges[leftitem].size():
 * 			assert ej.left == 0, '%d-best edge for %s of left item missing' % (             # <<<<<<<<<<<<<<
 * 						ej.left, chart.itemstr(v))
 * 			tmp = getcandidates(chart, leftitem, 1)
 */
          __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_d_best_edge_for_s_of_left_item, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 151, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_3);
          __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
          PyErr_SetObject(PyExc_AssertionError, __pyx_t_3);
          __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
          __PYX_ERR(0, 151, __pyx_L1_error)
        }
      }
      #endif

      /* "discodop/kbest.pyx":153
 * 			assert ej.left == 0, '%d-best edge for %s of left item missing' % (
 * 						ej.left, chart.itemstr(v))
 * 			tmp = getcandidates(chart, leftitem, 1)             # <<<<<<<<<<<<<<
 * 			if tmp.size() < 1:
 * 				abort()
 */
      __pyx_v_tmp = __pyx_f_8discodop_5kbest_getcandidates(__pyx_v_chart, __pyx_v_leftitem, 1);

      /* "discodop/kbest.pyx":154
 * 						ej.left, chart.itemstr(v))
 * 			tmp = getcandidates(chart, leftitem, 1)
 * 			if tmp.size() < 1:             # <<<<<<<<<<<<<<
 * 				abort()
 * 			entry = tmp.pop()
 */
      __pyx_t_1 = ((__pyx_v_tmp.size() < 1) != 0);
      if (__pyx_t_1) {

        /* "discodop/kbest.pyx":155
 * 			tmp = getcandidates(chart, leftitem, 1)
 * 			if tmp.size() < 1:
 * 				abort()             # <<<<<<<<<<<<<<
 * 			entry = tmp.pop()
 * 			chart.rankededges[leftitem].push_back(entry)
 */
        abort();

        /* "discodop/kbest.pyx":154
 * 						ej.left, chart.itemstr(v))
 * 			tmp = getcandidates(chart, leftitem, 1)
 * 			if tmp.size() < 1:             # <<<<<<<<<<<<<<
 * 				abort()
 * 			entry = tmp.pop()
 */
      }

      /* "discodop/kbest.pyx":156
 * 			if tmp.size() < 1:
 * 				abort()
 * 			entry = tmp.pop()             # <<<<<<<<<<<<<<
 * 			chart.rankededges[leftitem].push_back(entry)
 * 			explored.insert(entry.first)
 */
      __pyx_v_entry = __pyx_v_tmp.pop();

      /* "discodop/kbest.pyx":157
 * 				abort()
 * 			entry = tmp.pop()
 * 			chart.rankededges[leftitem].push_back(entry)             # <<<<<<<<<<<<<<
 * 			explored.insert(entry.first)
 * 		if not explorederivation(leftitem,
 */
      try {
        (__pyx_v_chart->rankededges[__pyx_v_leftitem]).push_back(__pyx_v_entry);
      } catch(...) {
        __Pyx_CppExn2PyErr();
        __PYX_ERR(0, 157, __pyx_L1_error)
      }

      /* "discodop/kbest.pyx":158
 * 			entry = tmp.pop()
 * 			chart.rankededges[leftitem].push_back(entry)
 * 			explored.insert(entry.first)             # <<<<<<<<<<<<<<
 * 		if not explorederivation(leftitem,
 * 				chart.rankededges[leftitem][ej.left].first,
 */
      __pyx_v_explored.insert(__pyx_v_entry.first);

      /* "discodop/kbest.pyx":150
 * 	if ej.left != -1:
 * 		leftitem = chart.left(ej)
 * 		if not chart.rankededges[leftitem].size():             # <<<<<<<<<<<<<<
 * 			assert ej.left == 0, '%d-best edge for %s of left item missing' % (
 * 						ej.left, chart.itemstr(v))
 */
    }

    /* "discodop/kbest.pyx":159
 * 			chart.rankededges[leftitem].push_back(entry)
 * 			explored.insert(entry.first)
 * 		if not explorederivation(leftitem,             # <<<<<<<<<<<<<<
 * 				chart.rankededges[leftitem][ej.left].first,
 * 				chart, explored, depthlimit - 1):
 */
    __pyx_t_8 = __pyx_f_8discodop_5kbest_explorederivation(__pyx_v_leftitem, ((__pyx_v_chart->rankededges[__pyx_v_leftitem])[__pyx_v_ej.left]).first, __pyx_v_chart, __pyx_v_explored, (__pyx_v_depthlimit - 1)); if (unlikely(__pyx_t_8 == -2)) __PYX_ERR(0, 159, __pyx_L1_error)
    __pyx_t_1 = ((!(__pyx_t_8 != 0)) != 0);
    if (__pyx_t_1) {

      /* "discodop/kbest.pyx":162
 * 				chart.rankededges[leftitem][ej.left].first,
 * 				chart, explored, depthlimit - 1):
 * 			return False             # <<<<<<<<<<<<<<
 * 	if ej.right != -1:
 * 		rightitem = chart.right(ej)
 */
      __pyx_r = 0;
      goto __pyx_L0;

      /* "discodop/kbest.pyx":159
 * 			chart.rankededges[leftitem].push_back(entry)
 * 			explored.insert(entry.first)
 * 		if not explorederivation(leftitem,             # <<<<<<<<<<<<<<
 * 				chart.rankededges[leftitem][ej.left].first,
 * 				chart, explored, depthlimit - 1):
 */
    }

    /* "discodop/kbest.pyx":148
 * 	if ej.edge.rule is NULL:
 * 		return True
 * 	if ej.left != -1:             # <<<<<<<<<<<<<<
 * 		leftitem = chart.left(ej)
 * 		if not chart.rankededges[leftitem].size():
 */
  }

  /* "discodop/kbest.pyx":163
 * 				chart, explored, depthlimit - 1):
 * 			return False
 * 	if ej.right != -1:             # <<<<<<<<<<<<<<
 * 		rightitem = chart.right(ej)
 * 		if not chart.rankededges[rightitem].size():
 */
  __pyx_t_1 = ((__pyx_v_ej.right != -1L) != 0);
  if (__pyx_t_1) {

    /* "discodop/kbest.pyx":164
 * 			return False
 * 	if ej.right != -1:
 * 		rightitem = chart.right(ej)             # <<<<<<<<<<<<<<
 * 		if not chart.rankededges[rightitem].size():
 * 			assert ej.right == 0, (('%d-best edge for right child '
 */
    __pyx_v_rightitem = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->right(__pyx_v_chart, __pyx_v_ej);

    /* "discodop/kbest.pyx":165
 * 	if ej.right != -1:
 * 		rightitem = chart.right(ej)
 * 		if not chart.rankededges[rightitem].size():             # <<<<<<<<<<<<<<
 * 			assert ej.right == 0, (('%d-best edge for right child '
 * 					'of %s missing') % (ej.right, chart.itemstr(v)))
 */
    __pyx_t_1 = ((!((__pyx_v_chart->rankededges[__pyx_v_rightitem]).size() != 0)) != 0);
    if (__pyx_t_1) {

      /* "discodop/kbest.pyx":166
 * 		rightitem = chart.right(ej)
 * 		if not chart.rankededges[rightitem].size():
 * 			assert ej.right == 0, (('%d-best edge for right child '             # <<<<<<<<<<<<<<
 * 					'of %s missing') % (ej.right, chart.itemstr(v)))
 * 			tmp = getcandidates(chart, rightitem, 1)
 */
      #ifndef CYTHON_WITHOUT_ASSERTIONS
      if (unlikely(!Py_OptimizeFlag)) {
        if (unlikely(!((__pyx_v_ej.right == 0) != 0))) {

          /* "discodop/kbest.pyx":167
 * 		if not chart.rankededges[rightitem].size():
 * 			assert ej.right == 0, (('%d-best edge for right child '
 * 					'of %s missing') % (ej.right, chart.itemstr(v)))             # <<<<<<<<<<<<<<
 * 			tmp = getcandidates(chart, rightitem, 1)
 * 			if tmp.size() < 1:
 */
          __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_ej.right); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 167, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_3);
          __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_chart), __pyx_n_s_itemstr); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_2);
          __pyx_t_7 = __Pyx_PyInt_From_uint32_t(__pyx_v_v); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 167, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_7);
          __pyx_t_5 = NULL;
          if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) {
            __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2);
            if (likely(__pyx_t_5)) {
              PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2);
              __Pyx_INCREF(__pyx_t_5);
              __Pyx_INCREF(function);
              __Pyx_DECREF_SET(__pyx_t_2, function);
            }
          }
          if (!__pyx_t_5) {
            __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 167, __pyx_L1_error)
            __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
            __Pyx_GOTREF(__pyx_t_4);
          } else {
            #if CYTHON_FAST_PYCALL
            if (PyFunction_Check(__pyx_t_2)) {
              PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_7};
              __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 167, __pyx_L1_error)
              __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
              __Pyx_GOTREF(__pyx_t_4);
              __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
            } else
            #endif
            #if CYTHON_FAST_PYCCALL
            if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) {
              PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_7};
              __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 167, __pyx_L1_error)
              __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
              __Pyx_GOTREF(__pyx_t_4);
              __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
            } else
            #endif
            {
              __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 167, __pyx_L1_error)
              __Pyx_GOTREF(__pyx_t_6);
              __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL;
              __Pyx_GIVEREF(__pyx_t_7);
              PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_7);
              __pyx_t_7 = 0;
              __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 167, __pyx_L1_error)
              __Pyx_GOTREF(__pyx_t_4);
              __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
            }
          }
          __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
          __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_2);
          __Pyx_GIVEREF(__pyx_t_3);
          PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3);
          __Pyx_GIVEREF(__pyx_t_4);
          PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4);
          __pyx_t_3 = 0;
          __pyx_t_4 = 0;
          __pyx_t_4 = PyUnicode_Format(__pyx_kp_u_d_best_edge_for_right_child_of, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 167, __pyx_L1_error)
          __Pyx_GOTREF(__pyx_t_4);
          __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
          PyErr_SetObject(PyExc_AssertionError, __pyx_t_4);
          __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
          __PYX_ERR(0, 166, __pyx_L1_error)
        }
      }
      #endif

      /* "discodop/kbest.pyx":168
 * 			assert ej.right == 0, (('%d-best edge for right child '
 * 					'of %s missing') % (ej.right, chart.itemstr(v)))
 * 			tmp = getcandidates(chart, rightitem, 1)             # <<<<<<<<<<<<<<
 * 			if tmp.size() < 1:
 * 				abort()
 */
      __pyx_v_tmp = __pyx_f_8discodop_5kbest_getcandidates(__pyx_v_chart, __pyx_v_rightitem, 1);

      /* "discodop/kbest.pyx":169
 * 					'of %s missing') % (ej.right, chart.itemstr(v)))
 * 			tmp = getcandidates(chart, rightitem, 1)
 * 			if tmp.size() < 1:             # <<<<<<<<<<<<<<
 * 				abort()
 * 			entry = tmp.pop()
 */
      __pyx_t_1 = ((__pyx_v_tmp.size() < 1) != 0);
      if (__pyx_t_1) {

        /* "discodop/kbest.pyx":170
 * 			tmp = getcandidates(chart, rightitem, 1)
 * 			if tmp.size() < 1:
 * 				abort()             # <<<<<<<<<<<<<<
 * 			entry = tmp.pop()
 * 			chart.rankededges[rightitem].push_back(entry)
 */
        abort();

        /* "discodop/kbest.pyx":169
 * 					'of %s missing') % (ej.right, chart.itemstr(v)))
 * 			tmp = getcandidates(chart, rightitem, 1)
 * 			if tmp.size() < 1:             # <<<<<<<<<<<<<<
 * 				abort()
 * 			entry = tmp.pop()
 */
      }

      /* "discodop/kbest.pyx":171
 * 			if tmp.size() < 1:
 * 				abort()
 * 			entry = tmp.pop()             # <<<<<<<<<<<<<<
 * 			chart.rankededges[rightitem].push_back(entry)
 * 			explored.insert(entry.first)
 */
      __pyx_v_entry = __pyx_v_tmp.pop();

      /* "discodop/kbest.pyx":172
 * 				abort()
 * 			entry = tmp.pop()
 * 			chart.rankededges[rightitem].push_back(entry)             # <<<<<<<<<<<<<<
 * 			explored.insert(entry.first)
 * 		return explorederivation(rightitem,
 */
      try {
        (__pyx_v_chart->rankededges[__pyx_v_rightitem]).push_back(__pyx_v_entry);
      } catch(...) {
        __Pyx_CppExn2PyErr();
        __PYX_ERR(0, 172, __pyx_L1_error)
      }

      /* "discodop/kbest.pyx":173
 * 			entry = tmp.pop()
 * 			chart.rankededges[rightitem].push_back(entry)
 * 			explored.insert(entry.first)             # <<<<<<<<<<<<<<
 * 		return explorederivation(rightitem,
 * 				chart.rankededges[rightitem][ej.right].first,
 */
      __pyx_v_explored.insert(__pyx_v_entry.first);

      /* "discodop/kbest.pyx":165
 * 	if ej.right != -1:
 * 		rightitem = chart.right(ej)
 * 		if not chart.rankededges[rightitem].size():             # <<<<<<<<<<<<<<
 * 			assert ej.right == 0, (('%d-best edge for right child '
 * 					'of %s missing') % (ej.right, chart.itemstr(v)))
 */
    }

    /* "discodop/kbest.pyx":174
 * 			chart.rankededges[rightitem].push_back(entry)
 * 			explored.insert(entry.first)
 * 		return explorederivation(rightitem,             # <<<<<<<<<<<<<<
 * 				chart.rankededges[rightitem][ej.right].first,
 * 				chart, explored, depthlimit - 1)
 */
    __pyx_t_8 = __pyx_f_8discodop_5kbest_explorederivation(__pyx_v_rightitem, ((__pyx_v_chart->rankededges[__pyx_v_rightitem])[__pyx_v_ej.right]).first, __pyx_v_chart, __pyx_v_explored, (__pyx_v_depthlimit - 1)); if (unlikely(__pyx_t_8 == -2)) __PYX_ERR(0, 174, __pyx_L1_error)
    __pyx_r = __pyx_t_8;
    goto __pyx_L0;

    /* "discodop/kbest.pyx":163
 * 				chart, explored, depthlimit - 1):
 * 			return False
 * 	if ej.right != -1:             # <<<<<<<<<<<<<<
 * 		rightitem = chart.right(ej)
 * 		if not chart.rankededges[rightitem].size():
 */
  }

  /* "discodop/kbest.pyx":177
 * 				chart.rankededges[rightitem][ej.right].first,
 * 				chart, explored, depthlimit - 1)
 * 	return True             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = 1;
  goto __pyx_L0;

  /* "discodop/kbest.pyx":137
 * 
 * 
 * cdef int explorederivation(ItemNo v, RankedEdge& ej, Chart chart,             # <<<<<<<<<<<<<<
 * 		RankedEdgeSet& explored, int depthlimit) except -2:
 * 	"""Traverse derivation to ensure all 1-best RankedEdges are present.
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_2);
  __Pyx_XDECREF(__pyx_t_3);
  __Pyx_XDECREF(__pyx_t_4);
  __Pyx_XDECREF(__pyx_t_5);
  __Pyx_XDECREF(__pyx_t_6);
  __Pyx_XDECREF(__pyx_t_7);
  __Pyx_AddTraceback("discodop.kbest.explorederivation", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = -2;
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "discodop/kbest.pyx":180
 * 
 * 
 * cdef inline _getderiv(string &result, ItemNo v, RankedEdge& ej, Chart chart):             # <<<<<<<<<<<<<<
 * 	"""Auxiliary function for ``getderiv()``.
 * 
 */

static CYTHON_INLINE PyObject *__pyx_f_8discodop_5kbest__getderiv(std::string &__pyx_v_result, ItemNo __pyx_v_v, RankedEdge &__pyx_v_ej, struct __pyx_obj_8discodop_10containers_Chart *__pyx_v_chart) {
  RankedEdge __pyx_v_rankededge;
  Label __pyx_v_label;
  char __pyx_v_buf[10];
  int __pyx_v_retval;
  ItemNo __pyx_v_item;
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  int __pyx_t_2;
  PyObject *__pyx_t_3 = NULL;
  PyObject *__pyx_t_4 = NULL;
  RankedEdge __pyx_t_5;
  __Pyx_RefNannySetupContext("_getderiv", 0);

  /* "discodop/kbest.pyx":185
 * 	:param result: provide an empty list for the initial call."""
 * 	cdef RankedEdge rankededge
 * 	cdef Label label = chart.label(v)             # <<<<<<<<<<<<<<
 * 	cdef char buf[10]
 * 	cdef int retval
 */
  __pyx_v_label = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->label(__pyx_v_chart, __pyx_v_v);

  /* "discodop/kbest.pyx":188
 * 	cdef char buf[10]
 * 	cdef int retval
 * 	result.append(b'(')             # <<<<<<<<<<<<<<
 * 	result.append(chart.grammar.tolabel.ob[label])
 * 	if ej.edge.rule is NULL:  # lexical rule, left child is terminal
 */
  __pyx_v_result.append(((char *)"("));

  /* "discodop/kbest.pyx":189
 * 	cdef int retval
 * 	result.append(b'(')
 * 	result.append(chart.grammar.tolabel.ob[label])             # <<<<<<<<<<<<<<
 * 	if ej.edge.rule is NULL:  # lexical rule, left child is terminal
 * 		# C++ way to convert int to string requires streams, C++11, or boost
 */
  __pyx_v_result.append((__pyx_v_chart->grammar->tolabel->ob[__pyx_v_label]));

  /* "discodop/kbest.pyx":190
 * 	result.append(b'(')
 * 	result.append(chart.grammar.tolabel.ob[label])
 * 	if ej.edge.rule is NULL:  # lexical rule, left child is terminal             # <<<<<<<<<<<<<<
 * 		# C++ way to convert int to string requires streams, C++11, or boost
 * 		retval = sprintf(buf, ' %d)', chart.lexidx(ej.edge))
 */
  __pyx_t_1 = ((__pyx_v_ej.edge.rule == NULL) != 0);
  if (__pyx_t_1) {

    /* "discodop/kbest.pyx":192
 * 	if ej.edge.rule is NULL:  # lexical rule, left child is terminal
 * 		# C++ way to convert int to string requires streams, C++11, or boost
 * 		retval = sprintf(buf, ' %d)', chart.lexidx(ej.edge))             # <<<<<<<<<<<<<<
 * 		if retval <= 0:
 * 			raise ValueError('sprintf error; return value %d' % retval)
 */
    __pyx_t_2 = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->lexidx(__pyx_v_chart, __pyx_v_ej.edge); if (unlikely(__pyx_t_2 == -1)) __PYX_ERR(0, 192, __pyx_L1_error)
    __pyx_v_retval = sprintf(__pyx_v_buf, ((char const *)" %d)"), __pyx_t_2);

    /* "discodop/kbest.pyx":193
 * 		# C++ way to convert int to string requires streams, C++11, or boost
 * 		retval = sprintf(buf, ' %d)', chart.lexidx(ej.edge))
 * 		if retval <= 0:             # <<<<<<<<<<<<<<
 * 			raise ValueError('sprintf error; return value %d' % retval)
 * 		result.append(buf)
 */
    __pyx_t_1 = ((__pyx_v_retval <= 0) != 0);
    if (__pyx_t_1) {

      /* "discodop/kbest.pyx":194
 * 		retval = sprintf(buf, ' %d)', chart.lexidx(ej.edge))
 * 		if retval <= 0:
 * 			raise ValueError('sprintf error; return value %d' % retval)             # <<<<<<<<<<<<<<
 * 		result.append(buf)
 * 	else:
 */
      __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_retval); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 194, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __pyx_t_4 = PyUnicode_Format(__pyx_kp_u_sprintf_error_return_value_d, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 194, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_4);
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
      __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 194, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __Pyx_GIVEREF(__pyx_t_4);
      PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4);
      __pyx_t_4 = 0;
      __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 194, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_4);
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
      __Pyx_Raise(__pyx_t_4, 0, 0, 0);
      __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
      __PYX_ERR(0, 194, __pyx_L1_error)

      /* "discodop/kbest.pyx":193
 * 		# C++ way to convert int to string requires streams, C++11, or boost
 * 		retval = sprintf(buf, ' %d)', chart.lexidx(ej.edge))
 * 		if retval <= 0:             # <<<<<<<<<<<<<<
 * 			raise ValueError('sprintf error; return value %d' % retval)
 * 		result.append(buf)
 */
    }

    /* "discodop/kbest.pyx":195
 * 		if retval <= 0:
 * 			raise ValueError('sprintf error; return value %d' % retval)
 * 		result.append(buf)             # <<<<<<<<<<<<<<
 * 	else:
 * 		result.append(b' ')
 */
    __pyx_v_result.append(__pyx_v_buf);

    /* "discodop/kbest.pyx":190
 * 	result.append(b'(')
 * 	result.append(chart.grammar.tolabel.ob[label])
 * 	if ej.edge.rule is NULL:  # lexical rule, left child is terminal             # <<<<<<<<<<<<<<
 * 		# C++ way to convert int to string requires streams, C++11, or boost
 * 		retval = sprintf(buf, ' %d)', chart.lexidx(ej.edge))
 */
    goto __pyx_L3;
  }

  /* "discodop/kbest.pyx":197
 * 		result.append(buf)
 * 	else:
 * 		result.append(b' ')             # <<<<<<<<<<<<<<
 * 		item = chart.left(ej)
 * 		rankededge = chart.rankededges[item][ej.left].first
 */
  /*else*/ {
    __pyx_v_result.append(((char *)" "));

    /* "discodop/kbest.pyx":198
 * 	else:
 * 		result.append(b' ')
 * 		item = chart.left(ej)             # <<<<<<<<<<<<<<
 * 		rankededge = chart.rankededges[item][ej.left].first
 * 		_getderiv(result, item, rankededge, chart)
 */
    __pyx_v_item = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->left(__pyx_v_chart, __pyx_v_ej);

    /* "discodop/kbest.pyx":199
 * 		result.append(b' ')
 * 		item = chart.left(ej)
 * 		rankededge = chart.rankededges[item][ej.left].first             # <<<<<<<<<<<<<<
 * 		_getderiv(result, item, rankededge, chart)
 * 		if ej.right != -1:
 */
    __pyx_t_5 = ((__pyx_v_chart->rankededges[__pyx_v_item])[__pyx_v_ej.left]).first;
    __pyx_v_rankededge = __pyx_t_5;

    /* "discodop/kbest.pyx":200
 * 		item = chart.left(ej)
 * 		rankededge = chart.rankededges[item][ej.left].first
 * 		_getderiv(result, item, rankededge, chart)             # <<<<<<<<<<<<<<
 * 		if ej.right != -1:
 * 			item = chart.right(ej)
 */
    __pyx_t_4 = __pyx_f_8discodop_5kbest__getderiv(__pyx_v_result, __pyx_v_item, __pyx_v_rankededge, __pyx_v_chart); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 200, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_4);
    __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;

    /* "discodop/kbest.pyx":201
 * 		rankededge = chart.rankededges[item][ej.left].first
 * 		_getderiv(result, item, rankededge, chart)
 * 		if ej.right != -1:             # <<<<<<<<<<<<<<
 * 			item = chart.right(ej)
 * 			result.append(b' ')
 */
    __pyx_t_1 = ((__pyx_v_ej.right != -1L) != 0);
    if (__pyx_t_1) {

      /* "discodop/kbest.pyx":202
 * 		_getderiv(result, item, rankededge, chart)
 * 		if ej.right != -1:
 * 			item = chart.right(ej)             # <<<<<<<<<<<<<<
 * 			result.append(b' ')
 * 			rankededge = chart.rankededges[item][ej.right].first
 */
      __pyx_v_item = ((struct __pyx_vtabstruct_8discodop_10containers_Chart *)__pyx_v_chart->__pyx_vtab)->right(__pyx_v_chart, __pyx_v_ej);

      /* "discodop/kbest.pyx":203
 * 		if ej.right != -1:
 * 			item = chart.right(ej)
 * 			result.append(b' ')             # <<<<<<<<<<<<<<
 * 			rankededge = chart.rankededges[item][ej.right].first
 * 			_getderiv(result, item, rankededge, chart)
 */
      __pyx_v_result.append(((char *)" "));

      /* "discodop/kbest.pyx":204
 * 			item = chart.right(ej)
 * 			result.append(b' ')
 * 			rankededge = chart.rankededges[item][ej.right].first             # <<<<<<<<<<<<<<
 * 			_getderiv(result, item, rankededge, chart)
 * 		result.append(b')')
 */
      __pyx_t_5 = ((__pyx_v_chart->rankededges[__pyx_v_item])[__pyx_v_ej.right]).first;
      __pyx_v_rankededge = __pyx_t_5;

      /* "discodop/kbest.pyx":205
 * 			result.append(b' ')
 * 			rankededge = chart.rankededges[item][ej.right].first
 * 			_getderiv(result, item, rankededge, chart)             # <<<<<<<<<<<<<<
 * 		result.append(b')')
 * 
 */
      __pyx_t_4 = __pyx_f_8discodop_5kbest__getderiv(__pyx_v_result, __pyx_v_item, __pyx_v_rankededge, __pyx_v_chart); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 205, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_4);
      __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;

      /* "discodop/kbest.pyx":201
 * 		rankededge = chart.rankededges[item][ej.left].first
 * 		_getderiv(result, item, rankededge, chart)
 * 		if ej.right != -1:             # <<<<<<<<<<<<<<
 * 			item = chart.right(ej)
 * 			result.append(b' ')
 */
    }

    /* "discodop/kbest.pyx":206
 * 			rankededge = chart.rankededges[item][ej.right].first
 * 			_getderiv(result, item, rankededge, chart)
 * 		result.append(b')')             # <<<<<<<<<<<<<<
 * 
 * 
 */
    __pyx_v_result.append(((char *)")"));
  }
  __pyx_L3:;

  /* "discodop/kbest.pyx":180
 * 
 * 
 * cdef inline _getderiv(string &result, ItemNo v, RankedEdge& ej, Chart chart):             # <<<<<<<<<<<<<<
 * 	"""Auxiliary function for ``getderiv()``.
 * 
 */

  /* function exit code */
  __pyx_r = Py_None; __Pyx_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_3);
  __Pyx_XDECREF(__pyx_t_4);
  __Pyx_AddTraceback("discodop.kbest._getderiv", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "discodop/kbest.pyx":209
 * 
 * 
 * cdef string getderiv(ItemNo v, RankedEdge ej, Chart chart):             # <<<<<<<<<<<<<<
 * 	"""Convert a RankedEdge to a string with a tree in bracket notation.
 * 
 */

static std::string __pyx_f_8discodop_5kbest_getderiv(ItemNo __pyx_v_v, RankedEdge __pyx_v_ej, struct __pyx_obj_8discodop_10containers_Chart *__pyx_v_chart) {
  std::string __pyx_v_result;
  std::string __pyx_r;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannySetupContext("getderiv", 0);

  /* "discodop/kbest.pyx":217
 * 	headed by S and having the 2nd best NP and the 1st best VP as children."""
 * 	cdef string result
 * 	_getderiv(result, v, ej, chart)             # <<<<<<<<<<<<<<
 * 	return result  # result.decode('utf8')
 * 
 */
  __pyx_t_1 = __pyx_f_8discodop_5kbest__getderiv(__pyx_v_result, __pyx_v_v, __pyx_v_ej, __pyx_v_chart); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 217, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;

  /* "discodop/kbest.pyx":218
 * 	cdef string result
 * 	_getderiv(result, v, ej, chart)
 * 	return result  # result.decode('utf8')             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = __pyx_v_result;
  goto __pyx_L0;

  /* "discodop/kbest.pyx":209
 * 
 * 
 * cdef string getderiv(ItemNo v, RankedEdge ej, Chart chart):             # <<<<<<<<<<<<<<
 * 	"""Convert a RankedEdge to a string with a tree in bracket notation.
 * 
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_WriteUnraisable("discodop.kbest.getderiv", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0);
  __Pyx_pretend_to_initialize(&__pyx_r);
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "discodop/kbest.pyx":221
 * 
 * 
 * def lazykbest(Chart chart, int k, bint derivs=True):             # <<<<<<<<<<<<<<
 * 	"""Wrapper function to run ``lazykthbest``.
 * 
 */

/* Python wrapper */
static PyObject *__pyx_pw_8discodop_5kbest_1lazykbest(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_8discodop_5kbest_lazykbest[] = "lazykbest(Chart chart, int k, bool derivs=True)\nWrapper function to run ``lazykthbest``.\n\n\tProduces the ranked chart, as well as derivations as strings (when\n\t``derivs`` is True). ``chart.parseforest`` should be a monotone hypergraph;\n\tshould be acyclic unless probabilities resolve the cycles (maybe nonzero\n\tweights for unary productions are sufficient?).\n\n\t:param k: the number of derivations to enumerate.";
static PyMethodDef __pyx_mdef_8discodop_5kbest_1lazykbest = {"lazykbest", (PyCFunction)__pyx_pw_8discodop_5kbest_1lazykbest, METH_VARARGS|METH_KEYWORDS, __pyx_doc_8discodop_5kbest_lazykbest};
static PyObject *__pyx_pw_8discodop_5kbest_1lazykbest(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  struct __pyx_obj_8discodop_10containers_Chart *__pyx_v_chart = 0;
  int __pyx_v_k;
  int __pyx_v_derivs;
  PyObject *__pyx_r = 0;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("lazykbest (wrapper)", 0);
  {
    static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_chart,&__pyx_n_s_k,&__pyx_n_s_derivs,0};
    PyObject* values[3] = {0,0,0};
    if (unlikely(__pyx_kwds)) {
      Py_ssize_t kw_args;
      const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
      switch (pos_args) {
        case  3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
        CYTHON_FALLTHROUGH;
        case  2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
        CYTHON_FALLTHROUGH;
        case  1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
        CYTHON_FALLTHROUGH;
        case  0: break;
        default: goto __pyx_L5_argtuple_error;
      }
      kw_args = PyDict_Size(__pyx_kwds);
      switch (pos_args) {
        case  0:
        if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_chart)) != 0)) kw_args--;
        else goto __pyx_L5_argtuple_error;
        CYTHON_FALLTHROUGH;
        case  1:
        if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_k)) != 0)) kw_args--;
        else {
          __Pyx_RaiseArgtupleInvalid("lazykbest", 0, 2, 3, 1); __PYX_ERR(0, 221, __pyx_L3_error)
        }
        CYTHON_FALLTHROUGH;
        case  2:
        if (kw_args > 0) {
          PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_derivs);
          if (value) { values[2] = value; kw_args--; }
        }
      }
      if (unlikely(kw_args > 0)) {
        if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "lazykbest") < 0)) __PYX_ERR(0, 221, __pyx_L3_error)
      }
    } else {
      switch (PyTuple_GET_SIZE(__pyx_args)) {
        case  3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
        CYTHON_FALLTHROUGH;
        case  2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
        values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
        break;
        default: goto __pyx_L5_argtuple_error;
      }
    }
    __pyx_v_chart = ((struct __pyx_obj_8discodop_10containers_Chart *)values[0]);
    __pyx_v_k = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_k == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 221, __pyx_L3_error)
    if (values[2]) {
      __pyx_v_derivs = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_derivs == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 221, __pyx_L3_error)
    } else {
      __pyx_v_derivs = ((int)1);
    }
  }
  goto __pyx_L4_argument_unpacking_done;
  __pyx_L5_argtuple_error:;
  __Pyx_RaiseArgtupleInvalid("lazykbest", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 221, __pyx_L3_error)
  __pyx_L3_error:;
  __Pyx_AddTraceback("discodop.kbest.lazykbest", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __Pyx_RefNannyFinishContext();
  return NULL;
  __pyx_L4_argument_unpacking_done:;
  if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_chart), __pyx_ptype_8discodop_10containers_Chart, 1, "chart", 0))) __PYX_ERR(0, 221, __pyx_L1_error)
  __pyx_r = __pyx_pf_8discodop_5kbest_lazykbest(__pyx_self, __pyx_v_chart, __pyx_v_k, __pyx_v_derivs);

  /* function exit code */
  goto __pyx_L0;
  __pyx_L1_error:;
  __pyx_r = NULL;
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

static PyObject *__pyx_pf_8discodop_5kbest_lazykbest(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_8discodop_10containers_Chart *__pyx_v_chart, int __pyx_v_k, int __pyx_v_derivs) {
  __pyx_t_8discodop_5kbest_agendas_type __pyx_v_cand;
  RankedEdgeSet __pyx_v_explored;
  std::pair<RankedEdge,Prob>  __pyx_v_entry;
  std::vector<std::pair<RankedEdge,Prob> >  __pyx_v_tmp;
  ItemNo __pyx_v_root;
  int __pyx_v_n;
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  PyObject *__pyx_t_2 = NULL;
  PyObject *__pyx_t_3 = NULL;
  ItemNo __pyx_t_4;
  int __pyx_t_5;
  std::vector<std::pair<RankedEdge,Prob> > ::iterator __pyx_t_6;
  std::vector<std::pair<RankedEdge,Prob> >  *__pyx_t_7;
  std::pair<RankedEdge,Prob>  __pyx_t_8;
  int __pyx_t_9;
  PyObject *__pyx_t_10 = NULL;
  __Pyx_RefNannySetupContext("lazykbest", 0);

  /* "discodop/kbest.pyx":234
 * 	cdef pair[RankedEdge, Prob] entry
 * 	cdef vector[pair[RankedEdge, Prob]] tmp
 * 	cdef ItemNo root = chart.root()             # <<<<<<<<<<<<<<
 * 	cdef int n = 0
 * 	if root == 0:
 */
  __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_chart), __pyx_n_s_root); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 234, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __pyx_t_3 = NULL;
  if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) {
    __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2);
    if (likely(__pyx_t_3)) {
      PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2);
      __Pyx_INCREF(__pyx_t_3);
      __Pyx_INCREF(function);
      __Pyx_DECREF_SET(__pyx_t_2, function);
    }
  }
  if (__pyx_t_3) {
    __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 234, __pyx_L1_error)
    __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
  } else {
    __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 234, __pyx_L1_error)
  }
  __Pyx_GOTREF(__pyx_t_1);
  __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  __pyx_t_4 = __Pyx_PyInt_As_uint32_t(__pyx_t_1); if (unlikely((__pyx_t_4 == ((ItemNo)-1)) && PyErr_Occurred())) __PYX_ERR(0, 234, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_v_root = __pyx_t_4;

  /* "discodop/kbest.pyx":235
 * 	cdef vector[pair[RankedEdge, Prob]] tmp
 * 	cdef ItemNo root = chart.root()
 * 	cdef int n = 0             # <<<<<<<<<<<<<<
 * 	if root == 0:
 * 		raise ValueError('kbest: no complete derivation in chart')
 */
  __pyx_v_n = 0;

  /* "discodop/kbest.pyx":236
 * 	cdef ItemNo root = chart.root()
 * 	cdef int n = 0
 * 	if root == 0:             # <<<<<<<<<<<<<<
 * 		raise ValueError('kbest: no complete derivation in chart')
 * 	chart.rankededges.clear()
 */
  __pyx_t_5 = ((__pyx_v_root == 0) != 0);
  if (__pyx_t_5) {

    /* "discodop/kbest.pyx":237
 * 	cdef int n = 0
 * 	if root == 0:
 * 		raise ValueError('kbest: no complete derivation in chart')             # <<<<<<<<<<<<<<
 * 	chart.rankededges.clear()
 * 	chart.rankededges.resize(chart.parseforest.size())
 */
    __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 237, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_1);
    __Pyx_Raise(__pyx_t_1, 0, 0, 0);
    __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
    __PYX_ERR(0, 237, __pyx_L1_error)

    /* "discodop/kbest.pyx":236
 * 	cdef ItemNo root = chart.root()
 * 	cdef int n = 0
 * 	if root == 0:             # <<<<<<<<<<<<<<
 * 		raise ValueError('kbest: no complete derivation in chart')
 * 	chart.rankededges.clear()
 */
  }

  /* "discodop/kbest.pyx":238
 * 	if root == 0:
 * 		raise ValueError('kbest: no complete derivation in chart')
 * 	chart.rankededges.clear()             # <<<<<<<<<<<<<<
 * 	chart.rankededges.resize(chart.parseforest.size())
 * 	lazykthbest(root, k, k, cand, chart, explored, MAX_DEPTH)
 */
  __pyx_v_chart->rankededges.clear();

  /* "discodop/kbest.pyx":239
 * 		raise ValueError('kbest: no complete derivation in chart')
 * 	chart.rankededges.clear()
 * 	chart.rankededges.resize(chart.parseforest.size())             # <<<<<<<<<<<<<<
 * 	lazykthbest(root, k, k, cand, chart, explored, MAX_DEPTH)
 * 	for entry in chart.rankededges[root]:
 */
  try {
    __pyx_v_chart->rankededges.resize(__pyx_v_chart->parseforest.size());
  } catch(...) {
    __Pyx_CppExn2PyErr();
    __PYX_ERR(0, 239, __pyx_L1_error)
  }

  /* "discodop/kbest.pyx":240
 * 	chart.rankededges.clear()
 * 	chart.rankededges.resize(chart.parseforest.size())
 * 	lazykthbest(root, k, k, cand, chart, explored, MAX_DEPTH)             # <<<<<<<<<<<<<<
 * 	for entry in chart.rankededges[root]:
 * 		if explorederivation(root, entry.first, chart, explored, MAX_DEPTH):
 */
  __pyx_t_1 = __pyx_f_8discodop_5kbest_lazykthbest(__pyx_v_root, __pyx_v_k, __pyx_v_k, __pyx_v_cand, __pyx_v_chart, __pyx_v_explored, 0xC8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 240, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;

  /* "discodop/kbest.pyx":241
 * 	chart.rankededges.resize(chart.parseforest.size())
 * 	lazykthbest(root, k, k, cand, chart, explored, MAX_DEPTH)
 * 	for entry in chart.rankededges[root]:             # <<<<<<<<<<<<<<
 * 		if explorederivation(root, entry.first, chart, explored, MAX_DEPTH):
 * 			tmp.push_back(entry)
 */
  __pyx_t_7 = &(__pyx_v_chart->rankededges[__pyx_v_root]);
  __pyx_t_6 = __pyx_t_7->begin();
  for (;;) {
    if (!(__pyx_t_6 != __pyx_t_7->end())) break;
    __pyx_t_8 = *__pyx_t_6;
    ++__pyx_t_6;
    __pyx_v_entry = __pyx_t_8;

    /* "discodop/kbest.pyx":242
 * 	lazykthbest(root, k, k, cand, chart, explored, MAX_DEPTH)
 * 	for entry in chart.rankededges[root]:
 * 		if explorederivation(root, entry.first, chart, explored, MAX_DEPTH):             # <<<<<<<<<<<<<<
 * 			tmp.push_back(entry)
 * 		n += 1
 */
    __pyx_t_9 = __pyx_f_8discodop_5kbest_explorederivation(__pyx_v_root, __pyx_v_entry.first, __pyx_v_chart, __pyx_v_explored, 0xC8); if (unlikely(__pyx_t_9 == -2)) __PYX_ERR(0, 242, __pyx_L1_error)
    __pyx_t_5 = (__pyx_t_9 != 0);
    if (__pyx_t_5) {

      /* "discodop/kbest.pyx":243
 * 	for entry in chart.rankededges[root]:
 * 		if explorederivation(root, entry.first, chart, explored, MAX_DEPTH):
 * 			tmp.push_back(entry)             # <<<<<<<<<<<<<<
 * 		n += 1
 * 		if n >= k:
 */
      try {
        __pyx_v_tmp.push_back(__pyx_v_entry);
      } catch(...) {
        __Pyx_CppExn2PyErr();
        __PYX_ERR(0, 243, __pyx_L1_error)
      }

      /* "discodop/kbest.pyx":242
 * 	lazykthbest(root, k, k, cand, chart, explored, MAX_DEPTH)
 * 	for entry in chart.rankededges[root]:
 * 		if explorederivation(root, entry.first, chart, explored, MAX_DEPTH):             # <<<<<<<<<<<<<<
 * 			tmp.push_back(entry)
 * 		n += 1
 */
    }

    /* "discodop/kbest.pyx":244
 * 		if explorederivation(root, entry.first, chart, explored, MAX_DEPTH):
 * 			tmp.push_back(entry)
 * 		n += 1             # <<<<<<<<<<<<<<
 * 		if n >= k:
 * 			break
 */
    __pyx_v_n = (__pyx_v_n + 1);

    /* "discodop/kbest.pyx":245
 * 			tmp.push_back(entry)
 * 		n += 1
 * 		if n >= k:             # <<<<<<<<<<<<<<
 * 			break
 * 	chart.rankededges[root] = tmp
 */
    __pyx_t_5 = ((__pyx_v_n >= __pyx_v_k) != 0);
    if (__pyx_t_5) {

      /* "discodop/kbest.pyx":246
 * 		n += 1
 * 		if n >= k:
 * 			break             # <<<<<<<<<<<<<<
 * 	chart.rankededges[root] = tmp
 * 	if derivs:
 */
      goto __pyx_L5_break;

      /* "discodop/kbest.pyx":245
 * 			tmp.push_back(entry)
 * 		n += 1
 * 		if n >= k:             # <<<<<<<<<<<<<<
 * 			break
 * 	chart.rankededges[root] = tmp
 */
    }

    /* "discodop/kbest.pyx":241
 * 	chart.rankededges.resize(chart.parseforest.size())
 * 	lazykthbest(root, k, k, cand, chart, explored, MAX_DEPTH)
 * 	for entry in chart.rankededges[root]:             # <<<<<<<<<<<<<<
 * 		if explorederivation(root, entry.first, chart, explored, MAX_DEPTH):
 * 			tmp.push_back(entry)
 */
  }
  __pyx_L5_break:;

  /* "discodop/kbest.pyx":247
 * 		if n >= k:
 * 			break
 * 	chart.rankededges[root] = tmp             # <<<<<<<<<<<<<<
 * 	if derivs:
 * 		# for entry in chart.rankededges[root]:
 */
  (__pyx_v_chart->rankededges[__pyx_v_root]) = __pyx_v_tmp;

  /* "discodop/kbest.pyx":248
 * 			break
 * 	chart.rankededges[root] = tmp
 * 	if derivs:             # <<<<<<<<<<<<<<
 * 		# for entry in chart.rankededges[root]:
 * 		# 	chart.derivations.push_back(getderiv(root, entry.first, chart))
 */
  __pyx_t_5 = (__pyx_v_derivs != 0);
  if (__pyx_t_5) {

    /* "discodop/kbest.pyx":251
 * 		# for entry in chart.rankededges[root]:
 * 		# 	chart.derivations.push_back(getderiv(root, entry.first, chart))
 * 		return [(getderiv(root, entry.first, chart).decode('utf8'),             # <<<<<<<<<<<<<<
 * 				entry.second) for entry in chart.rankededges[root]]
 * 	return None
 */
    __Pyx_XDECREF(__pyx_r);
    { /* enter inner scope */
      std::pair<RankedEdge,Prob>  __pyx_7genexpr__pyx_v_entry;
      __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 251, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);

      /* "discodop/kbest.pyx":252
 * 		# 	chart.derivations.push_back(getderiv(root, entry.first, chart))
 * 		return [(getderiv(root, entry.first, chart).decode('utf8'),
 * 				entry.second) for entry in chart.rankededges[root]]             # <<<<<<<<<<<<<<
 * 	return None
 * 
 */
      __pyx_t_7 = &(__pyx_v_chart->rankededges[__pyx_v_root]);
      __pyx_t_6 = __pyx_t_7->begin();
      for (;;) {
        if (!(__pyx_t_6 != __pyx_t_7->end())) break;
        __pyx_t_8 = *__pyx_t_6;
        ++__pyx_t_6;
        __pyx_7genexpr__pyx_v_entry = __pyx_t_8;

        /* "discodop/kbest.pyx":251
 * 		# for entry in chart.rankededges[root]:
 * 		# 	chart.derivations.push_back(getderiv(root, entry.first, chart))
 * 		return [(getderiv(root, entry.first, chart).decode('utf8'),             # <<<<<<<<<<<<<<
 * 				entry.second) for entry in chart.rankededges[root]]
 * 	return None
 */
        __pyx_t_2 = __Pyx_decode_cpp_string(__pyx_f_8discodop_5kbest_getderiv(__pyx_v_root, __pyx_7genexpr__pyx_v_entry.first, __pyx_v_chart), 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 251, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_2);

        /* "discodop/kbest.pyx":252
 * 		# 	chart.derivations.push_back(getderiv(root, entry.first, chart))
 * 		return [(getderiv(root, entry.first, chart).decode('utf8'),
 * 				entry.second) for entry in chart.rankededges[root]]             # <<<<<<<<<<<<<<
 * 	return None
 * 
 */
        __pyx_t_3 = PyFloat_FromDouble(__pyx_7genexpr__pyx_v_entry.second); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 252, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_3);

        /* "discodop/kbest.pyx":251
 * 		# for entry in chart.rankededges[root]:
 * 		# 	chart.derivations.push_back(getderiv(root, entry.first, chart))
 * 		return [(getderiv(root, entry.first, chart).decode('utf8'),             # <<<<<<<<<<<<<<
 * 				entry.second) for entry in chart.rankededges[root]]
 * 	return None
 */
        __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 251, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_10);
        __Pyx_GIVEREF(__pyx_t_2);
        PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_2);
        __Pyx_GIVEREF(__pyx_t_3);
        PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_3);
        __pyx_t_2 = 0;
        __pyx_t_3 = 0;
        if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_10))) __PYX_ERR(0, 251, __pyx_L1_error)
        __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0;

        /* "discodop/kbest.pyx":252
 * 		# 	chart.derivations.push_back(getderiv(root, entry.first, chart))
 * 		return [(getderiv(root, entry.first, chart).decode('utf8'),
 * 				entry.second) for entry in chart.rankededges[root]]             # <<<<<<<<<<<<<<
 * 	return None
 * 
 */
      }
    } /* exit inner scope */
    __pyx_r = __pyx_t_1;
    __pyx_t_1 = 0;
    goto __pyx_L0;

    /* "discodop/kbest.pyx":248
 * 			break
 * 	chart.rankededges[root] = tmp
 * 	if derivs:             # <<<<<<<<<<<<<<
 * 		# for entry in chart.rankededges[root]:
 * 		# 	chart.derivations.push_back(getderiv(root, entry.first, chart))
 */
  }

  /* "discodop/kbest.pyx":253
 * 		return [(getderiv(root, entry.first, chart).decode('utf8'),
 * 				entry.second) for entry in chart.rankededges[root]]
 * 	return None             # <<<<<<<<<<<<<<
 * 
 * __all__ = ['getderiv', 'lazykbest']
 */
  __Pyx_XDECREF(__pyx_r);
  __Pyx_INCREF(Py_None);
  __pyx_r = Py_None;
  goto __pyx_L0;

  /* "discodop/kbest.pyx":221
 * 
 * 
 * def lazykbest(Chart chart, int k, bint derivs=True):             # <<<<<<<<<<<<<<
 * 	"""Wrapper function to run ``lazykthbest``.
 * 
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_2);
  __Pyx_XDECREF(__pyx_t_3);
  __Pyx_XDECREF(__pyx_t_10);
  __Pyx_AddTraceback("discodop.kbest.lazykbest", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = NULL;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "cpython/array.pxd":93
 *             __data_union data
 * 
 *         def __getbuffer__(self, Py_buffer* info, int flags):             # <<<<<<<<<<<<<<
 *             # This implementation of getbuffer is geared towards Cython
 *             # requirements, and does not yet fullfill the PEP.
 */

/* Python wrapper */
static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/
static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) {
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0);
  __pyx_r = __pyx_pf_7cpython_5array_5array___getbuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags));

  /* function exit code */
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags) {
  PyObject *__pyx_v_item_count = NULL;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  char *__pyx_t_2;
  int __pyx_t_3;
  PyObject *__pyx_t_4 = NULL;
  Py_ssize_t __pyx_t_5;
  int __pyx_t_6;
  __Pyx_RefNannySetupContext("__getbuffer__", 0);
  if (__pyx_v_info != NULL) {
    __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None);
    __Pyx_GIVEREF(__pyx_v_info->obj);
  }

  /* "cpython/array.pxd":98
 *             # In particular strided access is always provided regardless
 *             # of flags
 *             item_count = Py_SIZE(self)             # <<<<<<<<<<<<<<
 * 
 *             info.suboffsets = NULL
 */
  __pyx_t_1 = PyInt_FromSsize_t(Py_SIZE(((PyObject *)__pyx_v_self))); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 98, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_v_item_count = __pyx_t_1;
  __pyx_t_1 = 0;

  /* "cpython/array.pxd":100
 *             item_count = Py_SIZE(self)
 * 
 *             info.suboffsets = NULL             # <<<<<<<<<<<<<<
 *             info.buf = self.data.as_chars
 *             info.readonly = 0
 */
  __pyx_v_info->suboffsets = NULL;

  /* "cpython/array.pxd":101
 * 
 *             info.suboffsets = NULL
 *             info.buf = self.data.as_chars             # <<<<<<<<<<<<<<
 *             info.readonly = 0
 *             info.ndim = 1
 */
  __pyx_t_2 = __pyx_v_self->data.as_chars;
  __pyx_v_info->buf = __pyx_t_2;

  /* "cpython/array.pxd":102
 *             info.suboffsets = NULL
 *             info.buf = self.data.as_chars
 *             info.readonly = 0             # <<<<<<<<<<<<<<
 *             info.ndim = 1
 *             info.itemsize = self.ob_descr.itemsize   # e.g. sizeof(float)
 */
  __pyx_v_info->readonly = 0;

  /* "cpython/array.pxd":103
 *             info.buf = self.data.as_chars
 *             info.readonly = 0
 *             info.ndim = 1             # <<<<<<<<<<<<<<
 *             info.itemsize = self.ob_descr.itemsize   # e.g. sizeof(float)
 *             info.len = info.itemsize * item_count
 */
  __pyx_v_info->ndim = 1;

  /* "cpython/array.pxd":104
 *             info.readonly = 0
 *             info.ndim = 1
 *             info.itemsize = self.ob_descr.itemsize   # e.g. sizeof(float)             # <<<<<<<<<<<<<<
 *             info.len = info.itemsize * item_count
 * 
 */
  __pyx_t_3 = __pyx_v_self->ob_descr->itemsize;
  __pyx_v_info->itemsize = __pyx_t_3;

  /* "cpython/array.pxd":105
 *             info.ndim = 1
 *             info.itemsize = self.ob_descr.itemsize   # e.g. sizeof(float)
 *             info.len = info.itemsize * item_count             # <<<<<<<<<<<<<<
 * 
 *             info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2)
 */
  __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_info->itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 105, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_v_item_count); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 105, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_4); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 105, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
  __pyx_v_info->len = __pyx_t_5;

  /* "cpython/array.pxd":107
 *             info.len = info.itemsize * item_count
 * 
 *             info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2)             # <<<<<<<<<<<<<<
 *             if not info.shape:
 *                 raise MemoryError()
 */
  __pyx_v_info->shape = ((Py_ssize_t *)PyObject_Malloc(((sizeof(Py_ssize_t)) + 2)));

  /* "cpython/array.pxd":108
 * 
 *             info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2)
 *             if not info.shape:             # <<<<<<<<<<<<<<
 *                 raise MemoryError()
 *             info.shape[0] = item_count      # constant regardless of resizing
 */
  __pyx_t_6 = ((!(__pyx_v_info->shape != 0)) != 0);
  if (__pyx_t_6) {

    /* "cpython/array.pxd":109
 *             info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2)
 *             if not info.shape:
 *                 raise MemoryError()             # <<<<<<<<<<<<<<
 *             info.shape[0] = item_count      # constant regardless of resizing
 *             info.strides = &info.itemsize
 */
    PyErr_NoMemory(); __PYX_ERR(1, 109, __pyx_L1_error)

    /* "cpython/array.pxd":108
 * 
 *             info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2)
 *             if not info.shape:             # <<<<<<<<<<<<<<
 *                 raise MemoryError()
 *             info.shape[0] = item_count      # constant regardless of resizing
 */
  }

  /* "cpython/array.pxd":110
 *             if not info.shape:
 *                 raise MemoryError()
 *             info.shape[0] = item_count      # constant regardless of resizing             # <<<<<<<<<<<<<<
 *             info.strides = &info.itemsize
 * 
 */
  __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_v_item_count); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 110, __pyx_L1_error)
  (__pyx_v_info->shape[0]) = __pyx_t_5;

  /* "cpython/array.pxd":111
 *                 raise MemoryError()
 *             info.shape[0] = item_count      # constant regardless of resizing
 *             info.strides = &info.itemsize             # <<<<<<<<<<<<<<
 * 
 *             info.format = <char*> (info.shape + 1)
 */
  __pyx_v_info->strides = (&__pyx_v_info->itemsize);

  /* "cpython/array.pxd":113
 *             info.strides = &info.itemsize
 * 
 *             info.format = <char*> (info.shape + 1)             # <<<<<<<<<<<<<<
 *             info.format[0] = self.ob_descr.typecode
 *             info.format[1] = 0
 */
  __pyx_v_info->format = ((char *)(__pyx_v_info->shape + 1));

  /* "cpython/array.pxd":114
 * 
 *             info.format = <char*> (info.shape + 1)
 *             info.format[0] = self.ob_descr.typecode             # <<<<<<<<<<<<<<
 *             info.format[1] = 0
 *             info.obj = self
 */
  __pyx_t_3 = __pyx_v_self->ob_descr->typecode;
  (__pyx_v_info->format[0]) = __pyx_t_3;

  /* "cpython/array.pxd":115
 *             info.format = <char*> (info.shape + 1)
 *             info.format[0] = self.ob_descr.typecode
 *             info.format[1] = 0             # <<<<<<<<<<<<<<
 *             info.obj = self
 * 
 */
  (__pyx_v_info->format[1]) = 0;

  /* "cpython/array.pxd":116
 *             info.format[0] = self.ob_descr.typecode
 *             info.format[1] = 0
 *             info.obj = self             # <<<<<<<<<<<<<<
 * 
 *         def __releasebuffer__(self, Py_buffer* info):
 */
  __Pyx_INCREF(((PyObject *)__pyx_v_self));
  __Pyx_GIVEREF(((PyObject *)__pyx_v_self));
  __Pyx_GOTREF(__pyx_v_info->obj);
  __Pyx_DECREF(__pyx_v_info->obj);
  __pyx_v_info->obj = ((PyObject *)__pyx_v_self);

  /* "cpython/array.pxd":93
 *             __data_union data
 * 
 *         def __getbuffer__(self, Py_buffer* info, int flags):             # <<<<<<<<<<<<<<
 *             # This implementation of getbuffer is geared towards Cython
 *             # requirements, and does not yet fullfill the PEP.
 */

  /* function exit code */
  __pyx_r = 0;
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_4);
  __Pyx_AddTraceback("cpython.array.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = -1;
  if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) {
    __Pyx_GOTREF(__pyx_v_info->obj);
    __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL;
  }
  goto __pyx_L2;
  __pyx_L0:;
  if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) {
    __Pyx_GOTREF(Py_None);
    __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL;
  }
  __pyx_L2:;
  __Pyx_XDECREF(__pyx_v_item_count);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "cpython/array.pxd":118
 *             info.obj = self
 * 
 *         def __releasebuffer__(self, Py_buffer* info):             # <<<<<<<<<<<<<<
 *             PyObject_Free(info.shape)
 * 
 */

/* Python wrapper */
static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/
static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) {
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0);
  __pyx_pf_7cpython_5array_5array_2__releasebuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info));

  /* function exit code */
  __Pyx_RefNannyFinishContext();
}

static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info) {
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__releasebuffer__", 0);

  /* "cpython/array.pxd":119
 * 
 *         def __releasebuffer__(self, Py_buffer* info):
 *             PyObject_Free(info.shape)             # <<<<<<<<<<<<<<
 * 
 *     array newarrayobject(PyTypeObject* type, Py_ssize_t size, arraydescr *descr)
 */
  PyObject_Free(__pyx_v_info->shape);

  /* "cpython/array.pxd":118
 *             info.obj = self
 * 
 *         def __releasebuffer__(self, Py_buffer* info):             # <<<<<<<<<<<<<<
 *             PyObject_Free(info.shape)
 * 
 */

  /* function exit code */
  __Pyx_RefNannyFinishContext();
}

/* "cpython/array.pxd":130
 * 
 * 
 * cdef inline array clone(array template, Py_ssize_t length, bint zero):             # <<<<<<<<<<<<<<
 *     """ fast creation of a new array, given a template array.
 *     type will be same as template.
 */

static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_clone(arrayobject *__pyx_v_template, Py_ssize_t __pyx_v_length, int __pyx_v_zero) {
  arrayobject *__pyx_v_op = NULL;
  arrayobject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  int __pyx_t_2;
  int __pyx_t_3;
  int __pyx_t_4;
  __Pyx_RefNannySetupContext("clone", 0);

  /* "cpython/array.pxd":134
 *     type will be same as template.
 *     if zero is true, new array will be initialized with zeroes."""
 *     op = newarrayobject(Py_TYPE(template), length, template.ob_descr)             # <<<<<<<<<<<<<<
 *     if zero and op is not None:
 *         memset(op.data.as_chars, 0, length * op.ob_descr.itemsize)
 */
  __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_template)), __pyx_v_length, __pyx_v_template->ob_descr)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 134, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_v_op = ((arrayobject *)__pyx_t_1);
  __pyx_t_1 = 0;

  /* "cpython/array.pxd":135
 *     if zero is true, new array will be initialized with zeroes."""
 *     op = newarrayobject(Py_TYPE(template), length, template.ob_descr)
 *     if zero and op is not None:             # <<<<<<<<<<<<<<
 *         memset(op.data.as_chars, 0, length * op.ob_descr.itemsize)
 *     return op
 */
  __pyx_t_3 = (__pyx_v_zero != 0);
  if (__pyx_t_3) {
  } else {
    __pyx_t_2 = __pyx_t_3;
    goto __pyx_L4_bool_binop_done;
  }
  __pyx_t_3 = (((PyObject *)__pyx_v_op) != Py_None);
  __pyx_t_4 = (__pyx_t_3 != 0);
  __pyx_t_2 = __pyx_t_4;
  __pyx_L4_bool_binop_done:;
  if (__pyx_t_2) {

    /* "cpython/array.pxd":136
 *     op = newarrayobject(Py_TYPE(template), length, template.ob_descr)
 *     if zero and op is not None:
 *         memset(op.data.as_chars, 0, length * op.ob_descr.itemsize)             # <<<<<<<<<<<<<<
 *     return op
 * 
 */
    memset(__pyx_v_op->data.as_chars, 0, (__pyx_v_length * __pyx_v_op->ob_descr->itemsize));

    /* "cpython/array.pxd":135
 *     if zero is true, new array will be initialized with zeroes."""
 *     op = newarrayobject(Py_TYPE(template), length, template.ob_descr)
 *     if zero and op is not None:             # <<<<<<<<<<<<<<
 *         memset(op.data.as_chars, 0, length * op.ob_descr.itemsize)
 *     return op
 */
  }

  /* "cpython/array.pxd":137
 *     if zero and op is not None:
 *         memset(op.data.as_chars, 0, length * op.ob_descr.itemsize)
 *     return op             # <<<<<<<<<<<<<<
 * 
 * cdef inline array copy(array self):
 */
  __Pyx_XDECREF(((PyObject *)__pyx_r));
  __Pyx_INCREF(((PyObject *)__pyx_v_op));
  __pyx_r = __pyx_v_op;
  goto __pyx_L0;

  /* "cpython/array.pxd":130
 * 
 * 
 * cdef inline array clone(array template, Py_ssize_t length, bint zero):             # <<<<<<<<<<<<<<
 *     """ fast creation of a new array, given a template array.
 *     type will be same as template.
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_AddTraceback("cpython.array.clone", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XDECREF((PyObject *)__pyx_v_op);
  __Pyx_XGIVEREF((PyObject *)__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "cpython/array.pxd":139
 *     return op
 * 
 * cdef inline array copy(array self):             # <<<<<<<<<<<<<<
 *     """ make a copy of an array. """
 *     op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr)
 */

static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_copy(arrayobject *__pyx_v_self) {
  arrayobject *__pyx_v_op = NULL;
  arrayobject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannySetupContext("copy", 0);

  /* "cpython/array.pxd":141
 * cdef inline array copy(array self):
 *     """ make a copy of an array. """
 *     op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr)             # <<<<<<<<<<<<<<
 *     memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize)
 *     return op
 */
  __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_self)), Py_SIZE(((PyObject *)__pyx_v_self)), __pyx_v_self->ob_descr)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 141, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_v_op = ((arrayobject *)__pyx_t_1);
  __pyx_t_1 = 0;

  /* "cpython/array.pxd":142
 *     """ make a copy of an array. """
 *     op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr)
 *     memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize)             # <<<<<<<<<<<<<<
 *     return op
 * 
 */
  memcpy(__pyx_v_op->data.as_chars, __pyx_v_self->data.as_chars, (Py_SIZE(((PyObject *)__pyx_v_op)) * __pyx_v_op->ob_descr->itemsize));

  /* "cpython/array.pxd":143
 *     op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr)
 *     memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize)
 *     return op             # <<<<<<<<<<<<<<
 * 
 * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1:
 */
  __Pyx_XDECREF(((PyObject *)__pyx_r));
  __Pyx_INCREF(((PyObject *)__pyx_v_op));
  __pyx_r = __pyx_v_op;
  goto __pyx_L0;

  /* "cpython/array.pxd":139
 *     return op
 * 
 * cdef inline array copy(array self):             # <<<<<<<<<<<<<<
 *     """ make a copy of an array. """
 *     op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr)
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_AddTraceback("cpython.array.copy", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XDECREF((PyObject *)__pyx_v_op);
  __Pyx_XGIVEREF((PyObject *)__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "cpython/array.pxd":145
 *     return op
 * 
 * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1:             # <<<<<<<<<<<<<<
 *     """ efficent appending of new stuff of same type
 *     (e.g. of same array type)
 */

static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *__pyx_v_self, char *__pyx_v_stuff, Py_ssize_t __pyx_v_n) {
  Py_ssize_t __pyx_v_itemsize;
  Py_ssize_t __pyx_v_origsize;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  __Pyx_RefNannySetupContext("extend_buffer", 0);

  /* "cpython/array.pxd":149
 *     (e.g. of same array type)
 *     n: number of elements (not number of bytes!) """
 *     cdef Py_ssize_t itemsize = self.ob_descr.itemsize             # <<<<<<<<<<<<<<
 *     cdef Py_ssize_t origsize = Py_SIZE(self)
 *     resize_smart(self, origsize + n)
 */
  __pyx_t_1 = __pyx_v_self->ob_descr->itemsize;
  __pyx_v_itemsize = __pyx_t_1;

  /* "cpython/array.pxd":150
 *     n: number of elements (not number of bytes!) """
 *     cdef Py_ssize_t itemsize = self.ob_descr.itemsize
 *     cdef Py_ssize_t origsize = Py_SIZE(self)             # <<<<<<<<<<<<<<
 *     resize_smart(self, origsize + n)
 *     memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize)
 */
  __pyx_v_origsize = Py_SIZE(((PyObject *)__pyx_v_self));

  /* "cpython/array.pxd":151
 *     cdef Py_ssize_t itemsize = self.ob_descr.itemsize
 *     cdef Py_ssize_t origsize = Py_SIZE(self)
 *     resize_smart(self, origsize + n)             # <<<<<<<<<<<<<<
 *     memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize)
 *     return 0
 */
  __pyx_t_1 = resize_smart(__pyx_v_self, (__pyx_v_origsize + __pyx_v_n)); if (unlikely(__pyx_t_1 == -1)) __PYX_ERR(1, 151, __pyx_L1_error)

  /* "cpython/array.pxd":152
 *     cdef Py_ssize_t origsize = Py_SIZE(self)
 *     resize_smart(self, origsize + n)
 *     memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize)             # <<<<<<<<<<<<<<
 *     return 0
 * 
 */
  memcpy((__pyx_v_self->data.as_chars + (__pyx_v_origsize * __pyx_v_itemsize)), __pyx_v_stuff, (__pyx_v_n * __pyx_v_itemsize));

  /* "cpython/array.pxd":153
 *     resize_smart(self, origsize + n)
 *     memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize)
 *     return 0             # <<<<<<<<<<<<<<
 * 
 * cdef inline int extend(array self, array other) except -1:
 */
  __pyx_r = 0;
  goto __pyx_L0;

  /* "cpython/array.pxd":145
 *     return op
 * 
 * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1:             # <<<<<<<<<<<<<<
 *     """ efficent appending of new stuff of same type
 *     (e.g. of same array type)
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_AddTraceback("cpython.array.extend_buffer", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = -1;
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "cpython/array.pxd":155
 *     return 0
 * 
 * cdef inline int extend(array self, array other) except -1:             # <<<<<<<<<<<<<<
 *     """ extend array with data from another array; types must match. """
 *     if self.ob_descr.typecode != other.ob_descr.typecode:
 */

static CYTHON_INLINE int __pyx_f_7cpython_5array_extend(arrayobject *__pyx_v_self, arrayobject *__pyx_v_other) {
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  int __pyx_t_2;
  __Pyx_RefNannySetupContext("extend", 0);

  /* "cpython/array.pxd":157
 * cdef inline int extend(array self, array other) except -1:
 *     """ extend array with data from another array; types must match. """
 *     if self.ob_descr.typecode != other.ob_descr.typecode:             # <<<<<<<<<<<<<<
 *         PyErr_BadArgument()
 *     return extend_buffer(self, other.data.as_chars, Py_SIZE(other))
 */
  __pyx_t_1 = ((__pyx_v_self->ob_descr->typecode != __pyx_v_other->ob_descr->typecode) != 0);
  if (__pyx_t_1) {

    /* "cpython/array.pxd":158
 *     """ extend array with data from another array; types must match. """
 *     if self.ob_descr.typecode != other.ob_descr.typecode:
 *         PyErr_BadArgument()             # <<<<<<<<<<<<<<
 *     return extend_buffer(self, other.data.as_chars, Py_SIZE(other))
 * 
 */
    __pyx_t_2 = PyErr_BadArgument(); if (unlikely(__pyx_t_2 == 0)) __PYX_ERR(1, 158, __pyx_L1_error)

    /* "cpython/array.pxd":157
 * cdef inline int extend(array self, array other) except -1:
 *     """ extend array with data from another array; types must match. """
 *     if self.ob_descr.typecode != other.ob_descr.typecode:             # <<<<<<<<<<<<<<
 *         PyErr_BadArgument()
 *     return extend_buffer(self, other.data.as_chars, Py_SIZE(other))
 */
  }

  /* "cpython/array.pxd":159
 *     if self.ob_descr.typecode != other.ob_descr.typecode:
 *         PyErr_BadArgument()
 *     return extend_buffer(self, other.data.as_chars, Py_SIZE(other))             # <<<<<<<<<<<<<<
 * 
 * cdef inline void zero(array self):
 */
  __pyx_t_2 = __pyx_f_7cpython_5array_extend_buffer(__pyx_v_self, __pyx_v_other->data.as_chars, Py_SIZE(((PyObject *)__pyx_v_other))); if (unlikely(__pyx_t_2 == -1)) __PYX_ERR(1, 159, __pyx_L1_error)
  __pyx_r = __pyx_t_2;
  goto __pyx_L0;

  /* "cpython/array.pxd":155
 *     return 0
 * 
 * cdef inline int extend(array self, array other) except -1:             # <<<<<<<<<<<<<<
 *     """ extend array with data from another array; types must match. """
 *     if self.ob_descr.typecode != other.ob_descr.typecode:
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_AddTraceback("cpython.array.extend", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = -1;
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "cpython/array.pxd":161
 *     return extend_buffer(self, other.data.as_chars, Py_SIZE(other))
 * 
 * cdef inline void zero(array self):             # <<<<<<<<<<<<<<
 *     """ set all elements of array to zero. """
 *     memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize)
 */

static CYTHON_INLINE void __pyx_f_7cpython_5array_zero(arrayobject *__pyx_v_self) {
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("zero", 0);

  /* "cpython/array.pxd":163
 * cdef inline void zero(array self):
 *     """ set all elements of array to zero. """
 *     memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize)             # <<<<<<<<<<<<<<
 */
  memset(__pyx_v_self->data.as_chars, 0, (Py_SIZE(((PyObject *)__pyx_v_self)) * __pyx_v_self->ob_descr->itemsize));

  /* "cpython/array.pxd":161
 *     return extend_buffer(self, other.data.as_chars, Py_SIZE(other))
 * 
 * cdef inline void zero(array self):             # <<<<<<<<<<<<<<
 *     """ set all elements of array to zero. """
 *     memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize)
 */

  /* function exit code */
  __Pyx_RefNannyFinishContext();
}

/* "containers.pxd":705
 * 
 * # defined here because circular import.
 * cdef inline size_t cellidx(short start, short end, short lensent,             # <<<<<<<<<<<<<<
 * 		Label nonterminals):
 * 	"""Return an index for a regular three dimensional array.
 */

static CYTHON_INLINE size_t __pyx_f_8discodop_10containers_cellidx(short __pyx_v_start, short __pyx_v_end, short __pyx_v_lensent, Label __pyx_v_nonterminals) {
  size_t __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("cellidx", 0);

  /* "containers.pxd":710
 * 
 * 	``chart[start][end][0] => chart[idx]`` """
 * 	return (start * lensent + (end - 1)) * nonterminals             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = (((__pyx_v_start * __pyx_v_lensent) + (__pyx_v_end - 1)) * __pyx_v_nonterminals);
  goto __pyx_L0;

  /* "containers.pxd":705
 * 
 * # defined here because circular import.
 * cdef inline size_t cellidx(short start, short end, short lensent,             # <<<<<<<<<<<<<<
 * 		Label nonterminals):
 * 	"""Return an index for a regular three dimensional array.
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "containers.pxd":713
 * 
 * 
 * cdef inline size_t compactcellidx(short start, short end, short lensent,             # <<<<<<<<<<<<<<
 * 		Label nonterminals):
 * 	"""Return an index to a triangular array, given start < end.
 */

static CYTHON_INLINE size_t __pyx_f_8discodop_10containers_compactcellidx(short __pyx_v_start, short __pyx_v_end, short __pyx_v_lensent, Label __pyx_v_nonterminals) {
  size_t __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("compactcellidx", 0);

  /* "containers.pxd":717
 * 	"""Return an index to a triangular array, given start < end.
 * 	The result of this function is the index to chart[start][end][0]."""
 * 	return nonterminals * (lensent * start             # <<<<<<<<<<<<<<
 * 			- ((start - 1) * start / 2) + end - start - 1)
 * 
 */
  __pyx_r = (__pyx_v_nonterminals * (((((__pyx_v_lensent * __pyx_v_start) - (((__pyx_v_start - 1) * __pyx_v_start) / 2)) + __pyx_v_end) - __pyx_v_start) - 1));
  goto __pyx_L0;

  /* "containers.pxd":713
 * 
 * 
 * cdef inline size_t compactcellidx(short start, short end, short lensent,             # <<<<<<<<<<<<<<
 * 		Label nonterminals):
 * 	"""Return an index to a triangular array, given start < end.
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "containers.pxd":724
 * 
 * 
 * cdef inline logprobadd(x, y):             # <<<<<<<<<<<<<<
 * 	""" Add two log probabilities in log space.
 * 
 */

static CYTHON_INLINE PyObject *__pyx_f_8discodop_10containers_logprobadd(PyObject *__pyx_v_x, PyObject *__pyx_v_y) {
  PyObject *__pyx_v_diff = NULL;
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  PyObject *__pyx_t_2 = NULL;
  PyObject *__pyx_t_3 = NULL;
  PyObject *__pyx_t_4 = NULL;
  int __pyx_t_5;
  double __pyx_t_6;
  PyObject *__pyx_t_7 = NULL;
  __Pyx_RefNannySetupContext("logprobadd", 0);

  /* "containers.pxd":734
 * 	:source: https://facwiki.cs.byu.edu/nlp/index.php/Log_Domain_Computations
 * 	"""
 * 	if isinf(x):             # <<<<<<<<<<<<<<
 * 		return y
 * 	elif isinf(y):
 */
  __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_isinf); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 734, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __pyx_t_3 = NULL;
  if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) {
    __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2);
    if (likely(__pyx_t_3)) {
      PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2);
      __Pyx_INCREF(__pyx_t_3);
      __Pyx_INCREF(function);
      __Pyx_DECREF_SET(__pyx_t_2, function);
    }
  }
  if (!__pyx_t_3) {
    __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_x); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 734, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_1);
  } else {
    #if CYTHON_FAST_PYCALL
    if (PyFunction_Check(__pyx_t_2)) {
      PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_x};
      __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 734, __pyx_L1_error)
      __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
      __Pyx_GOTREF(__pyx_t_1);
    } else
    #endif
    #if CYTHON_FAST_PYCCALL
    if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) {
      PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_x};
      __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 734, __pyx_L1_error)
      __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
      __Pyx_GOTREF(__pyx_t_1);
    } else
    #endif
    {
      __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 734, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_4);
      __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL;
      __Pyx_INCREF(__pyx_v_x);
      __Pyx_GIVEREF(__pyx_v_x);
      PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v_x);
      __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 734, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
    }
  }
  __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(2, 734, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  if (__pyx_t_5) {

    /* "containers.pxd":735
 * 	"""
 * 	if isinf(x):
 * 		return y             # <<<<<<<<<<<<<<
 * 	elif isinf(y):
 * 		return x
 */
    __Pyx_XDECREF(__pyx_r);
    __Pyx_INCREF(__pyx_v_y);
    __pyx_r = __pyx_v_y;
    goto __pyx_L0;

    /* "containers.pxd":734
 * 	:source: https://facwiki.cs.byu.edu/nlp/index.php/Log_Domain_Computations
 * 	"""
 * 	if isinf(x):             # <<<<<<<<<<<<<<
 * 		return y
 * 	elif isinf(y):
 */
  }

  /* "containers.pxd":736
 * 	if isinf(x):
 * 		return y
 * 	elif isinf(y):             # <<<<<<<<<<<<<<
 * 		return x
 * 	# If one value is much smaller than the other, keep the larger value.
 */
  __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_isinf); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 736, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __pyx_t_4 = NULL;
  if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) {
    __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2);
    if (likely(__pyx_t_4)) {
      PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2);
      __Pyx_INCREF(__pyx_t_4);
      __Pyx_INCREF(function);
      __Pyx_DECREF_SET(__pyx_t_2, function);
    }
  }
  if (!__pyx_t_4) {
    __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_y); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 736, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_1);
  } else {
    #if CYTHON_FAST_PYCALL
    if (PyFunction_Check(__pyx_t_2)) {
      PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_v_y};
      __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 736, __pyx_L1_error)
      __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0;
      __Pyx_GOTREF(__pyx_t_1);
    } else
    #endif
    #if CYTHON_FAST_PYCCALL
    if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) {
      PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_v_y};
      __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 736, __pyx_L1_error)
      __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0;
      __Pyx_GOTREF(__pyx_t_1);
    } else
    #endif
    {
      __pyx_t_3 = PyTuple_New(1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 736, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __pyx_t_4 = NULL;
      __Pyx_INCREF(__pyx_v_y);
      __Pyx_GIVEREF(__pyx_v_y);
      PyTuple_SET_ITEM(__pyx_t_3, 0+1, __pyx_v_y);
      __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 736, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
    }
  }
  __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(2, 736, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  if (__pyx_t_5) {

    /* "containers.pxd":737
 * 		return y
 * 	elif isinf(y):
 * 		return x             # <<<<<<<<<<<<<<
 * 	# If one value is much smaller than the other, keep the larger value.
 * 	elif x < (y - 460):  # log(1e200)
 */
    __Pyx_XDECREF(__pyx_r);
    __Pyx_INCREF(__pyx_v_x);
    __pyx_r = __pyx_v_x;
    goto __pyx_L0;

    /* "containers.pxd":736
 * 	if isinf(x):
 * 		return y
 * 	elif isinf(y):             # <<<<<<<<<<<<<<
 * 		return x
 * 	# If one value is much smaller than the other, keep the larger value.
 */
  }

  /* "containers.pxd":739
 * 		return x
 * 	# If one value is much smaller than the other, keep the larger value.
 * 	elif x < (y - 460):  # log(1e200)             # <<<<<<<<<<<<<<
 * 		return y
 * 	elif y < (x - 460):  # log(1e200)
 */
  __pyx_t_1 = __Pyx_PyInt_SubtractObjC(__pyx_v_y, __pyx_int_460, 0x1CC, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 739, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = PyObject_RichCompare(__pyx_v_x, __pyx_t_1, Py_LT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 739, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(2, 739, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  if (__pyx_t_5) {

    /* "containers.pxd":740
 * 	# If one value is much smaller than the other, keep the larger value.
 * 	elif x < (y - 460):  # log(1e200)
 * 		return y             # <<<<<<<<<<<<<<
 * 	elif y < (x - 460):  # log(1e200)
 * 		return x
 */
    __Pyx_XDECREF(__pyx_r);
    __Pyx_INCREF(__pyx_v_y);
    __pyx_r = __pyx_v_y;
    goto __pyx_L0;

    /* "containers.pxd":739
 * 		return x
 * 	# If one value is much smaller than the other, keep the larger value.
 * 	elif x < (y - 460):  # log(1e200)             # <<<<<<<<<<<<<<
 * 		return y
 * 	elif y < (x - 460):  # log(1e200)
 */
  }

  /* "containers.pxd":741
 * 	elif x < (y - 460):  # log(1e200)
 * 		return y
 * 	elif y < (x - 460):  # log(1e200)             # <<<<<<<<<<<<<<
 * 		return x
 * 	diff = y - x
 */
  __pyx_t_2 = __Pyx_PyInt_SubtractObjC(__pyx_v_x, __pyx_int_460, 0x1CC, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 741, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __pyx_t_1 = PyObject_RichCompare(__pyx_v_y, __pyx_t_2, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 741, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(2, 741, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  if (__pyx_t_5) {

    /* "containers.pxd":742
 * 		return y
 * 	elif y < (x - 460):  # log(1e200)
 * 		return x             # <<<<<<<<<<<<<<
 * 	diff = y - x
 * 	assert not isinf(diff)
 */
    __Pyx_XDECREF(__pyx_r);
    __Pyx_INCREF(__pyx_v_x);
    __pyx_r = __pyx_v_x;
    goto __pyx_L0;

    /* "containers.pxd":741
 * 	elif x < (y - 460):  # log(1e200)
 * 		return y
 * 	elif y < (x - 460):  # log(1e200)             # <<<<<<<<<<<<<<
 * 		return x
 * 	diff = y - x
 */
  }

  /* "containers.pxd":743
 * 	elif y < (x - 460):  # log(1e200)
 * 		return x
 * 	diff = y - x             # <<<<<<<<<<<<<<
 * 	assert not isinf(diff)
 * 	if isinf(exp(diff)):  # difference is too large
 */
  __pyx_t_1 = PyNumber_Subtract(__pyx_v_y, __pyx_v_x); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 743, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_v_diff = __pyx_t_1;
  __pyx_t_1 = 0;

  /* "containers.pxd":744
 * 		return x
 * 	diff = y - x
 * 	assert not isinf(diff)             # <<<<<<<<<<<<<<
 * 	if isinf(exp(diff)):  # difference is too large
 * 		return x if x > y else y
 */
  #ifndef CYTHON_WITHOUT_ASSERTIONS
  if (unlikely(!Py_OptimizeFlag)) {
    __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_isinf); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 744, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_2);
    __pyx_t_3 = NULL;
    if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) {
      __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2);
      if (likely(__pyx_t_3)) {
        PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2);
        __Pyx_INCREF(__pyx_t_3);
        __Pyx_INCREF(function);
        __Pyx_DECREF_SET(__pyx_t_2, function);
      }
    }
    if (!__pyx_t_3) {
      __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_diff); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 744, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
    } else {
      #if CYTHON_FAST_PYCALL
      if (PyFunction_Check(__pyx_t_2)) {
        PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_diff};
        __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 744, __pyx_L1_error)
        __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
        __Pyx_GOTREF(__pyx_t_1);
      } else
      #endif
      #if CYTHON_FAST_PYCCALL
      if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) {
        PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_diff};
        __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 744, __pyx_L1_error)
        __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
        __Pyx_GOTREF(__pyx_t_1);
      } else
      #endif
      {
        __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 744, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_4);
        __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL;
        __Pyx_INCREF(__pyx_v_diff);
        __Pyx_GIVEREF(__pyx_v_diff);
        PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v_diff);
        __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 744, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_1);
        __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
      }
    }
    __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
    __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(2, 744, __pyx_L1_error)
    __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
    if (unlikely(!((!__pyx_t_5) != 0))) {
      PyErr_SetNone(PyExc_AssertionError);
      __PYX_ERR(2, 744, __pyx_L1_error)
    }
  }
  #endif

  /* "containers.pxd":745
 * 	diff = y - x
 * 	assert not isinf(diff)
 * 	if isinf(exp(diff)):  # difference is too large             # <<<<<<<<<<<<<<
 * 		return x if x > y else y
 * 	# otherwise return the sum.
 */
  __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_isinf); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 745, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_v_diff); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(2, 745, __pyx_L1_error)
  __pyx_t_4 = PyFloat_FromDouble(exp(__pyx_t_6)); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 745, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  __pyx_t_3 = NULL;
  if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) {
    __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2);
    if (likely(__pyx_t_3)) {
      PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2);
      __Pyx_INCREF(__pyx_t_3);
      __Pyx_INCREF(function);
      __Pyx_DECREF_SET(__pyx_t_2, function);
    }
  }
  if (!__pyx_t_3) {
    __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 745, __pyx_L1_error)
    __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
    __Pyx_GOTREF(__pyx_t_1);
  } else {
    #if CYTHON_FAST_PYCALL
    if (PyFunction_Check(__pyx_t_2)) {
      PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_t_4};
      __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 745, __pyx_L1_error)
      __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
      __Pyx_GOTREF(__pyx_t_1);
      __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
    } else
    #endif
    #if CYTHON_FAST_PYCCALL
    if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) {
      PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_t_4};
      __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 745, __pyx_L1_error)
      __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
      __Pyx_GOTREF(__pyx_t_1);
      __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
    } else
    #endif
    {
      __pyx_t_7 = PyTuple_New(1+1); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 745, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_7);
      __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __pyx_t_3 = NULL;
      __Pyx_GIVEREF(__pyx_t_4);
      PyTuple_SET_ITEM(__pyx_t_7, 0+1, __pyx_t_4);
      __pyx_t_4 = 0;
      __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 745, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
    }
  }
  __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(2, 745, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  if (__pyx_t_5) {

    /* "containers.pxd":746
 * 	assert not isinf(diff)
 * 	if isinf(exp(diff)):  # difference is too large
 * 		return x if x > y else y             # <<<<<<<<<<<<<<
 * 	# otherwise return the sum.
 * 	return x + log(1.0 + exp(diff))
 */
    __Pyx_XDECREF(__pyx_r);
    __pyx_t_2 = PyObject_RichCompare(__pyx_v_x, __pyx_v_y, Py_GT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 746, __pyx_L1_error)
    __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(2, 746, __pyx_L1_error)
    __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
    if (__pyx_t_5) {
      __Pyx_INCREF(__pyx_v_x);
      __pyx_t_1 = __pyx_v_x;
    } else {
      __Pyx_INCREF(__pyx_v_y);
      __pyx_t_1 = __pyx_v_y;
    }
    __pyx_r = __pyx_t_1;
    __pyx_t_1 = 0;
    goto __pyx_L0;

    /* "containers.pxd":745
 * 	diff = y - x
 * 	assert not isinf(diff)
 * 	if isinf(exp(diff)):  # difference is too large             # <<<<<<<<<<<<<<
 * 		return x if x > y else y
 * 	# otherwise return the sum.
 */
  }

  /* "containers.pxd":748
 * 		return x if x > y else y
 * 	# otherwise return the sum.
 * 	return x + log(1.0 + exp(diff))             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_v_diff); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(2, 748, __pyx_L1_error)
  __pyx_t_1 = PyFloat_FromDouble(log((1.0 + exp(__pyx_t_6)))); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 748, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = PyNumber_Add(__pyx_v_x, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 748, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_r = __pyx_t_2;
  __pyx_t_2 = 0;
  goto __pyx_L0;

  /* "containers.pxd":724
 * 
 * 
 * cdef inline logprobadd(x, y):             # <<<<<<<<<<<<<<
 * 	""" Add two log probabilities in log space.
 * 
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_2);
  __Pyx_XDECREF(__pyx_t_3);
  __Pyx_XDECREF(__pyx_t_4);
  __Pyx_XDECREF(__pyx_t_7);
  __Pyx_AddTraceback("discodop.containers.logprobadd", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XDECREF(__pyx_v_diff);
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "containers.pxd":751
 * 
 * 
 * cdef inline double logprobsum(vector[Prob]& logprobs):             # <<<<<<<<<<<<<<
 * 	"""Sum a list of log probabilities producing a regular probability.
 * 
 */

static CYTHON_INLINE double __pyx_f_8discodop_10containers_logprobsum(std::vector<Prob>  &__pyx_v_logprobs) {
  double __pyx_v_maxprob;
  double __pyx_v_result;
  PyObject *__pyx_v_prob = NULL;
  double __pyx_r;
  __Pyx_RefNannyDeclarations
  std::vector<Prob> ::iterator __pyx_t_1;
  Prob __pyx_t_2;
  PyObject *__pyx_t_3 = NULL;
  PyObject *__pyx_t_4 = NULL;
  int __pyx_t_5;
  double __pyx_t_6;
  __Pyx_RefNannySetupContext("logprobsum", 0);

  /* "containers.pxd":769
 * 	# maxprob = max(logprobs)
 * 	# return exp(maxprob) * fsum([exp(prob - maxprob) for prob in logprobs])
 * 	cdef double maxprob = -800             # <<<<<<<<<<<<<<
 * 	cdef double result = 0
 * 	for prob in logprobs:
 */
  __pyx_v_maxprob = -800.0;

  /* "containers.pxd":770
 * 	# return exp(maxprob) * fsum([exp(prob - maxprob) for prob in logprobs])
 * 	cdef double maxprob = -800
 * 	cdef double result = 0             # <<<<<<<<<<<<<<
 * 	for prob in logprobs:
 * 		if prob <= maxprob:
 */
  __pyx_v_result = 0.0;

  /* "containers.pxd":771
 * 	cdef double maxprob = -800
 * 	cdef double result = 0
 * 	for prob in logprobs:             # <<<<<<<<<<<<<<
 * 		if prob <= maxprob:
 * 			result += exp(prob - maxprob)
 */
  __pyx_t_1 = __pyx_v_logprobs.begin();
  for (;;) {
    if (!(__pyx_t_1 != __pyx_v_logprobs.end())) break;
    __pyx_t_2 = *__pyx_t_1;
    ++__pyx_t_1;
    __pyx_t_3 = PyFloat_FromDouble(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 771, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_3);
    __Pyx_XDECREF_SET(__pyx_v_prob, __pyx_t_3);
    __pyx_t_3 = 0;

    /* "containers.pxd":772
 * 	cdef double result = 0
 * 	for prob in logprobs:
 * 		if prob <= maxprob:             # <<<<<<<<<<<<<<
 * 			result += exp(prob - maxprob)
 * 		else:
 */
    __pyx_t_3 = PyFloat_FromDouble(__pyx_v_maxprob); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 772, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_3);
    __pyx_t_4 = PyObject_RichCompare(__pyx_v_prob, __pyx_t_3, Py_LE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 772, __pyx_L1_error)
    __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
    __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(2, 772, __pyx_L1_error)
    __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
    if (__pyx_t_5) {

      /* "containers.pxd":773
 * 	for prob in logprobs:
 * 		if prob <= maxprob:
 * 			result += exp(prob - maxprob)             # <<<<<<<<<<<<<<
 * 		else:
 * 			result *= exp(maxprob - prob)
 */
      __pyx_t_4 = PyFloat_FromDouble(__pyx_v_maxprob); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 773, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_4);
      __pyx_t_3 = PyNumber_Subtract(__pyx_v_prob, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 773, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
      __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(2, 773, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
      __pyx_v_result = (__pyx_v_result + exp(__pyx_t_6));

      /* "containers.pxd":772
 * 	cdef double result = 0
 * 	for prob in logprobs:
 * 		if prob <= maxprob:             # <<<<<<<<<<<<<<
 * 			result += exp(prob - maxprob)
 * 		else:
 */
      goto __pyx_L5;
    }

    /* "containers.pxd":775
 * 			result += exp(prob - maxprob)
 * 		else:
 * 			result *= exp(maxprob - prob)             # <<<<<<<<<<<<<<
 * 			result += 1.0
 * 			maxprob = prob
 */
    /*else*/ {
      __pyx_t_3 = PyFloat_FromDouble(__pyx_v_maxprob); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 775, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_3);
      __pyx_t_4 = PyNumber_Subtract(__pyx_t_3, __pyx_v_prob); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 775, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_4);
      __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
      __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_t_4); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(2, 775, __pyx_L1_error)
      __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
      __pyx_v_result = (__pyx_v_result * exp(__pyx_t_6));

      /* "containers.pxd":776
 * 		else:
 * 			result *= exp(maxprob - prob)
 * 			result += 1.0             # <<<<<<<<<<<<<<
 * 			maxprob = prob
 * 	return exp(maxprob) * result
 */
      __pyx_v_result = (__pyx_v_result + 1.0);

      /* "containers.pxd":777
 * 			result *= exp(maxprob - prob)
 * 			result += 1.0
 * 			maxprob = prob             # <<<<<<<<<<<<<<
 * 	return exp(maxprob) * result
 * 
 */
      __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_v_prob); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(2, 777, __pyx_L1_error)
      __pyx_v_maxprob = __pyx_t_6;
    }
    __pyx_L5:;

    /* "containers.pxd":771
 * 	cdef double maxprob = -800
 * 	cdef double result = 0
 * 	for prob in logprobs:             # <<<<<<<<<<<<<<
 * 		if prob <= maxprob:
 * 			result += exp(prob - maxprob)
 */
  }

  /* "containers.pxd":778
 * 			result += 1.0
 * 			maxprob = prob
 * 	return exp(maxprob) * result             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = (exp(__pyx_v_maxprob) * __pyx_v_result);
  goto __pyx_L0;

  /* "containers.pxd":751
 * 
 * 
 * cdef inline double logprobsum(vector[Prob]& logprobs):             # <<<<<<<<<<<<<<
 * 	"""Sum a list of log probabilities producing a regular probability.
 * 
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_3);
  __Pyx_XDECREF(__pyx_t_4);
  __Pyx_WriteUnraisable("discodop.containers.logprobsum", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XDECREF(__pyx_v_prob);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "containers.pxd":781
 * 
 * 
 * cdef inline str yieldranges(list leaves):             # <<<<<<<<<<<<<<
 * 	"""Convert a sorted list of indices into a string with intervals.
 * 
 */

static CYTHON_INLINE PyObject *__pyx_f_8discodop_10containers_yieldranges(PyObject *__pyx_v_leaves) {
  PyObject *__pyx_v_yields = 0;
  int __pyx_v_a;
  int __pyx_v_start;
  int __pyx_v_prev;
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  Py_ssize_t __pyx_t_2;
  PyObject *__pyx_t_3 = NULL;
  int __pyx_t_4;
  int __pyx_t_5;
  PyObject *__pyx_t_6 = NULL;
  PyObject *__pyx_t_7 = NULL;
  int __pyx_t_8;
  __Pyx_RefNannySetupContext("yieldranges", 0);

  /* "containers.pxd":789
 * 	>>> yieldranges([0, 1, 2, 3, 4])
 * 	'0:1= 2:4='"""
 * 	cdef list yields = []             # <<<<<<<<<<<<<<
 * 	cdef int a, start = -2, prev = -2
 * 	for a in leaves:
 */
  __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 789, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_v_yields = ((PyObject*)__pyx_t_1);
  __pyx_t_1 = 0;

  /* "containers.pxd":790
 * 	'0:1= 2:4='"""
 * 	cdef list yields = []
 * 	cdef int a, start = -2, prev = -2             # <<<<<<<<<<<<<<
 * 	for a in leaves:
 * 		if a - 1 != prev:
 */
  __pyx_v_start = -2;
  __pyx_v_prev = -2;

  /* "containers.pxd":791
 * 	cdef list yields = []
 * 	cdef int a, start = -2, prev = -2
 * 	for a in leaves:             # <<<<<<<<<<<<<<
 * 		if a - 1 != prev:
 * 			if prev != -2:
 */
  if (unlikely(__pyx_v_leaves == Py_None)) {
    PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable");
    __PYX_ERR(2, 791, __pyx_L1_error)
  }
  __pyx_t_1 = __pyx_v_leaves; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0;
  for (;;) {
    if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break;
    #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
    __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(2, 791, __pyx_L1_error)
    #else
    __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 791, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_3);
    #endif
    __pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 791, __pyx_L1_error)
    __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
    __pyx_v_a = __pyx_t_4;

    /* "containers.pxd":792
 * 	cdef int a, start = -2, prev = -2
 * 	for a in leaves:
 * 		if a - 1 != prev:             # <<<<<<<<<<<<<<
 * 			if prev != -2:
 * 				yields.append('%d:%d' % (start, prev))
 */
    __pyx_t_5 = (((__pyx_v_a - 1) != __pyx_v_prev) != 0);
    if (__pyx_t_5) {

      /* "containers.pxd":793
 * 	for a in leaves:
 * 		if a - 1 != prev:
 * 			if prev != -2:             # <<<<<<<<<<<<<<
 * 				yields.append('%d:%d' % (start, prev))
 * 			start = a
 */
      __pyx_t_5 = ((__pyx_v_prev != -2L) != 0);
      if (__pyx_t_5) {

        /* "containers.pxd":794
 * 		if a - 1 != prev:
 * 			if prev != -2:
 * 				yields.append('%d:%d' % (start, prev))             # <<<<<<<<<<<<<<
 * 			start = a
 * 		prev = a
 */
        __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_start); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 794, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_3);
        __pyx_t_6 = __Pyx_PyInt_From_int(__pyx_v_prev); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 794, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_6);
        __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 794, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_7);
        __Pyx_GIVEREF(__pyx_t_3);
        PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3);
        __Pyx_GIVEREF(__pyx_t_6);
        PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_6);
        __pyx_t_3 = 0;
        __pyx_t_6 = 0;
        __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_d_d, __pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 794, __pyx_L1_error)
        __Pyx_GOTREF(__pyx_t_6);
        __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
        __pyx_t_8 = __Pyx_PyList_Append(__pyx_v_yields, __pyx_t_6); if (unlikely(__pyx_t_8 == -1)) __PYX_ERR(2, 794, __pyx_L1_error)
        __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;

        /* "containers.pxd":793
 * 	for a in leaves:
 * 		if a - 1 != prev:
 * 			if prev != -2:             # <<<<<<<<<<<<<<
 * 				yields.append('%d:%d' % (start, prev))
 * 			start = a
 */
      }

      /* "containers.pxd":795
 * 			if prev != -2:
 * 				yields.append('%d:%d' % (start, prev))
 * 			start = a             # <<<<<<<<<<<<<<
 * 		prev = a
 * 	yields.append('%d:%d' % (start, prev))
 */
      __pyx_v_start = __pyx_v_a;

      /* "containers.pxd":792
 * 	cdef int a, start = -2, prev = -2
 * 	for a in leaves:
 * 		if a - 1 != prev:             # <<<<<<<<<<<<<<
 * 			if prev != -2:
 * 				yields.append('%d:%d' % (start, prev))
 */
    }

    /* "containers.pxd":796
 * 				yields.append('%d:%d' % (start, prev))
 * 			start = a
 * 		prev = a             # <<<<<<<<<<<<<<
 * 	yields.append('%d:%d' % (start, prev))
 * 	return ' '.join(yields)
 */
    __pyx_v_prev = __pyx_v_a;

    /* "containers.pxd":791
 * 	cdef list yields = []
 * 	cdef int a, start = -2, prev = -2
 * 	for a in leaves:             # <<<<<<<<<<<<<<
 * 		if a - 1 != prev:
 * 			if prev != -2:
 */
  }
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;

  /* "containers.pxd":797
 * 			start = a
 * 		prev = a
 * 	yields.append('%d:%d' % (start, prev))             # <<<<<<<<<<<<<<
 * 	return ' '.join(yields)
 * 
 */
  __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_start); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 797, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_6 = __Pyx_PyInt_From_int(__pyx_v_prev); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 797, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_6);
  __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 797, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_7);
  __Pyx_GIVEREF(__pyx_t_1);
  PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_1);
  __Pyx_GIVEREF(__pyx_t_6);
  PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_6);
  __pyx_t_1 = 0;
  __pyx_t_6 = 0;
  __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_d_d, __pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 797, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_6);
  __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
  __pyx_t_8 = __Pyx_PyList_Append(__pyx_v_yields, __pyx_t_6); if (unlikely(__pyx_t_8 == -1)) __PYX_ERR(2, 797, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;

  /* "containers.pxd":798
 * 		prev = a
 * 	yields.append('%d:%d' % (start, prev))
 * 	return ' '.join(yields)             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_6 = PyUnicode_Join(__pyx_kp_u__2, __pyx_v_yields); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 798, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_6);
  __pyx_r = ((PyObject*)__pyx_t_6);
  __pyx_t_6 = 0;
  goto __pyx_L0;

  /* "containers.pxd":781
 * 
 * 
 * cdef inline str yieldranges(list leaves):             # <<<<<<<<<<<<<<
 * 	"""Convert a sorted list of indices into a string with intervals.
 * 
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_3);
  __Pyx_XDECREF(__pyx_t_6);
  __Pyx_XDECREF(__pyx_t_7);
  __Pyx_AddTraceback("discodop.containers.yieldranges", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XDECREF(__pyx_v_yields);
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "containers.pxd":801
 * 
 * 
 * cdef inline short termidx(short x):             # <<<<<<<<<<<<<<
 * 	"""Translate representation for terminal indices."""
 * 	return -x - 1
 */

static CYTHON_INLINE short __pyx_f_8discodop_10containers_termidx(short __pyx_v_x) {
  short __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("termidx", 0);

  /* "containers.pxd":803
 * cdef inline short termidx(short x):
 * 	"""Translate representation for terminal indices."""
 * 	return -x - 1             # <<<<<<<<<<<<<<
 */
  __pyx_r = ((-__pyx_v_x) - 1);
  goto __pyx_L0;

  /* "containers.pxd":801
 * 
 * 
 * cdef inline short termidx(short x):             # <<<<<<<<<<<<<<
 * 	"""Translate representation for terminal indices."""
 * 	return -x - 1
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":60
 * 
 * 
 * cdef inline bint testbit(unsigned_fused vec, uint32_t pos):             # <<<<<<<<<<<<<<
 * 	"""Mask a particular bit, return nonzero if set.
 * 
 */

static CYTHON_INLINE int __pyx_fuse_0__pyx_f_8discodop_3bit_testbit(uint8_t __pyx_v_vec, uint32_t __pyx_v_pos) {
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__pyx_fuse_0testbit", 0);

  /* "bit.pxd":73
 * 			or unsigned_fused is uint16_t
 * 			or unsigned_fused is uint32_t):
 * 		return vec & (1U << pos)             # <<<<<<<<<<<<<<
 * 	else:
 * 		return vec & ((<unsigned_fused>1U) << pos) != 0
 */
  __pyx_r = (__pyx_v_vec & (1U << __pyx_v_pos));
  goto __pyx_L0;

  /* "bit.pxd":60
 * 
 * 
 * cdef inline bint testbit(unsigned_fused vec, uint32_t pos):             # <<<<<<<<<<<<<<
 * 	"""Mask a particular bit, return nonzero if set.
 * 
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

static CYTHON_INLINE int __pyx_fuse_1__pyx_f_8discodop_3bit_testbit(uint16_t __pyx_v_vec, uint32_t __pyx_v_pos) {
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__pyx_fuse_1testbit", 0);

  /* "bit.pxd":73
 * 			or unsigned_fused is uint16_t
 * 			or unsigned_fused is uint32_t):
 * 		return vec & (1U << pos)             # <<<<<<<<<<<<<<
 * 	else:
 * 		return vec & ((<unsigned_fused>1U) << pos) != 0
 */
  __pyx_r = (__pyx_v_vec & (1U << __pyx_v_pos));
  goto __pyx_L0;

  /* "bit.pxd":60
 * 
 * 
 * cdef inline bint testbit(unsigned_fused vec, uint32_t pos):             # <<<<<<<<<<<<<<
 * 	"""Mask a particular bit, return nonzero if set.
 * 
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

static CYTHON_INLINE int __pyx_fuse_2__pyx_f_8discodop_3bit_testbit(uint32_t __pyx_v_vec, uint32_t __pyx_v_pos) {
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__pyx_fuse_2testbit", 0);

  /* "bit.pxd":73
 * 			or unsigned_fused is uint16_t
 * 			or unsigned_fused is uint32_t):
 * 		return vec & (1U << pos)             # <<<<<<<<<<<<<<
 * 	else:
 * 		return vec & ((<unsigned_fused>1U) << pos) != 0
 */
  __pyx_r = (__pyx_v_vec & (1U << __pyx_v_pos));
  goto __pyx_L0;

  /* "bit.pxd":60
 * 
 * 
 * cdef inline bint testbit(unsigned_fused vec, uint32_t pos):             # <<<<<<<<<<<<<<
 * 	"""Mask a particular bit, return nonzero if set.
 * 
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

static CYTHON_INLINE int __pyx_fuse_3__pyx_f_8discodop_3bit_testbit(uint64_t __pyx_v_vec, uint32_t __pyx_v_pos) {
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__pyx_fuse_3testbit", 0);

  /* "bit.pxd":75
 * 		return vec & (1U << pos)
 * 	else:
 * 		return vec & ((<unsigned_fused>1U) << pos) != 0             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = ((__pyx_v_vec & (((uint64_t)1U) << __pyx_v_pos)) != 0);
  goto __pyx_L0;

  /* "bit.pxd":60
 * 
 * 
 * cdef inline bint testbit(unsigned_fused vec, uint32_t pos):             # <<<<<<<<<<<<<<
 * 	"""Mask a particular bit, return nonzero if set.
 * 
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":78
 * 
 * 
 * cdef inline int nextset(uint64_t vec, uint32_t pos):             # <<<<<<<<<<<<<<
 * 	""" Return next set bit starting from pos, -1 if there is none.
 * 
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_nextset(uint64_t __pyx_v_vec, uint32_t __pyx_v_pos) {
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  uint32_t __pyx_t_1;
  __Pyx_RefNannySetupContext("nextset", 0);

  /* "bit.pxd":84
 * 	2
 * 	"""
 * 	return (pos + bit_ctz(vec >> pos)) if (vec >> pos) else -1             # <<<<<<<<<<<<<<
 * 	# mask instead of shift:
 * 	# return __builtin_ffsl(vec & (~0UL << pos)) - 1
 */
  if (((__pyx_v_vec >> __pyx_v_pos) != 0)) {
    __pyx_t_1 = (__pyx_v_pos + bit_ctz((__pyx_v_vec >> __pyx_v_pos)));
  } else {
    __pyx_t_1 = -1;
  }
  __pyx_r = __pyx_t_1;
  goto __pyx_L0;

  /* "bit.pxd":78
 * 
 * 
 * cdef inline int nextset(uint64_t vec, uint32_t pos):             # <<<<<<<<<<<<<<
 * 	""" Return next set bit starting from pos, -1 if there is none.
 * 
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":93
 * 
 * 
 * cdef inline int nextunset(uint64_t vec, uint32_t pos):             # <<<<<<<<<<<<<<
 * 	""" Return next unset bit starting from pos.
 * 
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_nextunset(uint64_t __pyx_v_vec, uint32_t __pyx_v_pos) {
  uint64_t __pyx_v_x;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  size_t __pyx_t_1;
  __Pyx_RefNannySetupContext("nextunset", 0);

  /* "bit.pxd":101
 * 	64
 * 	"""
 * 	cdef uint64_t x = ~vec & (~0UL << pos)             # <<<<<<<<<<<<<<
 * 	return bit_ctz(x) if x else (sizeof(uint64_t) * 8)
 * 
 */
  __pyx_v_x = ((~__pyx_v_vec) & ((~0UL) << __pyx_v_pos));

  /* "bit.pxd":102
 * 	"""
 * 	cdef uint64_t x = ~vec & (~0UL << pos)
 * 	return bit_ctz(x) if x else (sizeof(uint64_t) * 8)             # <<<<<<<<<<<<<<
 * 
 * 
 */
  if ((__pyx_v_x != 0)) {
    __pyx_t_1 = bit_ctz(__pyx_v_x);
  } else {
    __pyx_t_1 = ((sizeof(uint64_t)) * 8);
  }
  __pyx_r = __pyx_t_1;
  goto __pyx_L0;

  /* "bit.pxd":93
 * 
 * 
 * cdef inline int nextunset(uint64_t vec, uint32_t pos):             # <<<<<<<<<<<<<<
 * 	""" Return next unset bit starting from pos.
 * 
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":105
 * 
 * 
 * cdef inline int bitlength(uint64_t vec):             # <<<<<<<<<<<<<<
 * 	"""Return number of bits needed to represent vector.
 * 
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_bitlength(uint64_t __pyx_v_vec) {
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  size_t __pyx_t_1;
  __Pyx_RefNannySetupContext("bitlength", 0);

  /* "bit.pxd":112
 * 	>>> bitlength(0b0011101)
 * 	5"""
 * 	return sizeof(vec) * 8 - bit_clz(vec) if vec else 0             # <<<<<<<<<<<<<<
 * 
 * 
 */
  if ((__pyx_v_vec != 0)) {
    __pyx_t_1 = (((sizeof(__pyx_v_vec)) * 8) - bit_clz(__pyx_v_vec));
  } else {
    __pyx_t_1 = 0;
  }
  __pyx_r = __pyx_t_1;
  goto __pyx_L0;

  /* "bit.pxd":105
 * 
 * 
 * cdef inline int bitlength(uint64_t vec):             # <<<<<<<<<<<<<<
 * 	"""Return number of bits needed to represent vector.
 * 
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":115
 * 
 * 
 * cdef inline int abitcount(uint64_t *vec, int slots):             # <<<<<<<<<<<<<<
 * 	""" Return number of set bits in variable length bitvector """
 * 	cdef int a
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_abitcount(uint64_t *__pyx_v_vec, int __pyx_v_slots) {
  int __pyx_v_a;
  int __pyx_v_result;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  int __pyx_t_2;
  __Pyx_RefNannySetupContext("abitcount", 0);

  /* "bit.pxd":118
 * 	""" Return number of set bits in variable length bitvector """
 * 	cdef int a
 * 	cdef int result = 0             # <<<<<<<<<<<<<<
 * 	for a in range(slots):
 * 		result += bit_popcount(vec[a])
 */
  __pyx_v_result = 0;

  /* "bit.pxd":119
 * 	cdef int a
 * 	cdef int result = 0
 * 	for a in range(slots):             # <<<<<<<<<<<<<<
 * 		result += bit_popcount(vec[a])
 * 	return result
 */
  __pyx_t_1 = __pyx_v_slots;
  for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
    __pyx_v_a = __pyx_t_2;

    /* "bit.pxd":120
 * 	cdef int result = 0
 * 	for a in range(slots):
 * 		result += bit_popcount(vec[a])             # <<<<<<<<<<<<<<
 * 	return result
 * 
 */
    __pyx_v_result = (__pyx_v_result + bit_popcount((__pyx_v_vec[__pyx_v_a])));
  }

  /* "bit.pxd":121
 * 	for a in range(slots):
 * 		result += bit_popcount(vec[a])
 * 	return result             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = __pyx_v_result;
  goto __pyx_L0;

  /* "bit.pxd":115
 * 
 * 
 * cdef inline int abitcount(uint64_t *vec, int slots):             # <<<<<<<<<<<<<<
 * 	""" Return number of set bits in variable length bitvector """
 * 	cdef int a
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":124
 * 
 * 
 * cdef inline int abitlength(uint64_t *vec, int slots):             # <<<<<<<<<<<<<<
 * 	"""Return number of bits needed to represent vector.
 * 
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_abitlength(uint64_t *__pyx_v_vec, int __pyx_v_slots) {
  int __pyx_v_a;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  __Pyx_RefNannySetupContext("abitlength", 0);

  /* "bit.pxd":128
 * 
 * 	(equivalently: index of most significant set bit, plus one)."""
 * 	cdef int a = slots - 1             # <<<<<<<<<<<<<<
 * 	while not vec[a]:
 * 		a -= 1
 */
  __pyx_v_a = (__pyx_v_slots - 1);

  /* "bit.pxd":129
 * 	(equivalently: index of most significant set bit, plus one)."""
 * 	cdef int a = slots - 1
 * 	while not vec[a]:             # <<<<<<<<<<<<<<
 * 		a -= 1
 * 		if a < 0:
 */
  while (1) {
    __pyx_t_1 = ((!((__pyx_v_vec[__pyx_v_a]) != 0)) != 0);
    if (!__pyx_t_1) break;

    /* "bit.pxd":130
 * 	cdef int a = slots - 1
 * 	while not vec[a]:
 * 		a -= 1             # <<<<<<<<<<<<<<
 * 		if a < 0:
 * 			return 0
 */
    __pyx_v_a = (__pyx_v_a - 1);

    /* "bit.pxd":131
 * 	while not vec[a]:
 * 		a -= 1
 * 		if a < 0:             # <<<<<<<<<<<<<<
 * 			return 0
 * 	return (a + 1) * sizeof(uint64_t) * 8 - bit_clz(vec[a])
 */
    __pyx_t_1 = ((__pyx_v_a < 0) != 0);
    if (__pyx_t_1) {

      /* "bit.pxd":132
 * 		a -= 1
 * 		if a < 0:
 * 			return 0             # <<<<<<<<<<<<<<
 * 	return (a + 1) * sizeof(uint64_t) * 8 - bit_clz(vec[a])
 * 
 */
      __pyx_r = 0;
      goto __pyx_L0;

      /* "bit.pxd":131
 * 	while not vec[a]:
 * 		a -= 1
 * 		if a < 0:             # <<<<<<<<<<<<<<
 * 			return 0
 * 	return (a + 1) * sizeof(uint64_t) * 8 - bit_clz(vec[a])
 */
    }
  }

  /* "bit.pxd":133
 * 		if a < 0:
 * 			return 0
 * 	return (a + 1) * sizeof(uint64_t) * 8 - bit_clz(vec[a])             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = ((((__pyx_v_a + 1) * (sizeof(uint64_t))) * 8) - bit_clz((__pyx_v_vec[__pyx_v_a])));
  goto __pyx_L0;

  /* "bit.pxd":124
 * 
 * 
 * cdef inline int abitlength(uint64_t *vec, int slots):             # <<<<<<<<<<<<<<
 * 	"""Return number of bits needed to represent vector.
 * 
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":136
 * 
 * 
 * cdef inline int anextset(uint64_t *vec, uint32_t pos, int slots):             # <<<<<<<<<<<<<<
 * 	""" Return next set bit starting from pos, -1 if there is none. """
 * 	cdef int a = BITSLOT(pos)
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_anextset(uint64_t *__pyx_v_vec, uint32_t __pyx_v_pos, int __pyx_v_slots) {
  int __pyx_v_a;
  uint64_t __pyx_v_x;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  __Pyx_RefNannySetupContext("anextset", 0);

  /* "bit.pxd":138
 * cdef inline int anextset(uint64_t *vec, uint32_t pos, int slots):
 * 	""" Return next set bit starting from pos, -1 if there is none. """
 * 	cdef int a = BITSLOT(pos)             # <<<<<<<<<<<<<<
 * 	cdef uint64_t x
 * 	if a >= slots:
 */
  __pyx_v_a = BITSLOT(__pyx_v_pos);

  /* "bit.pxd":140
 * 	cdef int a = BITSLOT(pos)
 * 	cdef uint64_t x
 * 	if a >= slots:             # <<<<<<<<<<<<<<
 * 		return -1
 * 	x = vec[a] & (~0UL << (pos % BITSIZE))
 */
  __pyx_t_1 = ((__pyx_v_a >= __pyx_v_slots) != 0);
  if (__pyx_t_1) {

    /* "bit.pxd":141
 * 	cdef uint64_t x
 * 	if a >= slots:
 * 		return -1             # <<<<<<<<<<<<<<
 * 	x = vec[a] & (~0UL << (pos % BITSIZE))
 * 	while x == 0UL:
 */
    __pyx_r = -1;
    goto __pyx_L0;

    /* "bit.pxd":140
 * 	cdef int a = BITSLOT(pos)
 * 	cdef uint64_t x
 * 	if a >= slots:             # <<<<<<<<<<<<<<
 * 		return -1
 * 	x = vec[a] & (~0UL << (pos % BITSIZE))
 */
  }

  /* "bit.pxd":142
 * 	if a >= slots:
 * 		return -1
 * 	x = vec[a] & (~0UL << (pos % BITSIZE))             # <<<<<<<<<<<<<<
 * 	while x == 0UL:
 * 		a += 1
 */
  __pyx_v_x = ((__pyx_v_vec[__pyx_v_a]) & ((~0UL) << (__pyx_v_pos % BITSIZE)));

  /* "bit.pxd":143
 * 		return -1
 * 	x = vec[a] & (~0UL << (pos % BITSIZE))
 * 	while x == 0UL:             # <<<<<<<<<<<<<<
 * 		a += 1
 * 		if a == slots:
 */
  while (1) {
    __pyx_t_1 = ((__pyx_v_x == 0UL) != 0);
    if (!__pyx_t_1) break;

    /* "bit.pxd":144
 * 	x = vec[a] & (~0UL << (pos % BITSIZE))
 * 	while x == 0UL:
 * 		a += 1             # <<<<<<<<<<<<<<
 * 		if a == slots:
 * 			return -1
 */
    __pyx_v_a = (__pyx_v_a + 1);

    /* "bit.pxd":145
 * 	while x == 0UL:
 * 		a += 1
 * 		if a == slots:             # <<<<<<<<<<<<<<
 * 			return -1
 * 		x = vec[a]
 */
    __pyx_t_1 = ((__pyx_v_a == __pyx_v_slots) != 0);
    if (__pyx_t_1) {

      /* "bit.pxd":146
 * 		a += 1
 * 		if a == slots:
 * 			return -1             # <<<<<<<<<<<<<<
 * 		x = vec[a]
 * 	return a * BITSIZE + bit_ctz(x)
 */
      __pyx_r = -1;
      goto __pyx_L0;

      /* "bit.pxd":145
 * 	while x == 0UL:
 * 		a += 1
 * 		if a == slots:             # <<<<<<<<<<<<<<
 * 			return -1
 * 		x = vec[a]
 */
    }

    /* "bit.pxd":147
 * 		if a == slots:
 * 			return -1
 * 		x = vec[a]             # <<<<<<<<<<<<<<
 * 	return a * BITSIZE + bit_ctz(x)
 * 
 */
    __pyx_v_x = (__pyx_v_vec[__pyx_v_a]);
  }

  /* "bit.pxd":148
 * 			return -1
 * 		x = vec[a]
 * 	return a * BITSIZE + bit_ctz(x)             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = ((__pyx_v_a * BITSIZE) + bit_ctz(__pyx_v_x));
  goto __pyx_L0;

  /* "bit.pxd":136
 * 
 * 
 * cdef inline int anextset(uint64_t *vec, uint32_t pos, int slots):             # <<<<<<<<<<<<<<
 * 	""" Return next set bit starting from pos, -1 if there is none. """
 * 	cdef int a = BITSLOT(pos)
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":151
 * 
 * 
 * cdef inline int anextunset(uint64_t *vec, uint32_t pos, int slots):             # <<<<<<<<<<<<<<
 * 	""" Return next unset bit starting from pos. """
 * 	cdef int a = BITSLOT(pos)
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_anextunset(uint64_t *__pyx_v_vec, uint32_t __pyx_v_pos, int __pyx_v_slots) {
  int __pyx_v_a;
  uint64_t __pyx_v_x;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  __Pyx_RefNannySetupContext("anextunset", 0);

  /* "bit.pxd":153
 * cdef inline int anextunset(uint64_t *vec, uint32_t pos, int slots):
 * 	""" Return next unset bit starting from pos. """
 * 	cdef int a = BITSLOT(pos)             # <<<<<<<<<<<<<<
 * 	cdef uint64_t x
 * 	if a >= slots:
 */
  __pyx_v_a = BITSLOT(__pyx_v_pos);

  /* "bit.pxd":155
 * 	cdef int a = BITSLOT(pos)
 * 	cdef uint64_t x
 * 	if a >= slots:             # <<<<<<<<<<<<<<
 * 		return a * BITSIZE
 * 	x = vec[a] | (BITMASK(pos) - 1)
 */
  __pyx_t_1 = ((__pyx_v_a >= __pyx_v_slots) != 0);
  if (__pyx_t_1) {

    /* "bit.pxd":156
 * 	cdef uint64_t x
 * 	if a >= slots:
 * 		return a * BITSIZE             # <<<<<<<<<<<<<<
 * 	x = vec[a] | (BITMASK(pos) - 1)
 * 	while x == ~0UL:
 */
    __pyx_r = (__pyx_v_a * BITSIZE);
    goto __pyx_L0;

    /* "bit.pxd":155
 * 	cdef int a = BITSLOT(pos)
 * 	cdef uint64_t x
 * 	if a >= slots:             # <<<<<<<<<<<<<<
 * 		return a * BITSIZE
 * 	x = vec[a] | (BITMASK(pos) - 1)
 */
  }

  /* "bit.pxd":157
 * 	if a >= slots:
 * 		return a * BITSIZE
 * 	x = vec[a] | (BITMASK(pos) - 1)             # <<<<<<<<<<<<<<
 * 	while x == ~0UL:
 * 		a += 1
 */
  __pyx_v_x = ((__pyx_v_vec[__pyx_v_a]) | (BITMASK(__pyx_v_pos) - 1));

  /* "bit.pxd":158
 * 		return a * BITSIZE
 * 	x = vec[a] | (BITMASK(pos) - 1)
 * 	while x == ~0UL:             # <<<<<<<<<<<<<<
 * 		a += 1
 * 		if a == slots:
 */
  while (1) {
    __pyx_t_1 = ((__pyx_v_x == (~0UL)) != 0);
    if (!__pyx_t_1) break;

    /* "bit.pxd":159
 * 	x = vec[a] | (BITMASK(pos) - 1)
 * 	while x == ~0UL:
 * 		a += 1             # <<<<<<<<<<<<<<
 * 		if a == slots:
 * 			return a * BITSIZE
 */
    __pyx_v_a = (__pyx_v_a + 1);

    /* "bit.pxd":160
 * 	while x == ~0UL:
 * 		a += 1
 * 		if a == slots:             # <<<<<<<<<<<<<<
 * 			return a * BITSIZE
 * 		x = vec[a]
 */
    __pyx_t_1 = ((__pyx_v_a == __pyx_v_slots) != 0);
    if (__pyx_t_1) {

      /* "bit.pxd":161
 * 		a += 1
 * 		if a == slots:
 * 			return a * BITSIZE             # <<<<<<<<<<<<<<
 * 		x = vec[a]
 * 	return a * BITSIZE + bit_ctz(~x)
 */
      __pyx_r = (__pyx_v_a * BITSIZE);
      goto __pyx_L0;

      /* "bit.pxd":160
 * 	while x == ~0UL:
 * 		a += 1
 * 		if a == slots:             # <<<<<<<<<<<<<<
 * 			return a * BITSIZE
 * 		x = vec[a]
 */
    }

    /* "bit.pxd":162
 * 		if a == slots:
 * 			return a * BITSIZE
 * 		x = vec[a]             # <<<<<<<<<<<<<<
 * 	return a * BITSIZE + bit_ctz(~x)
 * 
 */
    __pyx_v_x = (__pyx_v_vec[__pyx_v_a]);
  }

  /* "bit.pxd":163
 * 			return a * BITSIZE
 * 		x = vec[a]
 * 	return a * BITSIZE + bit_ctz(~x)             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = ((__pyx_v_a * BITSIZE) + bit_ctz((~__pyx_v_x)));
  goto __pyx_L0;

  /* "bit.pxd":151
 * 
 * 
 * cdef inline int anextunset(uint64_t *vec, uint32_t pos, int slots):             # <<<<<<<<<<<<<<
 * 	""" Return next unset bit starting from pos. """
 * 	cdef int a = BITSLOT(pos)
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":166
 * 
 * 
 * cdef inline int iteratesetbits(uint64_t *vec, int slots,             # <<<<<<<<<<<<<<
 * 		uint64_t *cur, int *idx):
 * 	"""Iterate over set bits in an array of unsigned long.
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_iteratesetbits(uint64_t *__pyx_v_vec, int __pyx_v_slots, uint64_t *__pyx_v_cur, int *__pyx_v_idx) {
  int __pyx_v_tmp;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  long __pyx_t_2;
  __Pyx_RefNannySetupContext("iteratesetbits", 0);

  /* "bit.pxd":187
 * 	"""
 * 	cdef int tmp
 * 	while not cur[0]:             # <<<<<<<<<<<<<<
 * 		idx[0] += 1
 * 		if idx[0] >= slots:
 */
  while (1) {
    __pyx_t_1 = ((!((__pyx_v_cur[0]) != 0)) != 0);
    if (!__pyx_t_1) break;

    /* "bit.pxd":188
 * 	cdef int tmp
 * 	while not cur[0]:
 * 		idx[0] += 1             # <<<<<<<<<<<<<<
 * 		if idx[0] >= slots:
 * 			return -1
 */
    __pyx_t_2 = 0;
    (__pyx_v_idx[__pyx_t_2]) = ((__pyx_v_idx[__pyx_t_2]) + 1);

    /* "bit.pxd":189
 * 	while not cur[0]:
 * 		idx[0] += 1
 * 		if idx[0] >= slots:             # <<<<<<<<<<<<<<
 * 			return -1
 * 		cur[0] = vec[idx[0]]
 */
    __pyx_t_1 = (((__pyx_v_idx[0]) >= __pyx_v_slots) != 0);
    if (__pyx_t_1) {

      /* "bit.pxd":190
 * 		idx[0] += 1
 * 		if idx[0] >= slots:
 * 			return -1             # <<<<<<<<<<<<<<
 * 		cur[0] = vec[idx[0]]
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot
 */
      __pyx_r = -1;
      goto __pyx_L0;

      /* "bit.pxd":189
 * 	while not cur[0]:
 * 		idx[0] += 1
 * 		if idx[0] >= slots:             # <<<<<<<<<<<<<<
 * 			return -1
 * 		cur[0] = vec[idx[0]]
 */
    }

    /* "bit.pxd":191
 * 		if idx[0] >= slots:
 * 			return -1
 * 		cur[0] = vec[idx[0]]             # <<<<<<<<<<<<<<
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot
 * 	cur[0] ^= 1UL << tmp  # TOGGLEBIT(cur, tmp)
 */
    (__pyx_v_cur[0]) = (__pyx_v_vec[(__pyx_v_idx[0])]);
  }

  /* "bit.pxd":192
 * 			return -1
 * 		cur[0] = vec[idx[0]]
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot             # <<<<<<<<<<<<<<
 * 	cur[0] ^= 1UL << tmp  # TOGGLEBIT(cur, tmp)
 * 	return idx[0] * BITSIZE + tmp
 */
  __pyx_v_tmp = bit_ctz((__pyx_v_cur[0]));

  /* "bit.pxd":193
 * 		cur[0] = vec[idx[0]]
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot
 * 	cur[0] ^= 1UL << tmp  # TOGGLEBIT(cur, tmp)             # <<<<<<<<<<<<<<
 * 	return idx[0] * BITSIZE + tmp
 * 
 */
  __pyx_t_2 = 0;
  (__pyx_v_cur[__pyx_t_2]) = ((__pyx_v_cur[__pyx_t_2]) ^ (1UL << __pyx_v_tmp));

  /* "bit.pxd":194
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot
 * 	cur[0] ^= 1UL << tmp  # TOGGLEBIT(cur, tmp)
 * 	return idx[0] * BITSIZE + tmp             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = (((__pyx_v_idx[0]) * BITSIZE) + __pyx_v_tmp);
  goto __pyx_L0;

  /* "bit.pxd":166
 * 
 * 
 * cdef inline int iteratesetbits(uint64_t *vec, int slots,             # <<<<<<<<<<<<<<
 * 		uint64_t *cur, int *idx):
 * 	"""Iterate over set bits in an array of unsigned long.
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":197
 * 
 * 
 * cdef inline int iterateunsetbits(uint64_t *vec, int slots,             # <<<<<<<<<<<<<<
 * 		uint64_t *cur, int *idx):
 * 	"""Like ``iteratesetbits``, but return indices of zero bits.
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_iterateunsetbits(uint64_t *__pyx_v_vec, int __pyx_v_slots, uint64_t *__pyx_v_cur, int *__pyx_v_idx) {
  int __pyx_v_tmp;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  long __pyx_t_2;
  __Pyx_RefNannySetupContext("iterateunsetbits", 0);

  /* "bit.pxd":203
 * 	:param cur: should be initialized as: ``cur = ~vec[idx]``."""
 * 	cdef int tmp
 * 	while not cur[0]:             # <<<<<<<<<<<<<<
 * 		idx[0] += 1
 * 		if idx[0] >= slots:
 */
  while (1) {
    __pyx_t_1 = ((!((__pyx_v_cur[0]) != 0)) != 0);
    if (!__pyx_t_1) break;

    /* "bit.pxd":204
 * 	cdef int tmp
 * 	while not cur[0]:
 * 		idx[0] += 1             # <<<<<<<<<<<<<<
 * 		if idx[0] >= slots:
 * 			return -1
 */
    __pyx_t_2 = 0;
    (__pyx_v_idx[__pyx_t_2]) = ((__pyx_v_idx[__pyx_t_2]) + 1);

    /* "bit.pxd":205
 * 	while not cur[0]:
 * 		idx[0] += 1
 * 		if idx[0] >= slots:             # <<<<<<<<<<<<<<
 * 			return -1
 * 		cur[0] = ~vec[idx[0]]
 */
    __pyx_t_1 = (((__pyx_v_idx[0]) >= __pyx_v_slots) != 0);
    if (__pyx_t_1) {

      /* "bit.pxd":206
 * 		idx[0] += 1
 * 		if idx[0] >= slots:
 * 			return -1             # <<<<<<<<<<<<<<
 * 		cur[0] = ~vec[idx[0]]
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot
 */
      __pyx_r = -1;
      goto __pyx_L0;

      /* "bit.pxd":205
 * 	while not cur[0]:
 * 		idx[0] += 1
 * 		if idx[0] >= slots:             # <<<<<<<<<<<<<<
 * 			return -1
 * 		cur[0] = ~vec[idx[0]]
 */
    }

    /* "bit.pxd":207
 * 		if idx[0] >= slots:
 * 			return -1
 * 		cur[0] = ~vec[idx[0]]             # <<<<<<<<<<<<<<
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot
 * 	cur[0] ^= 1UL << tmp  # TOGGLEBIT(cur, tmp)
 */
    (__pyx_v_cur[0]) = (~(__pyx_v_vec[(__pyx_v_idx[0])]));
  }

  /* "bit.pxd":208
 * 			return -1
 * 		cur[0] = ~vec[idx[0]]
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot             # <<<<<<<<<<<<<<
 * 	cur[0] ^= 1UL << tmp  # TOGGLEBIT(cur, tmp)
 * 	return idx[0] * BITSIZE + tmp
 */
  __pyx_v_tmp = bit_ctz((__pyx_v_cur[0]));

  /* "bit.pxd":209
 * 		cur[0] = ~vec[idx[0]]
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot
 * 	cur[0] ^= 1UL << tmp  # TOGGLEBIT(cur, tmp)             # <<<<<<<<<<<<<<
 * 	return idx[0] * BITSIZE + tmp
 * 
 */
  __pyx_t_2 = 0;
  (__pyx_v_cur[__pyx_t_2]) = ((__pyx_v_cur[__pyx_t_2]) ^ (1UL << __pyx_v_tmp));

  /* "bit.pxd":210
 * 	tmp = bit_ctz(cur[0])  # index of bit in current slot
 * 	cur[0] ^= 1UL << tmp  # TOGGLEBIT(cur, tmp)
 * 	return idx[0] * BITSIZE + tmp             # <<<<<<<<<<<<<<
 * 
 * 
 */
  __pyx_r = (((__pyx_v_idx[0]) * BITSIZE) + __pyx_v_tmp);
  goto __pyx_L0;

  /* "bit.pxd":197
 * 
 * 
 * cdef inline int iterateunsetbits(uint64_t *vec, int slots,             # <<<<<<<<<<<<<<
 * 		uint64_t *cur, int *idx):
 * 	"""Like ``iteratesetbits``, but return indices of zero bits.
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "bit.pxd":213
 * 
 * 
 * cdef inline void setintersectinplace(uint64_t *dest, uint64_t *src, int slots):             # <<<<<<<<<<<<<<
 * 	"""dest gets the intersection of dest and src.
 * 
 */

static CYTHON_INLINE void __pyx_f_8discodop_3bit_setintersectinplace(uint64_t *__pyx_v_dest, uint64_t *__pyx_v_src, int __pyx_v_slots) {
  int __pyx_v_a;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  int __pyx_t_2;
  int __pyx_t_3;
  __Pyx_RefNannySetupContext("setintersectinplace", 0);

  /* "bit.pxd":218
 * 	both operands must have at least `slots' slots."""
 * 	cdef int a
 * 	for a in range(slots):             # <<<<<<<<<<<<<<
 * 		dest[a] &= src[a]
 * 
 */
  __pyx_t_1 = __pyx_v_slots;
  for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
    __pyx_v_a = __pyx_t_2;

    /* "bit.pxd":219
 * 	cdef int a
 * 	for a in range(slots):
 * 		dest[a] &= src[a]             # <<<<<<<<<<<<<<
 * 
 * 
 */
    __pyx_t_3 = __pyx_v_a;
    (__pyx_v_dest[__pyx_t_3]) = ((__pyx_v_dest[__pyx_t_3]) & (__pyx_v_src[__pyx_v_a]));
  }

  /* "bit.pxd":213
 * 
 * 
 * cdef inline void setintersectinplace(uint64_t *dest, uint64_t *src, int slots):             # <<<<<<<<<<<<<<
 * 	"""dest gets the intersection of dest and src.
 * 
 */

  /* function exit code */
  __Pyx_RefNannyFinishContext();
}

/* "bit.pxd":222
 * 
 * 
 * cdef inline void setunioninplace(uint64_t *dest, uint64_t *src, int slots):             # <<<<<<<<<<<<<<
 * 	"""dest gets the union of dest and src.
 * 
 */

static CYTHON_INLINE void __pyx_f_8discodop_3bit_setunioninplace(uint64_t *__pyx_v_dest, uint64_t *__pyx_v_src, int __pyx_v_slots) {
  int __pyx_v_a;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  int __pyx_t_2;
  int __pyx_t_3;
  __Pyx_RefNannySetupContext("setunioninplace", 0);

  /* "bit.pxd":227
 * 	Both operands must have at least ``slots`` slots."""
 * 	cdef int a
 * 	for a in range(slots):             # <<<<<<<<<<<<<<
 * 		dest[a] |= src[a]
 * 
 */
  __pyx_t_1 = __pyx_v_slots;
  for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
    __pyx_v_a = __pyx_t_2;

    /* "bit.pxd":228
 * 	cdef int a
 * 	for a in range(slots):
 * 		dest[a] |= src[a]             # <<<<<<<<<<<<<<
 * 
 * 
 */
    __pyx_t_3 = __pyx_v_a;
    (__pyx_v_dest[__pyx_t_3]) = ((__pyx_v_dest[__pyx_t_3]) | (__pyx_v_src[__pyx_v_a]));
  }

  /* "bit.pxd":222
 * 
 * 
 * cdef inline void setunioninplace(uint64_t *dest, uint64_t *src, int slots):             # <<<<<<<<<<<<<<
 * 	"""dest gets the union of dest and src.
 * 
 */

  /* function exit code */
  __Pyx_RefNannyFinishContext();
}

/* "bit.pxd":231
 * 
 * 
 * cdef inline void setintersect(uint64_t *dest, uint64_t *src1, uint64_t *src2,             # <<<<<<<<<<<<<<
 * 		int slots):
 * 	"""dest gets the intersection of src1 and src2.
 */

static CYTHON_INLINE void __pyx_f_8discodop_3bit_setintersect(uint64_t *__pyx_v_dest, uint64_t *__pyx_v_src1, uint64_t *__pyx_v_src2, int __pyx_v_slots) {
  int __pyx_v_a;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  int __pyx_t_2;
  __Pyx_RefNannySetupContext("setintersect", 0);

  /* "bit.pxd":237
 * 	operands must have at least ``slots`` slots."""
 * 	cdef int a
 * 	for a in range(slots):             # <<<<<<<<<<<<<<
 * 		dest[a] = src1[a] & src2[a]
 * 
 */
  __pyx_t_1 = __pyx_v_slots;
  for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
    __pyx_v_a = __pyx_t_2;

    /* "bit.pxd":238
 * 	cdef int a
 * 	for a in range(slots):
 * 		dest[a] = src1[a] & src2[a]             # <<<<<<<<<<<<<<
 * 
 * 
 */
    (__pyx_v_dest[__pyx_v_a]) = ((__pyx_v_src1[__pyx_v_a]) & (__pyx_v_src2[__pyx_v_a]));
  }

  /* "bit.pxd":231
 * 
 * 
 * cdef inline void setintersect(uint64_t *dest, uint64_t *src1, uint64_t *src2,             # <<<<<<<<<<<<<<
 * 		int slots):
 * 	"""dest gets the intersection of src1 and src2.
 */

  /* function exit code */
  __Pyx_RefNannyFinishContext();
}

/* "bit.pxd":241
 * 
 * 
 * cdef inline void setunion(uint64_t *dest, uint64_t *src1, uint64_t *src2,             # <<<<<<<<<<<<<<
 * 		int slots):
 * 	"""dest gets the union of src1 and src2.
 */

static CYTHON_INLINE void __pyx_f_8discodop_3bit_setunion(uint64_t *__pyx_v_dest, uint64_t *__pyx_v_src1, uint64_t *__pyx_v_src2, int __pyx_v_slots) {
  int __pyx_v_a;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  int __pyx_t_2;
  __Pyx_RefNannySetupContext("setunion", 0);

  /* "bit.pxd":247
 * 	operands must have at least ``slots`` slots."""
 * 	cdef int a
 * 	for a in range(slots):             # <<<<<<<<<<<<<<
 * 		dest[a] = src1[a] | src2[a]
 * 
 */
  __pyx_t_1 = __pyx_v_slots;
  for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
    __pyx_v_a = __pyx_t_2;

    /* "bit.pxd":248
 * 	cdef int a
 * 	for a in range(slots):
 * 		dest[a] = src1[a] | src2[a]             # <<<<<<<<<<<<<<
 * 
 * 
 */
    (__pyx_v_dest[__pyx_v_a]) = ((__pyx_v_src1[__pyx_v_a]) | (__pyx_v_src2[__pyx_v_a]));
  }

  /* "bit.pxd":241
 * 
 * 
 * cdef inline void setunion(uint64_t *dest, uint64_t *src1, uint64_t *src2,             # <<<<<<<<<<<<<<
 * 		int slots):
 * 	"""dest gets the union of src1 and src2.
 */

  /* function exit code */
  __Pyx_RefNannyFinishContext();
}

/* "bit.pxd":251
 * 
 * 
 * cdef inline bint subset(uint64_t *vec1, uint64_t *vec2, int slots):             # <<<<<<<<<<<<<<
 * 	"""Test whether vec1 is a subset of vec2.
 * 
 */

static CYTHON_INLINE int __pyx_f_8discodop_3bit_subset(uint64_t *__pyx_v_vec1, uint64_t *__pyx_v_vec2, int __pyx_v_slots) {
  int __pyx_v_a;
  int __pyx_r;
  __Pyx_RefNannyDeclarations
  int __pyx_t_1;
  int __pyx_t_2;
  int __pyx_t_3;
  __Pyx_RefNannySetupContext("subset", 0);

  /* "bit.pxd":256
 * 	i.e., all set bits of vec1 should be set in vec2."""
 * 	cdef int a
 * 	for a in range(slots):             # <<<<<<<<<<<<<<
 * 		if (vec1[a] & vec2[a]) != vec1[a]:
 * 			return False
 */
  __pyx_t_1 = __pyx_v_slots;
  for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
    __pyx_v_a = __pyx_t_2;

    /* "bit.pxd":257
 * 	cdef int a
 * 	for a in range(slots):
 * 		if (vec1[a] & vec2[a]) != vec1[a]:             # <<<<<<<<<<<<<<
 * 			return False
 * 	return True
 */
    __pyx_t_3 = ((((__pyx_v_vec1[__pyx_v_a]) & (__pyx_v_vec2[__pyx_v_a])) != (__pyx_v_vec1[__pyx_v_a])) != 0);
    if (__pyx_t_3) {

      /* "bit.pxd":258
 * 	for a in range(slots):
 * 		if (vec1[a] & vec2[a]) != vec1[a]:
 * 			return False             # <<<<<<<<<<<<<<
 * 	return True
 */
      __pyx_r = 0;
      goto __pyx_L0;

      /* "bit.pxd":257
 * 	cdef int a
 * 	for a in range(slots):
 * 		if (vec1[a] & vec2[a]) != vec1[a]:             # <<<<<<<<<<<<<<
 * 			return False
 * 	return True
 */
    }
  }

  /* "bit.pxd":259
 * 		if (vec1[a] & vec2[a]) != vec1[a]:
 * 			return False
 * 	return True             # <<<<<<<<<<<<<<
 */
  __pyx_r = 1;
  goto __pyx_L0;

  /* "bit.pxd":251
 * 
 * 
 * cdef inline bint subset(uint64_t *vec1, uint64_t *vec2, int slots):             # <<<<<<<<<<<<<<
 * 	"""Test whether vec1 is a subset of vec2.
 * 
 */

  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "string.to_py":31
 * 
 * @cname("__pyx_convert_PyObject_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyObject_FromStringAndSize(s.data(), s.size())
 * cdef extern from *:
 */

static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &__pyx_v_s) {
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannySetupContext("__pyx_convert_PyObject_string_to_py_std__in_string", 0);

  /* "string.to_py":32
 * @cname("__pyx_convert_PyObject_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s):
 *     return __Pyx_PyObject_FromStringAndSize(s.data(), s.size())             # <<<<<<<<<<<<<<
 * cdef extern from *:
 *     cdef object __Pyx_PyUnicode_FromStringAndSize(const char*, size_t)
 */
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_1 = __Pyx_PyObject_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 32, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_r = __pyx_t_1;
  __pyx_t_1 = 0;
  goto __pyx_L0;

  /* "string.to_py":31
 * 
 * @cname("__pyx_convert_PyObject_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyObject_FromStringAndSize(s.data(), s.size())
 * cdef extern from *:
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_AddTraceback("string.to_py.__pyx_convert_PyObject_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "string.to_py":37
 * 
 * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size())
 * cdef extern from *:
 */

static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &__pyx_v_s) {
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannySetupContext("__pyx_convert_PyUnicode_string_to_py_std__in_string", 0);

  /* "string.to_py":38
 * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s):
 *     return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size())             # <<<<<<<<<<<<<<
 * cdef extern from *:
 *     cdef object __Pyx_PyStr_FromStringAndSize(const char*, size_t)
 */
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_1 = __Pyx_PyUnicode_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 38, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_r = __pyx_t_1;
  __pyx_t_1 = 0;
  goto __pyx_L0;

  /* "string.to_py":37
 * 
 * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size())
 * cdef extern from *:
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_AddTraceback("string.to_py.__pyx_convert_PyUnicode_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "string.to_py":43
 * 
 * @cname("__pyx_convert_PyStr_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyStr_FromStringAndSize(s.data(), s.size())
 * cdef extern from *:
 */

static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &__pyx_v_s) {
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannySetupContext("__pyx_convert_PyStr_string_to_py_std__in_string", 0);

  /* "string.to_py":44
 * @cname("__pyx_convert_PyStr_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s):
 *     return __Pyx_PyStr_FromStringAndSize(s.data(), s.size())             # <<<<<<<<<<<<<<
 * cdef extern from *:
 *     cdef object __Pyx_PyBytes_FromStringAndSize(const char*, size_t)
 */
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_1 = __Pyx_PyStr_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 44, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_r = __pyx_t_1;
  __pyx_t_1 = 0;
  goto __pyx_L0;

  /* "string.to_py":43
 * 
 * @cname("__pyx_convert_PyStr_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyStr_FromStringAndSize(s.data(), s.size())
 * cdef extern from *:
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_AddTraceback("string.to_py.__pyx_convert_PyStr_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "string.to_py":49
 * 
 * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size())
 * cdef extern from *:
 */

static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &__pyx_v_s) {
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannySetupContext("__pyx_convert_PyBytes_string_to_py_std__in_string", 0);

  /* "string.to_py":50
 * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s):
 *     return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size())             # <<<<<<<<<<<<<<
 * cdef extern from *:
 *     cdef object __Pyx_PyByteArray_FromStringAndSize(const char*, size_t)
 */
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 50, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_r = __pyx_t_1;
  __pyx_t_1 = 0;
  goto __pyx_L0;

  /* "string.to_py":49
 * 
 * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size())
 * cdef extern from *:
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_AddTraceback("string.to_py.__pyx_convert_PyBytes_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

/* "string.to_py":55
 * 
 * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size())
 * 
 */

static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &__pyx_v_s) {
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  __Pyx_RefNannySetupContext("__pyx_convert_PyByteArray_string_to_py_std__in_string", 0);

  /* "string.to_py":56
 * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s):
 *     return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size())             # <<<<<<<<<<<<<<
 * 
 */
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_1 = __Pyx_PyByteArray_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 56, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_r = __pyx_t_1;
  __pyx_t_1 = 0;
  goto __pyx_L0;

  /* "string.to_py":55
 * 
 * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size())
 * 
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_AddTraceback("string.to_py.__pyx_convert_PyByteArray_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

static PyMethodDef __pyx_methods[] = {
  {0, 0, 0, 0}
};

#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef __pyx_moduledef = {
  #if PY_VERSION_HEX < 0x03020000
    { PyObject_HEAD_INIT(NULL) NULL, 0, NULL },
  #else
    PyModuleDef_HEAD_INIT,
  #endif
    "kbest",
    __pyx_k_Extract_the_k_best_derivations_f, /* m_doc */
    -1, /* m_size */
    __pyx_methods /* m_methods */,
    NULL, /* m_reload */
    NULL, /* m_traverse */
    NULL, /* m_clear */
    NULL /* m_free */
};
#endif

static __Pyx_StringTabEntry __pyx_string_tab[] = {
  {&__pyx_n_s_Grammar, __pyx_k_Grammar, sizeof(__pyx_k_Grammar), 0, 0, 1, 1},
  {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1},
  {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1},
  {&__pyx_kp_u__2, __pyx_k__2, sizeof(__pyx_k__2), 0, 1, 0, 0},
  {&__pyx_n_s_all, __pyx_k_all, sizeof(__pyx_k_all), 0, 0, 1, 1},
  {&__pyx_n_s_cand, __pyx_k_cand, sizeof(__pyx_k_cand), 0, 0, 1, 1},
  {&__pyx_n_s_chart, __pyx_k_chart, sizeof(__pyx_k_chart), 0, 0, 1, 1},
  {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1},
  {&__pyx_n_s_containers, __pyx_k_containers, sizeof(__pyx_k_containers), 0, 0, 1, 1},
  {&__pyx_kp_u_d_best_edge_for_right_child_of, __pyx_k_d_best_edge_for_right_child_of, sizeof(__pyx_k_d_best_edge_for_right_child_of), 0, 1, 0, 0},
  {&__pyx_kp_u_d_best_edge_for_s_of_left_item, __pyx_k_d_best_edge_for_s_of_left_item, sizeof(__pyx_k_d_best_edge_for_s_of_left_item), 0, 1, 0, 0},
  {&__pyx_kp_u_d_d, __pyx_k_d_d, sizeof(__pyx_k_d_d), 0, 1, 0, 0},
  {&__pyx_n_s_derivs, __pyx_k_derivs, sizeof(__pyx_k_derivs), 0, 0, 1, 1},
  {&__pyx_n_s_discodop_kbest, __pyx_k_discodop_kbest, sizeof(__pyx_k_discodop_kbest), 0, 0, 1, 1},
  {&__pyx_kp_s_discodop_kbest_pyx, __pyx_k_discodop_kbest_pyx, sizeof(__pyx_k_discodop_kbest_pyx), 0, 0, 1, 0},
  {&__pyx_n_s_entry, __pyx_k_entry, sizeof(__pyx_k_entry), 0, 0, 1, 1},
  {&__pyx_n_s_explored, __pyx_k_explored, sizeof(__pyx_k_explored), 0, 0, 1, 1},
  {&__pyx_n_u_getderiv, __pyx_k_getderiv, sizeof(__pyx_k_getderiv), 0, 1, 0, 1},
  {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1},
  {&__pyx_n_s_isinf, __pyx_k_isinf, sizeof(__pyx_k_isinf), 0, 0, 1, 1},
  {&__pyx_n_s_itemgetter, __pyx_k_itemgetter, sizeof(__pyx_k_itemgetter), 0, 0, 1, 1},
  {&__pyx_n_s_itemstr, __pyx_k_itemstr, sizeof(__pyx_k_itemstr), 0, 0, 1, 1},
  {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1},
  {&__pyx_kp_u_kbest_no_complete_derivation_in, __pyx_k_kbest_no_complete_derivation_in, sizeof(__pyx_k_kbest_no_complete_derivation_in), 0, 1, 0, 0},
  {&__pyx_n_s_lazykbest, __pyx_k_lazykbest, sizeof(__pyx_k_lazykbest), 0, 0, 1, 1},
  {&__pyx_n_u_lazykbest, __pyx_k_lazykbest, sizeof(__pyx_k_lazykbest), 0, 1, 0, 1},
  {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1},
  {&__pyx_n_s_n, __pyx_k_n, sizeof(__pyx_k_n), 0, 0, 1, 1},
  {&__pyx_kp_u_non_zero_rank_vector_d_not_in_ex, __pyx_k_non_zero_rank_vector_d_not_in_ex, sizeof(__pyx_k_non_zero_rank_vector_d_not_in_ex), 0, 1, 0, 0},
  {&__pyx_n_s_operator, __pyx_k_operator, sizeof(__pyx_k_operator), 0, 0, 1, 1},
  {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1},
  {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1},
  {&__pyx_n_s_root, __pyx_k_root, sizeof(__pyx_k_root), 0, 0, 1, 1},
  {&__pyx_kp_u_sprintf_error_return_value_d, __pyx_k_sprintf_error_return_value_d, sizeof(__pyx_k_sprintf_error_return_value_d), 0, 1, 0, 0},
  {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1},
  {&__pyx_n_s_tmp, __pyx_k_tmp, sizeof(__pyx_k_tmp), 0, 0, 1, 1},
  {0, 0, 0, 0, 0, 0, 0}
};
static int __Pyx_InitCachedBuiltins(void) {
  __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 80, __pyx_L1_error)
  __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(0, 122, __pyx_L1_error)
  __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 109, __pyx_L1_error)
  return 0;
  __pyx_L1_error:;
  return -1;
}

static int __Pyx_InitCachedConstants(void) {
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0);

  /* "discodop/kbest.pyx":237
 * 	cdef int n = 0
 * 	if root == 0:
 * 		raise ValueError('kbest: no complete derivation in chart')             # <<<<<<<<<<<<<<
 * 	chart.rankededges.clear()
 * 	chart.rankededges.resize(chart.parseforest.size())
 */
  __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_kbest_no_complete_derivation_in); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 237, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_tuple_);
  __Pyx_GIVEREF(__pyx_tuple_);

  /* "discodop/kbest.pyx":221
 * 
 * 
 * def lazykbest(Chart chart, int k, bint derivs=True):             # <<<<<<<<<<<<<<
 * 	"""Wrapper function to run ``lazykthbest``.
 * 
 */
  __pyx_tuple__3 = PyTuple_Pack(9, __pyx_n_s_chart, __pyx_n_s_k, __pyx_n_s_derivs, __pyx_n_s_cand, __pyx_n_s_explored, __pyx_n_s_entry, __pyx_n_s_tmp, __pyx_n_s_root, __pyx_n_s_n); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(0, 221, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_tuple__3);
  __Pyx_GIVEREF(__pyx_tuple__3);
  __pyx_codeobj__4 = (PyObject*)__Pyx_PyCode_New(3, 0, 9, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__3, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_discodop_kbest_pyx, __pyx_n_s_lazykbest, 221, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__4)) __PYX_ERR(0, 221, __pyx_L1_error)
  __Pyx_RefNannyFinishContext();
  return 0;
  __pyx_L1_error:;
  __Pyx_RefNannyFinishContext();
  return -1;
}

static int __Pyx_InitGlobals(void) {
  if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error);
  __pyx_int_460 = PyInt_FromLong(460); if (unlikely(!__pyx_int_460)) __PYX_ERR(0, 1, __pyx_L1_error)
  return 0;
  __pyx_L1_error:;
  return -1;
}

#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC initkbest(void); /*proto*/
PyMODINIT_FUNC initkbest(void)
#else
PyMODINIT_FUNC PyInit_kbest(void); /*proto*/
PyMODINIT_FUNC PyInit_kbest(void)
#endif
{
  PyObject *__pyx_t_1 = NULL;
  PyObject *__pyx_t_2 = NULL;
  PyObject *__pyx_t_3 = NULL;
  PyObject *__pyx_t_4 = NULL;
  PyObject *__pyx_t_5 = NULL;
  __Pyx_RefNannyDeclarations
  #if CYTHON_REFNANNY
  __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
  if (!__Pyx_RefNanny) {
      PyErr_Clear();
      __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
      if (!__Pyx_RefNanny)
          Py_FatalError("failed to import 'refnanny' module");
  }
  #endif
  __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_kbest(void)", 0);
  if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error)
  __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error)
  __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error)
  #ifdef __Pyx_CyFunction_USED
  if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  #endif
  #ifdef __Pyx_FusedFunction_USED
  if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  #endif
  #ifdef __Pyx_Coroutine_USED
  if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  #endif
  #ifdef __Pyx_Generator_USED
  if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  #endif
  #ifdef __Pyx_StopAsyncIteration_USED
  if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  #endif
  /*--- Library function declarations ---*/
  /*--- Threads initialization code ---*/
  #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
  #ifdef WITH_THREAD /* Python build with threading support? */
  PyEval_InitThreads();
  #endif
  #endif
  /*--- Module creation code ---*/
  #if PY_MAJOR_VERSION < 3
  __pyx_m = Py_InitModule4("kbest", __pyx_methods, __pyx_k_Extract_the_k_best_derivations_f, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m);
  #else
  __pyx_m = PyModule_Create(&__pyx_moduledef);
  #endif
  if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error)
  __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error)
  Py_INCREF(__pyx_d);
  __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error)
  __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error)
  #if CYTHON_COMPILING_IN_PYPY
  Py_INCREF(__pyx_b);
  #endif
  if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error);
  /*--- Initialize various global constants etc. ---*/
  if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)
  if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  #endif
  if (__pyx_module_is_main_discodop__kbest) {
    if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  }
  #if PY_MAJOR_VERSION >= 3
  {
    PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error)
    if (!PyDict_GetItemString(modules, "discodop.kbest")) {
      if (unlikely(PyDict_SetItemString(modules, "discodop.kbest", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error)
    }
  }
  #endif
  /*--- Builtin init code ---*/
  if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  /*--- Constants init code ---*/
  if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  /*--- Global init code ---*/
  /*--- Variable export code ---*/
  /*--- Function export code ---*/
  if (__Pyx_ExportFunction("getderiv", (void (*)(void))__pyx_f_8discodop_5kbest_getderiv, "std::string (ItemNo, RankedEdge, struct __pyx_obj_8discodop_10containers_Chart *)") < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  /*--- Type init code ---*/
  /*--- Type import code ---*/
  __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", 
  #if CYTHON_COMPILING_IN_PYPY
  sizeof(PyTypeObject),
  #else
  sizeof(PyHeapTypeObject),
  #endif
  0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(4, 9, __pyx_L1_error)
  __pyx_ptype_7cpython_5array_array = __Pyx_ImportType("array", "array", sizeof(arrayobject), 0); if (unlikely(!__pyx_ptype_7cpython_5array_array)) __PYX_ERR(1, 58, __pyx_L1_error)
  __pyx_ptype_8discodop_10containers_StringList = __Pyx_ImportType("discodop.containers", "StringList", sizeof(struct __pyx_obj_8discodop_10containers_StringList), 1); if (unlikely(!__pyx_ptype_8discodop_10containers_StringList)) __PYX_ERR(2, 509, __pyx_L1_error)
  __pyx_ptype_8discodop_10containers_StringIntDict = __Pyx_ImportType("discodop.containers", "StringIntDict", sizeof(struct __pyx_obj_8discodop_10containers_StringIntDict), 1); if (unlikely(!__pyx_ptype_8discodop_10containers_StringIntDict)) __PYX_ERR(2, 514, __pyx_L1_error)
  __pyx_ptype_8discodop_10containers_Grammar = __Pyx_ImportType("discodop.containers", "Grammar", sizeof(struct __pyx_obj_8discodop_10containers_Grammar), 1); if (unlikely(!__pyx_ptype_8discodop_10containers_Grammar)) __PYX_ERR(2, 519, __pyx_L1_error)
  __pyx_vtabptr_8discodop_10containers_Grammar = (struct __pyx_vtabstruct_8discodop_10containers_Grammar*)__Pyx_GetVtable(__pyx_ptype_8discodop_10containers_Grammar->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_10containers_Grammar)) __PYX_ERR(2, 519, __pyx_L1_error)
  __pyx_ptype_8discodop_10containers_Chart = __Pyx_ImportType("discodop.containers", "Chart", sizeof(struct __pyx_obj_8discodop_10containers_Chart), 1); if (unlikely(!__pyx_ptype_8discodop_10containers_Chart)) __PYX_ERR(2, 560, __pyx_L1_error)
  __pyx_vtabptr_8discodop_10containers_Chart = (struct __pyx_vtabstruct_8discodop_10containers_Chart*)__Pyx_GetVtable(__pyx_ptype_8discodop_10containers_Chart->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_10containers_Chart)) __PYX_ERR(2, 560, __pyx_L1_error)
  __pyx_ptype_8discodop_10containers_Whitelist = __Pyx_ImportType("discodop.containers", "Whitelist", sizeof(struct __pyx_obj_8discodop_10containers_Whitelist), 1); if (unlikely(!__pyx_ptype_8discodop_10containers_Whitelist)) __PYX_ERR(2, 591, __pyx_L1_error)
  __pyx_ptype_8discodop_10containers_Ctrees = __Pyx_ImportType("discodop.containers", "Ctrees", sizeof(struct __pyx_obj_8discodop_10containers_Ctrees), 1); if (unlikely(!__pyx_ptype_8discodop_10containers_Ctrees)) __PYX_ERR(2, 650, __pyx_L1_error)
  __pyx_vtabptr_8discodop_10containers_Ctrees = (struct __pyx_vtabstruct_8discodop_10containers_Ctrees*)__Pyx_GetVtable(__pyx_ptype_8discodop_10containers_Ctrees->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_10containers_Ctrees)) __PYX_ERR(2, 650, __pyx_L1_error)
  __pyx_ptype_8discodop_10containers_Vocabulary = __Pyx_ImportType("discodop.containers", "Vocabulary", sizeof(struct __pyx_obj_8discodop_10containers_Vocabulary), 1); if (unlikely(!__pyx_ptype_8discodop_10containers_Vocabulary)) __PYX_ERR(2, 677, __pyx_L1_error)
  __pyx_vtabptr_8discodop_10containers_Vocabulary = (struct __pyx_vtabstruct_8discodop_10containers_Vocabulary*)__Pyx_GetVtable(__pyx_ptype_8discodop_10containers_Vocabulary->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_10containers_Vocabulary)) __PYX_ERR(2, 677, __pyx_L1_error)
  __pyx_ptype_8discodop_10containers_FixedVocabulary = __Pyx_ImportType("discodop.containers", "FixedVocabulary", sizeof(struct __pyx_obj_8discodop_10containers_FixedVocabulary), 1); if (unlikely(!__pyx_ptype_8discodop_10containers_FixedVocabulary)) __PYX_ERR(2, 692, __pyx_L1_error)
  __pyx_vtabptr_8discodop_10containers_FixedVocabulary = (struct __pyx_vtabstruct_8discodop_10containers_FixedVocabulary*)__Pyx_GetVtable(__pyx_ptype_8discodop_10containers_FixedVocabulary->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_10containers_FixedVocabulary)) __PYX_ERR(2, 692, __pyx_L1_error)
  __pyx_ptype_8discodop_4pcfg_CFGChart = __Pyx_ImportType("discodop.pcfg", "CFGChart", sizeof(struct __pyx_obj_8discodop_4pcfg_CFGChart), 1); if (unlikely(!__pyx_ptype_8discodop_4pcfg_CFGChart)) __PYX_ERR(5, 48, __pyx_L1_error)
  __pyx_vtabptr_8discodop_4pcfg_CFGChart = (struct __pyx_vtabstruct_8discodop_4pcfg_CFGChart*)__Pyx_GetVtable(__pyx_ptype_8discodop_4pcfg_CFGChart->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_4pcfg_CFGChart)) __PYX_ERR(5, 48, __pyx_L1_error)
  __pyx_ptype_8discodop_4pcfg_DenseCFGChart = __Pyx_ImportType("discodop.pcfg", "DenseCFGChart", sizeof(struct __pyx_obj_8discodop_4pcfg_DenseCFGChart), 1); if (unlikely(!__pyx_ptype_8discodop_4pcfg_DenseCFGChart)) __PYX_ERR(5, 55, __pyx_L1_error)
  __pyx_vtabptr_8discodop_4pcfg_DenseCFGChart = (struct __pyx_vtabstruct_8discodop_4pcfg_DenseCFGChart*)__Pyx_GetVtable(__pyx_ptype_8discodop_4pcfg_DenseCFGChart->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_4pcfg_DenseCFGChart)) __PYX_ERR(5, 55, __pyx_L1_error)
  __pyx_ptype_8discodop_4pcfg_SparseCFGChart = __Pyx_ImportType("discodop.pcfg", "SparseCFGChart", sizeof(struct __pyx_obj_8discodop_4pcfg_SparseCFGChart), 1); if (unlikely(!__pyx_ptype_8discodop_4pcfg_SparseCFGChart)) __PYX_ERR(5, 64, __pyx_L1_error)
  __pyx_vtabptr_8discodop_4pcfg_SparseCFGChart = (struct __pyx_vtabstruct_8discodop_4pcfg_SparseCFGChart*)__Pyx_GetVtable(__pyx_ptype_8discodop_4pcfg_SparseCFGChart->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_4pcfg_SparseCFGChart)) __PYX_ERR(5, 64, __pyx_L1_error)
  __pyx_ptype_8discodop_6plcfrs_LCFRSChart = __Pyx_ImportType("discodop.plcfrs", "LCFRSChart", sizeof(struct __pyx_obj_8discodop_6plcfrs_LCFRSChart), 1); if (unlikely(!__pyx_ptype_8discodop_6plcfrs_LCFRSChart)) __PYX_ERR(6, 30, __pyx_L1_error)
  __pyx_vtabptr_8discodop_6plcfrs_LCFRSChart = (struct __pyx_vtabstruct_8discodop_6plcfrs_LCFRSChart*)__Pyx_GetVtable(__pyx_ptype_8discodop_6plcfrs_LCFRSChart->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_6plcfrs_LCFRSChart)) __PYX_ERR(6, 30, __pyx_L1_error)
  __pyx_ptype_8discodop_6plcfrs_SmallLCFRSChart = __Pyx_ImportType("discodop.plcfrs", "SmallLCFRSChart", sizeof(struct __pyx_obj_8discodop_6plcfrs_SmallLCFRSChart), 1); if (unlikely(!__pyx_ptype_8discodop_6plcfrs_SmallLCFRSChart)) __PYX_ERR(6, 38, __pyx_L1_error)
  __pyx_vtabptr_8discodop_6plcfrs_SmallLCFRSChart = (struct __pyx_vtabstruct_8discodop_6plcfrs_SmallLCFRSChart*)__Pyx_GetVtable(__pyx_ptype_8discodop_6plcfrs_SmallLCFRSChart->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_6plcfrs_SmallLCFRSChart)) __PYX_ERR(6, 38, __pyx_L1_error)
  __pyx_ptype_8discodop_6plcfrs_FatLCFRSChart = __Pyx_ImportType("discodop.plcfrs", "FatLCFRSChart", sizeof(struct __pyx_obj_8discodop_6plcfrs_FatLCFRSChart), 1); if (unlikely(!__pyx_ptype_8discodop_6plcfrs_FatLCFRSChart)) __PYX_ERR(6, 49, __pyx_L1_error)
  __pyx_vtabptr_8discodop_6plcfrs_FatLCFRSChart = (struct __pyx_vtabstruct_8discodop_6plcfrs_FatLCFRSChart*)__Pyx_GetVtable(__pyx_ptype_8discodop_6plcfrs_FatLCFRSChart->tp_dict); if (unlikely(!__pyx_vtabptr_8discodop_6plcfrs_FatLCFRSChart)) __PYX_ERR(6, 49, __pyx_L1_error)
  /*--- Variable import code ---*/
  __pyx_t_1 = __Pyx_ImportModule("discodop.containers"); if (!__pyx_t_1) __PYX_ERR(0, 1, __pyx_L1_error)
  if (__Pyx_ImportVoidPtr(__pyx_t_1, "log1e200", (void **)&__pyx_vp_8discodop_10containers_log1e200, "PyObject *") < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  Py_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  /*--- Function import code ---*/
  __pyx_t_2 = __Pyx_ImportModule("discodop.bit"); if (!__pyx_t_2) __PYX_ERR(0, 1, __pyx_L1_error)
  if (__Pyx_ImportFunction(__pyx_t_2, "bitcount", (void (**)(void))&__pyx_f_8discodop_3bit_bitcount, "int (uint64_t, int __pyx_skip_dispatch)") < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  Py_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  __pyx_t_3 = __Pyx_ImportModule("discodop.containers"); if (!__pyx_t_3) __PYX_ERR(0, 1, __pyx_L1_error)
  if (__Pyx_ImportFunction(__pyx_t_3, "CFGtoSmallChartItem", (void (**)(void))&__pyx_f_8discodop_10containers_CFGtoSmallChartItem, "SmallChartItem (Label, __pyx_t_8discodop_10containers_Idx, __pyx_t_8discodop_10containers_Idx)") < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  if (__Pyx_ImportFunction(__pyx_t_3, "CFGtoFatChartItem", (void (**)(void))&__pyx_f_8discodop_10containers_CFGtoFatChartItem, "FatChartItem (Label, __pyx_t_8discodop_10containers_Idx, __pyx_t_8discodop_10containers_Idx)") < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  Py_DECREF(__pyx_t_3); __pyx_t_3 = 0;
  /*--- Execution code ---*/
  #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)
  if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  #endif

  /* "discodop/kbest.pyx":6
 * http://www.cis.upenn.edu/~lhuang3/huang-iwpt-correct.pdf"""
 * from __future__ import print_function
 * from operator import itemgetter             # <<<<<<<<<<<<<<
 * from .containers import Grammar
 * 
 */
  __pyx_t_4 = PyList_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  __Pyx_INCREF(__pyx_n_s_itemgetter);
  __Pyx_GIVEREF(__pyx_n_s_itemgetter);
  PyList_SET_ITEM(__pyx_t_4, 0, __pyx_n_s_itemgetter);
  __pyx_t_5 = __Pyx_Import(__pyx_n_s_operator, __pyx_t_4, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_5);
  __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
  __pyx_t_4 = __Pyx_ImportFrom(__pyx_t_5, __pyx_n_s_itemgetter); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  if (PyDict_SetItem(__pyx_d, __pyx_n_s_itemgetter, __pyx_t_4) < 0) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
  __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;

  /* "discodop/kbest.pyx":7
 * from __future__ import print_function
 * from operator import itemgetter
 * from .containers import Grammar             # <<<<<<<<<<<<<<
 * 
 * cimport cython
 */
  __pyx_t_5 = PyList_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 7, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_5);
  __Pyx_INCREF(__pyx_n_s_Grammar);
  __Pyx_GIVEREF(__pyx_n_s_Grammar);
  PyList_SET_ITEM(__pyx_t_5, 0, __pyx_n_s_Grammar);
  __pyx_t_4 = __Pyx_Import(__pyx_n_s_containers, __pyx_t_5, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 7, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
  __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;

  /* "discodop/kbest.pyx":221
 * 
 * 
 * def lazykbest(Chart chart, int k, bint derivs=True):             # <<<<<<<<<<<<<<
 * 	"""Wrapper function to run ``lazykthbest``.
 * 
 */
  __pyx_t_4 = PyCFunction_NewEx(&__pyx_mdef_8discodop_5kbest_1lazykbest, NULL, __pyx_n_s_discodop_kbest); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 221, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  if (PyDict_SetItem(__pyx_d, __pyx_n_s_lazykbest, __pyx_t_4) < 0) __PYX_ERR(0, 221, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;

  /* "discodop/kbest.pyx":255
 * 	return None
 * 
 * __all__ = ['getderiv', 'lazykbest']             # <<<<<<<<<<<<<<
 */
  __pyx_t_4 = PyList_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 255, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  __Pyx_INCREF(__pyx_n_u_getderiv);
  __Pyx_GIVEREF(__pyx_n_u_getderiv);
  PyList_SET_ITEM(__pyx_t_4, 0, __pyx_n_u_getderiv);
  __Pyx_INCREF(__pyx_n_u_lazykbest);
  __Pyx_GIVEREF(__pyx_n_u_lazykbest);
  PyList_SET_ITEM(__pyx_t_4, 1, __pyx_n_u_lazykbest);
  if (PyDict_SetItem(__pyx_d, __pyx_n_s_all, __pyx_t_4) < 0) __PYX_ERR(0, 255, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;

  /* "discodop/kbest.pyx":1
 * """Extract the k-best derivations from a probabilistic parse forest.             # <<<<<<<<<<<<<<
 * 
 * Implementation of Huang & Chiang (2005): Better k-best parsing.
 */
  __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_4) < 0) __PYX_ERR(0, 1, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;

  /* "string.to_py":55
 * 
 * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string")
 * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s):             # <<<<<<<<<<<<<<
 *     return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size())
 * 
 */

  /*--- Wrapped vars code ---*/

  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_2);
  __Pyx_XDECREF(__pyx_t_3);
  __Pyx_XDECREF(__pyx_t_4);
  __Pyx_XDECREF(__pyx_t_5);
  if (__pyx_m) {
    if (__pyx_d) {
      __Pyx_AddTraceback("init discodop.kbest", 0, __pyx_lineno, __pyx_filename);
    }
    Py_DECREF(__pyx_m); __pyx_m = 0;
  } else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_ImportError, "init discodop.kbest");
  }
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  #if PY_MAJOR_VERSION < 3
  return;
  #else
  return __pyx_m;
  #endif
}

/* --- Runtime support code --- */
/* Refnanny */
#if CYTHON_REFNANNY
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) {
    PyObject *m = NULL, *p = NULL;
    void *r = NULL;
    m = PyImport_ImportModule((char *)modname);
    if (!m) goto end;
    p = PyObject_GetAttrString(m, (char *)"RefNannyAPI");
    if (!p) goto end;
    r = PyLong_AsVoidPtr(p);
end:
    Py_XDECREF(p);
    Py_XDECREF(m);
    return (__Pyx_RefNannyAPIStruct *)r;
}
#endif

/* GetBuiltinName */
static PyObject *__Pyx_GetBuiltinName(PyObject *name) {
    PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name);
    if (unlikely(!result)) {
        PyErr_Format(PyExc_NameError,
#if PY_MAJOR_VERSION >= 3
            "name '%U' is not defined", name);
#else
            "name '%.200s' is not defined", PyString_AS_STRING(name));
#endif
    }
    return result;
}

/* PyErrFetchRestore */
#if CYTHON_FAST_THREAD_STATE
static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) {
    PyObject *tmp_type, *tmp_value, *tmp_tb;
    tmp_type = tstate->curexc_type;
    tmp_value = tstate->curexc_value;
    tmp_tb = tstate->curexc_traceback;
    tstate->curexc_type = type;
    tstate->curexc_value = value;
    tstate->curexc_traceback = tb;
    Py_XDECREF(tmp_type);
    Py_XDECREF(tmp_value);
    Py_XDECREF(tmp_tb);
}
static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) {
    *type = tstate->curexc_type;
    *value = tstate->curexc_value;
    *tb = tstate->curexc_traceback;
    tstate->curexc_type = 0;
    tstate->curexc_value = 0;
    tstate->curexc_traceback = 0;
}
#endif

/* WriteUnraisableException */
static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno,
                                  CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename,
                                  int full_traceback, CYTHON_UNUSED int nogil) {
    PyObject *old_exc, *old_val, *old_tb;
    PyObject *ctx;
    __Pyx_PyThreadState_declare
#ifdef WITH_THREAD
    PyGILState_STATE state;
    if (nogil)
        state = PyGILState_Ensure();
#ifdef _MSC_VER
    else state = (PyGILState_STATE)-1;
#endif
#endif
    __Pyx_PyThreadState_assign
    __Pyx_ErrFetch(&old_exc, &old_val, &old_tb);
    if (full_traceback) {
        Py_XINCREF(old_exc);
        Py_XINCREF(old_val);
        Py_XINCREF(old_tb);
        __Pyx_ErrRestore(old_exc, old_val, old_tb);
        PyErr_PrintEx(1);
    }
    #if PY_MAJOR_VERSION < 3
    ctx = PyString_FromString(name);
    #else
    ctx = PyUnicode_FromString(name);
    #endif
    __Pyx_ErrRestore(old_exc, old_val, old_tb);
    if (!ctx) {
        PyErr_WriteUnraisable(Py_None);
    } else {
        PyErr_WriteUnraisable(ctx);
        Py_DECREF(ctx);
    }
#ifdef WITH_THREAD
    if (nogil)
        PyGILState_Release(state);
#endif
}

/* PyCFunctionFastCall */
#if CYTHON_FAST_PYCCALL
static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) {
    PyCFunctionObject *func = (PyCFunctionObject*)func_obj;
    PyCFunction meth = PyCFunction_GET_FUNCTION(func);
    PyObject *self = PyCFunction_GET_SELF(func);
    int flags = PyCFunction_GET_FLAGS(func);
    assert(PyCFunction_Check(func));
    assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS)));
    assert(nargs >= 0);
    assert(nargs == 0 || args != NULL);
    /* _PyCFunction_FastCallDict() must not be called with an exception set,
       because it may clear it (directly or indirectly) and so the
       caller loses its exception */
    assert(!PyErr_Occurred());
    if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) {
        return (*((__Pyx_PyCFunctionFastWithKeywords)meth)) (self, args, nargs, NULL);
    } else {
        return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs);
    }
}
#endif

/* PyFunctionFastCall */
#if CYTHON_FAST_PYCALL
#include "frameobject.h"
static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na,
                                               PyObject *globals) {
    PyFrameObject *f;
    PyThreadState *tstate = PyThreadState_GET();
    PyObject **fastlocals;
    Py_ssize_t i;
    PyObject *result;
    assert(globals != NULL);
    /* XXX Perhaps we should create a specialized
       PyFrame_New() that doesn't take locals, but does
       take builtins without sanity checking them.
       */
    assert(tstate != NULL);
    f = PyFrame_New(tstate, co, globals, NULL);
    if (f == NULL) {
        return NULL;
    }
    fastlocals = f->f_localsplus;
    for (i = 0; i < na; i++) {
        Py_INCREF(*args);
        fastlocals[i] = *args++;
    }
    result = PyEval_EvalFrameEx(f,0);
    ++tstate->recursion_depth;
    Py_DECREF(f);
    --tstate->recursion_depth;
    return result;
}
#if 1 || PY_VERSION_HEX < 0x030600B1
static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs) {
    PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
    PyObject *globals = PyFunction_GET_GLOBALS(func);
    PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
    PyObject *closure;
#if PY_MAJOR_VERSION >= 3
    PyObject *kwdefs;
#endif
    PyObject *kwtuple, **k;
    PyObject **d;
    Py_ssize_t nd;
    Py_ssize_t nk;
    PyObject *result;
    assert(kwargs == NULL || PyDict_Check(kwargs));
    nk = kwargs ? PyDict_Size(kwargs) : 0;
    if (Py_EnterRecursiveCall((char*)" while calling a Python object")) {
        return NULL;
    }
    if (
#if PY_MAJOR_VERSION >= 3
            co->co_kwonlyargcount == 0 &&
#endif
            likely(kwargs == NULL || nk == 0) &&
            co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
        if (argdefs == NULL && co->co_argcount == nargs) {
            result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals);
            goto done;
        }
        else if (nargs == 0 && argdefs != NULL
                 && co->co_argcount == Py_SIZE(argdefs)) {
            /* function called with no arguments, but all parameters have
               a default value: use default values as arguments .*/
            args = &PyTuple_GET_ITEM(argdefs, 0);
            result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals);
            goto done;
        }
    }
    if (kwargs != NULL) {
        Py_ssize_t pos, i;
        kwtuple = PyTuple_New(2 * nk);
        if (kwtuple == NULL) {
            result = NULL;
            goto done;
        }
        k = &PyTuple_GET_ITEM(kwtuple, 0);
        pos = i = 0;
        while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) {
            Py_INCREF(k[i]);
            Py_INCREF(k[i+1]);
            i += 2;
        }
        nk = i / 2;
    }
    else {
        kwtuple = NULL;
        k = NULL;
    }
    closure = PyFunction_GET_CLOSURE(func);
#if PY_MAJOR_VERSION >= 3
    kwdefs = PyFunction_GET_KW_DEFAULTS(func);
#endif
    if (argdefs != NULL) {
        d = &PyTuple_GET_ITEM(argdefs, 0);
        nd = Py_SIZE(argdefs);
    }
    else {
        d = NULL;
        nd = 0;
    }
#if PY_MAJOR_VERSION >= 3
    result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL,
                               args, nargs,
                               k, (int)nk,
                               d, (int)nd, kwdefs, closure);
#else
    result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL,
                               args, nargs,
                               k, (int)nk,
                               d, (int)nd, closure);
#endif
    Py_XDECREF(kwtuple);
done:
    Py_LeaveRecursiveCall();
    return result;
}
#endif
#endif

/* PyObjectCall */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) {
    PyObject *result;
    ternaryfunc call = func->ob_type->tp_call;
    if (unlikely(!call))
        return PyObject_Call(func, arg, kw);
    if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
        return NULL;
    result = (*call)(func, arg, kw);
    Py_LeaveRecursiveCall();
    if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
        PyErr_SetString(
            PyExc_SystemError,
            "NULL result without error in PyObject_Call");
    }
    return result;
}
#endif

/* PyObjectCallMethO */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) {
    PyObject *self, *result;
    PyCFunction cfunc;
    cfunc = PyCFunction_GET_FUNCTION(func);
    self = PyCFunction_GET_SELF(func);
    if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
        return NULL;
    result = cfunc(self, arg);
    Py_LeaveRecursiveCall();
    if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
        PyErr_SetString(
            PyExc_SystemError,
            "NULL result without error in PyObject_Call");
    }
    return result;
}
#endif

/* PyObjectCallOneArg */
#if CYTHON_COMPILING_IN_CPYTHON
static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) {
    PyObject *result;
    PyObject *args = PyTuple_New(1);
    if (unlikely(!args)) return NULL;
    Py_INCREF(arg);
    PyTuple_SET_ITEM(args, 0, arg);
    result = __Pyx_PyObject_Call(func, args, NULL);
    Py_DECREF(args);
    return result;
}
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) {
#if CYTHON_FAST_PYCALL
    if (PyFunction_Check(func)) {
        return __Pyx_PyFunction_FastCall(func, &arg, 1);
    }
#endif
    if (likely(PyCFunction_Check(func))) {
        if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) {
            return __Pyx_PyObject_CallMethO(func, arg);
#if CYTHON_FAST_PYCCALL
        } else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) {
            return __Pyx_PyCFunction_FastCall(func, &arg, 1);
#endif
        }
    }
    return __Pyx__PyObject_CallOneArg(func, arg);
}
#else
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) {
    PyObject *result;
    PyObject *args = PyTuple_Pack(1, arg);
    if (unlikely(!args)) return NULL;
    result = __Pyx_PyObject_Call(func, args, NULL);
    Py_DECREF(args);
    return result;
}
#endif

/* RaiseException */
#if PY_MAJOR_VERSION < 3
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb,
                        CYTHON_UNUSED PyObject *cause) {
    __Pyx_PyThreadState_declare
    Py_XINCREF(type);
    if (!value || value == Py_None)
        value = NULL;
    else
        Py_INCREF(value);
    if (!tb || tb == Py_None)
        tb = NULL;
    else {
        Py_INCREF(tb);
        if (!PyTraceBack_Check(tb)) {
            PyErr_SetString(PyExc_TypeError,
                "raise: arg 3 must be a traceback or None");
            goto raise_error;
        }
    }
    if (PyType_Check(type)) {
#if CYTHON_COMPILING_IN_PYPY
        if (!value) {
            Py_INCREF(Py_None);
            value = Py_None;
        }
#endif
        PyErr_NormalizeException(&type, &value, &tb);
    } else {
        if (value) {
            PyErr_SetString(PyExc_TypeError,
                "instance exception may not have a separate value");
            goto raise_error;
        }
        value = type;
        type = (PyObject*) Py_TYPE(type);
        Py_INCREF(type);
        if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) {
            PyErr_SetString(PyExc_TypeError,
                "raise: exception class must be a subclass of BaseException");
            goto raise_error;
        }
    }
    __Pyx_PyThreadState_assign
    __Pyx_ErrRestore(type, value, tb);
    return;
raise_error:
    Py_XDECREF(value);
    Py_XDECREF(type);
    Py_XDECREF(tb);
    return;
}
#else
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) {
    PyObject* owned_instance = NULL;
    if (tb == Py_None) {
        tb = 0;
    } else if (tb && !PyTraceBack_Check(tb)) {
        PyErr_SetString(PyExc_TypeError,
            "raise: arg 3 must be a traceback or None");
        goto bad;
    }
    if (value == Py_None)
        value = 0;
    if (PyExceptionInstance_Check(type)) {
        if (value) {
            PyErr_SetString(PyExc_TypeError,
                "instance exception may not have a separate value");
            goto bad;
        }
        value = type;
        type = (PyObject*) Py_TYPE(value);
    } else if (PyExceptionClass_Check(type)) {
        PyObject *instance_class = NULL;
        if (value && PyExceptionInstance_Check(value)) {
            instance_class = (PyObject*) Py_TYPE(value);
            if (instance_class != type) {
                int is_subclass = PyObject_IsSubclass(instance_class, type);
                if (!is_subclass) {
                    instance_class = NULL;
                } else if (unlikely(is_subclass == -1)) {
                    goto bad;
                } else {
                    type = instance_class;
                }
            }
        }
        if (!instance_class) {
            PyObject *args;
            if (!value)
                args = PyTuple_New(0);
            else if (PyTuple_Check(value)) {
                Py_INCREF(value);
                args = value;
            } else
                args = PyTuple_Pack(1, value);
            if (!args)
                goto bad;
            owned_instance = PyObject_Call(type, args, NULL);
            Py_DECREF(args);
            if (!owned_instance)
                goto bad;
            value = owned_instance;
            if (!PyExceptionInstance_Check(value)) {
                PyErr_Format(PyExc_TypeError,
                             "calling %R should have returned an instance of "
                             "BaseException, not %R",
                             type, Py_TYPE(value));
                goto bad;
            }
        }
    } else {
        PyErr_SetString(PyExc_TypeError,
            "raise: exception class must be a subclass of BaseException");
        goto bad;
    }
#if PY_VERSION_HEX >= 0x03030000
    if (cause) {
#else
    if (cause && cause != Py_None) {
#endif
        PyObject *fixed_cause;
        if (cause == Py_None) {
            fixed_cause = NULL;
        } else if (PyExceptionClass_Check(cause)) {
            fixed_cause = PyObject_CallObject(cause, NULL);
            if (fixed_cause == NULL)
                goto bad;
        } else if (PyExceptionInstance_Check(cause)) {
            fixed_cause = cause;
            Py_INCREF(fixed_cause);
        } else {
            PyErr_SetString(PyExc_TypeError,
                            "exception causes must derive from "
                            "BaseException");
            goto bad;
        }
        PyException_SetCause(value, fixed_cause);
    }
    PyErr_SetObject(type, value);
    if (tb) {
#if CYTHON_COMPILING_IN_PYPY
        PyObject *tmp_type, *tmp_value, *tmp_tb;
        PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb);
        Py_INCREF(tb);
        PyErr_Restore(tmp_type, tmp_value, tb);
        Py_XDECREF(tmp_tb);
#else
        PyThreadState *tstate = PyThreadState_GET();
        PyObject* tmp_tb = tstate->curexc_traceback;
        if (tb != tmp_tb) {
            Py_INCREF(tb);
            tstate->curexc_traceback = tb;
            Py_XDECREF(tmp_tb);
        }
#endif
    }
bad:
    Py_XDECREF(owned_instance);
    return;
}
#endif

/* RaiseArgTupleInvalid */
  static void __Pyx_RaiseArgtupleInvalid(
    const char* func_name,
    int exact,
    Py_ssize_t num_min,
    Py_ssize_t num_max,
    Py_ssize_t num_found)
{
    Py_ssize_t num_expected;
    const char *more_or_less;
    if (num_found < num_min) {
        num_expected = num_min;
        more_or_less = "at least";
    } else {
        num_expected = num_max;
        more_or_less = "at most";
    }
    if (exact) {
        more_or_less = "exactly";
    }
    PyErr_Format(PyExc_TypeError,
                 "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)",
                 func_name, more_or_less, num_expected,
                 (num_expected == 1) ? "" : "s", num_found);
}

/* RaiseDoubleKeywords */
  static void __Pyx_RaiseDoubleKeywordsError(
    const char* func_name,
    PyObject* kw_name)
{
    PyErr_Format(PyExc_TypeError,
        #if PY_MAJOR_VERSION >= 3
        "%s() got multiple values for keyword argument '%U'", func_name, kw_name);
        #else
        "%s() got multiple values for keyword argument '%s'", func_name,
        PyString_AsString(kw_name));
        #endif
}

/* ParseKeywords */
  static int __Pyx_ParseOptionalKeywords(
    PyObject *kwds,
    PyObject **argnames[],
    PyObject *kwds2,
    PyObject *values[],
    Py_ssize_t num_pos_args,
    const char* function_name)
{
    PyObject *key = 0, *value = 0;
    Py_ssize_t pos = 0;
    PyObject*** name;
    PyObject*** first_kw_arg = argnames + num_pos_args;
    while (PyDict_Next(kwds, &pos, &key, &value)) {
        name = first_kw_arg;
        while (*name && (**name != key)) name++;
        if (*name) {
            values[name-argnames] = value;
            continue;
        }
        name = first_kw_arg;
        #if PY_MAJOR_VERSION < 3
        if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) {
            while (*name) {
                if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key))
                        && _PyString_Eq(**name, key)) {
                    values[name-argnames] = value;
                    break;
                }
                name++;
            }
            if (*name) continue;
            else {
                PyObject*** argname = argnames;
                while (argname != first_kw_arg) {
                    if ((**argname == key) || (
                            (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key))
                             && _PyString_Eq(**argname, key))) {
                        goto arg_passed_twice;
                    }
                    argname++;
                }
            }
        } else
        #endif
        if (likely(PyUnicode_Check(key))) {
            while (*name) {
                int cmp = (**name == key) ? 0 :
                #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
                    (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 :
                #endif
                    PyUnicode_Compare(**name, key);
                if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
                if (cmp == 0) {
                    values[name-argnames] = value;
                    break;
                }
                name++;
            }
            if (*name) continue;
            else {
                PyObject*** argname = argnames;
                while (argname != first_kw_arg) {
                    int cmp = (**argname == key) ? 0 :
                    #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
                        (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 :
                    #endif
                        PyUnicode_Compare(**argname, key);
                    if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
                    if (cmp == 0) goto arg_passed_twice;
                    argname++;
                }
            }
        } else
            goto invalid_keyword_type;
        if (kwds2) {
            if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
        } else {
            goto invalid_keyword;
        }
    }
    return 0;
arg_passed_twice:
    __Pyx_RaiseDoubleKeywordsError(function_name, key);
    goto bad;
invalid_keyword_type:
    PyErr_Format(PyExc_TypeError,
        "%.200s() keywords must be strings", function_name);
    goto bad;
invalid_keyword:
    PyErr_Format(PyExc_TypeError,
    #if PY_MAJOR_VERSION < 3
        "%.200s() got an unexpected keyword argument '%.200s'",
        function_name, PyString_AsString(key));
    #else
        "%s() got an unexpected keyword argument '%U'",
        function_name, key);
    #endif
bad:
    return -1;
}

/* ArgTypeTest */
  static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) {
    PyErr_Format(PyExc_TypeError,
        "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)",
        name, type->tp_name, Py_TYPE(obj)->tp_name);
}
static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
    const char *name, int exact)
{
    if (unlikely(!type)) {
        PyErr_SetString(PyExc_SystemError, "Missing type object");
        return 0;
    }
    if (none_allowed && obj == Py_None) return 1;
    else if (exact) {
        if (likely(Py_TYPE(obj) == type)) return 1;
        #if PY_MAJOR_VERSION == 2
        else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1;
        #endif
    }
    else {
        if (likely(PyObject_TypeCheck(obj, type))) return 1;
    }
    __Pyx_RaiseArgumentTypeInvalid(name, obj, type);
    return 0;
}

/* PyObjectCallNoArg */
  #if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) {
#if CYTHON_FAST_PYCALL
    if (PyFunction_Check(func)) {
        return __Pyx_PyFunction_FastCall(func, NULL, 0);
    }
#endif
#ifdef __Pyx_CyFunction_USED
    if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) {
#else
    if (likely(PyCFunction_Check(func))) {
#endif
        if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) {
            return __Pyx_PyObject_CallMethO(func, NULL);
        }
    }
    return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL);
}
#endif

/* decode_c_bytes */
    static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes(
         const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop,
         const char* encoding, const char* errors,
         PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) {
    if (unlikely((start < 0) | (stop < 0))) {
        if (start < 0) {
            start += length;
            if (start < 0)
                start = 0;
        }
        if (stop < 0)
            stop += length;
    }
    if (stop > length)
        stop = length;
    length = stop - start;
    if (unlikely(length <= 0))
        return PyUnicode_FromUnicode(NULL, 0);
    cstring += start;
    if (decode_func) {
        return decode_func(cstring, length, errors);
    } else {
        return PyUnicode_Decode(cstring, length, encoding, errors);
    }
}

/* GetModuleGlobalName */
    static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) {
    PyObject *result;
#if !CYTHON_AVOID_BORROWED_REFS
    result = PyDict_GetItem(__pyx_d, name);
    if (likely(result)) {
        Py_INCREF(result);
    } else {
#else
    result = PyObject_GetItem(__pyx_d, name);
    if (!result) {
        PyErr_Clear();
#endif
        result = __Pyx_GetBuiltinName(name);
    }
    return result;
}

/* PyIntBinop */
      #if !CYTHON_COMPILING_IN_PYPY
static PyObject* __Pyx_PyInt_SubtractObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) {
    #if PY_MAJOR_VERSION < 3
    if (likely(PyInt_CheckExact(op1))) {
        const long b = intval;
        long x;
        long a = PyInt_AS_LONG(op1);
            x = (long)((unsigned long)a - b);
            if (likely((x^a) >= 0 || (x^~b) >= 0))
                return PyInt_FromLong(x);
            return PyLong_Type.tp_as_number->nb_subtract(op1, op2);
    }
    #endif
    #if CYTHON_USE_PYLONG_INTERNALS
    if (likely(PyLong_CheckExact(op1))) {
        const long b = intval;
        long a, x;
#ifdef HAVE_LONG_LONG
        const PY_LONG_LONG llb = intval;
        PY_LONG_LONG lla, llx;
#endif
        const digit* digits = ((PyLongObject*)op1)->ob_digit;
        const Py_ssize_t size = Py_SIZE(op1);
        if (likely(__Pyx_sst_abs(size) <= 1)) {
            a = likely(size) ? digits[0] : 0;
            if (size == -1) a = -a;
        } else {
            switch (size) {
                case -2:
                    if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
                        a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
                        break;
#ifdef HAVE_LONG_LONG
                    } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) {
                        lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
                        goto long_long;
#endif
                    }
                case 2:
                    if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
                        a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
                        break;
#ifdef HAVE_LONG_LONG
                    } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) {
                        lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
                        goto long_long;
#endif
                    }
                case -3:
                    if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
                        a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
                        break;
#ifdef HAVE_LONG_LONG
                    } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) {
                        lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
                        goto long_long;
#endif
                    }
                case 3:
                    if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
                        a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
                        break;
#ifdef HAVE_LONG_LONG
                    } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) {
                        lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
                        goto long_long;
#endif
                    }
                case -4:
                    if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
                        a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
                        break;
#ifdef HAVE_LONG_LONG
                    } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) {
                        lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
                        goto long_long;
#endif
                    }
                case 4:
                    if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
                        a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]));
                        break;
#ifdef HAVE_LONG_LONG
                    } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) {
                        lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0]));
                        goto long_long;
#endif
                    }
                default: return PyLong_Type.tp_as_number->nb_subtract(op1, op2);
            }
        }
                x = a - b;
            return PyLong_FromLong(x);
#ifdef HAVE_LONG_LONG
        long_long:
                llx = lla - llb;
            return PyLong_FromLongLong(llx);
#endif
        
        
    }
    #endif
    if (PyFloat_CheckExact(op1)) {
        const long b = intval;
        double a = PyFloat_AS_DOUBLE(op1);
            double result;
            PyFPE_START_PROTECT("subtract", return NULL)
            result = ((double)a) - (double)b;
            PyFPE_END_PROTECT(result)
            return PyFloat_FromDouble(result);
    }
    return (inplace ? PyNumber_InPlaceSubtract : PyNumber_Subtract)(op1, op2);
}
#endif

/* GetVTable */
      static void* __Pyx_GetVtable(PyObject *dict) {
    void* ptr;
    PyObject *ob = PyObject_GetItem(dict, __pyx_n_s_pyx_vtable);
    if (!ob)
        goto bad;
#if PY_VERSION_HEX >= 0x02070000
    ptr = PyCapsule_GetPointer(ob, 0);
#else
    ptr = PyCObject_AsVoidPtr(ob);
#endif
    if (!ptr && !PyErr_Occurred())
        PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type");
    Py_DECREF(ob);
    return ptr;
bad:
    Py_XDECREF(ob);
    return NULL;
}

/* Import */
      static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) {
    PyObject *empty_list = 0;
    PyObject *module = 0;
    PyObject *global_dict = 0;
    PyObject *empty_dict = 0;
    PyObject *list;
    #if PY_VERSION_HEX < 0x03030000
    PyObject *py_import;
    py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import);
    if (!py_import)
        goto bad;
    #endif
    if (from_list)
        list = from_list;
    else {
        empty_list = PyList_New(0);
        if (!empty_list)
            goto bad;
        list = empty_list;
    }
    global_dict = PyModule_GetDict(__pyx_m);
    if (!global_dict)
        goto bad;
    empty_dict = PyDict_New();
    if (!empty_dict)
        goto bad;
    {
        #if PY_MAJOR_VERSION >= 3
        if (level == -1) {
            if (strchr(__Pyx_MODULE_NAME, '.')) {
                #if PY_VERSION_HEX < 0x03030000
                PyObject *py_level = PyInt_FromLong(1);
                if (!py_level)
                    goto bad;
                module = PyObject_CallFunctionObjArgs(py_import,
                    name, global_dict, empty_dict, list, py_level, NULL);
                Py_DECREF(py_level);
                #else
                module = PyImport_ImportModuleLevelObject(
                    name, global_dict, empty_dict, list, 1);
                #endif
                if (!module) {
                    if (!PyErr_ExceptionMatches(PyExc_ImportError))
                        goto bad;
                    PyErr_Clear();
                }
            }
            level = 0;
        }
        #endif
        if (!module) {
            #if PY_VERSION_HEX < 0x03030000
            PyObject *py_level = PyInt_FromLong(level);
            if (!py_level)
                goto bad;
            module = PyObject_CallFunctionObjArgs(py_import,
                name, global_dict, empty_dict, list, py_level, NULL);
            Py_DECREF(py_level);
            #else
            module = PyImport_ImportModuleLevelObject(
                name, global_dict, empty_dict, list, level);
            #endif
        }
    }
bad:
    #if PY_VERSION_HEX < 0x03030000
    Py_XDECREF(py_import);
    #endif
    Py_XDECREF(empty_list);
    Py_XDECREF(empty_dict);
    return module;
}

/* ImportFrom */
      static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) {
    PyObject* value = __Pyx_PyObject_GetAttrStr(module, name);
    if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) {
        PyErr_Format(PyExc_ImportError,
        #if PY_MAJOR_VERSION < 3
            "cannot import name %.230s", PyString_AS_STRING(name));
        #else
            "cannot import name %S", name);
        #endif
    }
    return value;
}

/* CLineInTraceback */
      static int __Pyx_CLineForTraceback(int c_line) {
#ifdef CYTHON_CLINE_IN_TRACEBACK
    return ((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0;
#else
    PyObject **cython_runtime_dict;
    PyObject *use_cline;
    cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime);
    if (unlikely(!cython_runtime_dict)) {
      PyObject *ptype, *pvalue, *ptraceback;
      PyObject *use_cline_obj;
      PyErr_Fetch(&ptype, &pvalue, &ptraceback);
      use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback);
      if (use_cline_obj) {
        use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True;
        Py_DECREF(use_cline_obj);
      } else {
        use_cline = NULL;
      }
      PyErr_Restore(ptype, pvalue, ptraceback);
    } else {
      use_cline = PyDict_GetItem(*_PyObject_GetDictPtr(__pyx_cython_runtime), __pyx_n_s_cline_in_traceback);
    }
    if (!use_cline) {
        c_line = 0;
        PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False);
    }
    else if (PyObject_Not(use_cline) != 0) {
        c_line = 0;
    }
    return c_line;
#endif
}

/* CodeObjectCache */
      static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) {
    int start = 0, mid = 0, end = count - 1;
    if (end >= 0 && code_line > entries[end].code_line) {
        return count;
    }
    while (start < end) {
        mid = start + (end - start) / 2;
        if (code_line < entries[mid].code_line) {
            end = mid;
        } else if (code_line > entries[mid].code_line) {
             start = mid + 1;
        } else {
            return mid;
        }
    }
    if (code_line <= entries[mid].code_line) {
        return mid;
    } else {
        return mid + 1;
    }
}
static PyCodeObject *__pyx_find_code_object(int code_line) {
    PyCodeObject* code_object;
    int pos;
    if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) {
        return NULL;
    }
    pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
    if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) {
        return NULL;
    }
    code_object = __pyx_code_cache.entries[pos].code_object;
    Py_INCREF(code_object);
    return code_object;
}
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) {
    int pos, i;
    __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries;
    if (unlikely(!code_line)) {
        return;
    }
    if (unlikely(!entries)) {
        entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry));
        if (likely(entries)) {
            __pyx_code_cache.entries = entries;
            __pyx_code_cache.max_count = 64;
            __pyx_code_cache.count = 1;
            entries[0].code_line = code_line;
            entries[0].code_object = code_object;
            Py_INCREF(code_object);
        }
        return;
    }
    pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
    if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) {
        PyCodeObject* tmp = entries[pos].code_object;
        entries[pos].code_object = code_object;
        Py_DECREF(tmp);
        return;
    }
    if (__pyx_code_cache.count == __pyx_code_cache.max_count) {
        int new_max = __pyx_code_cache.max_count + 64;
        entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc(
            __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry));
        if (unlikely(!entries)) {
            return;
        }
        __pyx_code_cache.entries = entries;
        __pyx_code_cache.max_count = new_max;
    }
    for (i=__pyx_code_cache.count; i>pos; i--) {
        entries[i] = entries[i-1];
    }
    entries[pos].code_line = code_line;
    entries[pos].code_object = code_object;
    __pyx_code_cache.count++;
    Py_INCREF(code_object);
}

/* AddTraceback */
      #include "compile.h"
#include "frameobject.h"
#include "traceback.h"
static PyCodeObject* __Pyx_CreateCodeObjectForTraceback(
            const char *funcname, int c_line,
            int py_line, const char *filename) {
    PyCodeObject *py_code = 0;
    PyObject *py_srcfile = 0;
    PyObject *py_funcname = 0;
    #if PY_MAJOR_VERSION < 3
    py_srcfile = PyString_FromString(filename);
    #else
    py_srcfile = PyUnicode_FromString(filename);
    #endif
    if (!py_srcfile) goto bad;
    if (c_line) {
        #if PY_MAJOR_VERSION < 3
        py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
        #else
        py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
        #endif
    }
    else {
        #if PY_MAJOR_VERSION < 3
        py_funcname = PyString_FromString(funcname);
        #else
        py_funcname = PyUnicode_FromString(funcname);
        #endif
    }
    if (!py_funcname) goto bad;
    py_code = __Pyx_PyCode_New(
        0,
        0,
        0,
        0,
        0,
        __pyx_empty_bytes, /*PyObject *code,*/
        __pyx_empty_tuple, /*PyObject *consts,*/
        __pyx_empty_tuple, /*PyObject *names,*/
        __pyx_empty_tuple, /*PyObject *varnames,*/
        __pyx_empty_tuple, /*PyObject *freevars,*/
        __pyx_empty_tuple, /*PyObject *cellvars,*/
        py_srcfile,   /*PyObject *filename,*/
        py_funcname,  /*PyObject *name,*/
        py_line,
        __pyx_empty_bytes  /*PyObject *lnotab*/
    );
    Py_DECREF(py_srcfile);
    Py_DECREF(py_funcname);
    return py_code;
bad:
    Py_XDECREF(py_srcfile);
    Py_XDECREF(py_funcname);
    return NULL;
}
static void __Pyx_AddTraceback(const char *funcname, int c_line,
                               int py_line, const char *filename) {
    PyCodeObject *py_code = 0;
    PyFrameObject *py_frame = 0;
    if (c_line) {
        c_line = __Pyx_CLineForTraceback(c_line);
    }
    py_code = __pyx_find_code_object(c_line ? -c_line : py_line);
    if (!py_code) {
        py_code = __Pyx_CreateCodeObjectForTraceback(
            funcname, c_line, py_line, filename);
        if (!py_code) goto bad;
        __pyx_insert_code_object(c_line ? -c_line : py_line, py_code);
    }
    py_frame = PyFrame_New(
        PyThreadState_GET(), /*PyThreadState *tstate,*/
        py_code,             /*PyCodeObject *code,*/
        __pyx_d,      /*PyObject *globals,*/
        0                    /*PyObject *locals*/
    );
    if (!py_frame) goto bad;
    __Pyx_PyFrame_SetLineNumber(py_frame, py_line);
    PyTraceBack_Here(py_frame);
bad:
    Py_XDECREF(py_code);
    Py_XDECREF(py_frame);
}

/* CIntFromPyVerify */
      #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\
    __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0)
#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\
    __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1)
#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\
    {\
        func_type value = func_value;\
        if (sizeof(target_type) < sizeof(func_type)) {\
            if (unlikely(value != (func_type) (target_type) value)) {\
                func_type zero = 0;\
                if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\
                    return (target_type) -1;\
                if (is_unsigned && unlikely(value < zero))\
                    goto raise_neg_overflow;\
                else\
                    goto raise_overflow;\
            }\
        }\
        return (target_type) value;\
    }

/* CIntToPy */
      static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint32_t(uint32_t value) {
    const uint32_t neg_one = (uint32_t) -1, const_zero = (uint32_t) 0;
    const int is_unsigned = neg_one > const_zero;
    if (is_unsigned) {
        if (sizeof(uint32_t) < sizeof(long)) {
            return PyInt_FromLong((long) value);
        } else if (sizeof(uint32_t) <= sizeof(unsigned long)) {
            return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
        } else if (sizeof(uint32_t) <= sizeof(unsigned PY_LONG_LONG)) {
            return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
        }
    } else {
        if (sizeof(uint32_t) <= sizeof(long)) {
            return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
        } else if (sizeof(uint32_t) <= sizeof(PY_LONG_LONG)) {
            return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
        }
    }
    {
        int one = 1; int little = (int)*(unsigned char *)&one;
        unsigned char *bytes = (unsigned char *)&value;
        return _PyLong_FromByteArray(bytes, sizeof(uint32_t),
                                     little, !is_unsigned);
    }
}

/* CIntToPy */
      static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) {
    const int neg_one = (int) -1, const_zero = (int) 0;
    const int is_unsigned = neg_one > const_zero;
    if (is_unsigned) {
        if (sizeof(int) < sizeof(long)) {
            return PyInt_FromLong((long) value);
        } else if (sizeof(int) <= sizeof(unsigned long)) {
            return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
        } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) {
            return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
        }
    } else {
        if (sizeof(int) <= sizeof(long)) {
            return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
        } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) {
            return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
        }
    }
    {
        int one = 1; int little = (int)*(unsigned char *)&one;
        unsigned char *bytes = (unsigned char *)&value;
        return _PyLong_FromByteArray(bytes, sizeof(int),
                                     little, !is_unsigned);
    }
}

/* CIntFromPy */
      static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) {
    const int neg_one = (int) -1, const_zero = (int) 0;
    const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
    if (likely(PyInt_Check(x))) {
        if (sizeof(int) < sizeof(long)) {
            __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x))
        } else {
            long val = PyInt_AS_LONG(x);
            if (is_unsigned && unlikely(val < 0)) {
                goto raise_neg_overflow;
            }
            return (int) val;
        }
    } else
#endif
    if (likely(PyLong_Check(x))) {
        if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
            const digit* digits = ((PyLongObject*)x)->ob_digit;
            switch (Py_SIZE(x)) {
                case  0: return (int) 0;
                case  1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0])
                case 2:
                    if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) {
                            return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
                        }
                    }
                    break;
                case 3:
                    if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) {
                            return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
                        }
                    }
                    break;
                case 4:
                    if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) {
                            return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
                        }
                    }
                    break;
            }
#endif
#if CYTHON_COMPILING_IN_CPYTHON
            if (unlikely(Py_SIZE(x) < 0)) {
                goto raise_neg_overflow;
            }
#else
            {
                int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
                if (unlikely(result < 0))
                    return (int) -1;
                if (unlikely(result == 1))
                    goto raise_neg_overflow;
            }
#endif
            if (sizeof(int) <= sizeof(unsigned long)) {
                __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
            } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) {
                __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
            }
        } else {
#if CYTHON_USE_PYLONG_INTERNALS
            const digit* digits = ((PyLongObject*)x)->ob_digit;
            switch (Py_SIZE(x)) {
                case  0: return (int) 0;
                case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0]))
                case  1: __PYX_VERIFY_RETURN_INT(int,  digit, +digits[0])
                case -2:
                    if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
                            return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
                        }
                    }
                    break;
                case 2:
                    if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
                            return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
                        }
                    }
                    break;
                case -3:
                    if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
                            return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
                        }
                    }
                    break;
                case 3:
                    if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
                            return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
                        }
                    }
                    break;
                case -4:
                    if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
                            return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
                        }
                    }
                    break;
                case 4:
                    if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
                            return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
                        }
                    }
                    break;
            }
#endif
            if (sizeof(int) <= sizeof(long)) {
                __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
            } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) {
                __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
            }
        }
        {
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
            PyErr_SetString(PyExc_RuntimeError,
                            "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
            int val;
            PyObject *v = __Pyx_PyNumber_IntOrLong(x);
 #if PY_MAJOR_VERSION < 3
            if (likely(v) && !PyLong_Check(v)) {
                PyObject *tmp = v;
                v = PyNumber_Long(tmp);
                Py_DECREF(tmp);
            }
 #endif
            if (likely(v)) {
                int one = 1; int is_little = (int)*(unsigned char *)&one;
                unsigned char *bytes = (unsigned char *)&val;
                int ret = _PyLong_AsByteArray((PyLongObject *)v,
                                              bytes, sizeof(val),
                                              is_little, !is_unsigned);
                Py_DECREF(v);
                if (likely(!ret))
                    return val;
            }
#endif
            return (int) -1;
        }
    } else {
        int val;
        PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
        if (!tmp) return (int) -1;
        val = __Pyx_PyInt_As_int(tmp);
        Py_DECREF(tmp);
        return val;
    }
raise_overflow:
    PyErr_SetString(PyExc_OverflowError,
        "value too large to convert to int");
    return (int) -1;
raise_neg_overflow:
    PyErr_SetString(PyExc_OverflowError,
        "can't convert negative value to int");
    return (int) -1;
}

/* CIntFromPy */
      static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) {
    const long neg_one = (long) -1, const_zero = (long) 0;
    const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
    if (likely(PyInt_Check(x))) {
        if (sizeof(long) < sizeof(long)) {
            __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x))
        } else {
            long val = PyInt_AS_LONG(x);
            if (is_unsigned && unlikely(val < 0)) {
                goto raise_neg_overflow;
            }
            return (long) val;
        }
    } else
#endif
    if (likely(PyLong_Check(x))) {
        if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
            const digit* digits = ((PyLongObject*)x)->ob_digit;
            switch (Py_SIZE(x)) {
                case  0: return (long) 0;
                case  1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0])
                case 2:
                    if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) {
                            return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
                        }
                    }
                    break;
                case 3:
                    if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) {
                            return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
                        }
                    }
                    break;
                case 4:
                    if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) {
                            return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
                        }
                    }
                    break;
            }
#endif
#if CYTHON_COMPILING_IN_CPYTHON
            if (unlikely(Py_SIZE(x) < 0)) {
                goto raise_neg_overflow;
            }
#else
            {
                int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
                if (unlikely(result < 0))
                    return (long) -1;
                if (unlikely(result == 1))
                    goto raise_neg_overflow;
            }
#endif
            if (sizeof(long) <= sizeof(unsigned long)) {
                __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
            } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
                __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
            }
        } else {
#if CYTHON_USE_PYLONG_INTERNALS
            const digit* digits = ((PyLongObject*)x)->ob_digit;
            switch (Py_SIZE(x)) {
                case  0: return (long) 0;
                case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0]))
                case  1: __PYX_VERIFY_RETURN_INT(long,  digit, +digits[0])
                case -2:
                    if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
                            return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
                        }
                    }
                    break;
                case 2:
                    if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
                            return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
                        }
                    }
                    break;
                case -3:
                    if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
                            return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
                        }
                    }
                    break;
                case 3:
                    if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
                            return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
                        }
                    }
                    break;
                case -4:
                    if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
                            return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
                        }
                    }
                    break;
                case 4:
                    if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
                            return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
                        }
                    }
                    break;
            }
#endif
            if (sizeof(long) <= sizeof(long)) {
                __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
            } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
                __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
            }
        }
        {
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
            PyErr_SetString(PyExc_RuntimeError,
                            "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
            long val;
            PyObject *v = __Pyx_PyNumber_IntOrLong(x);
 #if PY_MAJOR_VERSION < 3
            if (likely(v) && !PyLong_Check(v)) {
                PyObject *tmp = v;
                v = PyNumber_Long(tmp);
                Py_DECREF(tmp);
            }
 #endif
            if (likely(v)) {
                int one = 1; int is_little = (int)*(unsigned char *)&one;
                unsigned char *bytes = (unsigned char *)&val;
                int ret = _PyLong_AsByteArray((PyLongObject *)v,
                                              bytes, sizeof(val),
                                              is_little, !is_unsigned);
                Py_DECREF(v);
                if (likely(!ret))
                    return val;
            }
#endif
            return (long) -1;
        }
    } else {
        long val;
        PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
        if (!tmp) return (long) -1;
        val = __Pyx_PyInt_As_long(tmp);
        Py_DECREF(tmp);
        return val;
    }
raise_overflow:
    PyErr_SetString(PyExc_OverflowError,
        "value too large to convert to long");
    return (long) -1;
raise_neg_overflow:
    PyErr_SetString(PyExc_OverflowError,
        "can't convert negative value to long");
    return (long) -1;
}

/* CIntFromPy */
      static CYTHON_INLINE uint32_t __Pyx_PyInt_As_uint32_t(PyObject *x) {
    const uint32_t neg_one = (uint32_t) -1, const_zero = (uint32_t) 0;
    const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
    if (likely(PyInt_Check(x))) {
        if (sizeof(uint32_t) < sizeof(long)) {
            __PYX_VERIFY_RETURN_INT(uint32_t, long, PyInt_AS_LONG(x))
        } else {
            long val = PyInt_AS_LONG(x);
            if (is_unsigned && unlikely(val < 0)) {
                goto raise_neg_overflow;
            }
            return (uint32_t) val;
        }
    } else
#endif
    if (likely(PyLong_Check(x))) {
        if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
            const digit* digits = ((PyLongObject*)x)->ob_digit;
            switch (Py_SIZE(x)) {
                case  0: return (uint32_t) 0;
                case  1: __PYX_VERIFY_RETURN_INT(uint32_t, digit, digits[0])
                case 2:
                    if (8 * sizeof(uint32_t) > 1 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(uint32_t) >= 2 * PyLong_SHIFT) {
                            return (uint32_t) (((((uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]));
                        }
                    }
                    break;
                case 3:
                    if (8 * sizeof(uint32_t) > 2 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(uint32_t) >= 3 * PyLong_SHIFT) {
                            return (uint32_t) (((((((uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]));
                        }
                    }
                    break;
                case 4:
                    if (8 * sizeof(uint32_t) > 3 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(uint32_t) >= 4 * PyLong_SHIFT) {
                            return (uint32_t) (((((((((uint32_t)digits[3]) << PyLong_SHIFT) | (uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]));
                        }
                    }
                    break;
            }
#endif
#if CYTHON_COMPILING_IN_CPYTHON
            if (unlikely(Py_SIZE(x) < 0)) {
                goto raise_neg_overflow;
            }
#else
            {
                int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
                if (unlikely(result < 0))
                    return (uint32_t) -1;
                if (unlikely(result == 1))
                    goto raise_neg_overflow;
            }
#endif
            if (sizeof(uint32_t) <= sizeof(unsigned long)) {
                __PYX_VERIFY_RETURN_INT_EXC(uint32_t, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
            } else if (sizeof(uint32_t) <= sizeof(unsigned PY_LONG_LONG)) {
                __PYX_VERIFY_RETURN_INT_EXC(uint32_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
            }
        } else {
#if CYTHON_USE_PYLONG_INTERNALS
            const digit* digits = ((PyLongObject*)x)->ob_digit;
            switch (Py_SIZE(x)) {
                case  0: return (uint32_t) 0;
                case -1: __PYX_VERIFY_RETURN_INT(uint32_t, sdigit, (sdigit) (-(sdigit)digits[0]))
                case  1: __PYX_VERIFY_RETURN_INT(uint32_t,  digit, +digits[0])
                case -2:
                    if (8 * sizeof(uint32_t) - 1 > 1 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(uint32_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(uint32_t) - 1 > 2 * PyLong_SHIFT) {
                            return (uint32_t) (((uint32_t)-1)*(((((uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])));
                        }
                    }
                    break;
                case 2:
                    if (8 * sizeof(uint32_t) > 1 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(uint32_t) - 1 > 2 * PyLong_SHIFT) {
                            return (uint32_t) ((((((uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])));
                        }
                    }
                    break;
                case -3:
                    if (8 * sizeof(uint32_t) - 1 > 2 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(uint32_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(uint32_t) - 1 > 3 * PyLong_SHIFT) {
                            return (uint32_t) (((uint32_t)-1)*(((((((uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])));
                        }
                    }
                    break;
                case 3:
                    if (8 * sizeof(uint32_t) > 2 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(uint32_t) - 1 > 3 * PyLong_SHIFT) {
                            return (uint32_t) ((((((((uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])));
                        }
                    }
                    break;
                case -4:
                    if (8 * sizeof(uint32_t) - 1 > 3 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(uint32_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(uint32_t) - 1 > 4 * PyLong_SHIFT) {
                            return (uint32_t) (((uint32_t)-1)*(((((((((uint32_t)digits[3]) << PyLong_SHIFT) | (uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])));
                        }
                    }
                    break;
                case 4:
                    if (8 * sizeof(uint32_t) > 3 * PyLong_SHIFT) {
                        if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
                            __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
                        } else if (8 * sizeof(uint32_t) - 1 > 4 * PyLong_SHIFT) {
                            return (uint32_t) ((((((((((uint32_t)digits[3]) << PyLong_SHIFT) | (uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])));
                        }
                    }
                    break;
            }
#endif
            if (sizeof(uint32_t) <= sizeof(long)) {
                __PYX_VERIFY_RETURN_INT_EXC(uint32_t, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
            } else if (sizeof(uint32_t) <= sizeof(PY_LONG_LONG)) {
                __PYX_VERIFY_RETURN_INT_EXC(uint32_t, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
            }
        }
        {
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
            PyErr_SetString(PyExc_RuntimeError,
                            "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
            uint32_t val;
            PyObject *v = __Pyx_PyNumber_IntOrLong(x);
 #if PY_MAJOR_VERSION < 3
            if (likely(v) && !PyLong_Check(v)) {
                PyObject *tmp = v;
                v = PyNumber_Long(tmp);
                Py_DECREF(tmp);
            }
 #endif
            if (likely(v)) {
                int one = 1; int is_little = (int)*(unsigned char *)&one;
                unsigned char *bytes = (unsigned char *)&val;
                int ret = _PyLong_AsByteArray((PyLongObject *)v,
                                              bytes, sizeof(val),
                                              is_little, !is_unsigned);
                Py_DECREF(v);
                if (likely(!ret))
                    return val;
            }
#endif
            return (uint32_t) -1;
        }
    } else {
        uint32_t val;
        PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
        if (!tmp) return (uint32_t) -1;
        val = __Pyx_PyInt_As_uint32_t(tmp);
        Py_DECREF(tmp);
        return val;
    }
raise_overflow:
    PyErr_SetString(PyExc_OverflowError,
        "value too large to convert to uint32_t");
    return (uint32_t) -1;
raise_neg_overflow:
    PyErr_SetString(PyExc_OverflowError,
        "can't convert negative value to uint32_t");
    return (uint32_t) -1;
}

/* CIntToPy */
      static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) {
    const long neg_one = (long) -1, const_zero = (long) 0;
    const int is_unsigned = neg_one > const_zero;
    if (is_unsigned) {
        if (sizeof(long) < sizeof(long)) {
            return PyInt_FromLong((long) value);
        } else if (sizeof(long) <= sizeof(unsigned long)) {
            return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
        } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
            return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
        }
    } else {
        if (sizeof(long) <= sizeof(long)) {
            return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
        } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
            return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
        }
    }
    {
        int one = 1; int little = (int)*(unsigned char *)&one;
        unsigned char *bytes = (unsigned char *)&value;
        return _PyLong_FromByteArray(bytes, sizeof(long),
                                     little, !is_unsigned);
    }
}

/* CheckBinaryVersion */
      static int __Pyx_check_binary_version(void) {
    char ctversion[4], rtversion[4];
    PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION);
    PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion());
    if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) {
        char message[200];
        PyOS_snprintf(message, sizeof(message),
                      "compiletime version %s of module '%.100s' "
                      "does not match runtime version %s",
                      ctversion, __Pyx_MODULE_NAME, rtversion);
        return PyErr_WarnEx(NULL, message, 1);
    }
    return 0;
}

/* FunctionExport */
      static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig) {
    PyObject *d = 0;
    PyObject *cobj = 0;
    union {
        void (*fp)(void);
        void *p;
    } tmp;
    d = PyObject_GetAttrString(__pyx_m, (char *)"__pyx_capi__");
    if (!d) {
        PyErr_Clear();
        d = PyDict_New();
        if (!d)
            goto bad;
        Py_INCREF(d);
        if (PyModule_AddObject(__pyx_m, (char *)"__pyx_capi__", d) < 0)
            goto bad;
    }
    tmp.fp = f;
#if PY_VERSION_HEX >= 0x02070000
    cobj = PyCapsule_New(tmp.p, sig, 0);
#else
    cobj = PyCObject_FromVoidPtrAndDesc(tmp.p, (void *)sig, 0);
#endif
    if (!cobj)
        goto bad;
    if (PyDict_SetItemString(d, name, cobj) < 0)
        goto bad;
    Py_DECREF(cobj);
    Py_DECREF(d);
    return 0;
bad:
    Py_XDECREF(cobj);
    Py_XDECREF(d);
    return -1;
}

/* ModuleImport */
      #ifndef __PYX_HAVE_RT_ImportModule
#define __PYX_HAVE_RT_ImportModule
static PyObject *__Pyx_ImportModule(const char *name) {
    PyObject *py_name = 0;
    PyObject *py_module = 0;
    py_name = __Pyx_PyIdentifier_FromString(name);
    if (!py_name)
        goto bad;
    py_module = PyImport_Import(py_name);
    Py_DECREF(py_name);
    return py_module;
bad:
    Py_XDECREF(py_name);
    return 0;
}
#endif

/* TypeImport */
      #ifndef __PYX_HAVE_RT_ImportType
#define __PYX_HAVE_RT_ImportType
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name,
    size_t size, int strict)
{
    PyObject *py_module = 0;
    PyObject *result = 0;
    PyObject *py_name = 0;
    char warning[200];
    Py_ssize_t basicsize;
#ifdef Py_LIMITED_API
    PyObject *py_basicsize;
#endif
    py_module = __Pyx_ImportModule(module_name);
    if (!py_module)
        goto bad;
    py_name = __Pyx_PyIdentifier_FromString(class_name);
    if (!py_name)
        goto bad;
    result = PyObject_GetAttr(py_module, py_name);
    Py_DECREF(py_name);
    py_name = 0;
    Py_DECREF(py_module);
    py_module = 0;
    if (!result)
        goto bad;
    if (!PyType_Check(result)) {
        PyErr_Format(PyExc_TypeError,
            "%.200s.%.200s is not a type object",
            module_name, class_name);
        goto bad;
    }
#ifndef Py_LIMITED_API
    basicsize = ((PyTypeObject *)result)->tp_basicsize;
#else
    py_basicsize = PyObject_GetAttrString(result, "__basicsize__");
    if (!py_basicsize)
        goto bad;
    basicsize = PyLong_AsSsize_t(py_basicsize);
    Py_DECREF(py_basicsize);
    py_basicsize = 0;
    if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred())
        goto bad;
#endif
    if (!strict && (size_t)basicsize > size) {
        PyOS_snprintf(warning, sizeof(warning),
            "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd",
            module_name, class_name, basicsize, size);
        if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad;
    }
    else if ((size_t)basicsize != size) {
        PyErr_Format(PyExc_ValueError,
            "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd",
            module_name, class_name, basicsize, size);
        goto bad;
    }
    return (PyTypeObject *)result;
bad:
    Py_XDECREF(py_module);
    Py_XDECREF(result);
    return NULL;
}
#endif

/* VoidPtrImport */
      #ifndef __PYX_HAVE_RT_ImportVoidPtr
#define __PYX_HAVE_RT_ImportVoidPtr
static int __Pyx_ImportVoidPtr(PyObject *module, const char *name, void **p, const char *sig) {
    PyObject *d = 0;
    PyObject *cobj = 0;
    d = PyObject_GetAttrString(module, (char *)"__pyx_capi__");
    if (!d)
        goto bad;
    cobj = PyDict_GetItemString(d, name);
    if (!cobj) {
        PyErr_Format(PyExc_ImportError,
            "%.200s does not export expected C variable %.200s",
                PyModule_GetName(module), name);
        goto bad;
    }
#if PY_VERSION_HEX >= 0x02070000
    if (!PyCapsule_IsValid(cobj, sig)) {
        PyErr_Format(PyExc_TypeError,
            "C variable %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
             PyModule_GetName(module), name, sig, PyCapsule_GetName(cobj));
        goto bad;
    }
    *p = PyCapsule_GetPointer(cobj, sig);
#else
    {const char *desc, *s1, *s2;
    desc = (const char *)PyCObject_GetDesc(cobj);
    if (!desc)
        goto bad;
    s1 = desc; s2 = sig;
    while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; }
    if (*s1 != *s2) {
        PyErr_Format(PyExc_TypeError,
            "C variable %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
             PyModule_GetName(module), name, sig, desc);
        goto bad;
    }
    *p = PyCObject_AsVoidPtr(cobj);}
#endif
    if (!(*p))
        goto bad;
    Py_DECREF(d);
    return 0;
bad:
    Py_XDECREF(d);
    return -1;
}
#endif

/* FunctionImport */
      #ifndef __PYX_HAVE_RT_ImportFunction
#define __PYX_HAVE_RT_ImportFunction
static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
    PyObject *d = 0;
    PyObject *cobj = 0;
    union {
        void (*fp)(void);
        void *p;
    } tmp;
    d = PyObject_GetAttrString(module, (char *)"__pyx_capi__");
    if (!d)
        goto bad;
    cobj = PyDict_GetItemString(d, funcname);
    if (!cobj) {
        PyErr_Format(PyExc_ImportError,
            "%.200s does not export expected C function %.200s",
                PyModule_GetName(module), funcname);
        goto bad;
    }
#if PY_VERSION_HEX >= 0x02070000
    if (!PyCapsule_IsValid(cobj, sig)) {
        PyErr_Format(PyExc_TypeError,
            "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
             PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj));
        goto bad;
    }
    tmp.p = PyCapsule_GetPointer(cobj, sig);
#else
    {const char *desc, *s1, *s2;
    desc = (const char *)PyCObject_GetDesc(cobj);
    if (!desc)
        goto bad;
    s1 = desc; s2 = sig;
    while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; }
    if (*s1 != *s2) {
        PyErr_Format(PyExc_TypeError,
            "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
             PyModule_GetName(module), funcname, sig, desc);
        goto bad;
    }
    tmp.p = PyCObject_AsVoidPtr(cobj);}
#endif
    *f = tmp.fp;
    if (!(*f))
        goto bad;
    Py_DECREF(d);
    return 0;
bad:
    Py_XDECREF(d);
    return -1;
}
#endif

/* InitStrings */
      static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
    while (t->p) {
        #if PY_MAJOR_VERSION < 3
        if (t->is_unicode) {
            *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
        } else if (t->intern) {
            *t->p = PyString_InternFromString(t->s);
        } else {
            *t->p = PyString_FromStringAndSize(t->s, t->n - 1);
        }
        #else
        if (t->is_unicode | t->is_str) {
            if (t->intern) {
                *t->p = PyUnicode_InternFromString(t->s);
            } else if (t->encoding) {
                *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL);
            } else {
                *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
            }
        } else {
            *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
        }
        #endif
        if (!*t->p)
            return -1;
        if (PyObject_Hash(*t->p) == -1)
            PyErr_Clear();
        ++t;
    }
    return 0;
}

static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) {
    return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str));
}
static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) {
    Py_ssize_t ignore;
    return __Pyx_PyObject_AsStringAndSize(o, &ignore);
}
static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
#if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)
    if (
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
            __Pyx_sys_getdefaultencoding_not_ascii &&
#endif
            PyUnicode_Check(o)) {
#if PY_VERSION_HEX < 0x03030000
        char* defenc_c;
        PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL);
        if (!defenc) return NULL;
        defenc_c = PyBytes_AS_STRING(defenc);
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
        {
            char* end = defenc_c + PyBytes_GET_SIZE(defenc);
            char* c;
            for (c = defenc_c; c < end; c++) {
                if ((unsigned char) (*c) >= 128) {
                    PyUnicode_AsASCIIString(o);
                    return NULL;
                }
            }
        }
#endif
        *length = PyBytes_GET_SIZE(defenc);
        return defenc_c;
#else
        if (__Pyx_PyUnicode_READY(o) == -1) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
        if (PyUnicode_IS_ASCII(o)) {
            *length = PyUnicode_GET_LENGTH(o);
            return PyUnicode_AsUTF8(o);
        } else {
            PyUnicode_AsASCIIString(o);
            return NULL;
        }
#else
        return PyUnicode_AsUTF8AndSize(o, length);
#endif
#endif
    } else
#endif
#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))
    if (PyByteArray_Check(o)) {
        *length = PyByteArray_GET_SIZE(o);
        return PyByteArray_AS_STRING(o);
    } else
#endif
    {
        char* result;
        int r = PyBytes_AsStringAndSize(o, &result, length);
        if (unlikely(r < 0)) {
            return NULL;
        } else {
            return result;
        }
    }
}
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
   int is_true = x == Py_True;
   if (is_true | (x == Py_False) | (x == Py_None)) return is_true;
   else return PyObject_IsTrue(x);
}
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) {
#if CYTHON_USE_TYPE_SLOTS
  PyNumberMethods *m;
#endif
  const char *name = NULL;
  PyObject *res = NULL;
#if PY_MAJOR_VERSION < 3
  if (PyInt_Check(x) || PyLong_Check(x))
#else
  if (PyLong_Check(x))
#endif
    return __Pyx_NewRef(x);
#if CYTHON_USE_TYPE_SLOTS
  m = Py_TYPE(x)->tp_as_number;
  #if PY_MAJOR_VERSION < 3
  if (m && m->nb_int) {
    name = "int";
    res = PyNumber_Int(x);
  }
  else if (m && m->nb_long) {
    name = "long";
    res = PyNumber_Long(x);
  }
  #else
  if (m && m->nb_int) {
    name = "int";
    res = PyNumber_Long(x);
  }
  #endif
#else
  res = PyNumber_Int(x);
#endif
  if (res) {
#if PY_MAJOR_VERSION < 3
    if (!PyInt_Check(res) && !PyLong_Check(res)) {
#else
    if (!PyLong_Check(res)) {
#endif
      PyErr_Format(PyExc_TypeError,
                   "__%.4s__ returned non-%.4s (type %.200s)",
                   name, name, Py_TYPE(res)->tp_name);
      Py_DECREF(res);
      return NULL;
    }
  }
  else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_TypeError,
                    "an integer is required");
  }
  return res;
}
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
  Py_ssize_t ival;
  PyObject *x;
#if PY_MAJOR_VERSION < 3
  if (likely(PyInt_CheckExact(b))) {
    if (sizeof(Py_ssize_t) >= sizeof(long))
        return PyInt_AS_LONG(b);
    else
        return PyInt_AsSsize_t(x);
  }
#endif
  if (likely(PyLong_CheckExact(b))) {
    #if CYTHON_USE_PYLONG_INTERNALS
    const digit* digits = ((PyLongObject*)b)->ob_digit;
    const Py_ssize_t size = Py_SIZE(b);
    if (likely(__Pyx_sst_abs(size) <= 1)) {
        ival = likely(size) ? digits[0] : 0;
        if (size == -1) ival = -ival;
        return ival;
    } else {
      switch (size) {
         case 2:
           if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
             return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
           }
           break;
         case -2:
           if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
             return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
           }
           break;
         case 3:
           if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
             return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
           }
           break;
         case -3:
           if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
             return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
           }
           break;
         case 4:
           if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
             return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
           }
           break;
         case -4:
           if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
             return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
           }
           break;
      }
    }
    #endif
    return PyLong_AsSsize_t(b);
  }
  x = PyNumber_Index(b);
  if (!x) return -1;
  ival = PyInt_AsSsize_t(x);
  Py_DECREF(x);
  return ival;
}
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
    return PyInt_FromSize_t(ival);
}


#endif /* Py_PYTHON_H */
