コード例 #1
0
ファイル: test_advancedcpp.py プロジェクト: mozillazg/pypy
    def test09_opaque_pointer_passing(self):
        """Test passing around of opaque pointers"""

        import cppyy
        some_concrete_class = cppyy.gbl.some_concrete_class

        o = some_concrete_class()

        # TODO: figure out the PyPy equivalent of CObject (may have to do this
        # through the C-API from C++)

        #cobj = cppyy.as_cobject(o)
        addr = cppyy.addressof(o)

        #assert o == cppyy.bind_object(cobj, some_concrete_class)
        #assert o == cppyy.bind_object(cobj, type(o))
        #assert o == cppyy.bind_object(cobj, o.__class__)
        #assert o == cppyy.bind_object(cobj, "some_concrete_class")
        assert cppyy.addressof(o) == cppyy.addressof(cppyy.bind_object(addr, some_concrete_class))
        assert o == cppyy.bind_object(addr, some_concrete_class)
        assert o == cppyy.bind_object(addr, type(o))
        assert o == cppyy.bind_object(addr, o.__class__)
        assert o == cppyy.bind_object(addr, "some_concrete_class")
        raises(TypeError, cppyy.bind_object, addr, "does_not_exist")
        raises(TypeError, cppyy.bind_object, addr, 1)
コード例 #2
0
ファイル: test_advancedcpp.py プロジェクト: mozillazg/pypy
    def test10_object_identity(self):
        """Test object identity"""

        import cppyy
        some_concrete_class  = cppyy.gbl.some_concrete_class
        some_class_with_data = cppyy.gbl.some_class_with_data

        o = some_concrete_class()
        addr = cppyy.addressof(o)

        o2 = cppyy.bind_object(addr, some_concrete_class)
        assert o is o2

        o3 = cppyy.bind_object(addr, some_class_with_data)
        assert not o is o3

        d1 = some_class_with_data()
        d2 = d1.gime_copy()
        assert not d1 is d2

        dd1a = d1.gime_data()
        dd1b = d1.gime_data()
        assert dd1a is dd1b

        dd2 = d2.gime_data()
        assert not dd1a is dd2
        assert not dd1b is dd2

        d2.destruct()
        d1.destruct()
コード例 #3
0
 def address_equality_test(a, b):
     assert cppyy.addressof(a) == cppyy.addressof(b)
     b2 = cppyy.bind_object(a, CppyyTestData)
     b.m_int = 888
     assert b.m_int == 888
     assert b == b2 and b.m_int == b2.m_int
     # TODO: in PyROOT, non-TObjects are not mem-regulated
     #assert b is b2    # memory regulator recycles
     b3 = cppyy.bind_object(cppyy.addressof(a), CppyyTestData)
     assert b3.m_int == 888
     assert b == b3 and b.m_int == b3.m_int
コード例 #4
0
ファイル: test_cint.py プロジェクト: Darriall/pypy
    def test08_opaque_pointer_passing(self):
        """Test passing around of opaque pointers"""

        import cppyy

        # TODO: figure out CObject (see also test_advanced.py)

        s = cppyy.gbl.TString("Hello World!")
        #cobj = cppyy.as_cobject(s)
        addr = cppyy.addressof(s)

        #assert s == cppyy.bind_object(cobj, s.__class__)
        #assert s == cppyy.bind_object(cobj, "TString")
        assert s == cppyy.bind_object(addr, s.__class__)
        assert s == cppyy.bind_object(addr, "TString")
コード例 #5
0
ファイル: pythonify.py プロジェクト: Darriall/pypy
 def __new__(cls, *args):
     # create a place-holder only as there may be a derived class defined
     import cppyy
     instance = cppyy.bind_object(0, class_name, True)
     if not instance.__class__ is cls:
         instance.__class__ = cls     # happens for derived class
     return instance
コード例 #6
0
ファイル: test_advancedcpp.py プロジェクト: mozillazg/pypy
    def test08_void_pointer_passing(self):
        """Test passing of variants of void pointer arguments"""

        import cppyy
        pointer_pass        = cppyy.gbl.pointer_pass
        some_concrete_class = cppyy.gbl.some_concrete_class

        pp = pointer_pass()
        o = some_concrete_class()

        assert cppyy.addressof(o) == pp.gime_address_ptr(o)
        assert cppyy.addressof(o) == pp.gime_address_ptr_ptr(o)
        assert cppyy.addressof(o) == pp.gime_address_ptr_ref(o)

        import array
        addressofo = array.array('l', [cppyy.addressof(o)])
        assert addressofo.buffer_info()[0] == pp.gime_address_ptr_ptr(addressofo)

        assert 0 == pp.gime_address_ptr(0)
        assert 0 == pp.gime_address_ptr(None)

        ptr = cppyy.bind_object(0, some_concrete_class)
        assert cppyy.addressof(ptr) == 0
        pp.set_address_ptr_ref(ptr)
        assert cppyy.addressof(ptr) == 0x1234
        pp.set_address_ptr_ptr(ptr)
        assert cppyy.addressof(ptr) == 0x4321
コード例 #7
0
ファイル: test_advancedcpp.py プロジェクト: cms-sw/root
    def test10_object_identity(self):
        """Test object identity"""

        import cppyy
        some_concrete_class  = cppyy.gbl.some_concrete_class
        some_class_with_data = cppyy.gbl.some_class_with_data

        o = some_concrete_class()
        addr = cppyy.addressof(o)

        o2 = cppyy.bind_object(addr, some_concrete_class)
        assert o is o2

        o3 = cppyy.bind_object(addr, some_class_with_data)
        assert not o is o3

        d1 = some_class_with_data()
        d2 = d1.gime_copy()
        assert not d1 is d2

        dd1a = d1.gime_data()
        dd1b = d1.gime_data()
        assert dd1a is dd1b

        dd2 = d2.gime_data()
        assert not dd1a is dd2
        assert not dd1b is dd2

        d2.__destruct__()
        d1.__destruct__()

        RTS = cppyy.gbl.refers_to_self

        r1 = RTS()
        r2 = RTS()
        r1.m_other = r2

        r3 = r1.m_other
        r4 = r1.m_other
        assert r3 is r4

        assert r3 == r2
        assert r3 is r2

        r3.extra = 42
        assert r2.extra == 42
        assert r4.extra == 42
コード例 #8
0
ファイル: test_advancedcpp.py プロジェクト: MichaelBlume/pypy
    def test09_opaque_pointer_assing(self):
        """Test passing around of opaque pointers"""

        import cppyy
        some_concrete_class = cppyy.gbl.some_concrete_class

        o = some_concrete_class()

        #cobj = cppyy.as_cobject(o)
        addr = cppyy.addressof(o)

        #assert o == cppyy.bind_object(cobj, some_concrete_class)
        #assert o == cppyy.bind_object(cobj, type(o))
        #assert o == cppyy.bind_object(cobj, o.__class__)
        #assert o == cppyy.bind_object(cobj, "some_concrete_class")
        assert cppyy.addressof(o) == cppyy.addressof(cppyy.bind_object(addr, some_concrete_class))
        assert o == cppyy.bind_object(addr, some_concrete_class)
        assert o == cppyy.bind_object(addr, type(o))
        assert o == cppyy.bind_object(addr, o.__class__)
コード例 #9
0
ファイル: test_doc_features.py プロジェクト: bellenot/root
    def test_casting(self):
        import cppyy
        from cppyy.gbl import Abstract, Concrete

        c = Concrete()
        assert 'Abstract' in Concrete.show_autocast.__doc__
        d = c.show_autocast()
        assert type(d) == cppyy.gbl.Concrete

        from cppyy import addressof, bind_object
        e = bind_object(addressof(d), Abstract)
        assert type(e) == cppyy.gbl.Abstract
コード例 #10
0
ファイル: test_advancedcpp.py プロジェクト: mozillazg/pypy
    def test12_actual_type(self):
        """Test that a pointer to base return does an auto-downcast"""

        import cppyy
        base_class = cppyy.gbl.base_class
        derived_class = cppyy.gbl.derived_class

        b = base_class()
        d = derived_class()

        assert b == b.cycle(b)
        assert id(b) == id(b.cycle(b))
        assert b == d.cycle(b)
        assert id(b) == id(d.cycle(b))
        assert d == b.cycle(d)
        assert id(d) == id(b.cycle(d))
        assert d == d.cycle(d)
        assert id(d) == id(d.cycle(d))

        assert isinstance(b.cycle(b), base_class)
        assert isinstance(d.cycle(b), base_class)
        assert isinstance(b.cycle(d), derived_class)
        assert isinstance(d.cycle(d), derived_class)

        assert isinstance(b.clone(), base_class)      # TODO: clone() leaks
        assert isinstance(d.clone(), derived_class)   # TODO: clone() leaks

        # special case when round-tripping through a void* ptr
        voidp = b.mask(d)
        assert not isinstance(voidp, base_class)
        assert not isinstance(voidp, derived_class)

        d1 = cppyy.bind_object(voidp, base_class, cast=True)
        assert isinstance(d1, derived_class)
        assert d1 is d

        b1 = cppyy.bind_object(voidp, base_class)
        assert isinstance(b1, base_class)
        assert cppyy.addressof(b1) == cppyy.addressof(d)
        assert not (b1 is d)
コード例 #11
0
ファイル: test_datatypes.py プロジェクト: Qointum/pypy
    def test18_object_and_pointer_comparisons(self):
        """Verify object and pointer comparisons"""

        import cppyy

        gbl = cppyy.gbl

        c1 = cppyy.bind_object(0, gbl.cppyy_test_data)
        assert c1 == None
        assert None == c1

        c2 = cppyy.bind_object(0, gbl.cppyy_test_data)
        assert c1 == c2
        assert c2 == c1

        # four_vector overrides operator==
        l1 = cppyy.bind_object(0, gbl.four_vector)
        assert l1 == None
        assert None == l1

        assert c1 != l1
        assert l1 != c1

        l2 = cppyy.bind_object(0, gbl.four_vector)
        assert l1 == l2
        assert l2 == l1

        l3 = gbl.four_vector(1, 2, 3, 4)
        l4 = gbl.four_vector(1, 2, 3, 4)
        l5 = gbl.four_vector(4, 3, 2, 1)
        assert l3 == l4
        assert l4 == l3

        assert l3 != None  # like this to ensure __ne__ is called
        assert None != l3  # id.
        assert l3 != l5
        assert l5 != l3
コード例 #12
0
ファイル: test_datatypes.py プロジェクト: fhalde/pypy
    def test18_object_and_pointer_comparisons(self):
        """Verify object and pointer comparisons"""

        import cppyy
        gbl = cppyy.gbl

        c1 = cppyy.bind_object(0, gbl.CppyyTestData)
        assert c1 == None
        assert None == c1

        c2 = cppyy.bind_object(0, gbl.CppyyTestData)
        assert c1 == c2
        assert c2 == c1

        # FourVector overrides operator==
        l1 = cppyy.bind_object(0, gbl.FourVector)
        assert l1 == None
        assert None == l1

        assert c1 != l1
        assert l1 != c1

        l2 = cppyy.bind_object(0, gbl.FourVector)
        assert l1 == l2
        assert l2 == l1

        l3 = gbl.FourVector(1, 2, 3, 4)
        l4 = gbl.FourVector(1, 2, 3, 4)
        l5 = gbl.FourVector(4, 3, 2, 1)
        assert l3 == l4
        assert l4 == l3

        assert l3 != None  # like this to ensure __ne__ is called
        assert None != l3  # id.
        assert l3 != l5
        assert l5 != l3
コード例 #13
0
ファイル: test_regression.py プロジェクト: zhufengGNSS/root
    def test22_copy_constructor(self):
        """Copy construct an object into an empty (NULL) proxy"""

        import cppyy, gc

        cppyy.cppdef("""
        namespace regression_test22 {
        struct Countable {
             static int s_count;
             Countable() { ++s_count; }
             Countable(const Countable&) { ++s_count; }
             Countable& operator=(const Countable&) { return *this; }
             ~Countable() { --s_count; }
        };
        int Countable::s_count = 0;
        }""")

        r22 = cppyy.gbl.regression_test22

        assert r22.Countable.s_count == 0
        c = r22.Countable()
        assert r22.Countable.s_count == 1

        raises(ReferenceError, c.__init__, r22.Countable())
        gc.collect()
        assert r22.Countable.s_count == 1

        c.__assign__(r22.Countable())
        gc.collect()
        assert r22.Countable.s_count == 1

        c.__destruct__()
        assert r22.Countable.s_count == 0
        c.__init__(r22.Countable())
        gc.collect()
        assert r22.Countable.s_count == 1

        del c
        gc.collect()
        assert r22.Countable.s_count == 0

        c = cppyy.bind_object(cppyy.nullptr, r22.Countable)
        assert r22.Countable.s_count == 0
        c.__init__(r22.Countable())
        gc.collect()
        assert r22.Countable.s_count == 1
コード例 #14
0
ファイル: test_doc_features.py プロジェクト: zhufengGNSS/root
    def test04_ptr_ptr_python_owns(self):
        """Example of ptr-ptr use where python owns"""

        import cppyy

        cppyy.cppdef("""namespace Advert04 {
        struct SomeStruct {
            SomeStruct(int i) : i(i) {}
            int i;
        };

        int count_them(SomeStruct** them, int sz) {
            int total = 0;
            for (int i = 0; i < sz; ++i) total += them[i]->i;
            return total;
        } }""")

        cppyy.gbl.Advert04
        from cppyy.gbl.Advert04 import SomeStruct, count_them

        # initialization on python side
        v = cppyy.gbl.std.vector['Advert04::SomeStruct*']()
        v._l = [SomeStruct(i) for i in range(10)]
        for s in v._l:
            v.push_back(s)
        assert count_them(v.data(), v.size()) == sum(range(10))

        # initialization on C++ side
        cppyy.cppdef("""namespace Advert04 {
        void ptr2ptr_init(SomeStruct** ref) {
            *ref = new SomeStruct(42);
        } }""")

        s = cppyy.bind_object(cppyy.nullptr, SomeStruct)
        cppyy.gbl.Advert04.ptr2ptr_init(s)
        assert s.i == 42
コード例 #15
0
 def process(self):
     if not any(socket.is_linked for socket in self.outputs):
         return
     topology = self.inputs['Topology'].sv_get(
         deepcopy=False)[0][0]  #Consider only one Topology
     selectorList = flatten(self.inputs['Selectors'].sv_get(deepcopy=False))
     dictionaryList = flatten(
         self.inputs['Dictionaries'].sv_get(deepcopy=False))
     typeFilter = self.inputs['Type Filter'].sv_get(
         deepcopy=False)[0][0]  #Consider only one TypeFilter
     if len(selectorList) != len(dictionaryList):
         return
     selectors = convert_to_stl_list(selectorList, Vertex.Ptr)
     dictionaries = convert_to_stl_list(dictionaryList, Dictionary)
     for aDictionary in dictionaries:
         values = aDictionary.Values()
         returnList = []
         for aValue in values:
             s = cppyy.bind_object(aValue.Value(), 'StringStruct')
             returnList.append(str(s.getString))
         print(returnList)
     result = topology.SetDictionaries(selectors, dictionaries, typeFilter)
     result = fixTopologyClass(result)
     self.outputs['Topology'].sv_set([result])
コード例 #16
0
 def cffi_callback(self, i_cp, i_colObj0, partId0, index0, i_colObj1,
                   partId1, index1):
     cp = cppyy.bind_object(i_cp, bt.ManifoldPoint)
     colObj0 = cppyy.bind_object(i_colObj0, bt.CollisionObject)
     colObj1 = cppyy.bind_object(i_colObj1, bt.CollisionObject)
     return bool(self.func(cp, colObj0, partId0, index0, colObj1, partId1, index1))
コード例 #17
0
 def _cffi_internalProcessTriangleIndex(self, i_triangle0, i_triangle1, i_triangle2, partId, triangleIndex):
     triangle0 = cppyy.bind_object(i_triangle0, bt.Vector3)
     triangle1 = cppyy.bind_object(i_triangle1, bt.Vector3)
     triangle2 = cppyy.bind_object(i_triangle2, bt.Vector3)
     self.internalProcessTriangleIndex((triangle0, triangle1, triangle2), partId, triangleIndex)
コード例 #18
0
def run_slic_seg(img: "NDArray[np.uint8]",
                 n_segments: int = 80000,
                 n_iter: int = 5,
                 compactness: float = 0.01,
                 enforce_connectivity: bool = True,
                 slic_zero: bool = True) -> "NDArray[int]":
    """
    Run gpu SLICO in C++.

    Parameters
    -----------
    img : 2D uint8 ndarray
        Input image, must be grayscale. 
    n_segments : int, optional
        The (approximate) number of labels in the segmented output image.
    n_iter : int, optional
        The number of iterations of k-means.
    compactness : float, optional
        Balances color proximity and space proximity. Higher values give
        more weight to space proximity, making superpixel shapes more
        square/cubic. In SLICO mode, this is the initial compactness.
        This parameter depends strongly on image contrast and on the
        shapes of objects in the image. We recommend exploring possible
        values on a log scale, e.g., 0.01, 0.1, 1, 10, 100, before
        refining around a chosen value.
    enforce_connectivity : bool, optional
        Whether the generated segments are connected or not.
    slic_zero : bool, optional
        Run SLIC-zero, the zero-parameter mode of SLIC. [2]_
        
    Returns
    -------
    segments_slic : 2D ndarray
        Integer mask indicating SLIC segment labels.
        
    References
    ----------
    .. [1] Radhakrishna Achanta, Appu Shaji, Kevin Smith, Aurelien Lucchi,
        Pascal Fua, and Sabine Süsstrunk, SLIC Superpixels Compared to
        State-of-the-art Superpixel Methods, TPAMI, May 2012.
    .. [2] http://ivrg.epfl.ch/research/superpixels#SLICO
    """
    assert img.dtype == np.uint8, 'Wrong numpy dtype, expected "np.uint8" but got "{}"'.format(
        img.dtype)
    assert img.ndim == 2, 'Wrong numpy dimension, expected "2" but got "{}" with shape {}'.format(
        img.ndim, img.shape)
    logger = logging.getLogger('run_slic_seg')
    logger.info('n_segments: %d', n_segments)
    logger.info('n_iter: %d', n_iter)
    logger.info('compactness: %s', compactness)
    logger.info('enforce_connectivity: %s', enforce_connectivity)
    logger.info('slic_zero: %s', slic_zero)

    height, width = img.shape
    # Create a Run_SLIC C++ class
    run_slic = gSLICr.Run_SLIC()

    # Specify settings
    gslic_settings = run_slic.get_settings()
    gslic_settings = cppyy.bind_object(gslic_settings, gSLICr.objects.settings)
    gslic_settings.img_size.x = width
    gslic_settings.img_size.y = height
    gslic_settings.no_segs = n_segments
    gslic_settings.no_iters = n_iter
    gslic_settings.coh_weight = compactness
    gslic_settings.do_enforce_connectivity = enforce_connectivity
    gslic_settings.slic_zero = slic_zero
    gslic_settings.color_space = gSLICr.GRAY
    gslic_settings.seg_method = gSLICr.GIVEN_NUM
    run_slic.print_settings()

    # Start running gSLIC
    run_slic.run(img)

    # Get the segmentation mask
    segments_slic = run_slic.get_mask()
    segments_slic.reshape((height * width, ))
    segments_slic = np.frombuffer(segments_slic,
                                  dtype=np.intc,
                                  count=height * width).reshape(
                                      (height, width)).copy()

    # Destruct the C++ class
    run_slic.__destruct__()
    return segments_slic
コード例 #19
0
 def string_cast(self):
     return cppyy.bind_object(self._org_Value(), 'std::string')
コード例 #20
0
 def address_equality_test(a, b):
     assert cppyy.addressof(a) == cppyy.addressof(b)
     b2 = cppyy.bind_object(a, CppyyTestData)
     assert b is b2    # memory regulator recycles
     b3 = cppyy.bind_object(cppyy.addressof(a), CppyyTestData)
     assert b is b3    # likewise
コード例 #21
0
keys.push_back(stringKey)

# Create a Dictionary
d = Dictionary.ByKeysValues(keys, values)

# Create a Vertex
v = Vertex.ByCoordinates(0, 0, 0)

# Assign Dictionary
v.SetDictionary(d)

# Retrieve Dictionary
dict = v.GetDictionary()

# Retrieve Values from Dictionary
newIntValue = dict.ValueAtKey(intKey)
newDoubleValue = dict.ValueAtKey(doubleKey)
newStringValue = dict.ValueAtKey(stringKey)

# Bind Retrieved Int Value and Print it
i = cppyy.bind_object(newIntValue.Value(), 'IntegerStruct')
print(str(i.getInteger) + " <--- Should be 340")

# Bind Retrieved Double Value and Print It
j = cppyy.bind_object(newDoubleValue.Value(), 'DoubleStruct')
print(str(j.getDouble) + " <--- Should be 120.567")

# Bind Retrieved String Value and Print It (How??)
k = cppyy.bind_object(newStringValue.Value(), 'StringStruct')
print(k.getString + " <--- Should be Hello World")
コード例 #22
0
ファイル: test_datatypes.py プロジェクト: Qointum/pypy
 def address_equality_test(a, b):
     assert cppyy.addressof(a) == cppyy.addressof(b)
     b2 = cppyy.bind_object(a, cppyy_test_data)
     assert b is b2  # memory regulator recycles
     b3 = cppyy.bind_object(cppyy.addressof(a), cppyy_test_data)
     assert b is b3  # likewise
コード例 #23
0
values = cppyy.gbl.std.list[Attribute.Ptr]()
keys.push_back(intKey)
values.push_back(intVal3)
dict3 = Dictionary.ByKeysValues(keys, values)

# Add the three dictionaries to a list of dictionaries
dictionaries = cppyy.gbl.std.list[Dictionary]()
dictionaries.push_back(dict1)
dictionaries.push_back(dict2)
dictionaries.push_back(dict3)

# Create a selectors list and add the vertices to items
selectors = cppyy.gbl.std.list[Vertex.Ptr]()
selectors.push_back(v1)
selectors.push_back(v2)
selectors.push_back(v3)

# Add the list of dictionaries to the Wire and restrict to assigning to Vertices
w1 = w1.SetDictionaries(selectors, dictionaries, Vertex.Type())

# Get the vertices of the wire
vertices = cppyy.gbl.std.list[Vertex.Ptr]()
_ = w1.Vertices(vertices)

# Cycle through the vertices, get the dictionary and print the value at the key
for aVertex in vertices:
    newDict = aVertex.GetDictionary()
    aValue = newDict.ValueAtKey(intKey)
    i = cppyy.bind_object(aValue.Value(), 'IntegerStruct')
    print(i.getInteger)
コード例 #24
0
 def cffi_callback(self, i_cp, i_body0, i_body1):
     cp = cppyy.bind_object(i_cp, bt.ManifoldPoint)
     body0 = cppyy.bind_object(i_body0, bt.CollisionObject)
     body1 = cppyy.bind_object(i_body1, bt.CollisionObject)
     return bool(self.func(cp, body0, body1))