### Scallop Installation: Verification Example Source: https://github.com/scallop-lang/scallop/blob/master/readme.md A command to run an example script to verify that Scallop has been installed successfully. Ensure you are within the activated virtual environment when running this command. ```bash $ python etc/scallopy/examples/edge_path.py ``` -------------------------------- ### Scallopy Context: Basic Program Execution Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/scallopy/getting_started.md Illustrates the core functionality of the Scallopy `Context` class for managing a Scallop program. This example shows how to define relations, add facts, specify rules, execute the program, and retrieve the computed 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)] ``` -------------------------------- ### Run Example Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy/readme.md Executes a sample Scallop Python script to verify the installation and functionality of the `scallopy` binding. ```bash python examples/edge_path.py ``` -------------------------------- ### Run Scallop Program with scli Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/installation.md Executes a Scallop Datalog program (`.scl` file) using the `scli` interpreter. This demonstrates how to test and run Scallop programs after installation. ```bash $ scli examples/datalog/edge_path.scl ``` -------------------------------- ### Scallopy Module for ML with PyTorch Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/scallopy/getting_started.md Demonstrates creating a Scallopy `Module` for efficient, batched execution, suitable for machine learning pipelines. It shows how to define a program, map inputs and outputs, and integrate with PyTorch tensors. ```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)) ``` -------------------------------- ### Using Scallop REPL (sclrepl) Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Instructions for installing and using the Scallop interactive command-line interface (`sclrepl`). It provides an example session demonstrating how to define relations, rules, and query results. ```bash $ cargo install --path etc/sclrepl ``` ```bash $ sclrepl scl> rel edge = {(0, 1), (1, 2)} scl> rel path(a, c) = edge(a, c) \/ path(a, b) /\ edge(b, c) scl> query path path: {(0, 1), (0, 2), (1, 2)} scl> ``` -------------------------------- ### Install Scallop Interpreter (scli) Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/installation.md Installs the Scallop command-line interpreter (`scli`) using the `make` utility. This command is essential for running Scallop programs directly from your terminal. ```bash $ make install-scli ``` -------------------------------- ### Scallop Installation: Virtual Environment Setup Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Instructions for setting up a Python virtual environment for Scallop on Mac/Linux systems using `venv`. It covers creating the environment and activating it, with a note for Fish shell users. ```bash # Mac/Linux (venv, requirement: Python 3.8) $ make py-venv # create a python virtual environment $ source .env/bin/activate # if you are using fish, use .env/bin/activate.fish ``` -------------------------------- ### Install Scallop Gemini Plugin Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy-plugins/gemini/readme.md Provides commands to install the Scallop Gemini plugin from source. Includes options for standard installation and development setup, allowing in-source editing for developers. ```bash make -C etc/scallopy-plugins install-gemini ``` ```bash make -C etc/scallopy-plugins develop-gemini ``` -------------------------------- ### Install scallopy Python Binding Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy/readme.md Installs the `scallopy` Python binding directly from the GitHub repository using pip. This is the recommended way for quick installation. ```bash pip install "git+https://github.com/scallop-lang/scallop.git#egg=scallopy&subdirectory=etc/scallopy" ``` -------------------------------- ### Using Scallop Interpreter (scli) Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Guides on installing and running the Scallop command-line interpreter (`scli`) to execute `.scl` files. It explains how to specify provenance semirings for probabilistic inputs. ```bash $ make install-scli ``` ```bash $ scli examples/animal.scl ``` ```bash $ scli examples/digit_sum_prob.scl -p minmaxprob ``` -------------------------------- ### Install Scallop GPT Plugin Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy-plugins/gpt/readme.md Installs the Scallop GPT plugin from source. This command navigates to the plugin directory and executes the install script. ```bash make -C etc/scallopy-plugins install-gpt ``` -------------------------------- ### Install Scallopy Plugins Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy-plugins/readme.md Commands to install or develop Scallopy plugins. The 'develop' option allows for live code changes without re-installation, while 'install' builds and installs a wheel package. ```bash make -C etc/scallopy-plugins develop # to develop all plugins # or make -C etc/scallopy-plugins install # to install all plugins # or make -C etc/scallopy-plugins develop- # to develop the specific # or make -C etc/scallopy-plugins install- # to install the specific ``` -------------------------------- ### Scallop Installation: Core Dependencies and Build Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Commands to install the core dependency `maturin` and then build and install the `scallopy` library using `make`. ```bash $ pip install maturin $ make install-scallopy ``` -------------------------------- ### Scallop Installation: Conda Environment Setup Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Instructions for setting up a Python virtual environment for Scallop on Linux systems using Conda. It covers creating and activating a Conda environment with Python 3.8. ```bash # Linux (Conda) $ conda create --name scallop-lab python=3.8 # change the name to whatever you want $ conda activate scallop-lab ``` -------------------------------- ### Scallop Plugin Core Functions Example Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy-plugins/readme.md An example Python implementation for a Scallop plugin, demonstrating the three core functions: setup_arg_parser for command-line arguments, configure for argument processing, and load_into_context for registering foreign functions into the Scallop context. ```python MY_KEY = None # a global variable holding the key def setup_arg_parser(parser: ArgumentParser): parser.add_argument("--key", type=str, default="12345678") def configure(args): global MY_KEY MY_KEY = args.key # load the key from cmd args def load_into_context(ctx: scallopy.Context): # Create a foreign function that returns the loaded key @scallopy.foreign_function def get_key() -> str: return MY_KEY # Register the `$get_key` foreign function into ctx ctx.register_foreign_function(get_key) ``` -------------------------------- ### Install Rust and Build Scallop Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Instructions for installing the Rust programming language with the nightly channel and cloning the Scallop project from GitHub. It also covers building the Scallop interpreter, compiler, and REPL tools. ```bash $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh $ rustup default nightly ``` ```bash $ git clone https://github.com/scallop-lang/scallop.git $ cd scallop ``` ```bash $ make install-scli # Scallop Interpreter $ make install-sclc # Scallop Compiler $ make install-sclrepl # Scallop REPL ``` -------------------------------- ### Scallop VSCode Plugin Installation Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Steps to install the Scallop VSCode plugin from source. This involves installing `vsce` globally, building the plugin, and then installing the generated `.vsix` file within VSCode. ```bash $ npm install -g vsce $ make vscode-plugin ``` -------------------------------- ### Scallop Example: Assignment and Variable Binding Source: https://github.com/scallop-lang/scallop/blob/master/res/notes/compiler/query_plan_notes.md Illustrates a Scallop rule with an assignment operation and provides a step-by-step example of how variables are bound and updated during program execution. ```Scallop r(a, b) and s(d) and b := a - d example: [1, 2, 3] [] -> [1] =====> old: {}, new: {a, b} [1] -> [1, 2] =====> old: {a, b}, new: {d} [1, 2] -> [3] =====> old: {a, b, d}, new: {d'}, inserted constraint: {d == d'} ``` -------------------------------- ### Install mdbook Source: https://github.com/scallop-lang/scallop/blob/master/doc/readme.md Installs the mdbook toolchain using cargo, the Rust package manager. This is a prerequisite for developing the book. ```bash $ cargo install mdbook ``` -------------------------------- ### Install Dependencies for Experiments Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy/readme.md Installs additional Python packages required for running experiments located in the `/experiments` folder, specifically PyTorch, PyTorch Vision, and `tqdm`. ```bash pip install tqdm torch torchvision ``` -------------------------------- ### Serve Scallop Book Locally Source: https://github.com/scallop-lang/scallop/blob/master/doc/readme.md Starts a local server to serve the Scallop book. Changes to markdown files will automatically refresh the browser page. ```bash $ make serve-book ``` -------------------------------- ### Scallop PyTorch Integration Example Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Demonstrates how to integrate Scallop with PyTorch by defining a neural network that uses Scallop for logical reasoning. It shows the setup of a Scallop context, adding relations, defining a sum rule, and creating a forward function that leverages Scallop's reasoning capabilities. ```python import scallopy import torch from torch import nn from typing import Tuple # Assume MNISTNet is defined elsewhere # class MNISTNet(nn.Module): # ... class MNISTSum2Net(nn.Module): def __init__(self, provenance="difftopkproofs", k): super(MNISTSum2Net, self).__init__() # MNIST Digit Recognition Network self.mnist_net = MNISTNet() # Scallop Context self.scl_ctx = scallopy.ScallopContext(provenance=provenance, k=k) self.scl_ctx.add_relation("digit_1", int, input_mapping=list(range(10))) self.scl_ctx.add_relation("digit_2", int, input_mapping=list(range(10))) self.scl_ctx.add_rule("sum_2(a + b) = digit_1(a), digit_2(b)") # The `sum_2` logical reasoning module self.sum_2 = self.scl_ctx.forward_function("sum_2", list(range(19))) def forward(self, x: Tuple[torch.Tensor, torch.Tensor]): (a_imgs, b_imgs) = x # First recognize the two digits a_distrs = self.mnist_net(a_imgs) b_distrs = self.mnist_net(b_imgs) # Then execute the reasoning module; the result is a size 19 tensor return self.sum_2(digit_1=a_distrs, digit_2=b_distrs) ``` -------------------------------- ### ScallopContext Setup and Execution Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/scallopy/context.md Demonstrates the fundamental workflow of creating a ScallopContext, defining relations and facts, adding rules, running the computation, and retrieving results. ```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"))) # Expected output: [(0, 1), (0, 2), (1, 2)] ``` -------------------------------- ### Scallop Example: Fibonacci Relation with Constraints Source: https://github.com/scallop-lang/scallop/blob/master/res/notes/compiler/query_plan_notes.md Demonstrates a Scallop rule for a Fibonacci-like relation, involving recursive calls and various equality/assignment constraints on intermediate variables. ```Scallop fib(x - 1, a) and fib(x - 2, b) and (y == a + b, y := a + b, a == y - b, ...) equivalent_classes: { {1}, {2}, {3, 4, 5, 6}, {7, 8, 9, 10} } example: 1. [] -> [1], old: {}, new: {U, a} 2. [1] -> [1, ] ``` -------------------------------- ### Scallop Probabilistic DataLog Program Example Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Demonstrates a simple probabilistic DataLog program written in Scallop, including facts, rules, probabilistic facts, and counting aggregates. This example showcases Scallop's ability to handle probabilistic 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 Variable Equivalence and Assignment Example Source: https://github.com/scallop-lang/scallop/blob/master/res/notes/compiler/query_plan_notes.md Shows a Scallop snippet focusing on variable equivalences and assignments, illustrating relationships like U == x - 1 and U := x - 1, along with their inverse operations. ```Scallop U == x - 1, U := x - 1, x == U + 1, x := U + 1 ---- 2 <---> 4 ^ < > ^ | x | 1 / \ 3 ``` -------------------------------- ### Import Scallop Files Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/reference_guide.md Demonstrates how to import other Scallop files into the current scope, allowing for modular code organization and reuse of definitions. ```scl import "path/to/other/file.scl" ``` -------------------------------- ### Scallop Recursive Relation Example Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/introduction.md Illustrates the definition of a recursive relation using Scallop's syntax for defining types, base cases, and recursive rules. This example defines the Fibonacci sequence. ```scl 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 Rule with Constraint and Recursion Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/reference_guide.md Demonstrates recursive rule definition combined with constraints, such as generating a sequence of numbers up to a limit. ```scl rel number(0) rel number(i + 1) = number(i) and i < 10 ``` -------------------------------- ### Scallop $string_index_of Function Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/foreign_functions.md Finds the starting index of the first occurrence of a substring within a larger string. Returns the index or an indicator if not found. Example: `$string_index_of("hello world", "world")` returns `6`. ```Scallop $string_index_of(s: String, pat: String) -> usize Description: Find the index of the first occurrence of the pattern `pat` in string `s` Example: $string_index_of("hello world", "world") => 6 ``` -------------------------------- ### Scallop $substring Function Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/foreign_functions.md Extracts a portion of a string given a starting index and an optional ending index. If the end index is omitted, it extracts to the end of the string. Example: `$substring("hello world", 6)` returns `"world"`. ```Scallop $substring(s: String, b: usize, e: usize?) -> String Description: Find the substring given begin index and optional the end index Example: $substring("hello world", 6) => "world" ``` -------------------------------- ### Scallop CLI Execution Example Source: https://github.com/scallop-lang/scallop/blob/master/experiments/hwf/readme.md Demonstrates how to run a Scallop program file using the Scallop interpreter (scli) with the --provenance topkproofs option. This command executes a Scallop program designed for the HWF project. ```shell $ scli examples/hwf_length_3_top_3_prob.scl --provenance topkproofs ``` -------------------------------- ### Build scallopy Python Binding Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy/readme.md Provides instructions for building the `scallopy` Python binding from source. This involves setting up a virtual environment, installing core dependencies like `maturin`, and executing the build process. ```bash # Mac/Linux (venv, requirement: Python 3.8) $ python3 -m venv .env $ source .env/bin/activate # if you are using fish, use .env/bin/activate.fish # Linux (Conda) $ conda create --name scallop-lab python=3.8 # change the name to whatever you want $ conda activate scallop-lab $ pip install maturin $ cd etc/scallopy # Go to this directory $ make # Build the library $ cd ../.. # Going back to the root `scallop` directory ``` -------------------------------- ### Ungrounded Variable Error Example Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/rules.md Illustrates a common error scenario where a variable in the head of a rule is not grounded by any variable or expression in the body. The example shows the resulting compilation error. ```scl rel path(a, c) = edge(a, b) ``` -------------------------------- ### Adding Scallop Program from String Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/scallopy/context.md Illustrates how to load a complete Scallop program directly into the context using a multi-line Python string. ```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) """) ``` -------------------------------- ### Scallop: Define Relations and Query Specific Output Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/query.md Demonstrates defining relations for classes and enrollments, computing the number of students in CS courses, and using the `query` keyword to specify which relations to output. ```scl // 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")) ``` ```scl query num_enroll_cs ``` -------------------------------- ### Develop Scallop GPT Plugin Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy-plugins/gpt/readme.md Sets up the Scallop GPT plugin for development. This allows for in-source editing and immediate reflection of changes during execution. ```bash make -C etc/scallopy-plugins develop-gpt ``` -------------------------------- ### Scallop Knowledge Base and Rules Example Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/introduction.md Demonstrates basic Scallop syntax for defining knowledge base facts, relational rules, probabilistic facts, and aggregation queries. It showcases how to represent relationships and count entities. ```scl // 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 Foreign Function Syntax and Examples Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/foreign_functions.md Defines the general syntax for Scallop foreign functions, including generic arguments, positional, optional, and variable arguments, and provides examples of common functions like string manipulation, absolute value, and formatting. Foreign functions are prefixed with '$' and must have a return type. ```APIDOC Scallop Foreign Function Signature: $FUNC_NAME(POS_ARG: POS_ARG_TYPE, ..., OPT_ARG: OPT_ARG_TYPE?, ..., VAR_ARG_TYPE...) -> RETURN_TYPE - FUNC_NAME: The name of the foreign function, prefixed with '$'. - ARG: Generic type arguments, optionally annotated with a type family. - POS_ARG: Positional arguments. - OPT_ARG: Optional arguments (appear after positional arguments). - VAR_ARG_TYPE: Variable number of arguments (appear last). - RETURN_TYPE: The type of the value returned by the function. Function Failures: - Foreign functions may fail (e.g., divide-by-zero, index-out-of-bounds). - Failed invocations are dropped silently and do not propagate values. Examples: $string_char_at(s: String, i: usize) -> char - Retrieves the character at a specific index in a string. - Arguments: s (String), i (usize). - Returns: char. $substring(s: String, b: usize, e: usize?) -> String - Extracts a substring from a given string. - Arguments: s (String), b (usize - start index), e (usize? - optional end index). - Can be invoked with 2 or 3 arguments. $abs(T) -> T - Computes the absolute value of a number. - Generic type T must be a Number (integer or float). - Returns the same type as the input. $format(f: String, Any...) -> String - Formats a string using placeholders '{}'. - Arguments: f (String - format string), followed by a variable number of arguments of Any type. - Example: $format("{} + {}", 3, "a") ==> "3 + a" - Example: $format("{}", true) ==> "true" ``` -------------------------------- ### Querying `to_string` Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/adt_and_entity.md Shows how to query the `to_string` relation to get the string representation of a Scallop expression. ```scl query to_string(MY_EXPR, s) // s = "((-3 + a) + 3)" ``` -------------------------------- ### Using scallopy Python Bindings Source: https://github.com/scallop-lang/scallop/blob/master/readme.md Demonstrates how to use the `scallopy` Python library for Scallop integration. It shows creating a context, adding relations and facts, defining rules, and running the program. ```python import scallopy # Create new context (with unit provenance) ctx = scallopy.ScallopContext() # Construct the program ctx.add_relation("edge", (int, int)) ctx.add_facts("edge", [(0, 1), (1, 2)]) ctx.add_rule("path(a, c) = edge(a, c)") ctx.add_rule("path(a, c) = edge(a, b), path(b, c)") # Run the program ctx.run() ``` -------------------------------- ### Importing Scallop Program from File Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/scallopy/context.md Demonstrates how to load a Scallop program from an external file (e.g., 'edge_path.scl') into the context. ```python ctx.import_file("edge_path.scl") ``` -------------------------------- ### Scallop $string_length Function Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/foreign_functions.md Returns the number of characters in a string. Example: `$string_length("hello")` returns `5`. ```Scallop $string_length(s: String) -> usize Description: Get the length of the string Example: $string_length("hello") => 5 ``` -------------------------------- ### ScallopContext Initialization with Provenance Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/scallopy/context.md Shows how to initialize a ScallopContext with different provenance types, including default, probabilistic, differentiable, and top-k proofs with custom parameters. ```python # Default provenance (unit) ctx = scallopy.ScallopContext() # Explicitly setting unit provenance ctx = scallopy.ScallopContext(provenance="unit") # Probabilistic provenance ctx = scallopy.ScallopContext(provenance="minmaxprob") # Differentiable probabilistic provenance ctx = scallopy.ScallopContext(provenance="diffminmaxprob") # Top-k proofs provenance with k=5 ctx = scallopy.ScallopContext(provenance="topkproofs", k=5) ``` -------------------------------- ### Scallop $datetime_year Function Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/foreign_functions.md Extracts the year component from a `DateTime` value. Example: `$datetime_year(t"2023-01-01")` returns `2023`. ```Scallop $datetime_year(d: DateTime) -> i32 Description: Get the year component of a `DateTime` Example: $datetime_year(t"2023-01-01") => 2023 ``` -------------------------------- ### Scallop Module Debugging Setup Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/scallopy/debug_proofs.md Details on configuring a Scallop Module for debugging in forward mode. The 'provenance' parameter must be set to 'difftopkproofsdebug'. The 'program' defines the Scallop logic, 'output_relation' specifies the main output, and 'output_mapping' maps elements of the output tuple to indices. ```APIDOC scallopy.Module: __init__(provenance: str = "", k: int = 1, program: str, output_relation: str, output_mapping: List[int], ...) provenance: Specifies the provenance strategy. For debugging, set to "difftopkproofsdebug". k: The top-k value used in the debugging provenance. program: A string containing the Scallop program definition. output_relation: The name of the relation that the module's output corresponds to. output_mapping: A list of integers specifying the indices of the output tuple that correspond to the relation's elements. ``` -------------------------------- ### Scallop Plugin pyproject.toml Template Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy-plugins/readme.md A template for the pyproject.toml file required for creating a new Scallop plugin. It defines project metadata, dependencies, and entry points for Scallop plugin functionalities. ```toml [project] name = "scallop-" version = "0.0.1" dependencies = ["", ""] [tool.setuptools.packages.find] where = ["src"] [project.entry-points."scallop.plugin.setup_arg_parser"] = "scallop_:setup_arg_parser" [project.entry-points."scallop.plugin.configure"] = "scallop_:configure" [project.entry-points."scallop.plugin.load_into_context"] = "scallop_:load_into_context" ``` -------------------------------- ### Define Scallop Set-of-Tuples Relation Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/reference_guide.md Initializes a relation with a predefined set of tuples. This is an alternative way to define facts for a relation. ```scl rel edge = {(1, 2), (2, 3), (3, 4)} ``` -------------------------------- ### Basic Scallop Context Usage Source: https://github.com/scallop-lang/scallop/blob/master/etc/scallopy/readme.md Demonstrates the fundamental usage of the `ScallopContext` in Python. It shows how to add relations, facts, rules, run the Scallop program, and inspect the results. ```python from scallopy import ScallopContext # Create new context ctx = ScallopContext() # Construct the program ctx.add_relation("edge", (int, int)) ctx.add_facts("edge", [(0, 1), (1, 2), (2, 3)]) ctx.add_rule("path(a, c) = edge(a, c)") ctx.add_rule("path(a, c) = edge(a, b), path(b, c)") # Run the program ctx.run() # Inspect the result paths = ctx.relation("path") for (s, t) in paths: print(f"elem: ({s}, {t})") ``` -------------------------------- ### Scallop $exp Function for Exponential Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/foreign_functions.md Calculates the exponential function \(e^x\). Supports floating-point types. Example: `$exp(0.0)` returns `1.0`. ```Scallop $exp(x: T) -> T Description: Exponential function \(e^x\) Example: $exp(0.0) => 1.0 ``` -------------------------------- ### Scallop: Dynamic Entity Creation with Lists Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/adt_and_entity.md Demonstrates dynamic entity creation in Scallop using the 'new' keyword. This example defines a List type, pretty-printing functions, and shows how to create a new list by prepending an element to an input list, followed by queries to verify the results. ```scl type List = Cons(i32, List) | Nil() rel to_string_2(l, "]") = case l is Nil() rel to_string_2(l, $format("{}]", i)) = case l is Cons(i, Nil()) rel to_string_2(l, $format("{}, {}", i, ts)) = case l is Cons(i, tl) and case tl is Cons(_, _) and to_string_2(tl, ts) rel to_string(l, $format("[{}", tl)) = to_string_2(l, tl) ``` ```scl type input_list(List) rel result_list(new Cons(1, l)) = input_list(l) ``` ```scl const MY_INPUT_LIST = Cons(2, Cons(3, Nil())) rel input_list(MY_INPUT_LIST) ``` ```scl rel input_list_str(s) = to_string(MY_INPUT_LIST, s) rel result_list_str(s) = result_list(l) and to_string(l, s) query input_list_str // [2, 3] query result_list_str // [1, 2, 3] ``` -------------------------------- ### Define Scallop Query Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/reference_guide.md Specifies a query to be executed against the Scallop knowledge base. Queries are used to retrieve information or test hypotheses. ```scl query path ``` -------------------------------- ### Scallop Rule with Negation Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/reference_guide.md Defines a rule using negation to specify conditions where a certain property does not hold, such as finding individuals with no children. ```scl rel has_no_child(p) = person(p) and not father(p, _) and not mother(p, _) ``` -------------------------------- ### ScallopContext Cloning Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/scallopy/context.md Demonstrates how to create a deep copy of an existing Scallop context. The cloned context will contain all program logic, configurations, and provenance information from the original. ```python new_ctx = ctx.clone() ``` -------------------------------- ### Debug Top-K Proofs in Forward Mode Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/scallopy/debug_proofs.md Shows how to set up and use a Scallop Module for debugging in forward mode. This involves configuring the module with debugging provenance and providing batched input facts, each with its associated fact ID. The output includes both the result tensor and detailed proof structures. ```python import scallopy import torch # Define a Scallop Module for debugging in forward mode sum_2_module = 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] # Maps output tuple elements to indices ) # Prepare batched input facts for forward mode debugging # Each fact is structured as ((probability_tensor, fact_id), data_tuple) # Fact IDs must be contiguous and start from 1. # Example for Datapoint 1: # Digit A: Fact ID 1 (prob 0.1), Fact ID 2 (prob 0.9) # Digit B: Fact ID 3 (prob 0.9), Fact ID 4 (prob 0.1) digit_a_input = [ [((torch.tensor(0.1), 1), (1,)), ((torch.tensor(0.9), 2), (2,))], # Datapoint 1 # ... other datapoints ] digit_b_input = [ [((torch.tensor(0.9), 3), (1,)), ((torch.tensor(0.1), 4), (2,))], # Datapoint 1 # ... other datapoints ] # Invoke the debug module # The output is a tuple: (result_tensor, proofs) (result_tensor, proofs) = sum_2_module(digit_a=digit_a_input, digit_b=digit_b_input) # result_tensor will be similar to non-debug output # result_tensor = torch.tensor([ # [0.09, 0.8119, 0.09], # Datapoint 1 # # ... # ]) # proofs structure: Batch -> Datapoint Results -> Proofs -> Proof -> Literal # proofs = [ # [ # Datapoint 1 # [ # Proofs of (2,) # [ (True, 1), (True, 3) ], # Proof: 1 + 1 (using fact IDs 1 and 3) # ], # [ # Proofs of (3,) # [ (True, 1), (True, 4) ], # Proof: 1 + 2 (using fact IDs 1 and 4) # [ (True, 2), (True, 3) ], # Proof: 2 + 1 (using fact IDs 2 and 3) # ], # [ # Proofs of (4,) # [ (True, 2), (True, 4) ], # Proof: 2 + 2 (using fact IDs 2 and 4) # ] # ], # # ... # ] # Each Literal is Tuple[bool, int] (positivity, fact_id) ``` -------------------------------- ### Scallop Rule with Disjunctive Head Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/reference_guide.md Defines a rule where the head can be one of multiple possible assignments, enabling more complex logical derivations. ```scl rel { assign(v, false); assign(v, true) } = variable(v) ``` -------------------------------- ### Define Scallop Relation Type Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/reference_guide.md Declares the schema for a relation, specifying the names and types of its arguments. This defines the structure for facts and rules. ```scl type edge(x: i32, y: i32) ``` -------------------------------- ### Scallop Program Output Example Source: https://github.com/scallop-lang/scallop/blob/master/experiments/hwf/readme.md Shows a sample output from a Scallop program, likely representing probabilistic results for a hand-written formula evaluation. The output includes probabilities associated with different evaluated values. ```scallop result: { 0.063::(0.125), 0.020870000000000003::(0.5), 0.14400000000000004::(2), 0.504::(8), 0.028::(32) } ``` -------------------------------- ### Declare Set of Integers Source: https://github.com/scallop-lang/scallop/blob/master/doc/src/language/relation.md Declares a relation containing a set of integer values. This is a simple example of a unary relation holding multiple distinct values. ```scl rel possible_digit = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} ``` -------------------------------- ### Integrate Scallop Core with Rust Source: https://github.com/scallop-lang/scallop/blob/master/core/readme.md Demonstrates integrating the Scallop core runtime into a Rust application. It uses the `scallop_core::integrate::interpret_string` function to execute a Scallop program defined as a string, including relation definitions and a query. ```rust fn main() { scallop_core::integrate::interpret_string(r#"\n rel edge = {(0, 1), (1, 2), (2, 3)}\n rel path(a, c) = edge(a, c) \/ path(a, b) /\ edge(b, c)\n query path(2, _)\n "#); } ```