neuralogic package

Subpackages

Submodules

neuralogic.exceptions module

Exception hierarchy for PyNeuraLogic.

All library-raised exceptions inherit from NeuraLogicError so that callers can write a single except NeuraLogicError block instead of catching the generic Exception.

exception BackendError[source]

Bases: NeuraLogicError

Raised when the Java backend encounters an internal error.

exception ConfigurationError[source]

Bases: NeuraLogicError

Raised when settings, JVM, or environment configuration is invalid.

exception DatasetError[source]

Bases: NeuraLogicError

Raised when dataset preparation or grounding fails.

exception ModelError[source]

Bases: NeuraLogicError

Raised when the model definition or build process fails.

exception NeuraLogicError[source]

Bases: Exception

Base class for all errors raised by PyNeuraLogic.

neuralogic.setup module

get_default_graphviz_path() str | None[source]

Gets the default path to Graphviz.

Returns:

The Graphviz path or None if not set.

Return type:

Optional[str]

initial_seed() int[source]

Returns the initial/current random seed for a random number generator used in the backend.

Returns:

The initial random seed.

Return type:

int

initialize(debug_mode: bool = False, debug_port: int = 12999, is_debug_server: bool = True, debug_suspend: bool = True, *, seed: int | None = None, graphviz_path: str | None = None, max_memory_size: int | None = None, log_handler: LogHandler | None = None, jar_path: str | None = None, started_check: bool = True)[source]

Initialize the NeuraLogic backend. This function is called implicitly when needed and should be called manually only for debugging.

Parameters:
  • debug_mode (bool) – Enable/Disable JVM debug mode.

  • debug_port (int) – Port for the debugger to listen on. Default: 12999.

  • is_debug_server (bool) – Act like server and listen for the debugger. Default: True

  • debug_suspend (bool) – Wait until the debugger is connected. Default: True

  • seed (Optional[int]) – The seed for the random number generator.

  • graphviz_path (Optional[str]) – The Graphviz path

  • max_memory_size (Optional[int]) – The maximum memory size (in gigabytes)

  • log_handler (Optional[LogHandler]) – The handler for logging

  • jar_path (Optional[str]) – The path to NeuraLogic java backend

  • started_check (bool) – Whether to check if the NeuraLogic has been started. If true and it has been started - raise an Exception

is_initialized() bool[source]

Checks whether the NeuraLogic backend has been initialized.

Returns:

True if the backend is initialized, False otherwise.

Return type:

bool

manual_seed(seed: int)[source]

Sets the seed for a random number generator used in the backend to the passed seed.

Parameters:

seed (int) – The seed for the random number generator.

seed() int[source]

Sets the seed for a random number generator used in the backend to a random seed and returns the seed.

Returns:

The newly generated random seed.

Return type:

int

set_graphviz_path(path: str | None)[source]

Set the default path to Graphviz

Parameters:

path (Optional[str]) – The Graphviz path

set_jvm_options(options: List[str])[source]

Set the jvm options - by default ["-Xms1g"].

Parameters:

options (List[str]) – List of JVM options

set_jvm_path(path: str | None)[source]

Set the JVM path.

Parameters:

path (Optional[str]) – The JVM path

set_max_memory_size(size: int)[source]

Sets the maximum memory size that can be utilized by the backend (in gigabytes).

Parameters:

size (int) – The maximum memory size (in gigabytes).

shutdown()[source]

Shut down the NeuraLogic JVM backend.

After calling this, you must call initialize() again before using any NeuraLogic functionality. If the backend was never started, this is a no-op.

Note

JPype does not support restarting a JVM within the same process, so re-initialization may fail. For reliable restart, use a fresh process.

Module contents

exception BackendError[source]

Bases: NeuraLogicError

Raised when the Java backend encounters an internal error.

exception ConfigurationError[source]

Bases: NeuraLogicError

Raised when settings, JVM, or environment configuration is invalid.

exception DatasetError[source]

Bases: NeuraLogicError

Raised when dataset preparation or grounding fails.

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 LogHandler(output: Any, level: Level = Level.FINER, formatter: Formatter = Formatter.COLOR)[source]

Bases: object

LogHandler stores settings for a log handler.

formatter: Formatter = 'color'
level: Level = 400
output: Any
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).

exception ModelError[source]

Bases: NeuraLogicError

Raised when the model definition or build process fails.

exception NeuraLogicError[source]

Bases: Exception

Base class for all errors raised by PyNeuraLogic.

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
add_log_handler(handler: LogHandler) None[source]

Add logger handler for an insight into the java backend. Overrides the default logger to stdout.

Parameters:

handler (LogHandler) – The log handler to add.

get_default_graphviz_path() str | None[source]

Gets the default path to Graphviz.

Returns:

The Graphviz path or None if not set.

Return type:

Optional[str]

initial_seed() int[source]

Returns the initial/current random seed for a random number generator used in the backend.

Returns:

The initial random seed.

Return type:

int

initialize(debug_mode: bool = False, debug_port: int = 12999, is_debug_server: bool = True, debug_suspend: bool = True, *, seed: int | None = None, graphviz_path: str | None = None, max_memory_size: int | None = None, log_handler: LogHandler | None = None, jar_path: str | None = None, started_check: bool = True)[source]

Initialize the NeuraLogic backend. This function is called implicitly when needed and should be called manually only for debugging.

Parameters:
  • debug_mode (bool) – Enable/Disable JVM debug mode.

  • debug_port (int) – Port for the debugger to listen on. Default: 12999.

  • is_debug_server (bool) – Act like server and listen for the debugger. Default: True

  • debug_suspend (bool) – Wait until the debugger is connected. Default: True

  • seed (Optional[int]) – The seed for the random number generator.

  • graphviz_path (Optional[str]) – The Graphviz path

  • max_memory_size (Optional[int]) – The maximum memory size (in gigabytes)

  • log_handler (Optional[LogHandler]) – The handler for logging

  • jar_path (Optional[str]) – The path to NeuraLogic java backend

  • started_check (bool) – Whether to check if the NeuraLogic has been started. If true and it has been started - raise an Exception

is_initialized() bool[source]

Checks whether the NeuraLogic backend has been initialized.

Returns:

True if the backend is initialized, False otherwise.

Return type:

bool

manual_seed(seed: int)[source]

Sets the seed for a random number generator used in the backend to the passed seed.

Parameters:

seed (int) – The seed for the random number generator.

seed() int[source]

Sets the seed for a random number generator used in the backend to a random seed and returns the seed.

Returns:

The newly generated random seed.

Return type:

int

set_graphviz_path(path: str | None)[source]

Set the default path to Graphviz

Parameters:

path (Optional[str]) – The Graphviz path

set_jvm_options(options: List[str])[source]

Set the jvm options - by default ["-Xms1g"].

Parameters:

options (List[str]) – List of JVM options

set_jvm_path(path: str | None)[source]

Set the JVM path.

Parameters:

path (Optional[str]) – The JVM path

set_max_memory_size(size: int)[source]

Sets the maximum memory size that can be utilized by the backend (in gigabytes).

Parameters:

size (int) – The maximum memory size (in gigabytes).

shutdown()[source]

Shut down the NeuraLogic JVM backend.

After calling this, you must call initialize() again before using any NeuraLogic functionality. If the backend was never started, this is a no-op.

Note

JPype does not support restarting a JVM within the same process, so re-initialization may fail. For reliable restart, use a fresh process.