### Scallopy ScallopContext Setup Source: https://www.scallop-lang.org/doc/print Provides a concise example of setting up and using a 'ScallopContext' in Python. It covers adding relations, facts, defining a rule for path computation, and executing the program. ```python import scallopy # Creating a new context ctx = scallopy.ScallopContext() # Add relation of `edge` ctx.add_relation("edge", (int, int)) ctx.add_facts("edge", [(0, 1), (1, 2)]) # Add rule of `path` ctx.add_rule("path(a, c) = edge(a, c) or path(a, b) and edge(b, c)") # Run! ctx.run() ``` -------------------------------- ### Scallop Context Setup and Execution Source: https://www.scallop-lang.org/doc/scallopy/context Demonstrates how to initialize a ScallopContext, define relations, add facts, declare rules, run the computation, and retrieve results. This is a fundamental example for interacting with the Scallop engine. ```Python import scallopy # Creating a new context ctx = scallopy.ScallopContext() # Add relation of `edge` ctx.add_relation("edge", (int, int)) ctx.add_facts("edge", [(0, 1), (1, 2)]) # Add rule of `path` ctx.add_rule("path(a, c) = edge(a, c) or path(a, b) and edge(b, c)") # Run! ctx.run() # Check the result! print(list(ctx.relation("path"))) # [(0, 1), (0, 2), (1, 2)] ``` -------------------------------- ### Install Scallop Interpreter (scli) Source: https://www.scallop-lang.org/doc/installation Installs the Scallop interpreter, named 'scli', using the provided Makefile command. This tool is used to test and run Scallop programs. ```shell $ make install-scli ``` -------------------------------- ### Scallop Pretty-Printing Execution Example Source: https://www.scallop-lang.org/doc/language/adt_and_entity An example demonstrating how to define an expression and query the pretty-printing relation. It shows the input expression and the expected output format. ```scallop const MY_EXPR = Sub(Add(Int(3), Int(5)), Int(1)) query to_string(MY_EXPR, s) ``` -------------------------------- ### Scallop Query Example Source: https://www.scallop-lang.org/doc/language/query Demonstrates how to define relations and rules in Scallop, and how to query specific relations to retrieve computed results. This example shows counting students enrolled in CS classes. ```Scallop rel classes = {0, 1, 2} rel enroll = { ("tom", "CS"), ("jenny", "Math"), // Class 0 ("alice", "CS"), ("bob", "CS"), // Class 1 ("jerry", "Math"), ("john", "Math"), // Class 2 } rel num_enroll_cs(n) = n := count(s: enroll(s, "CS")) query num_enroll_cs ``` -------------------------------- ### Install Scallop CLI Source: https://www.scallop-lang.org/doc/print Command to install the Scallop interpreter (scli) using the make build system. This command is typically run from the Scallop source directory. ```Shell $ make install-scli ``` -------------------------------- ### Scallop Example Usage and Query Source: https://www.scallop-lang.org/doc/print Demonstrates how to use the defined Scallop relations by providing input regex and string, and then querying the `matches` relation to check for a match. ```Scallop rel input_regex(A_STAR_B) rel input_string("aaaab") query matches // {()} ``` -------------------------------- ### Scallop Fixed-point Iteration Example Source: https://www.scallop-lang.org/doc/print Demonstrates the execution of Scallop rules through fixed-point iteration. It shows how relations are updated iteratively until no new facts are derived, illustrating the convergence process. ```Scallop rel edge = {(0, 1), (1, 2), (2, 3)} rel path(a, b) = edge(a, b) // rule 1 rel path(a, c) = path(a, b) and edge(b, c) // rule 2 Iter 0: path = {} Iter 1: path = {(0, 1), (1, 2), (2, 3)} Δpath = {(0, 1), (1, 2), (2, 3)} // through applying rule 1 Iter 2: path = {(0, 1), (1, 2), (2, 3), (0, 2), (1, 3)} Δpath = {(0, 2), (1, 3)} // through applying rule 2 Iter 3: path = {(0, 1), (1, 2), (2, 3), (0, 2), (1, 3), (0, 3)} Δpath = {(0, 3)} // through applying rule 2 Iter 4: path = {(0, 1), (1, 2), (2, 3), (0, 2), (1, 3), (0, 3)} Δpath = {} ``` -------------------------------- ### Scallop: Equality Saturation Setup Source: https://www.scallop-lang.org/doc/print Defines the necessary Scallop types for equality saturation: input expressions, equivalence relations, and weight functions. ```scallop type input_expr(expr: Expr) type equivalent(expr_1: Expr, expr_2: Expr) type weight(expr: Expr, w: i32) type simplest(expr: Expr) ``` -------------------------------- ### Scallop Debugging with difftopkproofsdebug Source: https://www.scallop-lang.org/doc/print Demonstrates how to use the 'difftopkproofsdebug' provenance in Scallop for debugging proofs. This method requires special handling when adding facts, necessitating the inclusion of a unique 'Fact ID' for each fact, typically starting from 1 and being contiguous. The example shows the structure for probabilistic facts with Fact IDs. ```python import scallopy import torch # Initialize Scallop context with debugging provenance and k value ctx = scallopy.ScallopContext(provenance="difftopkproofsdebug", k=3) # Add relations with their Python types ctx.add_relation("digit_a", int) ctx.add_relation("digit_b", int) # Define a rule ctx.add_rule("sum_2(a + b) = digit_a(a) and digit_b(b)") # Add facts with special treatment: ( (probability_tensor, fact_id), tuple_data ) # Fact IDs must be distinct and contiguous for debugging. ctx.add_facts("digit_a", [ ((torch.tensor(0.1), 1), (0,)), ((torch.tensor(0.9), 2), (1,)) ]) ctx.add_facts("digit_b", [ ((torch.tensor(0.9), 3), (1,)), ((torch.tensor(0.1), 4), (2,)) ]) # Run the computation ctx.run() # Retrieve the result relation result = ctx.relation("sum_2") # Example of the required fact structure for non-probabilistic facts (tag=None) # ctx.add_facts("SOME_RELATION", [ # ( ( None, 5 ) , ( 0, ) ) # Non-probabilistic fact with Fact ID 5 # ]) ``` -------------------------------- ### Scallop Graph Transitive Closure Example Source: https://www.scallop-lang.org/doc/print Provides an example of graph data and the resulting transitive closure computed by Scallop rules. It shows how edges and paths are derived. ```Scallop rel edge = {(0, 1), (1, 2)} ``` -------------------------------- ### Scallopy Python API Usage Example Source: https://www.scallop-lang.org/doc/scallopy/getting_started Demonstrates basic interaction with the Scallop Python API. It shows how to create a context, define relations, add facts, write rules, execute the program, and retrieve results. ```Python import scallopy ctx = scallopy.Context() ctx.add_relation("edge", (int, int)) ctx.add_facts("edge", [(1, 2), (2, 3)]) ctx.add_rule("path(a, c) = edge(a, c) or path(a, b) and edge(b, c)") ctx.run() print(list(ctx.relation("path"))) # [(1, 2), (1, 3), (2, 3)] ``` -------------------------------- ### Scallop: Example Edge Relation Source: https://www.scallop-lang.org/doc/language/recursion Provides a concrete example of facts for the `edge` relation, used to illustrate the pathfinding computation. This set of facts defines the initial graph structure. ```scallop rel edge = {(0, 1), (1, 2)} ``` -------------------------------- ### Scallop: Define Expression Type and Example Source: https://www.scallop-lang.org/doc/print Defines a symbolic expression type using Scallop's type system and provides an example expression for demonstration. ```scallop type Expr = Const(i32) | Var(String) | Add(Expr, Expr) const MY_EXPR = Add(Add(Const(-3), Var("a")), Const(3)) // (-3 + a) + 3 ``` -------------------------------- ### Scallopy Basic Context Example Source: https://www.scallop-lang.org/doc/print Illustrates the fundamental usage of the 'scallopy' Python binding. It shows how to create a context, add relations and facts, define a rule, run the computation, and retrieve results. ```python import scallopy ctx = scallopy.Context() ctx.add_relation("edge", (int, int)) ctx.add_facts("edge", [(1, 2), (2, 3)]) ctx.add_rule("path(a, c) = edge(a, c) or path(a, b) and edge(b, c)") ctx.run() print(list(ctx.relation("path"))) # [(1, 2), (1, 3), (2, 3)] ``` -------------------------------- ### Scallop Logic Programming: Fibonacci Example Source: https://www.scallop-lang.org/doc/introduction Demonstrates basic Scallop syntax for defining types, relations, and recursive rules to compute Fibonacci numbers. Includes a query to retrieve results. ```Scallop type fib(bound x: i32, y: i32) rel fib = {(0, 1), (1, 1)} rel fib(x, y1 + y2) = fib(x - 1, y1) and fib(x - 2, y2) and x > 1 query fib(10, y) ``` -------------------------------- ### Scallop Logic Programming: Fibonacci Example Source: https://www.scallop-lang.org/doc/index Demonstrates basic Scallop syntax for defining types, relations, and recursive rules to compute Fibonacci numbers. Includes a query to retrieve results. ```Scallop type fib(bound x: i32, y: i32) rel fib = {(0, 1), (1, 1)} rel fib(x, y1 + y2) = fib(x - 1, y1) and fib(x - 2, y2) and x > 1 query fib(10, y) ``` -------------------------------- ### Scallop Expression Example and String Conversion Source: https://www.scallop-lang.org/doc/language/adt_and_entity Demonstrates defining a Scallop expression and a `to_string` relation for its visualization. Includes a query to show the string representation. ```scallop const MY_EXPR = Add(Add(Const(-3), Var("a")), Const(3)) // (-3 + a) + 3 rel to_string(p, i as String) = case p is Const(i) rel to_string(p, v) = case p is Var(v) rel to_string(p, $format("({} + {})", s1, s2)) = case p is Add(p1, p2) and to_string(p1, s1) and to_string(p2, s2) query to_string(MY_EXPR, s) // s = "((-3 + a) + 3)" ``` -------------------------------- ### Scallop Neuro-Symbolic Example Source: https://www.scallop-lang.org/doc/print Demonstrates Scallop's ability to combine knowledge base facts, rules, probabilistic facts, and aggregations for relational reasoning. ```Scallop // Knowledge base facts rel is_a("giraffe", "mammal") rel is_a("tiger", "mammal") rel is_a("mammal", "animal") // Knowledge base rules rel name(a, b) :- name(a, c), is_a(c, b) // Recognized from an image, maybe probabilistic rel name = { 0.3::(1, "giraffe"), 0.7::(1, "tiger"), 0.9::(2, "giraffe"), 0.1::(2, "tiger"), } // Count the animals rel num_animals(n) :- n = count(o: name(o, "animal")) ``` -------------------------------- ### Scallop Interpreter Output for Probabilistic Query Source: https://www.scallop-lang.org/doc/print Example output from the Scallop interpreter (scli) showing the derived probability for a queried relation, demonstrating the result of probabilistic reasoning. ```Shell > scli alarm.scl alarm: {0.224::()} ``` -------------------------------- ### Instantiate Linked List Source: https://www.scallop-lang.org/doc/print Creates an instance of the `List` ADT to represent a sequence of integers. This example shows how to define constants for data structures and provides a common representation for lists. ```Scallop const MY_LIST = Cons(1, Cons(2, Cons(3, Nil()))) // [1, 2, 3] ``` -------------------------------- ### Basic Scallop Fact Addition and Execution Source: https://www.scallop-lang.org/doc/scallopy/debug_proofs Demonstrates the initial setup for adding facts to a Scallop context and running a relation. This includes defining probabilistic facts with associated fact IDs. ```python ctx.add_facts("digit_a", [((torch.tensor(0.1), 1), (1,)), ((torch.tensor(0.9), 2), (2,))]) ctx.add_facts("digit_b", [((torch.tensor(0.9), 3), (1,)), ((torch.tensor(0.1), 4), (2,))]) ctx.run() result = ctx.relation("sum_2") ``` -------------------------------- ### Scallop Expressions Bounding Variables Source: https://www.scallop-lang.org/doc/print Shows an example where an expression `b + 1` in the body of a rule is used to derive the variable `b` in the head, effectively grounding it. ```Scallop rel output_relation(a, b) = input_relation(a, b + 1) ``` -------------------------------- ### Execute Scallop Program and Show Output Source: https://www.scallop-lang.org/doc/probabilistic/provenance This snippet shows the command-line execution of a Scallop program file (`alarm.scl`) using the `scli` interpreter and the resulting output, which includes the inferred probability for the queried fact 'alarm'. ```shell > scli alarm.scl alarm: {0.224::()} ``` -------------------------------- ### Run Scallop Program with CLI Source: https://www.scallop-lang.org/doc/print Command to execute a Scallop Datalog program file using the installed scli interpreter. It takes the path to the Scallop source file as an argument. ```Shell $ scli examples/datalog/edge_path.scl ``` -------------------------------- ### Scallop Regex Matching Relations Setup Source: https://www.scallop-lang.org/doc/language/adt_and_entity Sets up the necessary relations for checking if a given regular expression matches a string. It defines input relations for the regex and string, and relations for substring matching. ```scallop type input_regex(r: Regex) type input_string(s: String) type matches_substr(r: Regex, begin: usize, end: usize) type matches() ``` -------------------------------- ### Scallop: Fixed-Point Iteration Example Source: https://www.scallop-lang.org/doc/language/recursion Illustrates the step-by-step execution of a Scallop program with recursion using fixed-point iteration. It shows how the `path` relation is populated over multiple iterations based on the `edge` relation and recursive rules. ```scallop rel edge = {(0, 1), (1, 2), (2, 3)} rel path(a, b) = edge(a, b) // rule 1 rel path(a, c) = path(a, b) and edge(b, c) // rule 2 ``` -------------------------------- ### Scallop Infinite Relation Fibonacci Example Source: https://www.scallop-lang.org/doc/print Shows how Scallop can define infinite relations using recursion and value creation, such as a Fibonacci sequence. It also demonstrates how to bound such relations to ensure termination. ```Scallop rel fib(x, y1 + y2) = fib(x - 1, y1) and fib(x - 2, y2) // Bounded version: rel fib(x, y1 + y2) = fib(x - 1, y1) and fib(x - 2, y2) and x <= 10 ``` -------------------------------- ### Scallop Data Definition and Counting Enrollments Source: https://www.scallop-lang.org/doc/print Defines relations for classes and student enrollments, and a rule to count the number of students enrolled in 'CS' courses. This sets up data for query examples. ```Scallop // There are three classes rel classes = {0, 1, 2} // Each student is enrolled in a course (Math or CS) rel enroll = { ("tom", "CS"), ("jenny", "Math"), // Class 0 ("alice", "CS"), ("bob", "CS"), // Class 1 ("jerry", "Math"), ("john", "Math"), // Class 2 } // Count how many student enrolls in CS course rel num_enroll_cs(n) = n := count(s: enroll(s, "CS")) ``` -------------------------------- ### Scallop Neurosymbolic Programming Example Source: https://www.scallop-lang.org/doc/introduction Demonstrates Scallop's capabilities by combining knowledge base facts, rules, and probabilistic facts recognized from images. It shows how to define relations, rules, probabilistic assignments, and perform aggregations. ```Scallop // Knowledge base facts rel is_a("giraffe", "mammal") rel is_a("tiger", "mammal") rel is_a("mammal", "animal") // Knowledge base rules rel name(a, b) :- name(a, c), is_a(c, b) // Recognized from an image, maybe probabilistic rel name = { 0.3::(1, "giraffe"), 0.7::(1, "tiger"), 0.9::(2, "giraffe"), 0.1::(2, "tiger"), } // Count the animals rel num_animals(n) :- n = count(o: name(o, "animal")) ``` -------------------------------- ### Scallop Neurosymbolic Programming Example Source: https://www.scallop-lang.org/doc/index Demonstrates Scallop's capabilities by combining knowledge base facts, rules, and probabilistic facts recognized from images. It shows how to define relations, rules, probabilistic assignments, and perform aggregations. ```Scallop // Knowledge base facts rel is_a("giraffe", "mammal") rel is_a("tiger", "mammal") rel is_a("mammal", "animal") // Knowledge base rules rel name(a, b) :- name(a, c), is_a(c, b) // Recognized from an image, maybe probabilistic rel name = { 0.3::(1, "giraffe"), 0.7::(1, "tiger"), 0.9::(2, "giraffe"), 0.1::(2, "tiger"), } // Count the animals rel num_animals(n) :- n = count(o: name(o, "animal")) ``` -------------------------------- ### Scallop Probabilistic Aggregation Example (Count) Source: https://www.scallop-lang.org/doc/print Shows how aggregators like 'count' can be used with probabilistic facts, potentially employing multi-world semantics to aggregate results across different probability distributions. ```Scallop type OBJ = OBJ_A | OBJ_B rel size = {0.8::(OBJ_A, "big"); 0.2::(OBJ_A, "small")} // obj A is very likely big rel size = {0.1::(OBJ_B, "big"); 0.9::(OBJ_B, "small")} // obj B is very likely small ``` -------------------------------- ### Scallop Dependency Graph Example Source: https://www.scallop-lang.org/doc/print Illustrates the dependency graph for the `has_no_child` rule, showing positive and negative dependencies between predicates. This helps visualize how rules relate to each other in terms of data flow and negation. ```Scallop person <--pos-- has_no_child --neg--> father | +-----neg-----> mother ``` -------------------------------- ### Scallop Atomic Query Example Source: https://www.scallop-lang.org/doc/language/query Illustrates writing an atomic query in Scallop to retrieve a specific value from a relation, such as finding the 8th Fibonacci number. It shows how to specify arguments in the query. ```Scallop type fib(x: i32, y: i32) rel fib = {(0, 1), (1, 1)} rel fib(x, y1 + y2) = fib(x - 1, y1) and fib(x - 2, y2) and x <= 10 query fib(8, y) ``` -------------------------------- ### Scallop: Create and Use Entities (Lists) Source: https://www.scallop-lang.org/doc/language/adt_and_entity Explains how to create constants, referred to as Entities, using the `const` keyword and ADT definitions. It provides an example of defining a list ADT and creating a list entity. ```scallop type List = Cons(i32, List) | Nil() const MY_LIST = Cons(1, Cons(2, Cons(3, Nil()))) // [1, 2, 3] ``` -------------------------------- ### Scallop Sampling with Probability Example Source: https://www.scallop-lang.org/doc/probabilistic/sampling Demonstrates the use of the 'top' sampler in Scallop, which allows retrieving top-ranked facts based on probability. Samplers share syntax with aggregators and can be used with or without probabilistic provenances. ```scallop rel symbols = {0.9::"+", 0.05::"-", 0.02::"3"} rel top_symbol(s) = s := top<1>(s: symbols(s)) // 0.9::top_symbol("+") ``` -------------------------------- ### Scallop Logic Programming: Fibonacci Example Source: https://www.scallop-lang.org/doc/print Defines a recursive Fibonacci relation using Scallop's Datalog-like syntax. It includes type definitions, base cases, recursive rules, and a query. ```Scallop type fib(bound x: i32, y: i32) rel fib = {(0, 1), (1, 1)} rel fib(x, y1 + y2) = fib(x - 1, y1) and fib(x - 2, y2) and x > 1 query fib(10, y) ``` -------------------------------- ### Scallop: Use Entities in Relations and Queries Source: https://www.scallop-lang.org/doc/language/adt_and_entity Shows how to incorporate constant entities into facts within relations and query them. It explains that identical entities receive the same unique identifier, demonstrated with list examples. ```scallop rel target(MY_LIST) query target // Expected output: target: {(entity(0xff08d5d60a201f17))} const MY_LIST_1 = Cons(1, Nil()), MY_LIST_2 = Cons(1, Nil()), MY_LIST_3 = Cons(2, Nil()) rel lists = { (1, MY_LIST_1), (2, MY_LIST_2), (3, MY_LIST_3), } query lists // Expected output: // lists: { // (1, entity(0x678defa0a65c83ab)), // Notice that the entity 1 and 2 are the same // (2, entity(0x678defa0a65c83ab)), // (3, entity(0x3734567c3d9f8d3f)), // This one is different than above // } ``` -------------------------------- ### Define Rule and Query Alarm Source: https://www.scallop-lang.org/doc/probabilistic/provenance Declares a rule where an `alarm()` occurs if either `earthquake()` or `burglary()` is true. It then queries the derived `alarm()` fact, showcasing rule definition and probabilistic inference in Scallop. ```scallop rel alarm() = earthquake() or burglary() query alarm ``` -------------------------------- ### Scallop: Using Conjunction (and, /\) in Rule Definitions Source: https://www.scallop-lang.org/doc/print Demonstrates how to combine relations using the `and` operator or its symbolic equivalent `/` in Scallop rule bodies. This is crucial for joining relations on common variables, as shown in the `grandmother` example. ```scallop rel grandmother(a, c) = mother(a, b) and father(b, c) // or rel grandmother(a, c) = mother(a, b) /\ father(b, c) ``` -------------------------------- ### Scallop: Infinite Relation Example (Fibonacci) Source: https://www.scallop-lang.org/doc/language/recursion Shows how Scallop can define infinite relations, such as a Fibonacci sequence generator, by allowing value creation through arithmetic operations in recursive rules. This can lead to non-terminating fixed-point iterations. ```scallop rel fib(x, y1 + y2) = fib(x - 1, y1) and fib(x - 2, y2) ``` -------------------------------- ### Create and Invoke Scallopy Module with PyTorch Source: https://www.scallop-lang.org/doc/scallopy/getting_started This example demonstrates defining a Scallopy `Module` with a logical program and input/output mappings. It shows how to invoke this module using PyTorch tensors, facilitating batched execution and integration into machine learning workflows. ```python import scallopy import torch # Creating a module for execution my_sum2 = scallopy.Module( program=""" type digit_1(a: i32), digit_2(b: i32) rel sum_2(a + b) = digit_1(a) and digit_2(b) """, input_mappings={"digit_1": range(10), "digit_2": range(10)}, output_mappings={"sum_2": range(19)}, provenance="difftopkproofs") # Invoking the module with torch tensors. `result` is a tensor of 16 x 19 result = my_sum2( digit_1=torch.softmax(torch.randn(16, 10), dim=0), digit_2=torch.softmax(torch.randn(16, 10), dim=0)) ``` -------------------------------- ### Scallop Rule Definition Example Source: https://www.scallop-lang.org/doc/language/rules Demonstrates the definition of relations and rules in Scallop. It shows how to declare facts for an 'edge' relation and define a 'path' relation based on the 'edge' relation, illustrating a basic rule structure. ```Scallop rel edge = {(0, 1), (1, 2)} rel path(a, b) = edge(a, b) // (0, 1), (1, 2) ``` -------------------------------- ### Instantiate Binary Tree Source: https://www.scallop-lang.org/doc/print Demonstrates creating an instance of the `Tree` ADT to represent a balanced binary search tree. This shows how to construct complex data structures using the defined ADT. ```Scallop // 3 // / \ // 1 5 // / \ / \ // 0 2 4 6 const MY_TREE = Node(3, Node(1, Node(0, Nil(), Nil()), Node(2, Nil(), Nil()), ), Node(5, Node(4, Nil(), Nil()), Node(6, Nil(), Nil()), ) ) ``` -------------------------------- ### Scallop: Unsigned Integer Type Error Example Source: https://www.scallop-lang.org/doc/language/value_type Illustrates a type inference error in Scallop when assigning negative numbers to unsigned integer types. The example shows the `sclrepl` output and the specific error message. ```scallop scl> type my_edge(usize, usize) scl> rel my_edge = {(-1, -5), (0, 3)} [Error] cannot unify types `usize` and `signed integer`, where the first is declared here REPL:0 | type my_edge(usize, usize) | ^^^^^ and the second is declared here REPL:1 | rel my_edge = {(-1, -5), (0, 3)} | ^^ ``` -------------------------------- ### Initialize ScallopContext with Provenance Source: https://www.scallop-lang.org/doc/print Demonstrates how to create a ScallopContext instance, specifying different provenance types for reasoning. Provenance options include 'unit' for untagged semantics, 'minmaxprob' for probabilistic reasoning, 'diffminmaxprob' for differentiable reasoning, and 'topkproofs' which can accept additional parameters like 'k'. ```python import scallopy # Default provenance (unit) ctx = scallopy.ScallopContext() # Explicitly specify provenance ctx = scallopy.ScallopContext(provenance="unit") # Probabilistic provenance ctx = scallopy.ScallopContext(provenance="minmaxprob") # Differentiable provenance ctx = scallopy.ScallopContext(provenance="diffminmaxprob") # Top-k proofs provenance with k=5 ctx = scallopy.ScallopContext(provenance="topkproofs", k=5) ``` -------------------------------- ### Scallop: Integer Type Inference Error Example Source: https://www.scallop-lang.org/doc/print Provides an example of a type inference error in Scallop when attempting to assign a negative number to a variable declared with an unsigned integer type. This highlights Scallop's strict type checking. ```scallop scl> type my_edge(usize, usize) scl> rel my_edge = {(-1, -5), (0, 3)} [Error] cannot unify types `usize` and `signed integer`, where the first is declared here REPL:0 | type my_edge(usize, usize) | ^^^^^ and the second is declared here REPL:1 | rel my_edge = {(-1, -5), (0, 3)} | ^^ ``` -------------------------------- ### Type Inference Failure Example Source: https://www.scallop-lang.org/doc/print Demonstrates a type inference failure in Scallop when a relation is assigned conflicting types. The example shows an 'edge' relation with one fact having an integer and another having a string for the same argument position, leading to a unification error. ```scallop rel edge = {(0, 1), (0, "1")} ``` -------------------------------- ### Scallop Negations Example Source: https://www.scallop-lang.org/doc/language/negation Demonstrates how to use negation in Scallop rules to define relations based on the absence of certain conditions. It shows how to identify individuals with no children by checking for the absence of them being a father or mother. The example includes the definition of relations, a rule using negation, and the expected output. ```Scallop rel person = {"bob", "alice", "christine"} // There are three persons of interest rel father = {("bob", "alice")} // Bob is Alice's father rel mother = {("alice", "christine")} // Alice is Christine's mother rel has_no_child(n) = person(n) and not father(n, _) and not mother(n, _) // Expected output: has_no_child: {("christine",)} ``` -------------------------------- ### Debug Top-K Proofs with Scallopy Source: https://www.scallop-lang.org/doc/scallopy/debug_proofs Demonstrates how to configure the Scallop context for debugging top-k proofs using the 'difftopkproofsdebug' provenance. It shows adding relations, defining rules, and setting the k-value for debugging. ```python ctx = scallopy.ScallopContext(provenance="difftopkproofsdebug", k=3) ctx.add_relation("digit_a", int) ctx.add_relation("digit_b", int) ctx.add_rule("sum_2(a + b) = digit_a(a) and digit_b(b)") ``` -------------------------------- ### ScallopContext Initialization Source: https://www.scallop-lang.org/doc/scallopy/context Demonstrates how to create a ScallopContext with different provenance settings. Provenance options include 'unit' for discrete Datalog, 'minmaxprob' for probabilistic reasoning, 'diffminmaxprob' for differentiable reasoning, and 'topkproofs' which accepts additional parameters like 'k'. ```python ctx = scallopy.ScallopContext(provenance="unit") # or ctx = scallopy.ScallopContext(provenance="minmaxprob") # or ctx = scallopy.ScallopContext(provenance="diffminmaxprob") # or ctx = scallopy.ScallopContext(provenance="topkproofs", k=5) ``` -------------------------------- ### Scallop Ungrounded Variable Example Source: https://www.scallop-lang.org/doc/print Illustrates a Scallop rule where a variable `c` in the head is not grounded by any relation or expression in the body, leading to a compilation error. ```Scallop rel path(a, c) = edge(a, b) ``` -------------------------------- ### Scallop Dynamic Entity Creation with Lists Source: https://www.scallop-lang.org/doc/print Demonstrates the dynamic creation of new entities using the 'new' keyword in Scallop. This example shows how to prepend an element to an existing list during a deductive process, effectively creating a new list instance. ```scallop type input_list(List) rel result_list(new Cons(1, l)) = input_list(l) ``` -------------------------------- ### Define Probabilistic Fact Earthquake Source: https://www.scallop-lang.org/doc/probabilistic/provenance Defines a probabilistic fact `earthquake()` with a probability of 0.03. This is a core concept in Scallop for representing uncertain events and their likelihoods. ```scallop rel 0.03::earthquake() ``` -------------------------------- ### Decompose List Entity in Rules Source: https://www.scallop-lang.org/doc/print Shows how to decompose an entity using the `case`-`is` operator within relation rules. This example computes the length of a list recursively. ```Scallop type length(list: List, len: i32) rel length(list, 0) = case list is Nil() rel length(list, l + 1) = case list is Cons(_, tl) and length(tl, l) ``` -------------------------------- ### Scallop Module Configuration for Debugging Source: https://www.scallop-lang.org/doc/scallopy/debug_proofs Shows how to configure a Scallop module for debugging in forward mode. Key parameters include `provenance`, `k`, the Scallop `program`, `output_relation`, and `output_mapping`. ```python sum_2 = scallopy.Module( provenance="difftopkproofsdebug", k=3, program=""" type digit_a(a: i32), digit_b(b: i32) rel sum_2(a + b) = digit_a(a) and digit_b(b) """, output_relation="sum_2", output_mapping=[2, 3, 4]) ``` -------------------------------- ### Scallop Atomic Query for Fibonacci Source: https://www.scallop-lang.org/doc/print Shows how to perform an atomic query to retrieve a specific value from a recursive relation. This example calculates the 8th Fibonacci number. ```Scallop type fib(x: i32, y: i32) rel fib = {(0, 1), (1, 1)} rel fib(x, y1 + y2) = fib(x - 1, y1) and fib(x - 2, y2) and x <= 10 query fib(8, y) // fib(8, y): {(8, 34)} ``` -------------------------------- ### Cloning a Scallop Context Source: https://www.scallop-lang.org/doc/print Shows how to create an exact copy of an existing Scallop context. The cloned context includes all program definitions, configurations, and provenance information from the original. ```python new_ctx = ctx.clone() ``` -------------------------------- ### Scallop Ungrounded Variable Example Source: https://www.scallop-lang.org/doc/language/rules Illustrates a Scallop rule where a variable `c` in the head is not grounded by any relation or expression in the body, leading to a compilation error. ```Scallop rel path(a, c) = edge(a, b) ``` -------------------------------- ### Define Probabilistic Fact Burglary Source: https://www.scallop-lang.org/doc/probabilistic/provenance Defines a probabilistic fact `burglary()` with a probability of 0.20. This demonstrates how to represent another uncertain event and its associated probability in Scallop. ```scallop rel 0.20::burglary() ``` -------------------------------- ### Run Scallop Program with scli Source: https://www.scallop-lang.org/doc/installation Executes a Scallop program file using the 'scli' interpreter. This command takes the path to a Scallop source file as an argument. ```shell $ scli examples/datalog/edge_path.scl ``` -------------------------------- ### Scallopy Python Module Initialization Source: https://www.scallop-lang.org/doc/print Shows how to initialize a Scallopy module using the Python binding. This involves defining the Scallop program string, input mappings, and output mapping. ```Python sum_2 = scallopy.Module( program="""type digit_1(i32), digit_2(i32) rel sum_2(a + b) = digit_1(a) and digit_2(b)""", input_mappings={"digit_1": range(10), "digit_2": range(10)}, output_mapping=("sum_2", range(19))) ``` -------------------------------- ### Declaring ADT Entities as Constants Source: https://www.scallop-lang.org/doc/print Declares an entity of an ADT as a constant. This example shows how to represent the list `[1, 2, 3]` using the `IntList` ADT definition. ```scallop const MY_LIST = Cons(1, Cons(2, Cons(3, Nil()))) ``` -------------------------------- ### Scallop: Specify Fields and Keys Source: https://www.scallop-lang.org/doc/print Shows how to use both `keys` and `fields` arguments in Scallop's `@file` annotation to define a type, specifying primary keys and selecting specific columns to load. ```scallop @file("enrollment.csv", keys=["student_id", "course_id"], fields=["grade"]) type enrollment(student_id: usize, course_id: String, field: String, value: String) // The following facts will be obtained // enrollment(1, "cse100", "grade", "a") // enrollment(1, "cse101", "grade", "a") // enrollment(2, "cse120", "grade", "b") ``` -------------------------------- ### Scallop Basic Atom Definition Source: https://www.scallop-lang.org/doc/print Defines a relation `path` based on an `edge` relation. This example shows how variables `a` and `b` in the head are grounded by the `edge` relation in the body. ```Scallop rel path(a, b) = edge(a, b) ``` -------------------------------- ### Scallop: String Declaration Source: https://www.scallop-lang.org/doc/language/value_type Shows how to declare and use strings in Scallop. Strings are double-quoted and support escaped characters. An example relation `greeting` is provided. ```scallop rel greeting = {"Hello World"} ``` -------------------------------- ### Scallop Expressions Bounding Variables Source: https://www.scallop-lang.org/doc/language/rules Shows an example where an expression `b + 1` in the body of a rule is used to derive the variable `b` in the head, effectively grounding it. ```Scallop rel output_relation(a, b) = input_relation(a, b + 1) ``` -------------------------------- ### Batched Input Data for Debug Mode Source: https://www.scallop-lang.org/doc/scallopy/debug_proofs Provides an example of how input data should be structured when using Scallop's debug mode. Data is batched, with each item in the batch representing a data point, and facts within a data point include probabilities and fact IDs. ```python digit_a = [ [((torch.tensor(0.1), 1), (1,)), ((torch.tensor(0.9), 2), (2,))], # Datapoint 1 # ... ] digit_b = [ [((torch.tensor(0.9), 3), (1,)), ((torch.tensor(0.1), 4), (2,))], # Datapoint 1 # ... ] ``` -------------------------------- ### Scallop Basic Atom Definition Source: https://www.scallop-lang.org/doc/language/rules Defines a relation `path` based on an `edge` relation. This example shows how variables `a` and `b` in the head are grounded by the `edge` relation in the body. ```Scallop rel path(a, b) = edge(a, b) ``` -------------------------------- ### Defining Enum Types Source: https://www.scallop-lang.org/doc/print Defines enum types with constant variables like RED, GREEN, BLUE. Values are unsigned integers starting from 0 by default and incrementing sequentially. ```scallop type Color = RED | GREEN | BLUE type Action = LEFT | UP | RIGHT | DOWN ``` -------------------------------- ### Scallop Sampling with Top K Source: https://www.scallop-lang.org/doc/print Demonstrates how to use the 'top' sampler in Scallop to retrieve the k facts with the highest probabilities. This rule defines how to get the top-ranked symbol from a relation. ```scallop rel symbols = {0.9::"+", 0.05::"-", 0.02::"3"} rel top_symbol(s) = s := top<1>(s: symbols(s)) // 0.9::top_symbol("+") ``` -------------------------------- ### Adding Programs to ScallopContext Source: https://www.scallop-lang.org/doc/scallopy/context Shows methods for loading Scallop programs into an initialized context. Programs can be added directly as a Python string or by importing an external '.scl' file. ```python ctx.add_program("\n rel edge = {(0, 1), (1, 2)}\n rel path(a, c) = edge(a, c) or path(a, b) and edge(b, c)\n") ctx.import_file("edge_path.scl") ``` -------------------------------- ### Scallop Sum Aggregator (Incorrect Usage) Source: https://www.scallop-lang.org/doc/print Shows an example of incorrect usage of the 'sum' aggregator by omitting the argument variable, which can lead to deduplication of values before summation, resulting in an inaccurate total. ```scallop rel total_sales_wrong(s) = s := sum(sp: sales(p, sp)) // 2200.0, since the two 1000.0 will be deduplicated without its key ``` -------------------------------- ### Scallop Negation Example Source: https://www.scallop-lang.org/doc/print Demonstrates the use of negation (`not`) in Scallop rules to derive facts, such as identifying individuals with no children. It highlights how negation helps in expressing conditions like 'absence of a relation'. ```Scallop rel person = {"bob", "alice", "christine"} // There are three persons of interest rel father = {("bob", "alice")} // Bob is Alice's father rel mother = {("alice", "christine")} // Alice is Christine's mother rel has_no_child(n) = person(n) and not father(n, _) and not mother(n, _) // Result: has_no_child: {("christine",)} ``` -------------------------------- ### Invoking Debug Module and Output Structure Source: https://www.scallop-lang.org/doc/scallopy/debug_proofs Demonstrates how to call a Scallop module configured for debugging and explains the structure of the returned output, which includes both the result tensor and detailed proofs. ```python (result_tensor, proofs) = sum_2(digit_a=digit_a, digit_b=digit_b) ``` -------------------------------- ### Add Scallop Program to Context Source: https://www.scallop-lang.org/doc/print Shows two methods for loading Scallop programs into a context: directly inserting a program as a Python string or importing it from an external '.scl' file. This allows defining relations and rules for computation. ```python ctx.add_program("" rel edge = {(0, 1), (1, 2)} rel path(a, c) = edge(a, c) or path(a, b) and edge(b, c) "") ``` ```python ctx.import_file("edge_path.scl") ``` -------------------------------- ### Scallop: Boolean Declaration and Usage Source: https://www.scallop-lang.org/doc/language/value_type Demonstrates the use of boolean values in Scallop. It shows how to declare a relation `variable_assign` with a boolean type and provides an example of a logical operation. ```scallop type variable_assign(String, bool) rel variable_assign = {("a", true), ("b", false)} rel result(a ^ b) = variable_assign("a", a) and variable_assign("b", b) // true ```