Domains

Creamas includes some functionality for different artifact domains, e.g. images.

Note

Generally, these modules need extra requirements to be installed:

pip install creamas[extras]

Warning

This functionality is currently being developed.

Images

Genetic Programming

class creamas.domains.image.gp.generator.GPImageGenerator(creator_name, toolbox, pset, generations, pop_size, evaluate_func, shape=(32, 32), super_pset=None)[source]

A generator class producing instances of GPImageArtifact using genetic programming.

The generator uses DEAP in its internal operation, and requires extras to be installed: pip install creamas[extras].

Generator class can be used in two different manners:

  • calling only the static functions of the class, or

  • creating a new instance of the class associated with a specific agent and calling GPImageGenerator.generate().

Most of the initialization arguments are used as defaults in the calls for generate(), and can be overridden when using it.

Parameters
  • creator_name (str) – Name of the creator agent used by generate() as a default.

  • toolbox – DEAP’s toolbox used by generate() as a default.

  • pset – DEAP’s primitive set which is used to create the images.

  • generations – Number of generations to evolve

  • pop_size – Population size.

  • shape – Shape of the produced images during the evolution. The resolution can be (indefinitely) up-scaled for the accepted artifacts.

  • evaluate_func (callable) – A function used to evaluate each image, e.g. evaluate() Function should accept one argument, a GPImageArtifact and return an evaluation of an artifact. Evaluation is supposed to be maximized.

  • super_pset – In a case an agent may create artifacts in conjunction with other agents, super_pset should contain all the primitives all the agents may use. If None, this is set to pset.

static create_population(size, pset, generation_method, individual_creator=None, toolbox=None)[source]

Creates a population of randomly generated individuals.

Parameters
  • size – The size of the generated population.

  • pset – The primitive set used in individual generation.

  • generation_method – Generation method to create individuals, e.g. deap.gp.genHalfAndHalf().

  • individual_creator – If None calls init_deap_creator() with class suffix “”.

  • toolbox – DEAP toolbox. If None a new toolbox is created.

Returns

DEAP toolbox and a list containing the generated population as DEAP individuals.

evaluate_individual(individual, shape)[source]

Evaluates a DEAP individual.

This method inherently changes the individual to GPImageArtifact for the evaluation.

Parameters
  • individual – The individual to be evaluated.

  • shape – Shape of the image.

Returns

The evaluation.

static evolve_population(population, generations, toolbox, pset, hall_of_fame, cxpb=0.75, mutpb=0.25, injected_individuals=[], use_selection_on_first=True)[source]

Evolves a population of individuals. Applies elitist selection strategy (k=1) in addition to toolbox’s selection strategy to the individuals.

Parameters
  • population – A list containing the individuals of the population.

  • generations – Number of generations to be evolved.

  • toolbox – DEAP toolbox with the necessary functions.

  • pset – DEAP primitive set used during the evolution.

  • hall_of_fame – DEAP’s hall-of-fame

  • cxpb (float) – Crossover probability

  • mutpb (float) – Mutation probability

  • injected_individuals (list) – A list of individuals which are injected into the starting population

  • use_selection_on_first (bool) – If True, uses selection on the first generation before producing offspring, otherwise produces offspring from the

generate(artifacts=1, generations=None, pset=None, pop_size=None, shape=None, old_artifacts=[], mutate_old=True)[source]

Generate new artifacts using instance’s own toolbox and given arguments.

Parameters
  • artifacts (int) – The number of the most fit artifacts to be returned.

  • generations (int) – Number of generations to be evolved. If None uses initialization parameters.

  • pset – DEAP’s primitive set used to create the individuals.

  • pop_size (int) – DEAP population size

  • shape (tuple) – Shape of the created images. This heavily affects the execution time.

  • old_artifacts (list) – A list of existing GPImageArtifact objects, which should be part of the initial population. Each artifact in the list should have the function tree for the individual stored in artifact.framings['function_tree'].

  • mutate_old (bool) – If True, forces mutation on the existing individuals from.

Returns

A list of generated GPImageArtifact objects. The artifacts returned do not have their framing information (evaluation, etc.) filled.

static individual_to_artifact(creator_name, individual, shape, pset=None, bw=True)[source]

Convert DEAP´s individual to GPImageArtifact.

This will create the inherent image object, if it is not already present in the individual. If individual has already an image associated with it, that image is used and shape and bw parameters are omitted.

Fails silently if the image creation does not succeed, i.e. deap.gp.compile fails for the given individual and pset, and returns None.

Parameters
  • creator_name (str) – Name of the creator of the image.

  • individual – Function (DEAP´s individual) of the image.

  • shape – Shape of the returned image.

  • pset – DEAP’s primitive set used to compile the individual.

  • bw – If True, the individual is assumed to represent grayscale image, otherwise it is assumed to be an RGB image.

Returns

GPImageArtifact or None

static init_deap_creator(class_suffix, pset)[source]

Initializes the DEAP deap.creator by creating classes which use the wanted primitive set to maximize fitness.

The created classes are found from deap.creator with names FitnessMax-[class_suffix] and Individual-[class_suffix] using, e.g. getattr(deap.creat or, "FitnessMax-{}".format(class_suffix)). The method should be called only once per class_suffix as subsequent calls will erase previously created classes.

Parameters
  • class_suffix (str) – Suffix for the created fitness and individual classes.

  • pset – Primitive set used by the individual creator.

Returns

Created classes

static initial_population(toolbox, pset, pop_size, individual_creator=None, old_artifacts=[], mutate_old=True)[source]

Create initial population for new evolution.

Population is formed by first creating individuals from old_artifacts and then the rest of the population is generated using deap.gp.genHalfAndHalf() with given pset.

Parameters
  • toolbox – DEAP toolbox.

  • pset – Primitive set for the population’s new individuals.

  • pop_size – Size of the population.

  • individual_creator – Class used to create new individuals, if None tries to use deap.creator.Individual.

  • old_artifacts (list) – A list of existing GPImageArtifact objects, which should be part of the initial population. Each artifact in the list should have the function tree for the individual stored in artifact.framings['function_tree'].

  • mutate_old (bool) – If True, forces mutation on the existing individuals from.

Returns

Created population

class creamas.domains.image.gp.artifact.GPImageArtifact(creator, obj, function_tree, string_repr=None)[source]

An artifact implementation for the images created using genetic programming, GPImageArtifact requiring pip install creamas[extras]. The artifact implementation is coupled with GPImageGenerator, the generator producing evolutionary art using genetic programming.

Each GPImageArtifact.obj should be a numpy array with a data type np.uint8.

Parameters
  • creator – Name of the creator agent.

  • obj – Image generated, numpy array with dtype==np.uint8.

  • function_tree – Function from which the image was generated. This is stored to framings[‘function_tree’].

  • string_repr (str) – String representation of the function. This is stored to framings[‘string_repr’].

static artifact_from_file(creator_name, individual_file, pset, shape=(32, 32), bw=True)[source]

Create an artifact object from given function file.

Parameters
  • creator_name (str) – Name of the creator

  • individual_file (str) – Path to the function

  • pset (deap.gp.PrimitiveSet) – Primitive set to recreate the image

  • shape (tuple) – Dimensions of the image

  • bw (bool) – If True, creates a grayscale image (2D numpy.array), otherwise creates 3D numpy.array.

static distance(artifact1, artifact2)[source]

Euclidean distance between two artifact’s which objects are images.

Images are expected to be of type np.uint8. The intensity values are converted to floats in [0, 1] before computing the distance.

static image_from_file(individual_file, image_file, pset, color_map=None, shape=(400, 400))[source]

Save an individual saved as a string into a file as a new image with given color mapping and resolution.

Parameters
  • individual_file (str) – Path to the file with the string representation of the individual.

  • image_file (str) – Path to the file where image is saved. The image type is defined by the file type.

  • pset (deap.gp.PrimitiveSet) – DEAP’s primitive set required to compile string representation of the individual into an individual.

  • color_map – Color map used to colorize a greyscale image, e.g. one of the matplotlib’s color maps.

  • shape (tuple) – Shape of the generated image. Default is (400, 400).

static image_from_function(func, shape=(32, 32), bw=True)[source]

Generate image from the given function.

Parameters
  • func – A function returned by deap.gp.compile() used to compute the color values.

  • shape (tuple) – Shape of the returned image.

  • bw (bool) – If True, func is assumed to represent a grayscale image, otherwise it is assumed to be an RGB image.

Returns

A numpy array containing the color values. The format is np.uint8 for opencv compatibility.

If any errors occur during the image creation, fails silently and returns a black image.

static max_distance(shape, bw=True)[source]

Maximum distance between two images is calculated as the euclidean distance between an image filled with zeros and an image filled with 255.

static png_compression_ratio(artifact)[source]

Compute png compression ratio for the image of the given artifact.

PNG compression ratio: size(png) / size(bmp)

If ratio is low (< 0.08), then the image can be seen as uninteresting.

static save(artifact, image_file, pset, color_map=None, shape=(400, 400), string_file=None)[source]

Saves an artifact as an image.

Parameters
  • artifact – The artifact to be saved.

  • image_file (str) – Path to the file where image is saved. The image type is defined by the file type.

  • pset (deap.gp.PrimitiveSet) – DEAP’s primitive set required to compile string representation of the individual into an individual.

  • color_map – Color map used to colorize a greyscale image, e.g. one of the matplotlib’s color maps.

  • shape (tuple) – Shape of the generated image. Default is (400, 400).

  • string_file (str) – If not None saves also the function associated with the artifact as txt in to the given file.

Tools

Utilities for the GPImageGenerator and agents utilizing it. The module requires extras to be installed.

creamas.domains.image.gp.tools.create_sample_pset(bw=True, sample_size=8)[source]

Create a sampled pset from all primitives.

creamas.domains.image.gp.tools.create_super_pset(bw=True)[source]

Create super pset which contains all the primitives for DEAP.

Parameters

bw (bool) – If True the returned primitive set is primed to create grayscale images, otherwise it will create RGB images.

Returns

Created primitive set

creamas.domains.image.gp.tools.create_toolbox(pset)[source]

Creates a DEAP toolbox with some reasonable defaults:

Parameters

pset – Primitive set

Returns

deap.base.Toolbox

creamas.domains.image.gp.tools.subtree_mutate(individual, pset, expr)[source]

Choose a random node and generate a subtree to that node using pset and expr.

creamas.domains.image.gp.tools.GP_TREE_MAX_DEPTH = 8

Maximum depth for GP trees created by functions in this module.

Features

Various feature implementations for images. See Feature for general usage of features.

class creamas.domains.image.features.ImageComplexityFeature[source]

Feature that computes the fractal dimension of an image. The color values must be in range [0, 255] and type int. Returns a float.

extract(artifact, canny_threshold1=100, canny_threshold2=200)[source]

Extract fractal dimension estimate from the given image artifact.

The method first extracts edges using Canny edge detection and the resulting edge image is passed down to the fractal dimension estimator.

class creamas.domains.image.features.ImageRednessFeature[source]

Feature that measures the redness of an RGB image. Returns float in range [0, 1].

extract(artifact)[source]

Extract redness of the image.

class creamas.domains.image.features.ImageGreennessFeature[source]

Feature that measures the greenness of an RGB image. Returns float in range [0, 1].

extract(artifact)[source]

Extract greenness of the image.

class creamas.domains.image.features.ImageBluenessFeature[source]

Feature that measures the blueness of an RGB image. Returns float in range [0, 1].

extract(artifact)[source]

Extract blueness of the image.

class creamas.domains.image.features.ImageIntensityFeature[source]

Feature that measures the intensity of an image. Returns float in range [0, 1].

extract(artifact)[source]

Extract average intensity of the image.

class creamas.domains.image.features.ImageBenfordsLawFeature[source]

Feature that computes the Benford’s Law for the image.

See also

Benford’s Law

extract(artifact)[source]

Extract Benford’s law from the image.

class creamas.domains.image.features.ImageEntropyFeature(normalize=False)[source]

Compute entropy of an image.

Entropy computation uses 256 bins and a grayscale image.

Parameters

normalize (bool) – Optional, normalize the returned entropy value.

extract(artifact)[source]

Extract entropy from the image.

class creamas.domains.image.features.ImageSymmetryFeature(axis, use_entropy=True)[source]

Compute symmetry of the image for given ax or combination of axis.

Feature allows adding the computed symmetry with “liveliness” of the image using use_entropy=True. If entropy is not used, simple images (e.g. single color images) will give high symmetry values.

Parameters
  • axis

    ImageSymmetryFeature.HORIZONTAL, ImageSymmetryFeature.VERTICAL, ImageSymmetryFeature.DIAGONAL, ImageSymmetryFeature.ALL_AXES

    These can be combined, e.g. axis=ImageSymmetryFeature.HORIZONTAL + ImageSymmetryFeature.VERTICAL.

  • use_entropy (bool) – If True multiples the computed symmetry value with image’s entropy (“liveliness”).

extract(artifact)[source]

Extract symmetry of the image.

Text

Tools

Markov Chains

Other domains

Other domains are currently being developed