neuralogic.core package

Subpackages

Submodules

neuralogic.core.enums module

class Grounder(value)[source]

Bases: Enum

BUP = 'BUP'
GRINGO = 'GRINGO'

neuralogic.core.model module

class Model(*, model_file: str | None = None)[source]

Bases: NeuralModule

Model is a collection of rules and relations that define the structure of the neural model.

add_module(module: Module) None[source]

Expands the module into rules and adds them into the model.

Parameters:

module (Module) – The module to expand and add.

add_rule(rule: BaseRelation | WeightedRelation | Rule | PredicateMetadata) None[source]

Adds one rule to the model.

Parameters:

rule (ModelEntries) – The rule to add.

add_rules(rules: list[BaseRelation | WeightedRelation | Rule | PredicateMetadata]) None[source]

Adds multiple rules to the model.

Parameters:

rules (list[ModelEntries]) – The rules to add.

build(settings: Settings | None = None, torch: bool = False) Model[source]

Builds the model into a neural model.

Parameters:
  • settings (Settings, optional) – The settings for building. Default: None.

  • torch (bool) – Whether to use PyTorch backend. Default: False.

Returns:

The built model (self).

Return type:

Model

clone() Model[source]
derivable_queries(example: list[BaseRelation | Rule] | None = None) list[BaseRelation] | dict[source]

Returns all derivable queries for the provided example.

Parameters:

example (list[BaseRelation | Rule], optional) – The example to derive queries from. Default: None.

Returns:

The list of derivable queries.

Return type:

list[BaseRelation] | dict

load(path: str | Path) None[source]

Load model weights from a file saved by save().

The model must already be built with the same architecture that produced the saved file.

Parameters:

path (str | Path) – Path to the saved file.

q(query: BaseRelation, examples: list[BaseRelation | Rule] | None = None) list[dict] | dict[source]
query(query: BaseRelation, examples: list[BaseRelation | Rule] | None = None) list[dict] | dict[source]

Performs a query on the model with the provided examples.

Parameters:
  • query (BaseRelation) – The query to perform.

  • examples (list[BaseRelation | Rule], optional) – The examples to use for the query. Default: None.

Returns:

The list of query results (substitutions).

Return type:

list[dict] | dict

remove_duplicates() None[source]

Removes duplicates from the model.

save(path: str | Path) None[source]

Save the model weights to a file.

The model must be built before calling save(). To restore, rebuild the same architecture and call load().

Parameters:

path (str | Path) – Path to the output file (.pkl extension recommended).

neuralogic.core.neural_module module

class NeuralModule[source]

Bases: object

NeuralModule is the base class for all neural models. It provides methods for grounding, building, training, and testing.

build_dataset(dataset: BaseDataset | GroundedDataset, *, batch_size: int = 1, learnable_facts: bool = False, progress: bool = False) BuiltDataset[source]

Builds (ground and neuralize) the provided dataset.

Parameters:
  • dataset (Union[BaseDataset, GroundedDataset]) – The dataset to build.

  • batch_size (int) – The batch size. Default: 1.

  • learnable_facts (bool) – Whether facts are learnable. Default: False.

  • progress (bool) – Whether to show progress. Default: False.

Returns:

The built dataset.

Return type:

BuiltDataset

draw(filename: str | None = None, show=True, img_type='png', value_detail: int = 0, graphviz_path: str | None = None, *args, **kwargs)[source]
forward(dataset)[source]
ground(dataset: BaseDataset, *, batch_size: int = 1, learnable_facts: bool = False, progress: bool = False) GroundedDataset[source]

Grounds the provided dataset using the model’s settings.

Parameters:
  • dataset (BaseDataset) – The dataset to ground.

  • batch_size (int) – The batch size for grounding. Default: 1.

  • learnable_facts (bool) – Whether facts are learnable. Default: False.

  • progress (bool) – Whether to show progress. Default: False.

Returns:

The grounded dataset.

Return type:

GroundedDataset

load_state_dict(state_dict: dict)[source]
parameters() dict[source]

Returns the model parameters.

Returns:

The model parameters.

Return type:

dict

reset_parameters()[source]
state_dict() dict[source]

Returns the state dictionary of the model.

Returns:

The state dictionary (weights and weight names).

Return type:

dict

tensor_parameters()[source]
test(dataset) list | float[source]

Tests the model on the provided dataset.

Parameters:

dataset (Any) – The dataset to test on.

Returns:

The test results (outputs).

Return type:

Union[Value, List[Value]]

train(dataset, epochs: int = 1) list | float[source]

Trains the model on the provided dataset.

Parameters:
  • dataset (Any) – The dataset to train on. Can be a Dataset, GroundedDataset, BuiltDataset, or a list of samples.

  • epochs (int) – The number of epochs to train. Default: 1.

Returns:

The training results (target, output, error).

Return type:

Union[Tuple[Value, Value, Value], List[Tuple[Value, Value, Value]]]

neuralogic.core.sources module

class Sources(sources: Any)[source]

Bases: object

Represents the logic sources (models, examples, queries) for the NeuraLogic backend.

static from_args(args: list[str], settings: SettingsProxy) Sources[source]

Creates Sources from command line arguments and settings.

Parameters:
  • args (List[str]) – The command line arguments.

  • settings (SettingsProxy) – The settings proxy.

Returns:

The created Sources object.

Return type:

Sources

static from_settings(settings: SettingsProxy) Sources[source]

Creates Sources from the provided settings.

Parameters:

settings (SettingsProxy) – The settings proxy.

Returns:

The created Sources object.

Return type:

Sources

to_json() str[source]

Exports the sources to a JSON string.

Returns:

The JSON representation of the sources.

Return type:

str

Module contents

class Aggregation[source]

Bases: object

Collection of aggregation functions. Aggregation functions are used to aggregate multiple inputs, typically from different groundings of the same rule.

AVG: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
CONCAT: ConcatAggregation = <neuralogic.core.constructs.function.concat.ConcatAggregation object>
COUNT: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
MAX: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
MIN: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
SOFTMAX: SoftmaxAggregation = <neuralogic.core.constructs.function.softmax.SoftmaxAggregation object>
SUM: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
class BuiltDataset(samples: list[NeuralSample], batch_size: int)[source]

Bases: object

BuiltDataset represents an already built dataset - that is, a dataset that has been grounded and neuralized.

class Combination[source]

Bases: object

Collection of combination functions. Combination functions are used to combine multiple inputs into a single output, often as part of a rule body or for combining multiple rules.

AVG: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
CONCAT: ConcatCombination = <neuralogic.core.constructs.function.concat.ConcatCombination object>
COSSIM: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
COUNT: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
CROSSSUM: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
ELPRODUCT: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
MAX: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
MIN: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
PRODUCT: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
SOFTMAX: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
SPARSEMAX: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
SUM: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
class F[source]

Bases: object

Utility class providing a flat namespace for common functions. It includes transformation, combination, and aggregation functions.

avg: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
avg_agg: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
concat: ConcatCombination = <neuralogic.core.constructs.function.concat.ConcatCombination object>
concat_agg: ConcatAggregation = <neuralogic.core.constructs.function.concat.ConcatAggregation object>
cossim: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
count: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
count_agg: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
crossum: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
elproduct: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
exp: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
identity: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
inverse: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
leaky_relu: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
log: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
lukasiewicz: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
max: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
max_agg: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
min: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
min_agg: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
norm: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
product: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
relu: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
reshape: Reshape = <neuralogic.core.constructs.function.reshape.Reshape object>
reverse: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
sigmoid: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
signum: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
slice: Slice = <neuralogic.core.constructs.function.slice.Slice object>
softmax: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
softmax_agg: SoftmaxAggregation = <neuralogic.core.constructs.function.softmax.SoftmaxAggregation object>
softmax_comb: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
sparsemax: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
sparsemax_comb: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
sqrt: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
sum: CombinationFunction = <neuralogic.core.constructs.function.function.CombinationFunction object>
sum_agg: AggregationFunction = <neuralogic.core.constructs.function.function.AggregationFunction object>
tanh: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
transp: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
class GroundedDataset(groundings, builder: Builder)[source]

Bases: object

GroundedDataset represents grounded examples that are not neuralized yet.

neuralize(*, batch_size: int = 1, progress: bool = False) BuiltDataset[source]
class Grounder(value)[source]

Bases: Enum

BUP = 'BUP'
GRINGO = 'GRINGO'
class Metadata(learnable: bool | None = None, transformation: TransformationFunction | CombinationFunction | None = None, combination: CombinationFunction | None = None, aggregation: AggregationFunction | None = None, duplicate_grounding: bool | None = None)[source]

Bases: object

Represents metadata for a logic construct (e.g., rule, predicate).

Metadata can specify properties like learnability, transformation functions, aggregation functions, and combination functions.

aggregation
combination
combine(other: Metadata) Metadata[source]

Combines this metadata with another Metadata object. Values from the other object take precedence.

Parameters:

other (Metadata) – The other Metadata object to combine with.

Returns:

A new combined Metadata object.

Return type:

Metadata

copy() Metadata[source]

Returns a shallow copy of the metadata.

Returns:

The copy of the metadata.

Return type:

Metadata

duplicate_grounding
static from_iterable(iterable: Iterable[Any]) Metadata[source]

Creates a Metadata object from an iterable of functions or values.

Parameters:

iterable (Iterable) – The iterable containing metadata entries.

Returns:

The created Metadata object.

Return type:

Metadata

learnable
transformation
class Model(*, model_file: str | None = None)[source]

Bases: NeuralModule

Model is a collection of rules and relations that define the structure of the neural model.

add_module(module: Module) None[source]

Expands the module into rules and adds them into the model.

Parameters:

module (Module) – The module to expand and add.

add_rule(rule: BaseRelation | WeightedRelation | Rule | PredicateMetadata) None[source]

Adds one rule to the model.

Parameters:

rule (ModelEntries) – The rule to add.

add_rules(rules: list[BaseRelation | WeightedRelation | Rule | PredicateMetadata]) None[source]

Adds multiple rules to the model.

Parameters:

rules (list[ModelEntries]) – The rules to add.

build(settings: Settings | None = None, torch: bool = False) Model[source]

Builds the model into a neural model.

Parameters:
  • settings (Settings, optional) – The settings for building. Default: None.

  • torch (bool) – Whether to use PyTorch backend. Default: False.

Returns:

The built model (self).

Return type:

Model

clone() Model[source]
derivable_queries(example: list[BaseRelation | Rule] | None = None) list[BaseRelation] | dict[source]

Returns all derivable queries for the provided example.

Parameters:

example (list[BaseRelation | Rule], optional) – The example to derive queries from. Default: None.

Returns:

The list of derivable queries.

Return type:

list[BaseRelation] | dict

load(path: str | Path) None[source]

Load model weights from a file saved by save().

The model must already be built with the same architecture that produced the saved file.

Parameters:

path (str | Path) – Path to the saved file.

q(query: BaseRelation, examples: list[BaseRelation | Rule] | None = None) list[dict] | dict[source]
query(query: BaseRelation, examples: list[BaseRelation | Rule] | None = None) list[dict] | dict[source]

Performs a query on the model with the provided examples.

Parameters:
  • query (BaseRelation) – The query to perform.

  • examples (list[BaseRelation | Rule], optional) – The examples to use for the query. Default: None.

Returns:

The list of query results (substitutions).

Return type:

list[dict] | dict

remove_duplicates() None[source]

Removes duplicates from the model.

save(path: str | Path) None[source]

Save the model weights to a file.

The model must be built before calling save(). To restore, rebuild the same architecture and call load().

Parameters:

path (str | Path) – Path to the output file (.pkl extension recommended).

class Rule(head: BaseRelation, body: RuleBody | Iterable[BodyItem] | BodyItem)[source]

Bases: object

Represents a rule in the model, consisting of a head and a body.

body: list[BodyItem] | FContainer
head
metadata: Metadata | None
to_str(_: bool = False) str[source]
class RuleBody(lit1: BaseRelation, lit2: BaseRelation)[source]

Bases: object

Represents the body of a rule, which is a collection of literals.

literals: list['BaseRelation' | FContainer]
metadata: Metadata | None
class Settings(*, optimizer: Optimizer = <neuralogic.nn.optim.adam.Adam object>, error_function: ErrorFunction = <neuralogic.nn.loss.MSE object>, initializer: Initializer = <neuralogic.nn.init.Uniform object>, iso_value_compression: bool = True, chain_pruning: bool = True, prune_only_identities: bool = False, grounder: Grounder = Grounder.BUP)[source]

Bases: object

property chain_pruning: bool
create_disconnected_proxy() SettingsProxy[source]
create_proxy() SettingsProxy[source]
property error_function: ErrorFunction
property grounder: Grounder
property initializer: Initializer
property iso_value_compression: bool
property optimizer: Optimizer
property prune_only_identities: bool
class SettingsProxy(*, optimizer: Optimizer, error_function: ErrorFunction, initializer: Initializer, iso_value_compression: bool, chain_pruning: bool, prune_only_identities: bool, grounder: Grounder)[source]

Bases: object

Proxy class for the Java Settings object.

It provides a Pythonic interface to configure various parameters of the NeuraLogic backend, such as optimizers, initializers, error functions, and grounding algorithms.

property chain_pruning: bool

Whether to use chain pruning (reducing redundant chains of operations).

property debug_exporting: bool
property default_fact_value: float
property error_function: Any

The error function used for training.

get_aggregation_function(aggregation: Aggregation) Any[source]
get_combination_function(combination: Combination) Any[source]

Returns the Java combination function for the given Python enum value.

Parameters:

combination (Combination) – The combination function enum value.

Returns:

The Java combination function object.

Return type:

Any

get_transformation_function(transformation: Transformation) Any[source]
property grounder: Any

The grounding algorithm to use.

property initializer: Any

The weight initializer used for model parameters.

property initializer_const: float
property initializer_uniform_scale: float
property iso_value_compression: bool

Whether to use iso-value compression.

property optimizer: Optimizer

The optimizer used for training.

property prune_only_identities: bool
property relation_combination: CombinationFunction
property relation_transformation: TransformationFunction
property rule_aggregation: AggregationFunction
property rule_combination: CombinationFunction
property rule_transformation: TransformationFunction
to_json() str[source]

Exports the settings to a JSON string.

Returns:

The JSON representation of the settings.

Return type:

str

class Transformation[source]

Bases: object

Collection of transformation functions. Transformation functions are applied element-wise or as join operations (e.g., Softmax, Transpose).

EXP: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
IDENTITY: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
INVERSE: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
LEAKY_RELU: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
LOG: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
LUKASIEWICZ: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
NORM: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
RELU: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
RESHAPE: Reshape = <neuralogic.core.constructs.function.reshape.Reshape object>
REVERSE: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
SIGMOID: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
SIGNUM: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
SLICE: Slice = <neuralogic.core.constructs.function.slice.Slice object>
SOFTMAX: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
SPARSEMAX: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
SQRT: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
TANH: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>
TRANSP: TransformationFunction = <neuralogic.core.constructs.function.function.TransformationFunction object>