soft.computing package

Subpackages

Submodules

soft.computing.core module

Implements core mechanisms used for KnowledgeBase - a significant component to PySoft.

class soft.computing.core.Core

Bases: object

Provides many essential low-level operations and overloads necessary for the KnowledgeBase class, which inherits from this class.

add_parent_relation(attr_type, args) list

Add a relation (attr_type) that references the provided items (args).

Parameters:
  • attr_type – The type of the relation, this can be a callable function as well

  • (e.g.

  • AlgebraicProduct).

  • args – A collection of lists, where each element in the collection (a list),

  • graph. (stores the 'type' of the vertex in the)

Returns:

A list of vertices that represent the parent relationships.

add_weighted_edges(edges) None

Add edges to the KnowledgeBase.graph, with a weight that is equal to its frequency (in the argument, ‘edges’).

Parameters:

edges – A list of edges to be added.

Returns:

None

create_compound_edges(args, target_vertices) list

A helper method to self.add_parent_relation

Parameters:
  • args – A collection of lists, where each element in the collection (a list),

  • graph. (stores the 'type' of the vertex in the)

  • target_vertices – The vertices that have been created that represent

  • relationships. (the parent)

Returns:

A list of edges to be added for the given relation (type) with respect to the given items (args).

create_compound_edges_helper(source, edges, targets)

A helper method for the create_compound_edges method that creates edges between the ‘source’ and ‘targets’, and appends them to the list ‘edges’. If the given ‘source’ is not an igraph.Vertex, attempt to look up the vertex, and then iterate over the ‘targets’. If a ‘target’ at any moment is not an igraph.Vertex, attempt to look up the vertex.

Parameters:
  • source

  • edges

  • targets

Returns:

A list of edges, where each edge is a 2-tuple in the form of (source, target)

export_visual(filename, file_format='png', engine='dot') None

Creates and exports a visual of the graph using the format (file_format) and the layout (engine), as specified.

Parameters:
  • filename – The name of the file to save.

  • file_format – The format of the file to save (e.g., ‘png’, ‘svg’).

  • engine – The method to use when creating the layout of the graph (e.g., ‘twopi’, ‘sfdp’).

Returns:

None

get_granules(is_input: bool) VertexSeq

Get the ‘granules’ of information; at the time of writing (April 22, 2023), these are vertices that have a ‘type’ attribute which is an instance of ContinuousFuzzySet.

Now, September 14, 2023, ‘granules’ are vertices that have a ‘type’ attribute that inherits from torch.nn.Module; this is because inheritance does not work for some classes/objects after KnowledgeBase has been saved or loaded. However, recognizing inheritance of torch.nn.Module remains intact.

Parameters:
  • is_input – If ‘True’, then select all input granules; if ‘False’, then select all

  • granules. (output)

Returns:

A VertexSeq of granules.

intra_dimensions(is_input: bool) ndarray

Calculate the dimensionality within dimensions. For example, calculate the number of linguistic terms available for the first input variable, and the second input variable, and so on. The result is a calculation for each variable, stored as a 1-dimensional Numpy array.

Parameters:
  • is_input – A boolean; if True, then calculate the dimensionality within the input

  • dimensions

  • else

  • dimensions. (calculate the dimensionality within the output)

Returns:

A 1-dimensional Numpy array where each element is a count of the possible terms for their respective dimension (e.g., the 0th element may say 3, meaning that there are 3 possible terms/sets within the first dimension).

set_granules(nodes, source=None, is_input: None | bool = None) None

Adds the given nodes to the graph to a layer, and increments the saved indexed layer.

Parameters:
  • nodes – The nodes to be added.

  • source – The source of the nodes.

  • is_input – Whether this vertex should be considered ‘input’ (e.g., input granules or

  • None (output granules). If)

  • True (then the 'input' attribute is not set. If)

  • the (then)

  • False ('input' attribute is set to True. If)

  • False. (then the 'input' attribute is set to)

  • None. (Default is)

Returns:

None

property universe: frozenset

Get the universe of discourse.

Returns:

A frozenset of elements in the universe of discourse.

var_dimensions(is_input: bool) int

Calculate the dimensionality of the variable space.

Parameters:
  • is_input – A boolean; if True, then calculate the dimensionality within the input

  • dimensions

  • else

  • dimensions. (calculate the dimensionality within the output)

Returns:

An integer.

soft.computing.hypercube module

Implements various functions that organize content in the KnowledgeBase, such as stacking the discovered ‘granules’ of information in a computationally efficient structure.

soft.computing.hypercube.add_stacked_granule(knowledge_base: KnowledgeBase) None

Constructs the granules for this mapping in a format that will be compatible with the expected functionality. Also, modifies a Knowledgebase such that the condensed (i.e., stacked) version of the granules is readily available.

Parameters:

knowledge_base – The KnowledgeBase object that contains the granules for this mapping.

Returns:

A single membership function that combines all the granules for faster computation; if there is an uneven number of granules in each dimension, then the values (e.g., centers, widths) have been padded with torch.nan (if not trainable) or 0 for centers and -1 for widths (if trainable).

soft.computing.hypercube.add_stacked_granule_helper(knowledge_base: KnowledgeBase, is_input: bool) Vertex | None

A helper method for the add_stacked_granule function. Connects the efficient stacked granule representation vertex to its origin vertices.

Parameters:
  • knowledge_base – The KnowledgeBase object that contains the granules for this mapping.

  • is_input – A boolean that indicates whether the granules are inputs or outputs.

Returns:

The vertex that represents the stacked granule representation, or None if there are no granules.

soft.computing.knowledge module

Implements the vital KnowledgeBase class.

class soft.computing.knowledge.KnowledgeBase(config=None, **attr)

Bases: FuzzyGraph, RoughDecisions

The KnowledgeBase class is a significant component to this Soft Computing library.

As the name suggests, it implements the concept of a Knowledge Base in the field of Artificial Intelligence.

Its implementation is abstract and generic, using a graph structure (i.e., self.graph) to store facts, data, functions, implications, relations, etc. in the form of vertices or edges, whichever is most appropriate.

Typically, facts, data, and functions are vertices, whereas implications and relations are implemented with edges in the graph structure.

The distinction between what each vertex represents is made by the vertex’s attributes, such as ‘type’.

The same can be said for edges.

For example, fuzzy sets may exist in the KnowledgeBase’s graph (i.e., self.graph) as vertices, and how those fuzzy sets are used is represented with an edge. At the time of writing (4/14/2023), these fuzzy sets are connected to another vertex representing the t-norm in which they are aggregated together (e.g., hot weather and cold soup) to offer flexibility in the choice of t-norm. In other words, it is possible to construct a KnowledgeBase where each fuzzy logic rule has its own independent t-norm definition. Then, this vertex representing the compound relation between the fuzzy sets can be interpreted as an antecedent, if a directed edge is connected from this compound relation to another compound relation such that (source_vertex, target_vertex) represent antecedents and consequences, respectively.

Naturally, this allows for fuzzy sets to be dynamically added or removed from fuzzy rules, or fuzzy rules to be dynamically added or removed. Allowing for the process of self-organizing with various methods (e.g., genetic algorithms, unsupervised learning, rough set theory) to be somewhat easily incorporated.

attributes(element: int | str) dict

Fetch the attributes and their values for the given element.

Parameters:

element – An element or object in the universe of discourse.

Returns:

A dictionary where each key is the attribute type (or relation) and the value associated with the key is the value of that attribute (or unique auto-generated id for relations).

static convert_str_attribute(attribute_value: str, file_path, idx, str_to_callables, unprocessed_values)

Convert a string attribute to a callable attribute.

static execute_module(file: str, file_with_prefix: str, root: str) Tuple[ModuleType, ModuleSpec]

Execute a Python module so that we can create callables.

Parameters:
  • file – The file name.

  • file_with_prefix – The file name with the prefix, such as the directory.

  • root – The root directory.

Returns:

The module and the spec.

static get_callables_from_files(files, prefix, root, str_to_callables) None

Iterates through the files in the project directory and adds the callables to the str_to_callables dictionary.

Parameters:
  • files

  • prefix

  • root

  • str_to_callables

Returns:

None

static load(file_path: Path) KnowledgeBase

Given a path to a directory, load the saved KnowledgeBase object at that location.

Parameters:

file_path – The path to the directory that the KnowledgeBase was saved at.

Returns:

KnowledgeBase

static load_graph_edges(path_to_edges: Path) DataFrame

Load the graph’s edges from a csv file.

Parameters:

path_to_edges – The path to the csv file containing the graph’s edges.

Returns:

The graph’s edges as a pandas DataFrame.

static parse_vertex_attributes(file_path: Path, vertices_df: DataFrame) None

Parse the vertex attributes from the vertices_df and modify them in-place.

Parameters:
  • file_path – The path to the directory that the KnowledgeBase was saved at.

  • vertices_df – The DataFrame containing the vertex attributes.

Returns:

None

static recognized_callables() dict

Crawl through the library and find all possible Python scripts. Then, collect all the possible callables such as classes or functions. This is used to convert the string representations stored in the vertices’ Pandas DataFrame back into a recognizable format, as many operations require immediate calling of vertices’ attributes.

Returns:

A dictionary that maps string representations of Classes or functions to their real callable reference/format.

remove(relation: str) Set[frozenset]

Given a relation, find its corresponding edges and delete its vertices.

Parameters:

relation – A relation in the KnowledgeBase.

Returns:

The edges that were deleted.

save(file_path: Path) Path

Save this Knowledgebase object for later use.

Parameters:

file_path – The path to the directory that this KnowledgeBase should be saved at.

Returns:

The path to the directory that the KnowledgeBase was saved at.

save_granules(new_file_path: Path, class_type: Any, extension: str) None

Save the granules to the given path.

Parameters:
  • new_file_path – The path to the directory that the granules should be saved at.

  • class_type – The type of the granules.

  • extension – The file extension to save the granules as.

Returns:

None

soft.computing.knowledge.get_graph_paths(path_to_graph: Path) Tuple[Path, Path, Path]

Create the paths to the subdirectories necessary to save the KnowledgeBase graph.

Parameters:

path_to_graph – The current path to the graph folder.

Returns:

The path to the network, the path to the vertices, the path to the edges

soft.computing.knowledge.make_subdirectory(file_path: Path, new_subdirectory: str) Path

Given a file path, create a new subdirectory if it does not already exist within it.

Parameters:
  • file_path – The file path.

  • new_subdirectory – The name of the subdirectory to create,

  • file_path. (if it does not already exist in)

Returns:

The file path with the new subdirectory concatenated to it.

soft.computing.organize module

Implements functions and classes responsible for the design of soft computing solutions, such as the SelfOrganize class.

class soft.computing.organize.SelfOrganize(config: Config, **attr)

Bases: KnowledgeBase

The SelfOrganize class facilitates the convenient design of self-organizing solutions by adding callable function references to a KnowledgeBase graph as vertices, and using the edges that connect the vertices (i.e., functions) to determine the flow of data/information from function to function.

add_data(data: SupervisedDataset | Dataset | Tensor | Module | list | Config, name: str) None

Add the input data as a vertex in the SelfOrganize graph. This is required if data is to be used during the self-organizing procedure.

Parameters:
  • data – PyTorch DataLoader, PyTorch tensor object, PyTorch Module, list or configuration settings.

  • name – The name of the data, such as ‘input’; some pre-existing blueprints may expect the name to be ‘input’.

Returns:

None

add_functions(functions: callable | Iterable[callable]) None

A function is a callable and threadable object. Add the functions that should be permitted for use by the SelfOrganize.start() method.

Parameters:

functions – A list of function references.

Returns:

None

check_or_find_functions(functions: List[str | callable] | None = None) List[str | callable] | None

Check if the functions are valid, and if not, find the functions that have been linked to the SelfOrganize graph.

Parameters:

functions – A list of function references; default is None and is appropriate for use if there are no specific functions to start from (i.e., keep functions=None if starting from the beginning of a self-organizing process).

Returns:

A list of function references.

find_vertex_output_and_assign_to_kwarg(full_arg_spec: FullArgSpec, kwargs: Dict[str, Any], source_vertex: Vertex, target_vertex: Vertex) None

Given a source vertex and a target vertex, retrieve the output located at the source vertex and assign it to the correct edge that feeds into the target vertex, such that it matches the correct keyword argument. Modifies the argument ‘kwargs’ in-place.

Parameters:
  • full_arg_spec – The full argument specification.

  • kwargs – The keyword arguments, stored as a dictionary.

  • source_vertex – The source vertex.

  • target_vertex – The target vertex.

Returns:

None

get_keyword_arguments(function: callable, predecessors_vertices: VertexSeq, target_vertex: Vertex) Dict[str, Any]

Given a function, predecessors (in the form of igraph.VertexSeq) and a target_vertex, collect all the output from the predecessors_vertices, and correctly assign them to the function’s keyword arguments; this is done according to how the edges between predecessors_vertices and target_vertex specify their ordering, so the correct outputs of predecessors_vertices are assigned to the correct arguments.

Parameters:
  • function – The function to inspect and retrieve the arguments of.

  • predecessors_vertices

  • target_vertex

Returns:

A dictionary of keyword arguments, where the keys are the names of the arguments, and the values are the outputs of the predecessors_vertices.

Links callable objects together in the SelfOrganize’s KnowledgeBase graph if they exist as vertices.

This allows the transfer of inputs and outputs to easily occur later on.

Parameters:
  • edges – An iterable collection called edges, where

  • that (each element in the collection is a 3-tuple such)

  • form (it follows the)

  • However

  • 'target' (this method expects 'source' and)

  • reference. (to be referencing a callable function)

  • the (The arg_order in a 3-tuple for an edge resolves)

  • expects (following dilemma; let's say Wang-Mendel)

  • it (CLIP and ECM to feed into)

  • arguments. (and expects 2)

  • arg_order (Which output from which function goes where? The)

  • order. (resolves this by specifying this)

  • debug_mode – Whether to display the verbose output that builds the SelfOrganize graph.

Returns:

None

start(functions: List[str | callable] | Set[str | callable] | None = None) KnowledgeBase

Self-organize the KnowledgeBase with the functions that have been linked.

Parameters:
  • functions – A list (or set) of function references; default is None and is appropriate

  • (i.e. (for use if there are no specific functions to start from)

  • if (keep functions=None)

  • process). (starting from the beginning of a self-organizing)

Returns:

None

soft.computing.organize.expert_design(linguistic_variables: LinguisticVariables, rules: Set[Rule] | List[Rule], config: Config) KnowledgeBase

A convenient helper method for the expert-design procedure of a Knowledge Base. The linguistic variable’s inputs member contains the premises and the targets member contains the consequences.

Parameters:
  • linguistic_variables – The linguistic variables involved and their terms.

  • rules – The fuzzy logic rules.

  • config – The configuration object.

Returns:

A KnowledgeBase object, with the linguistic_variables (i.e., antecedents, consequents), and fuzzy logic rules added.

soft.computing.threads module

Implements the necessary threading logic for the soft.computing.organize.SelfOrganize class.

class soft.computing.threads.ComponentThread(function: callable, name: str | None = None, **kwargs)

Bases: Thread

This class contains the necessary logic to prepare a callable function for the SelfOrganize class. It allows for the callable function to be partially initialized with keyword arguments, assign a name to it, as well as saves the function’s output in self.output when it finishes.

join(timeout=None) None

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

run() None

The function that is executed in a new thread.

Returns:

None

Module contents