cinnamon package
Subpackages
Submodules
cinnamon.command_line module
- cinnamon.command_line.run()
- cinnamon.command_line.setup()
cinnamon.component module
- class cinnamon.component.Component
Bases:
objectA component defines any logic of a program, including data loading, data visualization, and model training.
- classmethod build_component(registration_key=None, name=None, namespace=None, tags=None, **build_args)
Syntactic sugar for building a
Componentfrom aRegistrationKeyin implicit format.- Parameters:
registration_key (Optional[cinnamon.registry.Registration]) – the
RegistrationKeyused to register theConfigurationclass.name (Optional[str]) – the
namefield ofRegistrationKeytags (cinnamon.configuration.Tags) – the
tagsfield ofRegistrationKeynamespace (Optional[str]) – the
namespacefield ofRegistrationKeybuild_args – additional custom component constructor args
- Return type:
C
- Returns:
A
Componentinstance- Raises:
InvalidConfigurationTypeException – if there’s a mismatch between the
Configurationclass usedduring registration and the type of the built Configuration instance using the registered –
constructor` method (see ConfigurationInfo arguments) –
NotBoundException – if the
Configurationis not bound to anyComponent.
- class cinnamon.component.RunnableComponent
Bases:
ComponentA Component that can be executed as standalone through command-line.
- run(config=None)
- Parameters:
config (
Optional[Configuration]) – optionally, the cinnamon configuration of theComponent.
Run interface to execute components.
cinnamon.configuration module
- class cinnamon.configuration.Configuration
Bases:
objectA Configuration specifies the parameters of a Component. Configurations store parameters and allow flow control via conditions.
- add(name, value=None, type_hint=None, description=None, tags=None, allowed_range=None, is_required=True, variants=None)
Adds a Parameter to the Configuration. By default, Parameter’s default conditions are added as well.
- Parameters:
name (
str) – unique identifier of the Parametervalue (
Optional[Any]) – value of the Parametertype_hint (
Optional[Type]) – the type hint annotation ofvaluedescription (
Optional[str]) – a string description of theParameterfor readability purposestags (
Optional[Set[str]]) – a set of string tags to mark theParameterinstance with metadata.allowed_range (
Optional[Callable[[Any],bool]]) – allowed range of values forvalueis_required (
bool) – if True,valuecannot be Nonevariants (
Optional[Sized]) – set of variant values ofvalueof interest
- Raises:
AlreadyExistingParameterException – if the provided name already exists in the Configuration instance.
- add_condition(condition, name, description=None, tags=None, is_pre_condition=False)
Adds a condition to be validated.
- Parameters:
condition (
Callable[[Configuration],bool]) – a function that receives as input the currentConfigurationinstance and returns a boolean.name (
str) – unique identifier.description (
Optional[str]) – a string description for readability purposes.tags (
Optional[Set[str]]) – a set of string tags to mark the condition with metadata.is_pre_condition (
bool) – True if the condition concerns configuration parameters before build (i.e., flat parameters)
- Raises:
AlreadyExistingParameterException – if the provided name already exists in the Configuration instance.
- property conditions: Dict[str, P]
- classmethod default()
Returns the default
Configurationinstance.- Return type:
TypeVar(C, bound= Configuration)- Returns:
Configurationinstance.
- delta_copy(**kwargs)
Gets a delta copy of current
Configuration, including conditions.- Return type:
TypeVar(C, bound= Configuration)- Returns:
A delta copy of current
Configuration.
- property dependencies: Dict[str, P]
- get(name, default=None)
- Return type:
Optional[TypeVar(P, bound= Param)]
- property has_variants: bool
- property params: Dict[str, P]
- pre_validate(strict=True)
Calls all pre-built conditions to assess the correctness of the current
Configuration.- Parameters:
strict (
bool) – if True, a failed validation process will raiseInvalidConfigurationException- Return type:
- Returns:
A
ValidationResultobject that stores the boolean result of the validation process along with an error message if the result isFalse.- Raises:
ValidationFailureException – if
strict = Trueand the validation process failed
- search_condition(conditions)
Performs a custom condition search by given conditions.
- Parameters:
conditions (
List[Callable[[Callable[[Configuration],bool]],bool]]) – list of callable filter functions- Return type:
List[Param]- Returns:
A dictionary with
Param.nameas keys andParamas values corresponding to conditions.
- search_condition_by_tag(tags, exact_match=True)
Searches for all
Paramthat match specified tags set.- Parameters:
tags (
Union[Set[str],None,str]) – a set of string tags to look forexact_match (
bool) – if True, only theParamwithParam.tagsthat exactly matchtagswill be returned
- Return type:
List[Param]- Returns:
A dictionary with
Param.nameas keys andParamas values
- search_param(conditions)
Performs a custom
Paramsearch by given conditions.- Parameters:
conditions (
List[Callable[[TypeVar(P, bound= Param)],bool]]) – list of callable filter functions- Return type:
List[Param]- Returns:
A dictionary with
Param.nameas keys andParamas values
- search_param_by_tag(tags, exact_match=True)
Searches for all
Paramthat match specified tags set.- Parameters:
tags (
Union[Set[str],None,str]) – a set of string tags to look forexact_match (
bool) – if True, only theParamwithParam.tagsthat exactly matchtagswill be returned
- Return type:
List[Param]- Returns:
A dictionary with
Param.nameas keys andParamas values
- show()
Displays
Configurationparameters.
- to_value_dict()
Returns all
Configurationparameters in key:value format. The method supports nesting so that dependencies parameters are retrieved iteratively.- Return type:
Dict[str,Any]- Returns:
JSON normalized dict where keys are parameters names and values are their corresponding values.
- validate(strict=True)
Calls all conditions to assess the correctness of the current
Configuration.- Parameters:
strict (
bool) – if True, a failed validation process will raiseInvalidConfigurationException- Return type:
- Returns:
A
ValidationResultobject that stores the boolean result of the validation process along with an error message if the result isFalse.- Raises:
ValidationFailureException – if
strict = Trueand the validation process failed
- property values: Dict[str, Any]
- property variants: Tuple[List[Dict[str, Any]], List[Dict[str, int]]]
Gets all possible
Configurationvariant combinations of currentConfigurationinstance based on specified variants.- Returns:
A List of all possible key:value dict combinations of parameters that have variants. index_combinations: A List of all possible key:index dict combinations of parameters that have variants. Indexes refer to variant index in variants list.
- Return type:
value_combinations
- class cinnamon.configuration.Param(name, value=None, type_hint=None, description=None, tags=None, allowed_range=None, is_required=True, variants=None)
Bases:
object- A generic attribute wrapper that allows:
Type annotations
Textual description metadata
Tags metadata for categorization and general-purpose retrieval
- __eq__(other)
Two
Paraminstances are equal iff they have the same name and value.- Parameters:
other (
type[TypeVar(P, bound= Param)]) – anotherParaminstance- Return type:
bool- Returns:
True if the two
Paraminstances are equal. False, otherwise.
- property is_dependency: bool
- long_repr()
- Return type:
str
- short_repr()
- Return type:
str
- exception cinnamon.configuration.ValidationFailureException(validation_result)
Bases:
Exception
cinnamon.registry module
- exception cinnamon.registry.AlreadyRegisteredException(registration_key)
Bases:
Exception
- class cinnamon.registry.ConfigurationInfo(config_class, constructor, component_class, build_recursively)
Bases:
objectUtility dataclass used for registration. Behind the curtains, the
Configurationclass is stored in the Registry via its correspondingConfigurationInfowrapper.- This wrapper contains:
config_class: the
Configurationclass type- constructor: the method for creating an instance from the specified
class_type. By default, the constructor is set to
Configuration.default()method.
- constructor: the method for creating an instance from the specified
component_class: the
Componentclass typebuild_recursively: whether the
Configurationor its boundComponentdependencies
should be built recursively or not.
-
build_recursively:
bool
-
config_class:
Type[Configuration]
-
constructor:
Callable[[],Configuration]
- exception cinnamon.registry.InvalidDirectoryException(directory)
Bases:
Exception
- exception cinnamon.registry.NamespaceNotFoundException(registration_key, namespaces)
Bases:
Exception
- exception cinnamon.registry.NotRegisteredException(registration_key)
Bases:
Exception
- class cinnamon.registry.RegistrationKey(name, namespace, tags=None, description=None, metadata=None, special_tags=None)
Bases:
objectCompound key used for registration.
-
ATTRIBUTE_SEPARATOR:
str= '--'
-
HIERARCHY_SEPARATOR:
str= '.'
-
KEY_VALUE_SEPARATOR:
str= '='
-
MAX_TAGS_PER_LINE:
int= 6
- property compound_tags
- classmethod from_string(string_format)
Parses a
RegistrationKeyinstance from its string format.- Parameters:
string_format (
str) – the string format of aRegistrationKeyinstance.- Return type:
- Returns:
The corresponding parsed
RegistrationKeyinstance
- from_tags_simplification(tags)
Builds a new
RegistrationKeyfrom current instance by removing provided tags.- Parameters:
tags (
Optional[Set[str]]) – a Tag set containing tags to remove- Returns:
A
RegistrationKeyinstance that is the same as the current instance but withtagsremoved.
- from_variant(variant_kwargs, variant_indexes=None)
- Return type:
- property hierarchy_tags
- match(key, tags)
- Return type:
bool
- classmethod parse(registration_key=None, name=None, namespace=None, tags=None)
Parses a given
RegistrationKeyinstance. If the givenregistration_keyis in its string format, it is converted toRegistrationKeyinstance- Parameters:
registration_key (
Union[RegistrationKey,str,None]) – aRegistrationKeyinstance in its class instance or string formatname (
Optional[str]) – thenamefield ofRegistrationKeynamespace (
Optional[str]) – thenamespacefield ofRegistrationKeytags (
Optional[Set[str]]) – thetagsfield ofRegistrationKey
- Return type:
- Returns:
The parsed
RegistrationKeyinstance
- sanitize_variant_tag(param_name, param_index, param_value)
- Return type:
str
- toJSON()
- to_pretty_string()
- to_record()
- Return type:
Tuple[str,Optional[List[str]],str,Optional[str],Optional[str]]
-
ATTRIBUTE_SEPARATOR:
- class cinnamon.registry.Registry
Bases:
objectThe registration registry. The registry has three main functionalities: - Storing/Retrieving registered
Configuration: via theConfigurationInfointernal wrapper. - Storing/RetrievingConfigurationtoComponentbindings: the binding operation allows to build aComponentinstance from its registeredConfiguration. - Storing/Retrieving registered builtComponentinstances: aComponentinstance can be registered as well to mimic Singleton behaviours. This functionality is useful is a singleComponentinstance is used multiple times in a program.All the above functionalities require to specify a
RegistrationKey(either directly or indirectly).-
REGISTRATION_CONTEXT:
RegistrationContext
-
REGISTRATION_METHODS:
Dict[str,Callable]
- classmethod build_component(registration_key=None, name=None, namespace=None, tags=None, **build_args)
Builds a
Componentinstance from its boundedConfigurationvia the implicitRegistrationKey.- Parameters:
registration_key (
Union[RegistrationKey,str,None]) – theRegistrationKeyused to register theConfigurationclass.name (
Optional[str]) – thenameattribute ofRegistrationKeytags (
Optional[Set[str]]) – thetagsattribute ofRegistrationKeynamespace (
Optional[str]) – thenamespaceattribute ofRegistrationKeybuild_args – additional custom component constructor args
- Return type:
- Returns:
The built
Componentinstance- Raises:
InvalidConfigurationTypeException – if there’s a mismatch between the
Configurationclass usedduring registration and the type of the built Configuration instance using the registered –
constructor` method (see ConfigurationInfo arguments) –
NotBoundException – if the
Configurationis not bound to anyComponent.
- classmethod build_configuration(registration_key=None, name=None, namespace=None, tags=None)
Retrieves a configuration instance given its registration key.
- Parameters:
registration_key (
Union[RegistrationKey,str,None]) – key used to register the configurationname (
Optional[str]) – thenamefield ofRegistrationKeynamespace (
Optional[str]) – thenamespacefield ofRegistrationKeytags (
Optional[Set[str]]) – thetagsfield ofRegistrationKey
- Return type:
- Returns:
The built configuration
- Raises:
NotExpandedException – if the dependency DAG has not been expanded yet.
NotRegisteredException – if the provided
RegistrationKeyis not in the registry.
- classmethod check_registration_graph()
Checks if the dependency DAG is valid.
- Raises:
AlreadyExpandedException – if the dependency DAG has already been expanded.
NotADAGException – if the dependency DAG is not a DAG.
DisconnectedGraphException – if, for some reasons, the dependency DAG contains disconnected nodes.
This should never happen via cinnamon APIs, unless some manual intervention on the dependency DAG –
is carried out. –
- Return type:
bool
- classmethod dag_resolution()
Expands and resolves dependencies in registration DAG. The dependency traversal is done bottom-up by recursively expanding top nodes (i.e.,
RegistrationKeyinstances). Expanded keys are retrieved, and built for full validation.- Returns:
a
ResolutionInfo` object containing valid ``RegistrationKeyinvalid_keys: aResolutionInfo` object containing invalid ``RegistrationKey- Return type:
valid_keys
-
expanded:
bool= False
- classmethod in_graph(registration_key=None, name=None, namespace=None, tags=None)
- Return type:
bool
- classmethod in_registry(registration_key)
- Return type:
bool
- classmethod initialize()
- classmethod is_namespace_covered(registration_key)
- Return type:
bool
- classmethod load_registrations(directory)
Imports a Python’s module for registration. In particular, the Registry looks for
register()andregister_method()decorators. These functions are the entry points for registrations: that is, where theRegistryAPIs are invoked to issue registrations.- Parameters:
directory (
Union[AnyStr,Path]) – path of the module- Raises:
InvalidDirectoryException – if the provided directory is not a directory or does not exist.
- classmethod parse_configuration_files(directories)
Runs a static code analyzer to inspect code scripts containing cinnamon registrations with the goal of determining unique namespaces.
- Parameters:
directories (
List[Path]) – list of pathlib.Path directories containing cinnamon registrations.- Returns:
unique list of namespaces mapping: mapping from namespace to pathlib.Path directories.
- Return type:
namespaces
- classmethod register_configuration(config_class, name, namespace, tags=None, config_constructor=None, component_class=None, build_recursively=True)
Registers a
Configurationin the registry. In particular, aConfigurationInfowrapper is stored in theRegistry.- Parameters:
config_class (
Type[Configuration]) – the class of theConfigurationname (
str) – thenamefield ofRegistrationKeynamespace (
str) – thenamespacefield ofRegistrationKeytags (
Optional[Set[str]]) – thetagsfield ofRegistrationKeyconfig_constructor (
Optional[Callable[[],Configuration]]) – the constructor method to build theConfigurationinstance from its classcomponent_class (
Optional[Type[Component]]) – component class to perform binding, if anybuild_recursively (
bool) – if True, children are automatically built iteratively.
- Returns:
The built
RegistrationKeyinstance that can be used to retrieve the registeredConfigurationInfo.- Raises:
NotExpandedException – if the dependency DAG has not been expanded yet.
AlreadyRegisteredException – if the
RegistrationKeyis already usedNamespaceNotFoundException – if one of the dependencies of
RegistrationKeybelongs to anamespace not covered. –
- classmethod register_configuration_from_variant(config_class, name, namespace, variant_kwargs, tags=None, config_constructor=None, component_class=None, build_recursively=True)
Registers a configuration from its variant key:value dict.
- Parameters:
config_class (
Type[Configuration]) – the class of theConfigurationname (
str) – thenamefield ofRegistrationKeynamespace (
str) – thenamespacefield ofRegistrationKeyvariant_kwargs (
Dict[str,Any]) – the key:value dict containing parameter names and their variant values.tags (
Optional[Set[str]]) – thetagsfield ofRegistrationKeyconfig_constructor (
Optional[Callable[[],Configuration]]) – the constructor method to build theConfigurationinstance from its classcomponent_class (
Optional[Type[Component]]) – component class to perform binding, if anybuild_recursively (
bool) – if True, children are automatically built iteratively.
- Returns:
The built
RegistrationKeyinstance that can be used to retrieve the registeredConfigurationInfo.- Raises:
NotExpandedException – if the dependency DAG has not been expanded yet.
AlreadyRegisteredException – if the
RegistrationKeyis already usedNamespaceNotFoundException – if one of the dependencies of
RegistrationKeybelongs to anamespace not covered. –
- classmethod resolve_external_directories(external_directories)
Checks if provided directories are valid directories and exist.
- Parameters:
external_directories (
List[Union[AnyStr,Path]]) – list of directories to validate.- Returns:
list of validated directories as pathlib.Path instances
- Return type:
resolved_directories
- Raises:
InvalidDirectoryException – if any of the provided directories is not a directory or does not exist.
- classmethod retrieve_configuration(registration_key=None, name=None, namespace=None, tags=None)
Retrieves a
Configurationinstance from the registry via itsRegistrationKey.- Parameters:
registration_key (
Union[RegistrationKey,str,None]) – key used to register the configurationname (
Optional[str]) – thenamefield ofRegistrationKeynamespace (
Optional[str]) – thenamespacefield ofRegistrationKeytags (
Optional[Set[str]]) – thetagsfield ofRegistrationKey
- Returns:
the built configuration instance
- Return type:
config
- classmethod retrieve_configuration_info(registration_key=None, name=None, namespace=None, tags=None)
Retrieves a
ConfigurationInfofrom the registry via itsRegistrationKey.- Parameters:
registration_key (
Optional[RegistrationKey]) – key used to register the configurationname (
Optional[str]) – thenamefield ofRegistrationKeynamespace (
Optional[str]) – thenamespacefield ofRegistrationKeytags (
Optional[Set[str]]) – thetagsfield ofRegistrationKey
- Return type:
- Returns:
The
ConfigurationInfoinstance- Raises:
NotRegisteredException – if the provided
RegistrationKeyis not in the registry.
- classmethod retrieve_keys(names=None, namespaces=None, tags=None, keys=None)
Retrieves
RegistrationKeyfrom registry via given name, tags, namespaces filters. The search can be limited to a fixed set of keys, optionally given in input.- Parameters:
names (
Union[List[str],str,None]) – a name or a list of names to filter registration keys.namespaces (
Union[List[str],str,None]) – a namespace or a list of namespaces to filter registration keys.tags (
Optional[Set[str]]) – a tag set to filter registration keys.keys (
Optional[List[RegistrationKey]]) – an optional list ofRegistrationKeyon which to apply the search.
- Return type:
List[RegistrationKey]
Returns:
- classmethod setup(directory=None, external_directories=None)
Main entrypoint of cinnamon. The registry checks provided directories for configurations to populate its internal registry and build the dependency DAG. Eventually, the dependency DAG is expanded to account for variants and invalid configurations.
- Parameters:
directory (
Union[Path,AnyStr,None]) – the main directory of the project containing configurations.external_directories (
Optional[List[Union[AnyStr,Path]]]) – additional external directories containing configurations.
- Returns:
a
ResolutionInfo` object containing valid ``RegistrationKeyinvalid_keys: aResolutionInfo` object containing invalid ``RegistrationKey- Return type:
valid_keys
- Raises:
RuntimeWarning – if duplicate namespaces are found.
InvalidDirectoryException – if one of the provided directories does not exist or is not a directory.
AlreadyExpandedException – if the dependency DAG has already been expanded.
NotADAGException – if the dependency DAG is not a DAG.
DisconnectedGraphException – if, for some reasons, the dependency DAG contains disconnected nodes.
This should never happen via cinnamon APIs, unless some manual intervention on the dependency DAG –
is carried out. –
- classmethod update_namespaces(namespaces, module_mapping)
-
REGISTRATION_CONTEXT:
- class cinnamon.registry.ResolutionInfo
Bases:
objectContains information about
RegistrationKeyand correspondingConfigurationthat have been retrieved after Registry DAG resolution of dependencies.- add(key, config)
- cinnamon.registry.register(func)
- Return type:
Callable
- cinnamon.registry.register_method(name, namespace, tags=None, component_class=None, build_recursively=True)
- Return type:
Callable