Compute.is_triangle()#

relationalai.std.graphs
#Compute.is_triangle(node1: Producer, node2: Producer, node3: Producer) -> Expression

Filters node1, node2, and node3 for combinations of that form a triangle. In an undirected graph, a triangle is a set of three nodes where each node is connected to the other two nodes. In a directed graph, a triangle is a set of three nodes where there is an edge from the first node to the second node, an edge from the second node to the third node, and an edge from the third node to the first node. Must be called in a rule or query context.

Supported Graph Types#

Graph TypeSupportedNotes
DirectedYes
UndirectedYes
WeightedYesWeights are ignored.
UnweightedYes

Parameters#

NameTypeDescription
node1ProducerA node in the graph.
node2ProducerA node in the graph.
node3ProducerA node in the graph.

Returns#

An Expression object.

Example#

Use .is_triangle() to check if three nodes form a triangle in a graph. You access the .is_triangle() method from a Graph object’s .compute attribute:

#import relationalai as rai
from relationalai.std.graphs import Graph

# Create a model named "socialNetwork" with a Person type
model = rai.Model("socialNetwork")
Person = model.Type("Person")

# Add some people to the model and connect them with a multi-valued `follows` property.
with model.rule():
    alice = Person.add(name="Alice")
    bob = Person.add(name="Bob")
    charlie = Person.add(name="Charlie")
    diana = Person.add(name="Diana")
    alice.follows.add(bob)
    bob.follows.add(charlie)
    charlie.follows.extend([alice, diana])

# Create a directed graph with Person nodes and edges between followers.
# Note that graphs are directed by Default.
# This graph has edges from Alice to Bob, Bob to Charlie, Charlie to Alice, and Charlie to Diana.
graph = Graph(model)
graph.Node.extend(Person)
graph.Edge.extend(Person.follows)

# Find all nodes that form a triangle
with model.query() as select:
    # Get triples of Person objects.
    person1, person2, person3 = Person(), Person(), Person()
    # Filter triples based on whether they form a triangle.
    graph.compute.is_triangle(person1, person2, person3)
    # Select the names of people that form triangles.
    response = select(person1.name, person2.name, person3.name)

print(response.results)
# Output:
#       name    name2    name3
# 0    Alice      Bob  Charlie
# 1      Bob  Charlie    Alice
# 2  Charlie    Alice      Bob

The output has three rows, but each row is a permutation of the same three nodes.

See Also#