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 ../../

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 0x7f3817918050>
_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 = ['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.

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

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

ebsdMap = ebsd.Map(ebsdFilePath, dataType = 'OxfordBinary')
ebsdMap.buildQuatArray();
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

[9]:
for i, phase in enumerate(ebsdMap.phases):
    print(i+1)
    print(phase)
1
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

[10]:
print(ebsdMap.phases[0].printSlipSystems())
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]
None

Plot the EBSD map

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

[11]:
ebsdMap.plotEulerMap(plotScaleBar=True)
[11]:
<defdap.plotting.MapPlot at 0x7f38173df390>
_images/howtouse_23_1.png
[12]:
ebsdMap.plotIPFMap([1,0,0], plotScaleBar=True)
Finished building quaternion array (0:00:00)
[12]:
<defdap.plotting.MapPlot at 0x7f381738c750>
_images/howtouse_24_2.png

A KAM map can also be plotted as follows

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

[14]:
ebsdMap.findBoundaries(boundDef=8)
ebsdMap.findGrains(minGrainSize=10)
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.

[15]:
ebsdMap.calcAverageGrainSchmidFactors(loadVector=np.array([1,0,0]), slipSystems=None)
Finished calculating grain average Schmid factors (0:00:01)
[16]:
ebsdMap.plotAverageGrainSchmidFactorsMap()
[16]:
<defdap.plotting.MapPlot at 0x7f380fd2c950>
_images/howtouse_31_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.

[17]:
ebsdMap.locateGrainID()
[17]:
<defdap.plotting.MapPlot at 0x7f3817d85c10>
_images/howtouse_33_1.png

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

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

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

[19]:
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)
[19]:
<defdap.plotting.PolePlot at 0x7f380fb24550>
_images/howtouse_37_1.png

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

[20]:
grain.plotUnitCell()
[20]:
<defdap.plotting.CrystalPlot at 0x7f380fab8550>
_images/howtouse_39_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

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

[22]:
grain = ebsdMap[ebsdMap.currGrainId]
grain.buildMisOriList()
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/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/defdap/base.py in __getitem__(self, key)
     63         self.checkGrainsDetected()
     64
---> 65         return self.grainList[key]
     66
     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.

[23]:
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_45_0.png

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

[24]:
ebsdMap.calcGrainAvOris()
Finished calculating grain mean orientations (0:00:01)
[25]:
ebsdMap.calcGrainMisOri()
ebsdMap.plotMisOriMap(vmin=0, vmax=5, plotGBs=True, plotScaleBar=True)
Finished calculating grain misorientations (0:00:00)
[25]:
<defdap.plotting.MapPlot at 0x7f380fa12290>
_images/howtouse_48_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.

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

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/defdap/base.py in setHomogPoint(self, map_name, points, **kwargs)
    272
    273         binning = self.data.get_metadata(map_name, 'binning', 1)
--> 274         plot = self.plot_map(map_name, makeInteractive=True, **kwargs)
    275
    276         # Plot stored homog points if there are any

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/defdap/base.py in plot_map(self, map_name, component, **kwargs)
    758         map_data = self.crop(map_data, binning=binning)
    759
--> 760         return MapPlot.create(self, map_data, **plot_params)
    761
    762     def calcGrainAv(self, mapData, grainIds=-1):

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/defdap/plotting.py 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)
    667
    668         if mapData is not None:
--> 669             plot.addMap(mapData, cmap=cmap, vmin=vmin, vmax=vmax, **kwargs)
    670
    671         if plotColourBar:

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/defdap/plotting.py in addMap(self, mapData, vmin, vmax, cmap, **kwargs)
    357         """
    358         img = self.ax.imshow(mapData, vmin=vmin, vmax=vmax,
--> 359                              interpolation='None', cmap=cmap, **kwargs)
    360         self.draw()
    361

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/matplotlib/_api/deprecation.py 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)
    457
    458     # Don't modify *func*'s signature, as boilerplate.py needs it.

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/matplotlib/__init__.py 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)
   1413
   1414         bound = new_sig.bind(ax, *args, **kwargs)

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/matplotlib/axes/_axes.py 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)
   5441
   5442         im.set_data(X)

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/matplotlib/image.py 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         )
    941

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/matplotlib/image.py in __init__(self, ax, cmap, norm, interpolation, origin, filternorm, filterrad, resample, interpolation_stage, **kwargs)
    258         self._imcache = None
    259
--> 260         self.update(kwargs)
    261
    262     def __getstate__(self):

~/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/matplotlib/artist.py 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'
_images/howtouse_51_1.png
[27]:
ebsdMap.setHomogPoint()
_images/howtouse_52_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.

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

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

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

Show the transformation

[33]:
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)
[33]:
<matplotlib.image.AxesImage at 0x7f380f29f850>
_images/howtouse_62_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.

[34]:
dicMap.findGrains(minGrainSize=10)
Starting finding grains..
/home/docs/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/defdap/hrdic.py:540: 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.
  connectivity=2)
Finished finding grains (0:00:00)
[35]:
dicMap.plotMaxShear(vmin=0, vmax=0.1, plotScaleBar=True, plotGBs='line')
[35]:
<defdap.plotting.MapPlot at 0x7f380e9bf310>
_images/howtouse_65_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

[36]:
dicMap.locateGrainID(displaySelected=True)
[36]:
<defdap.plotting.MapPlot at 0x7f380e33e290>
_images/howtouse_67_1.png

Plotting examples

Some of the plotting features are shown in examples below.

Built-in plots

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

plot = dicGrain.plotMaxShear(
    plotScaleBar=True, plotSlipTraces=True, plotSlipBands=True
)
Number of bands detected: 2
_images/howtouse_73_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.

[40]:
# 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_76_0.png
[41]:
# 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_77_0.png

Create your own

[42]:
from defdap.plotting import MapPlot, GrainPlot, HistPlot
[43]:
mapData = dicMap.data['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/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/defdap/hrdic.py:540: 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.
  connectivity=2)
_images/howtouse_80_1.png
[44]:
plot.addScaleBar()

Functions for grain averaging and grain segmentation

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

_images/howtouse_83_0.png
[46]:
plot.addGrainBoundaries(dilate=True, colour="white")
[46]:
<matplotlib.image.AxesImage at 0x7f380e762450>
[47]:
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_85_0.png
[48]:
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_86_0.png
[49]:
plot.addSlipTraces()

Composite plots

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

[50]:
from matplotlib import gridspec
[51]:
# 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.data.max_shear),
    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/develop/lib/python3.7/site-packages/defdap/hrdic.py:540: 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.
  connectivity=2)
/home/docs/checkouts/readthedocs.org/user_builds/defdap/envs/develop/lib/python3.7/site-packages/defdap/plotting.py:1367: 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)
[51]:
Text(0.5, 13.559999999999967, 'Effective shear strain')
_images/howtouse_91_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:

[52]:
#plt.savefig("test_save_fig.png", dpi=200)
#plt.savefig("test_save_fig.eps", dpi=200)
[53]:
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.data.max_shear),
    ax=ax3, fig=fig,
    axesType="logy", bins=50, range=(0,0.06))

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


plt.tight_layout()
_images/howtouse_94_0.png

Find and plot twin boundaries

[54]:
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))

    crystal_dir_family.add(crystal_dir_symm)

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


ebsdMap.buildNeighbourNetwork()
nn = ebsdMap.neighbourNetwork

twin_bSegs = []
twin_lines = []
for _, _, bseg in nn.edges.data('boundary'):

    misOri, misOriAxis = bseg.misorientation()

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

    # 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(np.dot(misOriAxis, crystal_dir)))
        if misOriAxisDev < misOriAxisTol:
            break
    else:
        twin = False

    if not twin:
        continue

    twin_bSegs.append(bseg)
    twin_lines += bseg.boundaryLines

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