secml.core

CCreator

class secml.core.c_creator.CCreator[source]

Bases: object

The magnificent global superclass.

Attributes
class_typestr

Defines class type.

__super__str or None

String with superclass name. Can be None to explicitly NOT support .create() and .load().

Methods

copy(self)

Returns a shallow copy of current class.

create([class_item])

This method creates an instance of a class with given type.

deepcopy(self)

Returns a deep copy of current class.

get_class_from_type(class_type)

Return the class associated with input type.

get_params(self)

Returns the dictionary of class hyperparameters.

get_state(self)

Returns the object state dictionary.

get_subclasses()

Get all the subclasses of the calling class.

list_class_types()

This method lists all types of available subclasses of calling one.

load(path)

Loads object from file.

load_state(self, path)

Sets the object state from file.

save(self, path)

Save class object to file.

save_state(self, path)

Store the object state to file.

set(self, param_name, param_value[, copy])

Set a parameter of the class.

set_params(self, params_dict[, copy])

Set all parameters passed as a dictionary {key: value}.

set_state(self, state_dict[, copy])

Sets the object state using input dictionary.

timed([msg])

Timer decorator.

property class_type

Defines class type.

copy(self)[source]

Returns a shallow copy of current class.

As shallow copy creates a new instance of current object and then insert in the new object a reference (if possible) to each attribute of the original object.

classmethod create(class_item=None, *args, **kwargs)[source]

This method creates an instance of a class with given type.

The list of subclasses of calling superclass is looked for any class defining class_item = ‘value’. If found, the class type is listed.

Also a class instance can be passed as main argument. In this case the class instance is returned as is.

Parameters
class_itemstr or class instance or None, optional

Type of the class to instantiate. If a class instance of cls is passed, instead, it returns the instance directly. If this is None, an instance of the classing superclass is created.

args, kwargsoptional arguments

Any other argument for the class to create. If a class instance is passed as class_item, optional arguments are NOT allowed.

Returns
instance_classany class

Instance of the class having the given type (class_type) or the same class instance passed as input.

deepcopy(self)[source]

Returns a deep copy of current class.

As deep copy is time consuming in most cases, can sometimes be acceptable to select a subset of attributes and assign them to a new instance of the current class using .set_params.

classmethod get_class_from_type(class_type)[source]

Return the class associated with input type.

This will NOT check for classes with duplicated class type. The first class found with matching type will be returned.

Parameters
class_typestr

Type of the class which will be looked up for.

Returns
class_objclass

Desired class, if found. This is NOT an instance of the class.

get_params(self)[source]

Returns the dictionary of class hyperparameters.

A hyperparameter is a PUBLIC or READ/WRITE attribute.

get_state(self)[source]

Returns the object state dictionary.

Returns
dict

Dictionary containing the state of the object.

classmethod get_subclasses()[source]

Get all the subclasses of the calling class.

Returns
subclasseslist of tuple

The list containing a tuple (class.__name__, class) for each subclass of calling class. Keep in mind that in Python each class is a “subclass” of itself.

classmethod list_class_types()[source]

This method lists all types of available subclasses of calling one.

The list of subclasses of calling superclass is looked for any class defining class_item = ‘value’. If found, the class type is listed.

Returns
typeslist

List of the types of available subclasses of calling class.

classmethod load(path)[source]

Loads object from file.

This function loads an object from file (with pickle).

The object can be correctly loaded in the following cases:
  • loaded and calling class have the same type.

  • calling class is the superclass of the loaded class’s package.

  • calling class is .CCreator.

Parameters
pathstr

Path of the target object file.

load_state(self, path)[source]

Sets the object state from file.

Parameters
pathstr

The full path of the file from which to load the object state.

See also

set_state

Sets the object state using input dictionary.

property logger

Logger for current object.

save(self, path)[source]

Save class object to file.

This function stores an object to file (with pickle).

.load() can be used to restore the object later.

Parameters
pathstr

Path of the target object file.

Returns
obj_pathstr

The full path of the stored object.

save_state(self, path)[source]

Store the object state to file.

Parameters
pathstr

Path of the file where to store object state.

Returns
str

The full path of the stored object.

See also

get_state

Returns the object state dictionary.

set(self, param_name, param_value, copy=False)[source]

Set a parameter of the class.

Only writable attributes of the class, i.e. PUBLIC or READ/WRITE, can be set.

The following checks are performed before setting:
  • if param_name is an attribute of current class, set directly;

  • else, iterate over __dict__ and look for a class attribute

    having the desired parameter as an attribute;

  • else, if attribute is not found on the 2nd level,

    raise AttributeError.

If possible, a reference to the attribute to set is assigned. Use copy=True to always make a deepcopy before set.

Parameters
param_namestr

Name of the parameter to set.

param_valueany

Value to set for the parameter.

copybool

By default (False) a reference to the parameter to assign is set. If True or a reference cannot be extracted, a deepcopy of the parameter value is done first.

set_params(self, params_dict, copy=False)[source]

Set all parameters passed as a dictionary {key: value}.

This function natively takes as input the dictionary created by .get_params. Only parameters, i.e. PUBLIC or READ/WRITE attributes, can be set.

For more information on the setting behaviour see .CCreator.set.

If possible, a reference to the parameter to set is assigned. Use copy=True to always make a deepcopy before set.

Parameters
params_dictdict

Dictionary of parameters to set.

copybool

By default (False) a reference to the parameter to assign is set. If True or a reference cannot be extracted, a deepcopy of the parameter is done first.

See also

get_params

returns the dictionary of class parameters.

set_state(self, state_dict, copy=False)[source]

Sets the object state using input dictionary.

Only readable attributes of the class, i.e. PUBLIC or READ/WRITE or READ ONLY, can be set.

If possible, a reference to the attribute to set is assigned. Use copy=True to always make a deepcopy before set.

Parameters
state_dictdict

Dictionary containing the state of the object.

copybool, optional

By default (False) a reference to the attribute to assign is set. If True or a reference cannot be extracted, a deepcopy of the attribute is done first.

static timed(msg=None)[source]

Timer decorator.

Returns a decorator that can be used to measure execution time of any method. Performance data will be stored inside the class logger. Messages will be logged using the INFO logging level. As this decorator accepts optional arguments, must be called as a method. See examples.

Parameters
msgstr or None, optional

Custom message to display when entering the timed block. If None, “Entering timed block method_name…” will printed.

property verbose

Verbosity level of logger output.

Available levels are:

0 = no verbose output 1 = info-level logging 2 = debug-level logging

secml.core.c_creator.has_super(cls)[source]

Returns True if input class __super__ is not None.

__super__ is defined and not None for class trees having a main superclass and one or more inherited classes.

Parameters
clsobj

Any class or class isntance.

secml.core.c_creator.import_class_types(classes)[source]

Returns types associated with input list of classes.

Abstract properties are ignored.

Returns
typeslist

List of class types associated with input list of classes.

secml.core.c_creator.import_package_classes(cls)[source]

Get all the classes inside a package.

Returns
memberslist

Return all members of an object as (name, value) pairs sorted by name.

attr_utils

secml.core.attr_utils.as_public(attr)[source]

Return the public name associated with a protected attribute.

Examples

>>> from secml.core.attr_utils import as_public
>>> as_public('_attr1')
'attr1'
>>> as_public('attr1')  # Public attributes are returned as is
'attr1'
>>> as_public('__attr1')  # This is NOT a private attribute!
'_attr1'
secml.core.attr_utils.as_protected(attr)[source]

Return the protected name associated with a public attribute.

Examples

>>> from secml.core.attr_utils import as_protected
>>> as_protected('attr1')
'_attr1'
>>> as_protected('__attr1')
'_attr1'
>>> as_protected('_attr1')  # Protected attributes are returned as is
'_attr1'
secml.core.attr_utils.has_protected(obj, attr)[source]

True if attribute is a protected attribute of class.

Parameters
objobject

Target class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.get_protected(obj_class, attr, default=<no value>)[source]

Return the protected attribute of class.

Parameters
obj_classclass

Target class (usually extracted using obj.__class__).

attrstr

Name of the attribute to return.

defaultany, optional

Value that is returned when the named attribute is not found.

secml.core.attr_utils.as_private(obj_class, attr)[source]

Return the PRIVATE name associated with input attribute.

Parameters
obj_classclass

Target class (usually extracted using obj.__class__).

attrstr

Name of the target attribute.

secml.core.attr_utils.has_private(obj_class, attr)[source]

True if attribute is a private attribute of class.

Parameters
obj_classclass

Target class (usually extracted using obj.__class__).

attrstr

Name of the attribute to check.

secml.core.attr_utils.get_private(obj_class, attr, default=<no value>)[source]

Return the private attribute of class.

Parameters
obj_classclass

Target class (usually extracted using obj.__class__).

attrstr

Name of the attribute to return.

defaultany, optional

Value that is returned when the named attribute is not found.

secml.core.attr_utils.has_property(obj, attr)[source]

True if attribute is a property or has an associated property.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.get_property(obj, attr)[source]

Return the property associated with input attribute.

If no property is associated with input attribute, raise AttributeError.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.has_getter(obj, attr)[source]

True if an attribute has an associated getter.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.has_setter(obj, attr)[source]

True if an attribute has an associated setter.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.add_readonly(obj, attr, value=None)[source]

Add a READ ONLY attribute to object.

A read only attribute is defined as a protected attribute plus a getter associated with it.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to set.

valueany, optional

Value to assign to the attribute. If not given, None is used.

secml.core.attr_utils.add_readwrite(obj, attr, value=None)[source]

Add a READ/WRITE attribute to object.

A read/write attribute is defined as a protected attribute plus a getter AND a setter associated with it.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to set.

valueany, optional

Value to assign to the attribute. If not given, None is used.

secml.core.attr_utils.is_public(obj, attr)[source]

Return True if input attribute is PUBLIC.

A public attribute has the name without ‘_’ as a prefix.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.is_protected(obj, attr)[source]

Return True if input attribute is PROTECTED.

A protected attribute has the name starting with only ‘_’ and no getter/setter associated with it.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.is_readonly(obj, attr)[source]

Return True if input attribute is READ ONLY.

A read only attribute has ONLY a getter associated with it.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.is_readwrite(obj, attr)[source]

Return True if input attribute is READ/WRITE.

A read/write attribute has BOTH a getter AND a setter associated with it.

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.is_readable(obj, attr)[source]

Return True if input attribute is READABLE.

A readable attribute can be one of the following:
  • public

  • read/write (getter/setter associated with property)

  • read only (getter associated with property)

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.is_writable(obj, attr)[source]

Return True if input attribute is WRITABLE.

A writable attribute can be one of the following:
  • public

  • read/write (getter/setter associated with property)

Parameters
objobject

Any class instance.

attrstr

Name of the attribute to check.

secml.core.attr_utils.extract_attr(obj, mode)[source]

Generates a sequence of attributes from an input dictionary.

This function returns a generator with the dictionary’s keys having a name compatible with specified mode.

The following modalities are available:
  • ‘pub’ -> PUBLIC (standard attribute, no ‘_’ in the prefix)

  • ‘rw’ -> READ/WRITE (a getter/setter is associated with it)

  • ‘r’ -> READ ONLY (a getter is associated with it)

  • ‘pro’ -> PROTECTED (‘_’ as the prefix and no getter/setter associated)

All modes can be stacked up using ‘+’ (see examples).

Parameters
objany object

Any class which attributes should be extracted.

modestr

Extraction modality. All available modalities can be combined using a plus ‘+’.

Notes

Sorting of the attributes in the output generator is random.

constants

secml.core.constants.inf = inf

Not a number.

secml.core.constants.nan = nan

Machine epsilon.

This is defined as the smallest number that, when added to one, yields a result different from one.

Notes

This value can be different from machine to machine, but generally yelds approximately 1.49e-08.

Examples

>>> from secml.core.constants import eps
>>> print(eps)
1.4901161193847656e-08
secml.core.constants.eps = 1.4901161193847656e-08

The mathematical constant e = 2.718281…, to available precision.

Examples

>>> from secml.core.constants import e
>>> print(e)
2.718281828459045
secml.core.constants.e = 2.718281828459045

The mathematical constant pi = 3.141592…, to available precision.

Examples

>>> from secml.core.constants import pi
>>> pi
3.141592653589793

decorators

class secml.core.decorators.deprecated(version, extra='')[source]

Bases: object

Decorator to mark a function or class as deprecated.

Issue a warning when the function is called/the class is instantiated and adds a warning to the docstring.

The optional extra argument will be appended to the deprecation message and the docstring.

Note: to use this with the default value for extra, put in an empty of parentheses: >>> from secml.core.decorators import deprecated >>> deprecated() # doctest: +ELLIPSIS <secml.core.decorators.deprecated object at …>

>>> @deprecated()
... def some_function(): pass
Parameters
versionstr

Version since which the function or class is deprecated.

extrastr, optional

Extra text to be added to the deprecation messages.

Notes

Adapted from:

Methods

__call__(self, obj)

Call method.

exceptions

exception secml.core.exceptions.NotFittedError[source]

Bases: ValueError, AttributeError

Exception to raise if the object is used before training.

This class inherits from both ValueError and AttributeError.

Examples

>>> from secml.ml.classifiers import CClassifierSVM
>>> from secml.array import CArray
>>> from secml.core.exceptions import NotFittedError
>>> try:
...     CClassifierSVM().predict(CArray([[1, 2]]))
... except NotFittedError as e:
...     print(repr(e))
...                        
NotFittedError('this `CClassifierSVM` is not trained. Call `.fit()` first.',)

type_utils

secml.core.type_utils.is_bool(x)[source]
secml.core.type_utils.is_int(x)[source]
secml.core.type_utils.is_intlike(x)[source]

Return True if input is integer or list/array of 1 integer.

Examples

>>> from secml.core.type_utils import is_intlike
>>> print(is_intlike(0))  # Standard int
True
>>> print(is_intlike(0.1))  # Standard float
False
>>> print(is_intlike(np.array([0])))  # ndarray with one int
True
>>> print(is_intlike(np.array([0.1])))  # ndarray with one float
False
secml.core.type_utils.is_float(x)[source]
secml.core.type_utils.is_floatlike(x)[source]

Return True if input is float or list/array of 1 float.

Examples

>>> from secml.core.type_utils import is_floatlike
>>> print(is_floatlike(0.1))  # Standard float
True
>>> print(is_floatlike(0))  # Standard int
False
>>> print(is_floatlike(np.array([0.1])))  # ndarray with one float
True
>>> print(is_floatlike(np.array([0])))  # ndarray with one int
False
secml.core.type_utils.is_scalar(x)[source]

True if input is integer or float.

secml.core.type_utils.is_scalarlike(x)[source]

True if input is scalar (int or float) or list/array of 1 real.

secml.core.type_utils.is_inf(x)[source]

True if input is a positive/negative infinity.

Parameters
xscalar

Examples

>>> from secml.core.type_utils import is_inf
>>> from secml.core.constants import inf, nan
>>> print(is_inf(inf))
True
>>> print(is_inf(-inf))
True
>>> print(is_inf(nan))
False
>>> print(is_inf(0.1))
False
>>> from secml.array import CArray
>>> print(is_inf(CArray([inf])))  # Use `CArray.is_inf()` instead
Traceback (most recent call last):
    ...
TypeError: input must be a scalar.
secml.core.type_utils.is_posinf(x)[source]

True if input is a positive infinity.

Parameters
xscalar

Examples

>>> from secml.core.type_utils import is_posinf
>>> from secml.core.constants import inf, nan
>>> print(is_posinf(inf))
True
>>> print(is_posinf(-inf))
False
>>> from secml.array import CArray
>>> print(is_posinf(CArray([inf])))  # Use `CArray.is_posinf()` instead
Traceback (most recent call last):
    ...
TypeError: input must be a scalar.
secml.core.type_utils.is_neginf(x)[source]

True if input is a negative infinity.

Parameters
xscalar

Examples

>>> from secml.core.type_utils import is_neginf
>>> from secml.core.constants import inf, nan
>>> print(is_neginf(-inf))
True
>>> print(is_neginf(inf))
False
>>> from secml.array import CArray
>>> print(is_neginf(CArray([-inf])))  # Use `CArray.is_neginf()` instead
Traceback (most recent call last):
    ...
TypeError: input must be a scalar.
secml.core.type_utils.is_nan(x)[source]

True if input is Not a Number (NaN).

Parameters
xscalar

Notes

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity.

Examples

>>> from secml.core.type_utils import is_nan
>>> from secml.core.constants import inf, nan
>>> print(is_nan(nan))
True
>>> print(is_nan(inf))
False
>>> print(is_nan(0.1))
False
>>> from secml.array import CArray
>>> print(is_neginf(CArray([nan])))  # Use `CArray.is_nan()` instead
Traceback (most recent call last):
    ...
TypeError: input must be a scalar.
secml.core.type_utils.is_list(x)[source]
secml.core.type_utils.is_list_of_lists(x)[source]

Return True if input is a list of lists, otherwise False.

Examples

>>> is_list_of_lists([[1, 2], [3]])
True
>>> is_list_of_lists([[1], 2, [3]])
False
>>> is_list_of_lists([])
False
secml.core.type_utils.is_ndarray(x)[source]
secml.core.type_utils.is_scsarray(x)[source]

Returns True if input is a scipy.sparse array.

secml.core.type_utils.is_slice(x)[source]
secml.core.type_utils.is_str(x)[source]
secml.core.type_utils.is_bytes(x)[source]
secml.core.type_utils.is_tuple(x)[source]
secml.core.type_utils.is_set(x)[source]
secml.core.type_utils.is_dict(x)[source]
secml.core.type_utils.to_builtin(x)[source]

Convert input to the corresponding built-in type.

Works with the following types:
  • bool, np.bool_ -> bool

  • int, np.integer -> int

  • float, `np.floating -> float

  • str, np.str_, np.unicode_ -> str

  • bytes, np.bytes_ -> bytes