This page was built from the example_notebook Jupyter notebook available on Github

How to use

These pages will outline basic usage of DefDAP, including loading a DIC and EBSD map, linking them with homologous points and producing maps

Load in packages

DefDAP is split into modules for processing EBSD (defdap.ebsd) and HRDIC (defdap.hrdic) data. There are also modules for manpulating orientations (defdap.quat) and creating custom figures (defdap.plotting) which is introduced later. We also import some of the usual suspects of the python scientific stack: numpy and matplotlib.

import numpy as np
import matplotlib.pyplot as plt

import defdap.hrdic as hrdic
import defdap.ebsd as ebsd
from defdap.quat import Quat

# try tk, qt, osx (if using mac) or notebook for interactive plots. If none work, use inline
%matplotlib inline
%cd -q ../../

Load in a HRDIC map

dicFilePath = "tests/data/"
dicMap = hrdic.Map(dicFilePath, "testDataDIC.txt")
Loaded DaVis 8.4.0 data (dimensions: 300 x 200 pixels, sub-window size: 12 x 12 pixels)

Set the scale of the map

This is defined as the pixel size in the DIC pattern images, measured in microns per pixel.

fieldWidth = 20 # microns
numPixels = 2048
pixelSize = fieldWidth / numPixels


Plot the map with a scale bar

dicMap.plotMaxShear(vmin=0, vmax=0.10, plotScaleBar=True)
<defdap.plotting.MapPlot at 0x7f3817918050>

Crop the map

HRDIC maps often contain spurious data at the edges which should be removed before performing any analysis. The crop is defined by the number of points to remove from each edge of the map, where xMin, xMax, yMin and yMax are the left, right, top and bottom edges respectively. Note that the test data doesn not require cropping as it is a subset of a larger dataset.

dicMap.setCrop(xMin=0, xMax=0, yMin=0, yMax=0)


Some simple statistics such as the minimum, mean and maximum of the effective shear strain, E11 and E22 components can be printed.

dicMap.printStatsTable(percentiles=[0, 50, 100], components = ['max_shear', 'e'])
dicMap (dimensions: 300 x 200 pixels, sub-window size: 12 x 12 pixels, number of points: 60000)

Component             0          50         100
max_shear        0.0000      0.0085      0.0910
e11             -0.1083     -0.0097      0.0168
e12             -0.0478      0.0005      0.0630
e21             -0.0478      0.0005      0.0630
e22             -0.0493      0.0045      0.0850

Set the location of the DIC pattern images

The pattern images are used later to define the position of homologous material points. The path is relative to the directory set when loading in the map. The second parameter is the pixel binning factor of the image relative to the DIC sub-region size i.e. the number of pixels in the image across a single datapoint in the DIC map. We recommend binning the pattern images by the same factor as the DIC sub-region size, doing so enhances the contrast between microstructure features.

# set the path of the pattern image, this is relative to the location of the DIC data file
dicMap.setPatternPath("testDataPat.bmp", 1)
AttributeError                            Traceback (most recent call last)
<ipython-input-7-632d4e481b5c> in <module>
      1 # set the path of the pattern image, this is relative to the location of the DIC data file
----> 2 dicMap.setPatternPath("testDataPat.bmp", 1)

AttributeError: 'Map' object has no attribute 'setPatternPath'

Load in an EBSD map

Currently, OxfordBinary (a .crc and .cpr file pair), OxfordText (.ctf file), EdaxAng (.ang file) or PythonDict (Python dictionary) filetypes are supported. The crystal structure and slip systems are automatically loaded for each phase in the map. The orientation in the EBSD are converted to a quaternion representation so calculations can be applied later.

ebsdFilePath = "tests/data/testDataEBSD"

ebsdMap = ebsd.Map(ebsdFilePath, dataType = 'OxfordBinary')
Loaded EBSD data (dimensions: 359 x 243 pixels, step size: 0.12 um)
Finished building quaternion array (0:00:00)

A list of detected phases and crystal structures can be printed

for i, phase in enumerate(ebsdMap.phases):
Phase: Ni-superalloy
  Crystal structure: cubic
  Lattice params: (3.57, 3.57, 3.57, 90, 90, 90)
  Slip systems: cubic_fcc

A list of the slip planes, colours and slip directions can be printed

Plane 0: (111)  Colour: blue
  Direction 0: [011̅]
  Direction 1: [1̅01]
  Direction 2: [11̅0]
Plane 1: (111̅) Colour: green
  Direction 0: [011]
  Direction 1: [1̅01̅]
  Direction 2: [11̅0]
Plane 2: (1̅11) Colour: red
  Direction 0: [011̅]
  Direction 1: [101]
  Direction 2: [1̅1̅0]
Plane 3: (11̅1) Colour: white
  Direction 0: [01̅1̅]
  Direction 1: [1̅01]
  Direction 2: [110]

Plot the EBSD map

Using an Euler colour mapping or inverse pole figure colouring with the sample reference direction passed as a vector.

<defdap.plotting.MapPlot at 0x7f38173df390>
ebsdMap.plotIPFMap([1,0,0], plotScaleBar=True)
Finished building quaternion array (0:00:00)
<defdap.plotting.MapPlot at 0x7f381738c750>

A KAM map can also be plotted as follows

ebsdMap.plotKamMap(vmin=0, vmax=1)
AttributeError                            Traceback (most recent call last)
<ipython-input-13-39888d787fa4> in <module>
----> 1 ebsdMap.plotKamMap(vmin=0, vmax=1)

AttributeError: 'Map' object has no attribute 'plotKamMap'

Detect grains in the EBSD

This is done in two stages: first bounaries are detected in the map as any point with a misorientation to a neighbouring point greater than a critical value (boundDef in degrees). A flood fill type algorithm is then applied to segment the map into grains, with any grains containining fewer than a critical number of pixels removed (minGrainSize in pixels). The data e.g. orientations associated with each grain are then stored (referenced strictly, the data isn’t stored twice) in a grain object and a list of the grains is stored in the EBSD map (named grainList). This allows analysis routines to be applied to each grain in a map in turn.

Finished finding grain boundaries (0:00:00)
Finished finding grains (0:00:00)

The Schmid factors for each grain can be calculated and plotted. The slipSystems argument can be specified, to only calculate the Schmid factor for certain planes, otherwise the maximum for all slip systems is calculated.

ebsdMap.calcAverageGrainSchmidFactors(loadVector=np.array([1,0,0]), slipSystems=None)
Finished calculating grain average Schmid factors (0:00:01)
<defdap.plotting.MapPlot at 0x7f380fd2c950>

Single grain analysis

The locateGrainID method allows interactive selection of a grain of intereset to apply any analysis to. Clicking on grains in the map will highlight the grain and print out the grain ID (position in the grain list) of the grain.

<defdap.plotting.MapPlot at 0x7f3817d85c10>

A built-in example is to calculate the average orientation of the grain and plot this orientation in a IPF

grainID = 48
grain = ebsdMap[grainID]
grain.calcAverageOri()  # stored as a quaternion named grain.refOri
grain.plotRefOri(direction=[0, 0, 1])
[0.3393, 0.1397, 0.4032, 0.8383]
<defdap.plotting.PolePlot at 0x7f380fc30510>

The spread of orientations in a given grain can also be plotted on an IPF

plot = grain.plotOriSpread(direction=np.array([0, 0, 1]), c='b', s=1, alpha=0.2)
grain.plotRefOri(direction=[0, 0, 1], c='k', plot=plot)
<defdap.plotting.PolePlot at 0x7f380fb24550>

The unit cell for the average grain orientation can also be ploted

<defdap.plotting.CrystalPlot at 0x7f380fab8550>

Printing a list of the slip plane indices, angle of slip plane intersection with the screen (defined as counter-clockwise from upwards), colour defined for the slip plane and also the slip directions and corresponding Schmid factors, is also built in

(111)   Colour: blue    Angle: 55.77
  [011̅]   SF: 0.026
  [1̅01]   SF: 0.025
  [11̅0]   SF: 0.051
(111̅)  Colour: green   Angle: 89.67
  [011]   SF: 0.003
  [1̅01̅]   SF: 0.003
  [11̅0]   SF: 0.006
(1̅11)  Colour: red     Angle: 29.68
  [011̅]   SF: 0.404
  [101]   SF: 0.432
  [1̅1̅0]   SF: 0.027
(11̅1)  Colour: white   Angle: 152.39
  [01̅1̅]   SF: 0.381
  [1̅01]   SF: 0.410
  [110]   SF: 0.029

A second built-in example is to calcuate the grain misorientation, specifically the grain reference orientation deviation (GROD). This shows another feature of the locateGrainID method, which stores the ID of the last selected grain in a variable called currGrainId in the EBSD map.

grain = ebsdMap[ebsdMap.currGrainId]
grain.plotMisOri(plotScaleBar=True, vmin=0, vmax=5)
TypeError                                 Traceback (most recent call last)
<ipython-input-22-363e0f2b0499> in <module>
----> 1 grain = ebsdMap[ebsdMap.currGrainId]
      2 grain.buildMisOriList()
      3 grain.plotMisOri(plotScaleBar=True, vmin=0, vmax=5)

~/checkouts/ in __getitem__(self, key)
     63         self.checkGrainsDetected()
---> 65         return self.grainList[key]
     67     @property

TypeError: list indices must be integers or slices, not NoneType

Multi grain analysis

Once an analysis routine has been prototyped for a single grain it can be applied to all the grains in a map using a loop over the grains and any results added to a list for use later. Of couse you could also apply to a smaller subset of grains as well.

grainAvOris = []
for grain in ebsdMap:

# Plot all the grain orientations in the map
Quat.plotIPF(grainAvOris, [0, 0, 1], ebsdMap.crystalSym, marker='o', s=10)

Some common grain analysis routines are built into the EBSD map object, including:

Finished calculating grain mean orientations (0:00:01)
ebsdMap.plotMisOriMap(vmin=0, vmax=5, plotGBs=True, plotScaleBar=True)
Finished calculating grain misorientations (0:00:00)
<defdap.plotting.MapPlot at 0x7f380fa12290>

There are also methods for plotting GND density, phases and boundaries. All of the plotting functions in DefDAP use the same parameters to modify the plot, examples seen so far are plotGBs, plotScaleBar, vmin, vmax.

Linking the HRDIC and EBSD

Define homologous points

To register the two datasets, homologous points (points at the same material location) within each map are used to estimate a transformation between the two frames the data are defined in. The homologous points are selected manually using an interactive tool within DefDAP. To select homologous call the method setHomogPoint on each of the data maps, which will open a plot window with a button labelled ‘save point’ in the bottom right. You select a point by right clicking on the map, adjust the position with the arrow and accept the point by with the save point button. Then select the same location in the other map. Note that as we set the location of the pattern image for the HRDIC map that the points can be selected on the pattern image rather than the strain data.

AttributeError                            Traceback (most recent call last)
<ipython-input-26-a4aeea9c6c07> in <module>
----> 1 dicMap.setHomogPoint(display="pattern")

~/checkouts/ in setHomogPoint(self, map_name, points, **kwargs)
    273         binning =, 'binning', 1)
--> 274         plot = self.plot_map(map_name, makeInteractive=True, **kwargs)
    276         # Plot stored homog points if there are any

~/checkouts/ in plot_map(self, map_name, component, **kwargs)
    758         map_data = self.crop(map_data, binning=binning)
--> 760         return MapPlot.create(self, map_data, **plot_params)
    762     def calcGrainAv(self, mapData, grainIds=-1):

~/checkouts/ in create(cls, callingMap, mapData, fig, figParams, ax, axParams, plot, makeInteractive, plotColourBar, vmin, vmax, cmap, clabel, plotGBs, dilateBoundaries, boundaryColour, plotScaleBar, scale, highlightGrains, highlightColours, highlightAlpha, **kwargs)
    668         if mapData is not None:
--> 669             plot.addMap(mapData, cmap=cmap, vmin=vmin, vmax=vmax, **kwargs)
    671         if plotColourBar:

~/checkouts/ in addMap(self, mapData, vmin, vmax, cmap, **kwargs)
    357         """
    358         img =, vmin=vmin, vmax=vmax,
--> 359                              interpolation='None', cmap=cmap, **kwargs)
    360         self.draw()

~/checkouts/ in wrapper(*args, **kwargs)
    454                 "parameter will become keyword-only %(removal)s.",
    455                 name=name, obj_type=f"parameter of {func.__name__}()")
--> 456         return func(*args, **kwargs)
    458     # Don't modify *func*'s signature, as needs it.

~/checkouts/ in inner(ax, data, *args, **kwargs)
   1410     def inner(ax, *args, data=None, **kwargs):
   1411         if data is None:
-> 1412             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1414         bound = new_sig.bind(ax, *args, **kwargs)

~/checkouts/ in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, interpolation_stage, filternorm, filterrad, resample, url, **kwargs)
   5438                               filterrad=filterrad, resample=resample,
   5439                               interpolation_stage=interpolation_stage,
-> 5440                               **kwargs)
   5442         im.set_data(X)

~/checkouts/ in __init__(self, ax, cmap, norm, interpolation, origin, extent, filternorm, filterrad, resample, interpolation_stage, **kwargs)
    937             resample=resample,
    938             interpolation_stage=interpolation_stage,
--> 939             **kwargs
    940         )

~/checkouts/ in __init__(self, ax, cmap, norm, interpolation, origin, filternorm, filterrad, resample, interpolation_stage, **kwargs)
    258         self._imcache = None
--> 260         self.update(kwargs)
    262     def __getstate__(self):

~/checkouts/ in update(self, props)
   1062                     func = getattr(self, f"set_{k}", None)
   1063                     if not callable(func):
-> 1064                         raise AttributeError(f"{type(self).__name__!r} object "
   1065                                              f"has no property {k!r}")
   1066                     ret.append(func(v))

AttributeError: 'AxesImage' object has no property 'display'

The points are stored as a list of tuples (x, y) in each of the maps. This means the points can be set from previous values.


Here are some example homologous points for this data, after setting these by running the cells below you can view the locations in the maps by running the setHomogPoint methods (above) again

dicMap.homogPoints = [
    (36, 72),
    (279, 27),
    (162, 174),
    (60, 157)
ebsdMap.homogPoints = [
    (68, 95),
    (308, 45),
    (191, 187),
    (89, 174)

Show the transformation

from skimage import transform as tf

data = np.zeros((2000, 2000), dtype=float)
data[500:1500, 500:1500] = 1.
dataWarped = tf.warp(data, dicMap.ebsdTransform)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,4))
<matplotlib.image.AxesImage at 0x7f380f29f850>

Segment into grains

The HRDIC map can now be segmented into grains using the grain boundaries detected in the EBSD map. Analysis rountines can then be applied to individual grain, as with the EBSD grains. The grain finding process will also attempt to link the grains between the EBSD and HRDIC and each grain in the HRDIC has a reference (ebsdGrain) to the corrosponding grain in the EBSD map.

Starting finding grains..
/home/docs/checkouts/ FutureWarning: in_place argument is deprecated and will be removed in version 1.0. To avoid this warning, please do not use the in_place argument. Please see remove_small_objects documentation for more details. Please use out argument instead.
Finished finding grains (0:00:00)
dicMap.plotMaxShear(vmin=0, vmax=0.1, plotScaleBar=True, plotGBs='line')
<defdap.plotting.MapPlot at 0x7f380e9bf310>

Now, a grain can also be selected interactively in the DIC map, in the same way a grain can be selected from an EBSD map. If displaySelected is set to true, then a pop-out window shows the map segmented for the grain

<defdap.plotting.MapPlot at 0x7f380e33e290>

Plotting examples

Some of the plotting features are shown in examples below.

Built-in plots

plot = dicMap.plotMaxShear(
    vmin=0, vmax=0.1, plotScaleBar=True,
    plotGBs=True, dilateBoundaries=True
plot = ebsdMap.plotEulerMap(
    plotScaleBar=True, plotGBs=True,
    highlightGrains=[10, 20, 45], highlightAlpha=0.9, highlightColours=['y']
dicGrainID = 41
dicGrain = dicMap[dicGrainID]

plot = dicGrain.plotMaxShear(
    plotScaleBar=True, plotSlipTraces=True, plotSlipBands=True
Number of bands detected: 2

IPF plotting

This plot will show the positions of selected grains in an IPF pole figure, with the marker size representing grain area and mean effective shear strain.

# For all grains in the DIC map

# Make an array of quaternions
grainOris = [grain.ebsdGrain.refOri for grain in dicMap]

# Make an array of grain area
grainAreas = np.array([len(grain) for grain in dicMap]) * dicMap.scale**2

# Scaling the grain area, so that the maximum size of a marker is 200 points^2
grainAreaScaling = 200. / grainAreas.max()

# Make an array of mean effective shear strain
grainStrains = [np.array(grain.maxShearList).mean() for grain in dicMap]

plot = Quat.plotIPF(grainOris, direction=[1,0,0], symGroup='cubic', marker='o',
                    s=grainAreas*grainAreaScaling, vmin=0, vmax=0.018, cmap='viridis', c=grainStrains)
plot.addColourBar(label='Mean Effective Shear Strain')
# For selected grains in the DIC map

# Select grains from the DIC map
dicGrainIDs = [2, 5, 7, 9, 15, 17, 18, 23, 29, 32, 33, 37, 40, 42, 49, 50, 51, 54, 58, 60]

# Make an array of quaternions
grainOris = np.array([dicMap[grainID].ebsdGrain.refOri for grainID in dicGrainIDs])

# Make an array of grain area
grainAreas = np.array([len(dicMap[grainID]) for grainID in dicGrainIDs]) * dicMap.scale**2

# Scaling the grain area, so that the maximum size of a marker is 200 points^2
grainAreaScaling = 200. / grainAreas.max()

# Make an array of mean effective shear strain
grainStrains = np.array([np.mean(dicMap[grain].maxShearList) for grain in dicGrainIDs])

plot = Quat.plotIPF(grainOris, direction=[1,0,0], symGroup='cubic', marker='o',
                    s=grainAreas*grainAreaScaling, vmin=0, vmax=0.018, cmap='viridis', c=grainStrains)
plot.addColourBar(label='Mean Effective Shear Strain')

Create your own

from defdap.plotting import MapPlot, GrainPlot, HistPlot
mapData =['e'][0,0]
mapData = dicMap.crop(mapData)

plot = MapPlot.create(
    dicMap, mapData,
    vmin=-0.1, vmax=0.1, plotColourBar=True, cmap="seismic",
    plotGBs=True, dilateBoundaries=True, boundaryColour='black'
/home/docs/checkouts/ FutureWarning: in_place argument is deprecated and will be removed in version 1.0. To avoid this warning, please do not use the in_place argument. Please see remove_small_objects documentation for more details. Please use out argument instead.

Functions for grain averaging and grain segmentation

plot = dicMap.plotGrainDataMap(
    vmin=-0.06, vmax=0.06, plotColourBar=True,
    cmap="seismic", clabel="Axial strain ($e_11$)",

plot.addGrainBoundaries(dilate=True, colour="white")
<matplotlib.image.AxesImage at 0x7f380e762450>
plot = dicMap.plotGrainDataIPF(
    np.array((1,0,0)), mapData, marker='o',
    vmin=-0.06, vmax=0.06, plotColourBar=True,
    clabel="Axial strain ($e_11$)", cmap="seismic",

dicGrainID = 41
dicGrain = dicMap[dicGrainID]

plot = dicGrain.plotGrainData(
    vmin=-0.1, vmax=0.1, plotColourBar=True,
    clabel="Axial strain ($e_11$)", cmap="seismic",


Composite plots

By utilising some additional functionality within matplotlib, composite plots can be produced.

from matplotlib import gridspec
# Create a figure with 3 sets of axes
fig = plt.figure(figsize=(8, 4))
gs = gridspec.GridSpec(2, 2, width_ratios=[3, 1],
                       wspace=0.15, hspace=0.15,
                       left=0.02, right=0.98,
                       bottom=0.12, top=0.95)
ax0 = plt.subplot(gs[:, 0])
ax1 = plt.subplot(gs[0, 1])
ax2 = plt.subplot(gs[1, 1])

# add a strain map
plot0 = dicMap.plotMaxShear(
    ax=ax0, fig=fig,
    vmin=0, vmax=0.08, plotScaleBar=True,
    plotGBs=True, dilateBoundaries=True

# add an IPF of grain orientations
dicOris = []
for grain in dicMap:
    if len(grain) > 20:
plot1 = Quat.plotIPF(
    dicOris, np.array((1,0,0)), 'cubic',
    ax=ax1, fig=fig, s=10

# add histrogram of strain values
plot2 = HistPlot.create(
    ax=ax2, fig=fig, marker='o', markersize=2,
    axesType="logy", bins=50, range=(0,0.06)
)"Effective shear strain")
/home/docs/checkouts/ FutureWarning: in_place argument is deprecated and will be removed in version 1.0. To avoid this warning, please do not use the in_place argument. Please see remove_small_objects documentation for more details. Please use out argument instead.
/home/docs/checkouts/ UserWarning: marker is redundantly defined by the 'marker' keyword argument and the fmt string "o" (-> marker='o'). The keyword argument will take precedence., yVals, line, label=label, **kwargs)
Text(0.5, 13.559999999999967, 'Effective shear strain')

Figures can be saved to raster (png, jpg, ..) and vector formats (eps, svg), the format is guessed from the file extension given. The last displayed figure can be saved using:

#plt.savefig("test_save_fig.png", dpi=200)
#plt.savefig("test_save_fig.eps", dpi=200)
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2, figsize=(8, 6))

dicGrainID = 41
dicGrain = dicMap[dicGrainID]

# add a strain map
plot0 = dicGrain.plotMaxShear(
    ax=ax0, fig=fig,
    vmin=0, vmax=0.08, plotScaleBar=True,

# add a misorientation
ebsdGrain = dicGrain.ebsdGrain
plot1 = ebsdGrain.plotMisOri(component=0, ax=ax1, fig=fig, vmin=0, vmax=1, clabel="GROD", plotScaleBar=True)

# add an IPF
plot2 = ebsdGrain.plotOriSpread(
    direction=np.array((1,0,0)), c='b', s=1, alpha=0.2,
    ax=ax2, fig=fig
    direction=np.array((1,0,0)), c='k', s=100, plot=plot2

# add histrogram of strain values
plot3 = HistPlot.create(
    ax=ax3, fig=fig,
    axesType="logy", bins=50, range=(0,0.06))"Effective shear strain")


Find and plot twin boundaries

from defdap.crystal import posIdc, safeIntCast

# find twin boundary points
misOriExp = 60
misOriTol = 5
misOriAxisExp = (1, 1, 1)  # plane indices (only for cubic)
misOriAxisTol = 5

# convert to radians
misOriExp *= np.pi / 180
misOriTol *= np.pi / 180
misOriAxisTol *= np.pi / 180

symms = Quat.symEqv('cubic')

# calculate symmetrically equivalent directions
crystal_dir = misOriAxisExp
crystal_dir_family = set()
for symm in symms:
    symm = symm.conjugate

    crystal_dir_symm = symm.transformVector(crystal_dir)
    crystal_dir_symm = posIdc(safeIntCast(crystal_dir_symm))


# convert to list of unit vectors
crystal_dir_family = list(crystal_dir_family)
crystal_dir_family = [d / np.sqrt(, d)) for d in crystal_dir_family]

nn = ebsdMap.neighbourNetwork

twin_bSegs = []
twin_lines = []
for _, _, bseg in'boundary'):

    misOri, misOriAxis = bseg.misorientation()

    # check if misorientation is close to expected
    misOriDev = abs(misOri - misOriExp)
    if misOriDev > misOriTol:

    # check if misorientation axis is close to any <111>
    # make first componenet positive
    misOriAxis /= np.sign(misOriAxis[0])
    twin = True
    for crystal_dir in crystal_dir_family:
        misOriAxisDev = np.abs(np.arccos(, crystal_dir)))
        if misOriAxisDev < misOriAxisTol:
        twin = False

    if not twin:

    twin_lines += bseg.boundaryLines

twin_lines_dic = dicMap.warp_lines_to_dic_frame(twin_lines)
Finished constructing neighbour network (0:00:00)
plot = ebsdMap.plotIPFMap([1,0,0], plotScaleBar=True, plotGBs='line')
plot.addGrainBoundaries(boundaries=twin_lines, kind='line', colour='black')
plot = dicMap.plotMaxShear(vmin=0, vmax=0.1, plotScaleBar=True, plotGBs='line')
plot.addGrainBoundaries(boundaries=twin_lines_dic, kind='line', colour='yellow')