예제 #1
0
 def test_bytecode(self):
     g = traversal().withGraph(Graph())
     bytecode = g.V().out("created").bytecode
     assert 0 == len(bytecode.bindings.keys())
     assert 0 == len(bytecode.source_instructions)
     assert 2 == len(bytecode.step_instructions)
     assert "V" == bytecode.step_instructions[0][0]
     assert "out" == bytecode.step_instructions[1][0]
     assert "created" == bytecode.step_instructions[1][1]
     assert 1 == len(bytecode.step_instructions[0])
     assert 2 == len(bytecode.step_instructions[1])
     ##
     bytecode = g.withSack(1).E().groupCount().by("weight").bytecode
     assert 0 == len(bytecode.bindings.keys())
     assert 1 == len(bytecode.source_instructions)
     assert "withSack" == bytecode.source_instructions[0][0]
     assert 1 == bytecode.source_instructions[0][1]
     assert 3 == len(bytecode.step_instructions)
     assert "E" == bytecode.step_instructions[0][0]
     assert "groupCount" == bytecode.step_instructions[1][0]
     assert "by" == bytecode.step_instructions[2][0]
     assert "weight" == bytecode.step_instructions[2][1]
     assert 1 == len(bytecode.step_instructions[0])
     assert 1 == len(bytecode.step_instructions[1])
     assert 2 == len(bytecode.step_instructions[2])
     ##
     bytecode = g.V(Bindings.of('a', [1, 2, 3])) \
         .out(Bindings.of('b', 'created')) \
         .where(__.in_(Bindings.of('c', 'created'), Bindings.of('d', 'knows')) \
                .count().is_(Bindings.of('e', P.gt(2)))).bytecode
     assert 5 == len(bytecode.bindings.keys())
     assert [1, 2, 3] == bytecode.bindings['a']
     assert 'created' == bytecode.bindings['b']
     assert 'created' == bytecode.bindings['c']
     assert 'knows' == bytecode.bindings['d']
     assert P.gt(2) == bytecode.bindings['e']
     assert Binding('b', 'created') == bytecode.step_instructions[1][1]
     assert 'binding[b=created]' == str(bytecode.step_instructions[1][1])
     assert isinstance(hash(bytecode.step_instructions[1][1]), int)
예제 #2
0
 def test_bytecode(self):
     g = Graph().traversal()
     bytecode = g.V().out("created").bytecode
     assert 0 == len(bytecode.bindings.keys())
     assert 0 == len(bytecode.source_instructions)
     assert 2 == len(bytecode.step_instructions)
     assert "V" == bytecode.step_instructions[0][0]
     assert "out" == bytecode.step_instructions[1][0]
     assert "created" == bytecode.step_instructions[1][1]
     assert 1 == len(bytecode.step_instructions[0])
     assert 2 == len(bytecode.step_instructions[1])
     ##
     bytecode = g.withSack(1).E().groupCount().by("weight").bytecode
     assert 0 == len(bytecode.bindings.keys())
     assert 1 == len(bytecode.source_instructions)
     assert "withSack" == bytecode.source_instructions[0][0]
     assert 1 == bytecode.source_instructions[0][1]
     assert 3 == len(bytecode.step_instructions)
     assert "E" == bytecode.step_instructions[0][0]
     assert "groupCount" == bytecode.step_instructions[1][0]
     assert "by" == bytecode.step_instructions[2][0]
     assert "weight" == bytecode.step_instructions[2][1]
     assert 1 == len(bytecode.step_instructions[0])
     assert 1 == len(bytecode.step_instructions[1])
     assert 2 == len(bytecode.step_instructions[2])
     ##
     bytecode = g.V(Bindings.of('a', [1,2,3])) \
         .out(Bindings.of('b','created')) \
         .where(__.in_(Bindings.of('c','created'), Bindings.of('d','knows')) \
         .count().is_(Bindings.of('e',P.gt(2)))).bytecode
     assert 5 == len(bytecode.bindings.keys())
     assert [1,2,3] == bytecode.bindings['a']
     assert 'created' == bytecode.bindings['b']
     assert 'created' == bytecode.bindings['c']
     assert 'knows' == bytecode.bindings['d']
     assert P.gt(2) == bytecode.bindings['e']
     assert Binding('b','created') == bytecode.step_instructions[1][1]
     assert 'binding[b=created]' == str(bytecode.step_instructions[1][1])
     assert isinstance(hash(bytecode.step_instructions[1][1]),int)
예제 #3
0
def link_nodes(g, source_node, target_node, property_term, rdf_graph):
    """
        establish a new link/edge between two existent nodes
    :param g: gremlin graph
    :param source_node: from gremlin node
    :param target_node: to gremlin node
    :param property_term: edge label rdf term
    :param rdf_graph: the RDF graph
    :return: the newly created edge
    """
    # pg = g if g else setup_graph()
    if isinstance(property_term, rdflib.URIRef) and rdf_graph:
        property_label = rdf_graph.qname(property_term) if rdf_graph.qname(
            property_term) else str(property_term)
    else:
        property_label = str(property_term)

    logging.debug('Adding the link "%s" from %s to %s.' %
                  (str(property_label), str(source_node), str(target_node)))

    return g.V(Bindings.of(
        'id', source_node)).addE(property_label).to(target_node).iterate()
    def test_traversals(self, remote_connection):
        statics.load_statics(globals())
        g = traversal().withRemote(remote_connection)

        assert long(6) == g.V().count().toList()[0]
        # #
        assert Vertex(1) == g.V(1).next()
        assert 1 == g.V(1).id().next()
        assert Traverser(Vertex(1)) == g.V(1).nextTraverser()
        assert 1 == len(g.V(1).toList())
        assert isinstance(g.V(1).toList(), list)
        results = g.V().repeat(out()).times(2).name
        results = results.toList()
        assert 2 == len(results)
        assert "lop" in results
        assert "ripple" in results
        # #
        assert 10 == g.V().repeat(both()).times(5)[0:10].count().next()
        assert 1 == g.V().repeat(both()).times(5)[0:1].count().next()
        assert 0 == g.V().repeat(both()).times(5)[0:0].count().next()
        assert 4 == g.V()[2:].count().next()
        assert 2 == g.V()[:2].count().next()
        # #
        results = g.withSideEffect(
            'a', ['josh', 'peter'
                  ]).V(1).out('created').in_('created').values('name').where(
                      P.within('a')).toList()
        assert 2 == len(results)
        assert 'josh' in results
        assert 'peter' in results
        # #
        results = g.V().out().profile().toList()
        assert 1 == len(results)
        assert 'metrics' in results[0]
        assert 'dur' in results[0]
        # #
        results = g.V().has('name',
                            'peter').as_('a').out('created').as_('b').select(
                                'a', 'b').by(__.valueMap()).toList()
        assert 1 == len(results)
        assert 'peter' == results[0]['a']['name'][0]
        assert 35 == results[0]['a']['age'][0]
        assert 'lop' == results[0]['b']['name'][0]
        assert 'java' == results[0]['b']['lang'][0]
        assert 2 == len(results[0]['a'])
        assert 2 == len(results[0]['b'])
        # #
        results = g.V(1).inject(g.V(2).next()).values('name').toList()
        assert 2 == len(results)
        assert 'marko' in results
        assert 'vadas' in results
        # #
        results = g.V().has('person', 'name', 'marko').map(
            lambda: ("it.get().value('name')", "gremlin-groovy")).toList()
        assert 1 == len(results)
        assert 'marko' in results
        # #
        # this test just validates that the underscored versions of steps conflicting with Gremlin work
        # properly and can be removed when the old steps are removed - TINKERPOP-2272
        results = g.V().filter_(
            __.values('age').sum_().and_(__.max_().is_(gt(0)),
                                         __.min_().is_(gt(0)))).range_(
                                             0, 1).id_().next()
        assert 1 == results
        # #
        # test binding in P
        results = g.V().has('person', 'age',
                            Bindings.of('x', lt(30))).count().next()
        assert 2 == results
        # #
        # test dict keys which can only work on GraphBinary and GraphSON3 which include specific serialization
        # types for dict
        if not isinstance(remote_connection._client._message_serializer,
                          GraphSONSerializersV2d0):
            results = g.V().has(
                'person', 'name',
                'marko').elementMap("name").groupCount().next()
            assert {
                HashableDict.of({
                    T.id: 1,
                    T.label: 'person',
                    'name': 'marko'
                }): 1
            } == results
예제 #5
0
class TrajectoryGraph:
    # use for binding
    LABEL = "label"
    CAMID = "camId"
    TIME = "time"
    IMAGE = "image"
    OUT_V = "outV"
    IN_V = "inV"
    LIMIT = "limit"
    VID = "vid"
    FEA = "feature"
    CONFIDENCE = "confidence"
    INDEX = "index"

    def __init__( self ):
        self.b = Bindings()
        self.graph = Graph()
        self.connection = DriverRemoteConnection('ws://130.207.122.57:8182/gremlin','g')
        self.g = self.graph.traversal().withRemote(self.connection)
        logging.info("Connected")
    
    def addDetection(self, vehId, camId, timestamp, index):
        v = self.g.addV(self.b.of(TrajectoryGraph.LABEL, vehId))\
            .property(TrajectoryGraph.CAMID, self.b.of(TrajectoryGraph.CAMID, camId))\
            .property(TrajectoryGraph.TIME, self.b.of(TrajectoryGraph.TIME, timestamp))\
            .property(TrajectoryGraph.INDEX, self.b.of(TrajectoryGraph.INDEX, index))\
            .id().next()
        
        logging.info("Trajectory Vertex v[{}] ({}, {}, {}) created.".format(v, vehId, camId, timestamp))
        
        return v
        
    def linkDetection(self, src, dest, confidence):
        logging.info("Link vertex v[{}] to v[{}]. Confidence {}".format(src, dest, confidence))
        self.g.V(self.b.of(TrajectoryGraph.OUT_V, src))\
            .as_("a")\
            .V(self.b.of(TrajectoryGraph.IN_V, dest))\
            .addE(self.b.of(TrajectoryGraph.LABEL, "next"))\
            .from_("a")\
            .property(TrajectoryGraph.CONFIDENCE, self.b.of(TrajectoryGraph.CONFIDENCE, confidence))\
            .iterate()
    
    def getValueMapById(self,id):
        value = self.g.V(self.b.of(TrajectoryGraph.VID, id)).valueMap(True).next()
        logging.info("Get detection valuemap {} for V[{}]".format(value.keys(), id))
        return value


    def getLatestDetectionsByCamId(self, camId,limit):
        # timelimit support can be considered.
        vehIds = self.g.V().has(TrajectoryGraph.CAMID, self.b.of(TrajectoryGraph.CAMID, camId)).order().by(TrajectoryGraph.TIME, Order.decr).limit(self.b.of(TrajectoryGraph.LIMIT, limit)).id().toList()
        logging.info("LatestDetections by camera {}: {}".format(camId, vehIds))
        return vehIds

    def getNextDetectionsById(self, id, limit):
        #  This can be used to return self
        vehIds = self.g.V(self.b.of(TrajectoryGraph.OUT_V, id)).emit().repeat(__.out()).times(self.b.of(TrajectoryGraph.LIMIT, limit)).id().toList()
        logging.info("NextDetections from V[{}]: {}".format(id, vehIds))
        return vehIds

    def getPrevDetectionsById(self, id, limit):
        vehIds = self.g.V(self.b.of(TrajectoryGraph.IN_V, id)).repeat(__.in_()).times(limit).emit().id().toList()
        vehIds = vehIds[::-1]
        logging.info("PrevDetections from V[{}]: {}".format(id, vehIds))
        return vehIds

    def clear(self):
        logging.info("TrajectoryGraph dropped")
        self.g.V().drop().iterate()
    
    def shutdown(self):
        logging.info("TrajectoryGraph closed")
        self.connection.close()
        self.g = None
        self.graph = None
예제 #6
0
import os
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.traversal import Order
from gremlin_python.process.traversal import P
from gremlin_python.process.traversal import Bindings

g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin', 'g'))
statics.load_statics(globals())

v1 = g.addV('model').property('name', 'marko').next()
v2 = g.addV('person').property('name', 'stephen').next()

print("count: ", g.V(v2).properties('name').count())

l = g.V(Bindings.of('id',v1)).addE('knows').to(v2).property('weight',0.75).iterate()
print(l)

marko = g.V().has('person','name','marko').next()
peopleMarkoKnows = g.V().has('person','name','marko').out('knows').toList()

print("marko: ", marko)
print("peopleMarkoKnows: ", peopleMarkoKnows)

print("{}".format(g.V(v1).properties()))



current_work_directory = os.getcwd()
k = g.io(current_work_directory + "/" + "world_model.xml").write().iterate()
k = g.io(current_work_directory + "/" + "world_model.json").write().iterate()
예제 #7
0
    #     "connected": true
    # }
    v_esp32 = g.addV("esp32").property(id, 3).property(
        "name", "le_arm_esp32").property("hardware",
                                         "esp32").property("connected",
                                                           True).next()
    v_variables = g.addV("variables").property(
        id, 4).property("servo1", 1500).property("servo2", 1500).property(
            "servo3",
            1500).property("servo4", 1500).property("servo5", 1500).property(
                "servo6", 1500).property("servo_limit_min", 500).property(
                    "servo_limit_max",
                    2500).property("servo_speed",
                                   150).property("servo_delay_after",
                                                 5).next()
    l = g.V(Bindings.of('id',
                        v_esp32)).addE('stores').to(v_variables).iterate()

    # send_requests = False
    # command_delay = 0.05  # seconds
    # center_init = True
    # angle_degree_limit = 75  # degrees
    # trajectory_steps = 10
    # current_servo_monotony = [-1.0, -1.0, 1.0, -1.0, -1.0, -1.0]
    # active_links_mask = [True, True, True, True, False, True]  # Enabled/disabled links
    # gripper_servo = 2
    # gripper_open = 600
    # target_position = [-20, -20, 25]
    # init_position = [0, 0, 1]
    # min_steps = 1
    # max_steps = 5000
    # detect_last_position = False