# droplets package¶

Functions and classes for analyzing emulsions and droplets

## droplets.droplet_tracks module¶

Classes representing the time evolution of droplets

 DropletTrack information about a single droplet over multiple time steps DropletTrackList a list of instances of DropletTrack
class DropletTrack(droplets=None, times=None)[source]

Bases: object

information about a single droplet over multiple time steps

Parameters
• emulsions (list) – List of emulsions that describe this time course

• times (list) – Times associated with the emulsions

append(droplet: SphericalDroplet, time: float = None) None[source]

append a new droplet with a time code

Parameters
property data: Optional[ndarray]

an array containing the data of the full track

Type

ndarray

property dim: Optional[int]

return the space dimension of the droplets

property duration: float

total duration of the track

Type

float

property end: float

last time point

Type

float

property first: SphericalDroplet

first droplet instance

Type

SphericalDroplet

classmethod from_file(path: str) [source]

create droplet track by reading from file

Parameters

path (str) – The path from which the data is read. This function assumes that the data was written as an HDF5 file using to_file().

get_position(time: float) [source]

ndarray: returns the droplet position at a specific time

ndarray: returns the droplet radius for each time point

get_trajectory(smoothing: float = 0) [source]

return a list of positions over time

Parameters

smoothing (float) – Determines the length scale for some gaussian smoothing of the trajectory. Setting this to zero disables smoothing.

Returns

An array giving the position of the droplet at each

time instance

Return type

ndarray

get_volumes() [source]

ndarray: returns the droplet volume for each time point

items()[source]

iterate over all times and droplets, returning them in pairs

property last: SphericalDroplet

last droplet instance

Type

SphericalDroplet

plot(attribute: str = 'radius', *args, title: str = None, filename: str = None, action: str = 'auto', ax_style: Optional[Dict[str, Any]] = None, fig_style: Optional[Dict[str, Any]] = None, ax=None, **kwargs) PlotReference[source]

plot the time evolution of the droplet

Parameters
• attribute (str) – The attribute to plot. Typical values include radius and volume, but others might be defined on the droplet class.

• title (str) – Title of the plot. If omitted, the title might be chosen automatically.

• filename (str, optional) – If given, the plot is written to the specified file.

• action (str) – Decides what to do with the final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given. The default value auto implies that the plot is shown if it is not a nested plot call.

• ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item in this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

• fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

• ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

• **kwargs – All remaining parameters are forwarded to the ax.plot method. For example, passing color=None, will use different colors for different droplets.

Returns

Return type

PlotReference

plot_positions(grid: Optional[GridBase] = None, arrow: bool = True, *args, title: str = None, filename: str = None, action: str = 'auto', ax_style: Optional[Dict[str, Any]] = None, fig_style: Optional[Dict[str, Any]] = None, ax=None, **kwargs) PlotReference[source]

plot the droplet track

Parameters
• grid (GridBase, optional) – The grid on which the droplets are defined. If given, periodic boundary conditions can be respected in the plotting.

• arrow (bool, optional) – Flag determining whether an arrow head is shown to indicate the direction of the droplet drift.

• title (str) – Title of the plot. If omitted, the title might be chosen automatically.

• filename (str, optional) – If given, the plot is written to the specified file.

• action (str) – Decides what to do with the final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given. The default value auto implies that the plot is shown if it is not a nested plot call.

• ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item in this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

• fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

• ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

• **kwargs – Additional keyword arguments are passed to the matplotlib plot function to affect the appearance. For example, passing color=None, will use different colors for different droplets.

Returns

Return type

PlotReference

property start: float

first time point

Type

float

time_overlaps(other: DropletTrack) bool[source]

determine whether two DropletTrack instances overlaps in time

Parameters

other (DropletTrack) – The other droplet track

Returns

True when both tracks contain droplets at the same time step

Return type

bool

to_file(path: str, info: Optional[Dict[str, Any]] = None) None[source]

store data in hdf5 file

The data can be read using the classmethod DropletTrack.from_file().

Parameters
• path (str) – The path to which the data is written as an HDF5 file.

• info (dict) – Additional data stored alongside the droplet track list

class DropletTrackList(iterable=(), /)[source]

Bases: list

a list of instances of DropletTrack

classmethod from_emulsion_time_course(time_course: EmulsionTimeCourse, method: str = 'overlap', progress: bool = False, **kwargs) [source]

obtain droplet tracks from an emulsion time course

Parameters
• time_course (droplets.emulsions.EmulsionTimeCourse) – A collection of temporally arranged emulsions

• method (str) – The method used for tracking droplet identities. Possible methods are “overlap” (adding droplets that overlap with those in previous frames) and “distance” (matching droplets to minimize center-to-center distances).

• progress (bool) – Whether to show the progress of the process.

• **kwargs – Additional parameters for the tracking algorithm. Currently, one can only specify a maximal distance (using max_dist) for the “distance” method.

Returns

the resulting droplet tracks

Return type

DropletTrackList

classmethod from_file(path: str) [source]

create droplet track list by reading file

Parameters

path (str) – The path from which the data is read. This function assumes that the data was written as an HDF5 file using to_file().

Returns

an instance describing the droplet track list

Return type

DropletTrackList

classmethod from_storage(storage: StorageBase, refine: bool = False, method: str = 'overlap', progress: = None) [source]

obtain droplet tracks from stored scalar field data

This method first determines an emulsion time course and than collects tracks by tracking droplets.

Parameters
• storage (StorageBase) – The phase fields for many time instances

• refine (bool) – Flag determining whether the droplet properties should be refined using fitting. This is a potentially slow procedure.

• method (str) – The method used for tracking droplet identities. Possible methods are “overlap” (adding droplets that overlap with those in previous frames) and “distance” (matching droplets to minimize center-to-center distances).

• progress (bool) – Whether to show the progress of the process. If None, the progress is not shown, except for the first step if refine is True.

Returns

the resulting droplet tracks

Return type

DropletTrackList

plot(attribute: str = 'radius', *args, title: str = None, filename: str = None, action: str = 'auto', ax_style: Optional[Dict[str, Any]] = None, fig_style: Optional[Dict[str, Any]] = None, ax=None, **kwargs) PlotReference[source]

plot the time evolution of all droplets

Parameters
• attribute (str) – The attribute to plot. Typical values include radius and volume, but others might be defined on the droplet class.

• title (str) – Title of the plot. If omitted, the title might be chosen automatically.

• filename (str, optional) – If given, the plot is written to the specified file.

• action (str) – Decides what to do with the final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given. The default value auto implies that the plot is shown if it is not a nested plot call.

• ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item in this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

• fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

• ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

• **kwargs – Additional keyword arguments are passed to the matplotlib plot function to affect the appearance. The special value color=”cycle” implies that the default color cycle is used for the tracks, using different colors for different tracks.

Returns

Return type

PlotReference

plot_positions(*args, title: str = None, filename: str = None, action: str = 'auto', ax_style: Optional[Dict[str, Any]] = None, fig_style: Optional[Dict[str, Any]] = None, ax=None, **kwargs) PlotReference[source]

plot all droplet tracks

Parameters
• title (str) – Title of the plot. If omitted, the title might be chosen automatically.

• filename (str, optional) – If given, the plot is written to the specified file.

• action (str) – Decides what to do with the final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given. The default value auto implies that the plot is shown if it is not a nested plot call.

• ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item in this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

• fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

• ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

• **kwargs – Additional keyword arguments are passed to the matplotlib plot function to affect the appearance.

Returns

Return type

PlotReference

remove_short_tracks(min_duration: float = 0) None[source]

remove tracks that a shorter than a minimal duration

Parameters

min_duration (float) – The minimal duration a droplet track must have in order to be retained. This is measured in actual time and not in the number of time steps stored in the track.

to_file(path: str, info: Optional[Dict[str, Any]] = None) None[source]

store data in hdf5 file

The data can be read using the classmethod DropletTrackList.from_file().

Parameters
• path (str) – The path to which the data is written as an HDF5 file.

• info (dict) – Additional data stored alongside the droplet track list

## droplets.droplets module¶

Classes representing (perturbed) droplets in various dimensions

 SphericalDroplet Represents a single, spherical droplet DiffuseDroplet Represents a single, spherical droplet with a diffuse interface PerturbedDroplet2D Represents a single droplet in two dimensions with a perturbed shape PerturbedDroplet3D Represents a single droplet in two dimensions with a perturbed shape

Inheritance structure of the classes:

The details of the classes are explained below:

class DiffuseDroplet(position: ndarray, radius: float, interface_width: float = None)[source]

Represents a single, spherical droplet with a diffuse interface

Parameters
• position (ndarray) – Position of the droplet center

• interface_width (float, optional) – Width of the interface

data: recarray
property data_bounds: Tuple[ndarray, ndarray]

lower and upper bounds on the parameters

Type

tuple

classmethod get_dtype(**kwargs)[source]

determine the dtype representing this droplet class

Parameters

position (ndarray) – The position vector of the droplet. This is used to determine the space dimension.

Returns

the (structured) dtype associated with this class

Return type

numpy.dtype

property interface_width: Optional[float]

the width of the interface of this droplet

Type

float

class PerturbedDroplet2D(position: ndarray, radius: float, interface_width: float = None, amplitudes: = None)[source]

Bases: PerturbedDropletBase

Represents a single droplet in two dimensions with a perturbed shape

The shape is described using the distance $$R(\phi)$$ of the interface from the position, which is a function of the polar angle $$\phi$$. This function is expressed as a truncated series of harmonics:

$R(\phi) = R_0 + R_0\sum_{n=1}^N \left[ \epsilon^{(1)}_n \sin(n \phi) + \epsilon^{(2)}_n \cos(n \phi) \right]$

where $$N$$ is the number of perturbation modes considered, which is given by half the length of the amplitudes array. Consequently, amplitudes should always be an even number, to consider both sin and cos terms.

Parameters
• position (ndarray) – Position of the droplet center

• interface_width (float, optional) – Width of the interface

• amplitudes (ndarray) – (dimensionless) perturbation amplitudes $$\{\epsilon^{(1)}_1, \epsilon^{(2)}_1, \epsilon^{(1)}_2, \epsilon^{(2)}_2, \epsilon^{(1)}_3, \epsilon^{(2)}_3, \dots \}$$. The length of the array needs to be even to capture perturbations of the highest mode consistently.

data: recarray
dim = 2
interface_curvature(φ)[source]

calculates the mean curvature of the interface of the droplet

For simplicity, the effect of the perturbations are only included to linear order in the perturbation amplitudes $$\epsilon^{(1/2)}_n$$.

Parameters

φ (float or array) – The angle in the polar coordinate system that is used to describe the interface

Returns

An array with the curvature at the interfacial points associated with each angle given by φ.

interface_distance(φ)[source]

calculates the distance of the droplet interface to the origin

Parameters

φ (float or array) – The angle in the polar coordinate system that is used to describe the interface

Returns

An array with the distances of the interfacial points associated with each angle given by φ.

interface_position(φ)[source]

calculates the position of the interface of the droplet

Parameters

φ (float or array) – The angle in the polar coordinate system that is used to describe the interface

Returns

An array with the coordinates of the interfacial points associated with each angle given by φ.

property surface_area: float

surface area of the droplet

Type

float

property surface_area_approx: float

surface area of the droplet (quadratic in amplitudes)

Type

float

property volume: float

volume of the droplet

Type

float

class PerturbedDroplet3D(position: ndarray, radius: float, interface_width: float = None, amplitudes: = None)[source]

Bases: PerturbedDropletBase

Represents a single droplet in two dimensions with a perturbed shape

The shape is described using the distance $$R(\theta, \phi)$$ of the interface from the origin as a function of the azimuthal angle $$\theta$$ and the polar angle $$\phi$$. This function is developed as a truncated series of spherical harmonics $$Y_{l,m}(\theta, \phi)$$:

$R(\theta, \phi) = R_0 \left[1 + \sum_{l=1}^{N_l}\sum_{m=-l}^l \epsilon_{l,m} Y_{l,m}(\theta, \phi) \right]$

where $$N_l$$ is the number of perturbation modes considered, which is deduced from the length of the amplitudes array.

Parameters
• position (ndarray) – Position of the droplet center

• interface_width (float, optional) – Width of the interface

• amplitudes (ndarray) – Perturbation amplitudes $$\epsilon_{l,m}$$. Note that the zero-th mode, which would only change the radius, is skipped. Consequently, the length of the array needs to be 0, 3, 8, 15, 24, … to capture perturbations of the highest mode consistently.

data: recarray
dim = 3
interface_curvature(θ, φ)[source]

calculates the mean curvature of the interface of the droplet

For simplicity, the effect of the perturbations are only included to linear order in the perturbation amplitudes $$\epsilon_{l,m}$$.

Parameters
• θ (float or array) – Azimuthal angle (in $$[0, \pi]$$)

• φ (float or array) – Polar angle (in $$[0, 2\pi]$$)

Returns

An array with the curvature at the interfacial points associated with the angles

interface_distance(θ, φ)[source]

calculates the distance of the droplet interface to the origin

Parameters
• θ (float or array) – Azimuthal angle (in $$[0, \pi]$$)

• φ (float or array) – Polar angle (in $$[0, 2\pi]$$)

Returns

An array with the distances of the interfacial points associated with the angles.

interface_position(θ, φ)[source]

calculates the position of the interface of the droplet

Parameters
• θ (float or array) – Azimuthal angle (in $$[0, \pi]$$)

• φ (float or array) – Polar angle (in $$[0, 2\pi]$$)

Returns

An array with the coordinates of the interfacial points associated with the angles.

property volume: float

volume of the droplet (determined numerically)

Type

float

property volume_approx: float

approximate volume to linear order in the perturbation

Type

float

Bases: DropletBase

Represents a single, spherical droplet

Parameters
property bbox: Cuboid

bounding box of the droplet

Type

Cuboid

check_data()[source]

method that checks the validity and consistency of self.data

data: recarray
property data_bounds: Tuple[ndarray, ndarray]

lower and upper bounds on the parameters

Type

tuple

property dim: int

the spatial dimension this droplet is embedded in

Type

int

classmethod from_volume(position: ndarray, volume: float)[source]

Parameters
• position (ndarray) – center of the droplet

• volume (float) – volume of the droplet

• interface_width (float, optional) – width of the interface

classmethod get_dtype(**kwargs)[source]

determine the dtype representing this droplet class

Parameters

position (ndarray) – The position vector of the droplet. This is used to determine the space dimension.

Returns

the (structured) dtype associated with this class

Return type

numpy.dtype

get_phase_field(grid: GridBase, *, vmin: float = 0, vmax: float = 1, label: str = None) [source]

Creates an image of the droplet on the grid

Parameters
• grid (GridBase) – The grid used for discretizing the droplet phase field

• vmin (float) – Minimal value the phase field will attain (far away from droplet)

• vmax (float) – Maximal value the phase field will attain (inside the droplet)

• label (str) – The label associated with the returned scalar field

Returns

A scalar field representing the droplet

Return type

ScalarField

get_triangulation(resolution: float = 1) Dict[str, Any][source]

obtain a triangulated shape of the droplet surface

Parameters

resolution (float) – The length of a typical triangulation element. This affects the resolution of the triangulation.

Returns

A dictionary containing information about the triangulation. The exact details depend on the dimension of the problem.

Return type

dict

property interface_curvature: float

the mean curvature of the interface of the droplet

Type

float

interface_position(*args) [source]

calculates the position of the interface of the droplet

Parameters

*args (float or ndarray) – The angles identifying the interface points. For 2d droplets, this is simply the angle in polar coordinates. For 3d droplets, both the azimuthal angle θ (in $$[0, \pi]$$) and the polar angle φ (in $$[0, 2\pi]$$) need to be specified.

Returns

An array with the coordinates of the interfacial points associated with each angle given by φ.

Return type

ndarray

Raises

ValueError – If the dimension of the space is not 2

overlaps(other: SphericalDroplet, grid: Optional[GridBase] = None) bool[source]

determine whether another droplet overlaps with this one

Note that this function so far only compares the distances of the droplets to their radii, which does not respect perturbed droplets correctly.

Parameters
• other (SphericalDroplet) – instance of the other droplet

• grid (GridBase) – grid that determines how distances are measured, which is for instance important to respect periodic boundary conditions. If omitted, an Eucledian distance is assumed.

Returns

whether the droplets overlap or not

Return type

bool

plot(value: Callable = None, *args, title: str = None, filename: str = None, action: str = 'auto', ax_style: Optional[Dict[str, Any]] = None, fig_style: Optional[Dict[str, Any]] = None, ax=None, **kwargs) PlotReference[source]

Plot the droplet

Parameters
• title (str) – Title of the plot. If omitted, the title might be chosen automatically.

• filename (str, optional) – If given, the plot is written to the specified file.

• action (str) – Decides what to do with the final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given. The default value auto implies that the plot is shown if it is not a nested plot call.

• ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item in this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

• fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

• ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

• value (callable) – Sets the color of the droplet. This could be either a matplotlib color or a function that takes the droplet instance and returns a color in which this droplet is drawn. If given, it overwrites the color argument.

• **kwargs – Additional keyword arguments are passed to the class that creates the patch that represents the droplet. For instance, to only draw the outlines of the droplets, you may need to supply fill=False.

Returns

Return type

PlotReference

property position: ndarray

the position of the droplet

Type

ndarray

Type

float

property surface_area: float

surface area of the droplet

Type

float

property volume: float

volume of the droplet

Type

float

## droplets.emulsions module¶

Classes that describe collections of droplets, i.e. emulsions, and their temporal dynamics.

 Emulsion class representing a collection of droplets in a common system EmulsionTimeCourse represents emulsions as a function of time
class Emulsion(droplets: = None, grid: Optional[GridBase] = None, copy: bool = True)[source]

Bases: list

class representing a collection of droplets in a common system

Parameters
• droplets – A list or generator of instances of SphericalDroplet.

• grid (GridBase) – The grid on which the droplets are defined. This information can helpful to measure distances between droplets correctly.

• copy (bool, optional) – Whether to make a copy of the droplet or not

append(droplet: SphericalDroplet, copy: bool = True) None[source]

add a droplet to the emulsion

Parameters
• droplet (droplets.dropelts.SphericalDroplet) – Droplet to add to the emulsion

• copy (bool, optional) – Whether to make a copy of the droplet or not

property bbox: Cuboid

bounding box of the emulsion

Type

Cuboid

copy(min_radius: float = - 1) [source]

return a copy of this emulsion

Parameters

min_radius (float) – The minimal radius of the droplets that are retained. Droplets with exactly min_radius are removed, so min_radius == 0 can be used to filter vanished droplets.

property data: Optional[ndarray]

an array containing the data of the full emulsion

This requires all droplets to be of the same class

Type

ndarray

extend(droplets: , copy: bool = True) None[source]

add many droplets to the emulsion

Parameters
• droplets (list) – List of droplets to add to the emulsion

• copy (bool, optional) – Whether to make a copy of the droplets or not

classmethod from_file(path: str) [source]

Parameters

path (str) – The path from which the data is read. This function assumes that the data was written as an HDF5 file using to_file().

link the data of all droplets in a single array

Returns

The array containing all droplet data. If entries in

this array are modified, it will be reflected in the droplets.

Return type

ndarray

calculates the distance of each droplet to its nearest neighbor

Warning: Nearest neighbors are defined by comparing the distances between the centers of the droplets, not their surfaces.

Parameters

subtract_radius (bool) – Determines whether to subtract the radius from the distance, i.e., whether to return the distance between the surfaces instead of the positions

Returns

a vector with a distance for each droplet

Return type

ndarray

return the pairwise distance between droplets

Parameters

subtract_radius (bool) – determines whether the distance is measured from interface to interface (for round droplets) or center to center.

Returns

a matrix with the distances between all droplets

Return type

ndarray

get_phasefield(grid: Optional[GridBase] = None, label: str = None) [source]

create a phase field representing a list of droplets

Parameters
• grid (pde.grids.base.GridBase) – The grid on which the phase field is created. If omitted, the grid associated with the emulsion is used.

• label (str) – Optional label for the returned scalar field

Returns

the actual phase field

Return type

ScalarField

get_size_statistics() Dict[str, float][source]

determine size statistics of the current emulsion

Returns

a dictionary with various size statistics

Return type

dict

property interface_width: Optional[float]

the average interface width across all droplets

This averages the interface widths of the individual droplets weighted by their surface area, i.e., the amount of interface

Type

float

plot(field: ScalarField = None, image_args: dict = None, repeat_periodically: bool = True, color_value: Callable = None, cmap=None, norm=None, colorbar: Union[bool, str] = True, *args, title: str = None, filename: str = None, action: str = 'auto', ax_style: Optional[Dict[str, Any]] = None, fig_style: Optional[Dict[str, Any]] = None, ax=None, **kwargs) PlotReference[source]

plot the current emulsion together with a corresponding field

If the emulsion is defined in a 3d geometry, only a projection on the first two axes is shown.

Parameters
• title (str) – Title of the plot. If omitted, the title might be chosen automatically.

• filename (str, optional) – If given, the plot is written to the specified file.

• action (str) – Decides what to do with the final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given. The default value auto implies that the plot is shown if it is not a nested plot call.

• ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item in this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

• fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

• ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

• field (pde.fields.scalar.ScalarField) – provides the phase field that is shown as a background

• image_args (dict) – additional arguments determining how the phase field in the background is plotted. Acceptable arguments are described in plot().

• repeat_periodically (bool) – flag determining whether droplets are shown on both sides of periodic boundary conditions. This option can slow down plotting

• color_value (callable) – Function used to determine the color of a droplet. The function is called with individual droplet objects and must return a single scalar value, which is then mapped to a color using the colormap given by cmap and a suitable normalization given by norm.

• cmap (str or Colormap) – The colormap used to map normalized data values to RGBA colors.

• norm (Normalize) – The normalizing object which scales data, typically into the interval [0, 1]. If None, norm defaults to a colors.Normalize object which maps the range of values obtained from color_value to [0, 1].

• colorbar (bool or str) – Determines whether a colorbar is shown when color_value is supplied. If a string is given, it is used as a label for the colorbar.

• **kwargs – Additional keyword arguments are passed to the function creating the patch that represents the droplet. For instance, to only draw the outlines of the droplets, you may need to supply fill=False.

Returns

Return type

PlotReference

remove_overlapping(min_distance: float = 0) None[source]

remove all droplets that are overlapping.

If a pair of overlapping droplets was found, the smaller one of these is removed from the current emulsion. This method modifies the emulsion in place and thus does not return anything.

Parameters

min_distance (float) – The minimal distance droplets need to be apart. The default value of 0 corresponds to just remove overlapping droplets. Larger values ensure that droplets keep a distance, while negative values allow for some overlap.

remove_small(min_radius: float = - inf) None[source]

remove droplets that are very small

The emulsions is modified in-place.

Parameters

min_radius (float) – The minimal radius of the droplets that are retained. Droplets with exactly min_radius are removed, so min_radius == 0 can be used to filter vanished droplets. The default value does not remove any droplets

to_file(path: str) None[source]

store data in hdf5 file

The data can be read using the classmethod Emulsion.from_file().

Parameters

path (str) – The path to which the data is written as an HDF5 file.

property total_droplet_volume: float

the total volume of all droplets

Type

float

class EmulsionTimeCourse(emulsions=None, times=None)[source]

Bases: object

represents emulsions as a function of time

Parameters
• emulsions (list) – List of emulsions that describe this time course

• times (list) – Times associated with the emulsions

append(emulsion: Emulsion, time: float = None, copy: bool = True) None[source]

add an emulsion to the list

Parameters
• emulsions (Emulsion) – An Emulsion instance that is added to the time course

• time (float) – The time point associated with this emulsion

• copy (bool) – Whether to copy the emulsion

clear() None[source]

removes all data stored in this instance

classmethod from_file(path: str, progress: bool = True) [source]

create emulsion time course by reading file

Parameters
• path (str) – The path from which the data is read. This function assumes that the data was written as an HDF5 file using to_file().

• progress (bool) – Whether to show the progress of the process in a progress bar

Returns

an instance describing the emulsion time course

Return type

EmulsionTimeCourse

classmethod from_storage(storage: StorageBase, refine: bool = False, progress: = None, **kwargs) [source]

create an emulsion time course from a stored phase field

Parameters
• storage (StorageBase) – The phase fields for many time instances

• refine (bool) – Flag determining whether the droplet properties should be refined using fitting. This is a potentially slow procedure.

• progress (bool) – Whether to show the progress of the process. If None, the progress is only shown when refine is True.

• **kwargs – All other parameters are forwarded to the locate_droplets().

Returns

an instance describing the emulsion time course

Return type

EmulsionTimeCourse

items()[source]

iterate over all times and emulsions, returning them in pairs

to_file(path: str, info: Optional[Dict[str, Any]] = None) None[source]

store data in hdf5 file

The data can be read using the classmethod EmulsionTimeCourse.from_file().

Parameters
• path (str) – The path to which the data is written as an HDF5 file.

• info (dict) – Additional data stored alongside the droplet track list

tracker(interval: Union[int, float, ConstantIntervals] = 1, filename: str = None) [source]

return a tracker that analyzes emulsions during simulations

Parameters
• interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in intervals can be given for more control.

• filename (str) – determines where the EmulsionTimeCourse data is stored

## droplets.image_analysis module¶

Functions for analyzing phase field images of emulsions.

 locate_droplets Locates droplets in the phase field refine_droplet Refines droplet parameters by fitting to phase field get_structure_factor Calculates the structure factor associated with a field get_length_scale Calculates a length scale associated with a phase field
get_length_scale(scalar_field: ScalarField, method: str = 'structure_factor_maximum', **kwargs) Union[float, Tuple[float, Any]][source]

Calculates a length scale associated with a phase field

Parameters
• scalar_field (ScalarField) – The scala field being analyzed

• method (str) – A string determining which method is used to calculate the length scale. Valid options are structure_factor_maximum (numerically determine the maximum in the structure factor) and structure_factor_mean (calculate the mean of the structure factor).

Additional supported keyword arguments depend on the chosen method. For instance, the methods involving the structure factor allow for a boolean flag full_output, which also returns the actual structure factor. The method structure_factor_maximum also allows for some smoothing of the radially averaged structure factor. If the parameter smoothing is set to None the amount of smoothing is determined automatically from the typical discretization of the underlying grid. For the method droplet_detection, additional arguments are forwarded to locate_droplets().

Returns

The determine length scale

If full_output = True, a tuple with the length scale and an additional object with further information is returned.

Return type

float

LengthScaleTracker: Tracker measuring length scales

get_structure_factor(scalar_field: ScalarField, smoothing: = 'auto', wave_numbers: = 'auto', add_zero: bool = False) [source]

Calculates the structure factor associated with a field

Here, the structure factor is basically the power spectral density of the field scalar_field normalized so that re-gridding or rescaling the field does not change the result.

Parameters
• scalar_field (ScalarField) – The scalar_field being analyzed

• smoothing (float, optional) – Length scale that determines the smoothing of the radially averaged structure factor. If omitted, the full data about the discretized structure factor is returned. The special value auto calculates a value automatically.

• wave_numbers (list of floats, optional) – The magnitude of the wave vectors at which the structure factor is evaluated. This only applies when smoothing is used. If auto, the wave numbers are determined automatically.

• add_zero (bool) – Determines whether the value at k=0 (defined to be 1) should also be returned.

Returns

Two arrays giving the wave numbers and the associated structure factor

Return type
locate_droplets(phase_field: ScalarField, threshold: = 0.5, modes: int = 0, minimal_radius: float = 0, refine: bool = False, interface_width: float = None) [source]

Locates droplets in the phase field

This uses a binarized image to locate clusters of large concentration in the phase field, which are interpreted as droplets. Basic quantities, like position and size, are determined for these clusters.

Parameters
• phase_field (ScalarField) – Scalar field that describes the concentration field of droplets

• threshold (float or str) –

The threshold for binarizing the image. If a value is given it is used directly. Otherwise, the following algorithms are supported:

• extrema: take mean between the minimum and the maximum of the data

• mean: take the mean over the entire data

• otsu: use Otsu’s method implemented in threshold_otsu()

The special value auto currently defaults to the extrema method.

• modes (int) – The number of perturbation modes that should be included. If modes=0, droplets are assumed to be spherical. Note that the mode amplitudes are only determined when refine=True.

• minimal_radius (float) – The smallest radius of droplets to include in the list. This can be used to filter out fluctuations in noisy simulations.

• refine (bool) – Flag determining whether the droplet properties should be refined using fitting. This is a potentially slow procedure.

• interface_width (float, optional) – Interface width of the located droplets, which is also used as a starting value for the fitting if droplets are refined.

Returns

All detected droplets

Return type

Emulsion

refine_droplet(phase_field: ScalarField, droplet: DiffuseDroplet, least_squares_params: Optional[Dict[str, Any]] = None) [source]

Refines droplet parameters by fitting to phase field

This function varies droplet parameters, like position, size, interface width, and potential perturbation amplitudes until the overlap with the respective phase field region is maximized. Here, we use a constraint fitting routine.

Parameters
• phase_field (ScalarField) – Phase_field that is being used to refine the droplet

• droplet (SphericalDroplet) – Droplet that should be refined. This could also be a subclass of SphericalDroplet

• least_squares_params (dict) – Dictionary of parameters that influence the fitting; see the documentation of scipy.optimize.least_squares

Returns

The refined droplet as an instance of the argument droplet

Return type

droplets.droplets.DiffuseDroplet

threshold_otsu(data: ndarray, nbins: int = 256) [source]

Find the threshold value for a bimodal histogram using the Otsu method.

If you have a distribution that is bimodal, i.e., with two peaks and a valley between them, then you can use this to find the location of that valley, which splits the distribution into two.

Parameters
• data (ndarray) – The data to be analyzed

• nbins (int) – The number of bins in the histogram, which defines the accuracy of the determined threshold.

Modified from https://stackoverflow.com/a/71345917/932593, which is based on the the SciKit Image threshold_otsu implementation: https://github.com/scikit-image/scikit-image/blob/70fa904eee9ef370c824427798302551df57afa1/skimage/filters/thresholding.py#L312

## droplets.trackers module¶

Module defining classes for tracking droplets in simulations.

 LengthScaleTracker Tracker that stores length scales measured in simulations DropletTracker Detect droplets in a scalar field during simulations
class DropletTracker(interval: Union[ConstantIntervals, float, int, str] = 1, filename: str = None, *, emulsion_timecourse=None, source: = None, threshold: = 0.5, minimal_radius: float = 0, refine: bool = False, perturbation_modes: int = 0)[source]

Bases: TrackerBase

Detect droplets in a scalar field during simulations

This tracker is useful when only the parameters of actual droplets are needed, since it stores considerably less information compared to the full scalar field.

data

Contains the data of the tracked droplets after the simulation is done.

Type

EmulsionTimeCourse

Parameters
• interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in intervals can be given for more control.

• filename (str, optional) – Determines the file to which the final data is written as an HDF5 file.

• emulsion_timecourse (EmulsionTimeCourse, optional) – Can be an instance of EmulsionTimeCourse that is used to store the data.

• source (int or callable, optional) – Determines how a field is extracted from fields. If None, fields is passed as is, assuming it is already a scalar field. This works for the simple, standard case where only a single ScalarField is treated. Alternatively, source can be an integer, indicating which field is extracted from an instance of FieldCollection. Lastly, source can be a function that takes fields as an argument and returns the desired field.

• threshold (float or str) – The threshold for binarizing the image. The special value ‘auto’ takes the mean between the minimum and the maximum of the data as a guess.

• minimal_radius (float) – Minimal radius of droplets that will be retained.

• refine (bool) – Flag determining whether the droplet coordinates should be refined using fitting. This is a potentially slow procedure.

• perturbation_modes (int) – An option describing how many perturbation modes should be considered when refining droplets.

finalize(info: Optional[Dict[str, Any]] = None) None[source]

finalize the tracker, supplying additional information

Parameters

info (dict) – Extra information from the simulation

handle(field: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
initialize(field: FieldBase, info: Optional[Dict[str, Any]] = None) [source]
Parameters
• field (FieldBase) – An example of the data that will be analyzed by the tracker

• info (dict) – Extra information from the simulation

Returns

The first time the tracker needs to handle data

Return type

float

class LengthScaleTracker(interval: Union[ConstantIntervals, float, int, str] = 1, filename: str = None, *, method: str = 'structure_factor_mean', source: = None, verbose: bool = False)[source]

Bases: TrackerBase

Tracker that stores length scales measured in simulations

times

The time points at which the length scales are stored

Type

list

length_scales

The associated length scales

Type

list

Parameters
• interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in intervals can be given for more control.

• filename (str, optional) – Determines the file to which the data is written in JSON format

• method (str) – Method used for determining the length scale. Details are explained in the function get_length_scale().

• source (int or callable, optional) – Determines how a field is extracted from fields. If None, fields is passed as is, assuming it is already a scalar field. This works for the simple, standard case where only a single ScalarField is treated. Alternatively, source can be an integer, indicating which field is extracted from an instance of FieldCollection. Lastly, source can be a function that takes fields as an argument and returns the desired field.

• verbose (bool) – Determines whether errors in determining the length scales are logged.

finalize(info: Optional[Dict[str, Any]] = None) None[source]

finalize the tracker, supplying additional information

Parameters

info (dict) – Extra information from the simulation

handle(field: FieldBase, t: float)[source]

handle data supplied to this tracker

Parameters
• field (FieldBase) – The current state of the simulation

• t (float) – The associated time

## droplets.version module¶

Contains the version information of the package