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

https://mybinder.org/badge_logo.svg

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.

[1]:
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 ../
/home/docs/checkouts/readthedocs.org/user_builds/defdap/envs/latest/lib/python3.10/site-packages/IPython/core/magics/osm.py:417: UserWarning: This is now an optional IPython functionality, setting dhist requires you to install the `pickleshare` library.
  self.shell.db['dhist'] = compress_dhist(dhist)[-100:]

Load in a HRDIC map

[2]:
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.

[3]:
fieldWidth = 20 # microns
numPixels = 2048
pixelSize = fieldWidth / numPixels

dicMap.setScale(pixelSize)

Plot the map with a scale bar

[4]:
dicMap.plotMaxShear(vmin=0, vmax=0.10, plotScaleBar=True)
[4]:
<defdap.plotting.MapPlot at 0x7fee24956f80>
_images/howtouse_9_1.png

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.

[5]:
dicMap.setCrop(xMin=0, xMax=0, yMin=0, yMax=0)

Statistics

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

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

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

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.

[7]:
# set the path of the pattern image, this is relative to the location of the DIC data file
dicMap.setPatternPath("testDataPat.bmp", 1)

Load in an EBSD map

The crystal structure of each phase is read from file and used to set the slip systems for the phase. The orientation in the EBSD are converted to a quaternion representation so calculations can be applied later.

[8]:
ebsdFilePath = "../tests/data/testDataEBSD"

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

Plot the EBSD map

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

[9]:
ebsdMap.plotEulerMap(plotScaleBar=True)
[9]:
<defdap.plotting.MapPlot at 0x7fee23fb0c10>
_images/howtouse_19_1.png
[10]:
ebsdMap.plotIPFMap([1,0,0], plotScaleBar=True)
[10]:
<defdap.plotting.MapPlot at 0x7fee23ff2d40>
_images/howtouse_20_1.png

A KAM map can also be plotted as follows

[11]:
ebsdMap.plotKamMap(vmin=0, vmax=1)
[11]:
<defdap.plotting.MapPlot at 0x7fee249a5150>
_images/howtouse_22_1.png

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.

[12]:
ebsdMap.findBoundaries(boundDef=8)
ebsdMap.findGrains(minGrainSize=10)
Finished finding grain boundaries (0:00:00)
Finished finding grains (0:00:00)

A list of the slip planes, colours and slip directions can be printed for each phase in the map.

[13]:
phase = ebsdMap.phases[0]
print(phase.name)
phase.printSlipSystems()
Ni-superalloy
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]

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.

[14]:
ebsdMap.calcAverageGrainSchmidFactors(loadVector=np.array([1,0,0]), slipSystems=None)
Finished calculating grain average Schmid factors (0:00:01)
[15]:
ebsdMap.plotAverageGrainSchmidFactorsMap()
[15]:
<defdap.plotting.MapPlot at 0x7fee1bf97220>
_images/howtouse_29_1.png

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.

[16]:
ebsdMap.locateGrainID()
[16]:
<defdap.plotting.MapPlot at 0x7fee1b4b1f00>
_images/howtouse_31_1.png

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

[17]:
grainID = 48
grain = ebsdMap[grainID]
grain.calcAverageOri()  # stored as a quaternion named grain.refOri
print(grain.refOri)
grain.plotRefOri(direction=[0, 0, 1])
[0.3393, 0.1397, 0.4032, 0.8383]
[17]:
<defdap.plotting.PolePlot at 0x7fee1b697b50>
_images/howtouse_33_2.png

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

[18]:
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)
[18]:
<defdap.plotting.PolePlot at 0x7fee1a88e650>
_images/howtouse_35_1.png

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

[19]:
grain.plotUnitCell()
[19]:
<defdap.plotting.CrystalPlot at 0x7fee1bf974f0>
_images/howtouse_37_1.png

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

[20]:
grain.printSlipTraces()
(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.

[21]:
grain = ebsdMap[ebsdMap.currGrainId]
grain.buildMisOriList()
grain.plotMisOri(plotScaleBar=True, vmin=0, vmax=5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[21], line 1
----> 1 grain = ebsdMap[ebsdMap.currGrainId]
      2 grain.buildMisOriList()
      3 grain.plotMisOri(plotScaleBar=True, vmin=0, vmax=5)

File ~/checkouts/readthedocs.org/user_builds/defdap/envs/latest/lib/python3.10/site-packages/defdap/base.py:63, in Map.__getitem__(self, key)
     59 def __getitem__(self, key):
     60     # Check that grains have been detected in the map
     61     self.checkGrainsDetected()
---> 63     return self.grainList[key]

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.

[22]:
grainAvOris = []
for grain in ebsdMap:
    grain.calcAverageOri()
    grainAvOris.append(grain.refOri)

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

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

[23]:
ebsdMap.calcGrainAvOris()
Finished calculating grain mean orientations (0:00:01)
[24]:
ebsdMap.calcGrainMisOri()
ebsdMap.plotMisOriMap(vmin=0, vmax=5, plotGBs=True, plotScaleBar=True)
Finished calculating grain misorientations (0:00:00)
[24]:
<defdap.plotting.MapPlot at 0x7fee1a3bbbe0>
_images/howtouse_46_2.png

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.

[25]:
dicMap.setHomogPoint(display="pattern")
_images/howtouse_49_0.png
[26]:
ebsdMap.setHomogPoint()
_images/howtouse_50_0.png

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.

[27]:
dicMap.homogPoints
[27]:
[]
[28]:
ebsdMap.homogPoints
[28]:
[]

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

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

Show the transformation

[32]:
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))
ax1.set_title('Reference')
ax1.imshow(data)
ax2.set_title('Transformed')
ax2.imshow(dataWarped)
[32]:
<matplotlib.image.AxesImage at 0x7fee19d29900>
_images/howtouse_60_1.png

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.

[33]:
dicMap.findGrains(minGrainSize=10)
Finished finding grains (0:00:00)
[34]:
dicMap.plotMaxShear(vmin=0, vmax=0.1, plotScaleBar=True, plotGBs=True)
[34]:
<defdap.plotting.MapPlot at 0x7fee1a62cb80>
_images/howtouse_63_1.png

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

[35]:
dicMap.locateGrainID(displaySelected=True)
[35]:
<defdap.plotting.MapPlot at 0x7fee19e7bb20>
_images/howtouse_65_1.png

Plotting examples

Some of the plotting features are shown in examples below.

Built-in plots

[36]:
plot = dicMap.plotMaxShear(
    vmin=0, vmax=0.1, plotScaleBar=True,
    plotGBs=True, dilateBoundaries=True
)
_images/howtouse_69_0.png
[37]:
plot = ebsdMap.plotEulerMap(
    plotScaleBar=True, plotGBs=True,
    highlightGrains=[10, 20, 45], highlightAlpha=0.9, highlightColours=['y']
)
_images/howtouse_70_0.png
[38]:
dicGrainID = 41
dicGrain = dicMap[dicGrainID]

plot = dicGrain.plotMaxShear(
    plotScaleBar=True, plotSlipTraces=True, plotSlipBands=True
)
Number of bands detected: 2
_images/howtouse_71_1.png

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.

[39]:
# 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')
plot.addLegend(scaling=grainAreaScaling)
_images/howtouse_74_0.png
[40]:
# 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')
plot.addLegend(scaling=grainAreaScaling)
_images/howtouse_75_0.png

Create your own

[41]:
from defdap.plotting import MapPlot, GrainPlot, HistPlot
[42]:
mapData = dicMap.e11
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'
)
_images/howtouse_78_0.png
[43]:
plot.addScaleBar()

Functions for grain averaging and grain segmentation

[44]:
plot = dicMap.plotGrainDataMap(
    mapData,
    vmin=-0.06, vmax=0.06, plotColourBar=True,
    cmap="seismic", clabel="Axial strain ($e_11$)",
    plotScaleBar=True
)

_images/howtouse_81_0.png
[45]:
plot.addGrainBoundaries(dilate=True, colour="white")
[45]:
<matplotlib.image.AxesImage at 0x7fee191d65c0>
[46]:
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",
)

_images/howtouse_83_0.png
[47]:
dicGrainID = 41
dicGrain = dicMap[dicGrainID]

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

_images/howtouse_84_0.png
[48]:
plot.addSlipTraces()

Composite plots

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

[49]:
from matplotlib import gridspec
[50]:
# 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:
        dicOris.append(grain.refOri)
plot1 = Quat.plotIPF(
    dicOris, np.array((1,0,0)), 'cubic',
    ax=ax1, fig=fig, s=10
)

# add histrogram of strain values
plot2 = HistPlot.create(
    dicMap.crop(dicMap.eMaxShear),
    ax=ax2, fig=fig, marker='o', markersize=2,
    axesType="logy", bins=50, range=(0,0.06)
)
plot2.ax.set_xlabel("Effective shear strain")
/home/docs/checkouts/readthedocs.org/user_builds/defdap/envs/latest/lib/python3.10/site-packages/defdap/plotting.py:1385: UserWarning: marker is redundantly defined by the 'marker' keyword argument and the fmt string "o" (-> marker='o'). The keyword argument will take precedence.
  self.ax.plot(xVals, yVals, line, label=label, **kwargs)
[50]:
Text(0.5, 18.72222222222218, 'Effective shear strain')
_images/howtouse_89_2.png

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:

[51]:
plt.savefig("test_save_fig.png", dpi=200)
plt.savefig("test_save_fig.eps", dpi=200)
<Figure size 640x480 with 0 Axes>
[52]:
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,
    plotSlipTraces=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
)
ebsdGrain.plotRefOri(
    direction=np.array((1,0,0)), c='k', s=100, plot=plot2
)

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

plot3.ax.set_xlabel("Effective shear strain")


plt.tight_layout()
_images/howtouse_92_0.png
[ ]: