This notebook will outline basic usage of DefDAP, including loading a DIC and EBSD map, linking them with homologous points and producing maps
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 tk
dicFilePath = "tests/data/"
dicMap = hrdic.Map(dicFilePath, "testDataDIC.txt")
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
dicMap.setScale(pixelSize)
dicMap.plotMaxShear(vmin=0, vmax=0.10, plotScaleBar=True)
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 = ['eMaxShear', 'e11', 'e22', 'e12'])
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)
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.
ebsdFilePath = "tests/data/testDataEBSD"
ebsdMap = ebsd.Map(ebsdFilePath)
ebsdMap.buildQuatArray()
Using an Euler colour mapping or inverse pole figure colouring with the sample reference direction passed as a vector.
ebsdMap.plotEulerMap(plotScaleBar=True)
ebsdMap.plotIPFMap([1,0,0], plotScaleBar=True)
A KAM map can also be plotted as follows
ebsdMap.plotKamMap(vmin=0, vmax=1)
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.
ebsdMap.findBoundaries(boundDef=8)
ebsdMap.findGrains(minGrainSize=10)
A list of the slip planes, colours and slip directions can be printed for each phase in the map.
phase = ebsdMap.phases[0]
print(phase.name)
phase.printSlipSystems()
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)
ebsdMap.plotAverageGrainSchmidFactorsMap()
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.
ebsdMap.locateGrainID()
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
print(grain.refOri)
grain.plotRefOri(direction=[0, 0, 1])
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)
The unit cell for the average grain orientation can also be ploted
grain.plotUnitCell()
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
grain.printSlipTraces()
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.buildMisOriList()
grain.plotMisOri(plotScaleBar=True, vmin=0, vmax=5)
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:
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()
Some common grain analysis routines are built into the EBSD map object, including:
ebsdMap.calcGrainAvOris()
ebsdMap.calcGrainMisOri()
ebsdMap.plotMisOriMap(vmin=0, vmax=5, plotGBs=True, plotScaleBar=True)
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
.
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.
dicMap.setHomogPoint(display="pattern")
ebsdMap.setHomogPoint()
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.
dicMap.homogPoints
ebsdMap.homogPoints
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)
]
Finally the two data maps are linked. The type of transform between the two frames can be affine, projective, polynomial.
dicMap.linkEbsdMap(ebsdMap, transformType="affine")
# dicMap.linkEbsdMap(ebsdMap, transformType="projective")
# dicMap.linkEbsdMap(ebsdMap, transformType="polynomial", order=2)
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)
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.
dicMap.findGrains(minGrainSize=10)
dicMap.plotMaxShear(vmin=0, vmax=0.1, plotScaleBar=True, plotGBs=True)
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
dicMap.locateGrainID(displaySelected=True)
Some of the plotting features are shown in examples below.
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
)
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')
plot.addLegend(scaling=grainAreaScaling)
# 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)
from defdap.plotting import MapPlot, GrainPlot, HistPlot
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'
)
plot.addScaleBar()
plot = dicMap.plotGrainDataMap(
mapData,
vmin=-0.06, vmax=0.06, plotColourBar=True,
cmap="seismic", clabel="Axial strain ($e_11$)",
plotScaleBar=True
)
plot.addGrainBoundaries(dilate=True, colour="white")
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(
mapData,
vmin=-0.1, vmax=0.1, plotColourBar=True,
clabel="Axial strain ($e_11$)", cmap="seismic",
plotScaleBar=True
)
plot.addSlipTraces()
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:
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")
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,
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()