Пример #1
0
 def test_merge_microstructures(self):
     m1 = Microstructure(os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'm1_data.h5'))
     m2 = Microstructure(os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'm2_data.h5'))
     # merge the two microstructures
     m1m2 = Microstructure.merge_microstructures([m1, m2], overlap=16)
     m1m2.autodelete = True
     h5_file = m1m2.h5_file
     xdmf_file = m1m2.xdmf_file
     dims = (64, 64, 64)
     for i in range(3):
         self.assertEqual(m1m2.get_grain_map().shape[i], dims[i])
     self.assertEqual(m1m2.get_number_of_grains(), 27)
     del m1m2
     self.assertTrue(not os.path.exists(h5_file))
     self.assertTrue(not os.path.exists(xdmf_file))
     del m1, m2
Пример #2
0
 def test_from_copy(self):
     # test computing of grain geometrical quantities and copy of an
     # existing Microstructure dataset
     # create new microstructure copy of an already existing file
     filename = os.path.join(PYMICRO_EXAMPLES_DATA_DIR,
                             't5_dct_slice_data.h5')
     new_file = os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'tmp_slice_dct')
     m = Microstructure.copy_sample(filename, new_file, autodelete=True,
                                    get_object=True)
     h5_file = m.h5_path
     xdmf_file = m.xdmf_path
     self.assertTrue(os.path.exists(h5_file))
     self.assertTrue(os.path.exists(xdmf_file))
     m.recompute_grain_bounding_boxes()
     m.recompute_grain_centers()
     # m.recompute_grain_volumes()
     m_ref = Microstructure(filename=filename)
     for i in range(m_ref.grains.nrows):
         print(' n°1 :',m.grains[i])
         print(' n°2 :',m_ref.grains[i])
         self.assertEqual(m.grains[i], m_ref.grains[i])
     volume = np.sum(m.get_mask(as_numpy=True))
     self.assertEqual(volume, 194025)
     del m
     self.assertTrue(not os.path.exists(h5_file))
     self.assertTrue(not os.path.exists(xdmf_file))
     del m_ref
Пример #3
0
 def setUp(self):
     print('testing the Microstructure class')
     self.test_eulers = [(45., 45, 0.), (10., 20, 30.), (191.9, 69.9, 138.9)]
     self.micro = Microstructure()
     self.micro.name = 'test'
     for i in range(len(self.test_eulers)):
         euler = self.test_eulers[i]
         self.micro.grains.append(Grain(i + 1, Orientation.from_euler(euler)))
Пример #4
0
 def test_find_neighbors(self):
     # read a test microstructure already created
     m = Microstructure(filename=os.path.join(PYMICRO_EXAMPLES_DATA_DIR,
                                              't5_dct_slice_data.h5'))
     neighbors = m.find_neighbors(grain_id=5, distance=3)
     self.assertEqual(len(neighbors), 9)
     for gid in [0, 1, 3, 14, 17, 18, 25, 51, 115]:
         self.assertTrue(gid in neighbors)
     del m
Пример #5
0
 def set_microstructure(self, microstructure):
     if microstructure is None:
         # Create random name to avoid opening another microstructure with
         # same file name when initializing another sample
         randint = str(np.random.randint(1, 10000 + 1))
         microstructure = Microstructure(name='tmp_micro_' + randint,
                                         autodelete=True,
                                         verbose=True)
     self.microstructure = microstructure
Пример #6
0
 def test_from_file(self):
     # read a test microstructure already created
     m = Microstructure(filename=os.path.join(PYMICRO_EXAMPLES_DATA_DIR,
                                              't5_dct_slice_data.h5'))
     self.assertEqual(m.grains.nrows, 21)
     self.assertEqual(m.get_voxel_size(), 0.0014)
     self.assertEqual(type(m.get_grain_map(as_numpy=True)), np.ndarray)
     self.assertEqual(type(m.get_mask(as_numpy=True)), np.ndarray)
     self.assertTrue(True)
     del m
Пример #7
0
 def test_base(self):
     micro = Microstructure(name='test', autodelete=True)
     micro.add_grains(self.test_eulers)
     self.assertTrue(micro.get_sample_name() == 'test')
     self.assertTrue(os.path.exists(micro.h5_file))
     self.assertTrue(os.path.exists(micro.xdmf_file))
     h5_file = micro.h5_file
     xdmf_file = micro.xdmf_file
     del micro
     self.assertTrue(not os.path.exists(h5_file))
     self.assertTrue(not os.path.exists(xdmf_file))
Пример #8
0
    def __init__(self,
                 microstructure=None,
                 lattice=None,
                 axis='Z',
                 hkl='111',
                 proj='stereo',
                 verbose=False):
        """
        Create an empty PoleFigure object associated with an empty Microstructure.

        :param microstructure: the :py:class:`~pymicro.crystal.microstructure.Microstructure` containing the collection of orientations to plot (None by default).
        :param lattice: the crystal :py:class:`~pymicro.crystal.lattice.Lattice`.
        :param str axis: the pole figure axis ('Z' by default), vertical axis in the direct pole figure and direction plotted on the inverse pole figure.

        .. warning::

           Any crystal structure is now supported (you have to set the proper
           crystal lattice) but it has only really be tested for cubic.

        :param str hkl: slip plane family ('111' by default)
        :param str proj: projection type, can be either 'stereo' (default) or 'flat'
        :param bool verbose: verbose mode (False by default)
        """
        self.proj = proj
        self.axis = axis
        self.map_field = None
        if microstructure:
            self.microstructure = microstructure
        else:
            self.microstructure = Microstructure()
        if lattice:
            self.lattice = lattice
        else:
            self.lattice = Lattice.cubic(1.0)
        self.family = None
        self.poles = []
        self.set_hkl_poles(hkl)
        self.verbose = verbose
        self.mksize = 12
        self.color_by_grain_id = False
        self.pflegend = False
        self.x = np.array([1., 0., 0.])
        self.y = np.array([0., 1., 0.])
        self.z = np.array([0., 0., 1.])

        # list all crystal directions
        self.c001s = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]],
                              dtype=np.float)
        self.c011s = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0], [0, -1, 1],
                               [-1, 0, 1], [-1, 1, 0]],
                              dtype=np.float) / np.sqrt(2)
        self.c111s = np.array([[1, 1, 1], [-1, -1, 1], [1, -1, 1], [-1, 1, 1]],
                              dtype=np.float) / np.sqrt(3)
Пример #9
0
    def plot(orientations, **kwargs):
        '''Plot a pole figure (both direct and inverse) for a list of orientations.

        :param orientations: the list of crystalline :py:class:`~pymicro.crystal.microstructure.Orientation` to plot.
        '''
        micro = Microstructure()
        if isinstance(orientations, list):
            for i in range(len(orientations)):
                micro.grains.append(Grain(i + 1, orientations[i]))
        elif isinstance(orientations, Orientation):
            micro.grains.append(Grain(1, orientations))
        else:
            print('Unrecognized argument: %s' % orientations.__repr__)
        pf = PoleFigure(microstructure=micro, **kwargs)
        pf.plot_pole_figures(display=True)
Пример #10
0
 def test_grain_geometry(self):
     m = Microstructure(name='test', autodelete=True)
     grain_map = np.ones((8, 8, 8), dtype=np.uint8)
     m.set_grain_map(grain_map, voxel_size=1.0)
     grain = m.grains.row
     grain['idnumber'] = 1
     grain['orientation'] = Orientation.from_euler([10, 20, 30]).rod
     grain.append()
     m.grains.flush()
     m.recompute_grain_bounding_boxes()
     m.recompute_grain_centers()
     m.recompute_grain_volumes()
     bb1 = m.compute_grain_bounding_box(gid=1)
     self.assertEqual(bb1, ((0, 8), (0, 8), (0, 8)))
     c1 = m.compute_grain_center(gid=1).tolist()
     self.assertEqual(c1, [0., 0., 0.])
     self.assertEqual(m.compute_grain_volume(gid=1), 512)
Пример #11
0
    def plot(orientations, **kwargs):
        """Plot a pole figure (both direct and inverse) for a list of crystal
        orientations.

        :param orientations: the list of crystalline
            :py:class:`~pymicro.crystal.microstructure.Orientation` to
            plot.
        
        """
        micro = Microstructure(autodelete=True)
        if isinstance(orientations, list):
            for i in range(len(orientations)):
                micro.add_grains([o.euler for o in orientations])
        elif isinstance(orientations, Orientation):
            micro.add_grains([orientations.euler])
        else:
            print('Unrecognized argument: %s' % orientations.__repr__)
        pf = PoleFigure(microstructure=micro, **kwargs)
        pf.plot_pole_figures(display=True)
Пример #12
0
 def test_crop(self):
     # read a test microstructure
     m = Microstructure(os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'n27-id1_data.h5'))
     # crop the microstructure
     m1 = m.crop(x_start=20, x_end=40, y_start=10, y_end=40, z_start=15, z_end=55, autodelete=True)
     h5_file = m1.h5_file
     xdmf_file = m1.xdmf_file
     dims = (20, 30, 40)
     for i in range(3):
         self.assertEqual(m1.get_grain_map().shape[i], dims[i])
     self.assertEqual(m1.get_number_of_grains(), 16)
     gids_crop = [1, 2, 3, 4, 6, 7, 8, 13, 14, 15, 17, 20, 21, 22, 26, 27]
     for gid in m1.get_grain_ids():
         self.assertTrue(gid in gids_crop)
     self.assertEqual(np.sum(m1.get_grain_map(as_numpy=True) == 14), 396)
     del m1
     # verify that the mirostructure files have been deleted
     self.assertTrue(not os.path.exists(h5_file))
     self.assertTrue(not os.path.exists(xdmf_file))
     del m
Пример #13
0
#!/usr/bin/env python
import os, numpy as np
from pymicro.crystal.microstructure import Microstructure, Grain, Orientation
from pymicro.crystal.texture import PoleFigure
from matplotlib import pyplot as plt, colors, cm

if __name__ == '__main__':
    '''
    200 Pole figure of a copper sample containing 10000 grains with a fibre
    texture.
    '''
    eulers = Orientation.read_euler_txt('../data/Cu_200.dat')
    micro = Microstructure(name='Cu_200')
    for index in eulers:
        # if index > 1000: continue
        micro.grains.append(Grain(index, eulers[index]))

    # create pole figure (both direct and inverse)
    pf = PoleFigure(hkl='200',
                    proj='stereo',
                    microstructure=micro,
                    verbose=False)
    pf.color_by_grain_id = False
    pf.mksize = 5
    pf.pflegend = False
    pf.plot_pole_figures(plot_sst=True, display=False, save_as='png')

    image_name = os.path.splitext(__file__)[0] + '.png'
    print('writting %s' % image_name)

    from matplotlib import image
#!/usr/bin/env python
import os, numpy as np
from pymicro.crystal.microstructure import Microstructure, Grain, Orientation
from pymicro.crystal.texture import PoleFigure
from matplotlib import pyplot as plt, colors, cm

if __name__ == '__main__':
    '''
    Pole figure of a gold sample containing 6 grains with a strong <111> fiber texture.
    A Microstructure object is first created with the 6 grains of interest.
    The grain ids corerespond to the actual grain number (in an EBSD scan for instance).
    A PoleFigure object is then created using this microstructure and the pole figures
    (both direct and inverse) are drawn by calling the plot_pole_figures() method.
    '''
    micro = Microstructure(name='Au_6grains', overwrite_hdf5=True)
    micro.autodelete = True
    gid_list = [1158, 1349, 1585, 1805, 1833, 2268]
    euler_list = [(344.776, 52.2589, 53.9933), 
                  (344.899, 125.961, 217.330),
                  (228.039, 57.4791, 143.171),
                  (186.741, 60.333, 43.311),
                  (151.709, 55.0406, 44.1051),
                  (237.262, 125.149, 225.615),
                  ]
    micro.add_grains(euler_list, grain_ids=gid_list)

    # create pole figure (both direct and inverse)
    pf = PoleFigure(hkl='111', axis='Z', proj='stereo', microstructure=micro)
    pf.mksize = 100
    pf.set_map_field('grain_id')
    pf.pflegend = True  # this works well for a few grains
Пример #15
0
#!/usr/bin/env python
import os, numpy as np
from pymicro.crystal.microstructure import Microstructure, Grain, Orientation
from pymicro.crystal.texture import PoleFigure
from matplotlib import pyplot as plt, colors, cm

if __name__ == '__main__':
    '''
    111 Pole figure of a copper sample containing 10000 grains with a fibre
    texture.
    '''
    eulers = Orientation.read_euler_txt('../data/Cu_111.dat')
    micro = Microstructure(name='Cu_111')
    for index in eulers:
        micro.grains.append(Grain(index, eulers[index]))

    # create pole figure (both direct and inverse)
    pf = PoleFigure(hkl='111',
                    proj='stereo',
                    microstructure=micro,
                    verbose=False)
    pf.color_by_grain_id = False
    pf.mksize = 5
    pf.pflegend = False
    pf.plot_pole_figures(plot_sst=True, display=False, save_as='png')

    image_name = os.path.splitext(__file__)[0] + '.png'
    print('writting %s' % image_name)

    from matplotlib import image
Пример #16
0
#!/usr/bin/env python
import os, numpy as np
from pymicro.crystal.microstructure import Microstructure
from pymicro.crystal.texture import PoleFigure

if __name__ == '__main__':
    """
    111 Pole figure of a copper sample containing 10000 grains with a fibre
    texture.
    """
    euler_list = np.genfromtxt('../data/Cu_111.dat', usecols=(0, 1, 2), max_rows=1000)
    micro = Microstructure(name='Cu_111', autodelete=True)
    micro.add_grains(euler_list)

    # create pole figure (both direct and inverse)
    pf = PoleFigure(hkl='111', proj='stereo', microstructure=micro)
    pf.color_by_grain_id = False
    pf.mksize = 5
    pf.pflegend = False
    pf.plot_pole_figures(plot_sst=True, display=False, save_as='png')
    del pf
    del micro

    image_name = os.path.splitext(__file__)[0] + '.png'
    print('writing %s' % image_name)

    from matplotlib import image

    image.thumbnail(image_name, 'thumb_' + image_name, 0.2)
Пример #17
0
import numpy as np
import os
from pymicro.crystal.microstructure import Microstructure, Orientation, Grain
from pymicro.crystal.texture import PoleFigure
from matplotlib import pyplot as plt

# read data from Z-set calculation (50% tension load)
data = np.genfromtxt('../data/R_1g.dat')
t, R11, R22, R33, R12, R23, R31, R21, R32, R13, _, _, _, _ = data.T
step = 1  # plot every step point
max_step = data.shape[0]

# create a microstructure with the initial grain orientation
micro = Microstructure(name='1g', autodelete=True)
g = Grain(50, Orientation.from_euler((12.293, 149.266, -167.068)))
micro.add_grains([(12.293, 149.266, -167.068)], grain_ids=[50])

ipf = PoleFigure(proj='stereo', microstructure=micro)
ipf.mksize = 100
ipf.set_map_field('grain_id')

fig = plt.figure(1, figsize=(6, 5))  # for IPF
ax1 = fig.add_subplot(111, aspect='equal')
print('** plotting the initial orientation (with label for legend) **')
ipf.plot_sst(ax=ax1, mk='.', col='k', ann=False)
ax1.set_title('grain rotation in tension')
axis = np.array([0, 0, 1])

grain = micro.get_grain(50)
cgid = Microstructure.rand_cmap().colors[grain.id]  # color by grain id
g = grain.orientation_matrix()
Пример #18
0
#!/usr/bin/env python
import os, numpy as np
from pymicro.crystal.microstructure import Microstructure, Grain, Orientation
from pymicro.crystal.texture import PoleFigure
from matplotlib import pyplot as plt, colors, cm

if __name__ == '__main__':
    '''
    Pole figure of a gold sample containing 6 grains with a strong <111> fiber texture.
    A Microstructure object is first created with the 6 grains of interest.
    The grain ids corerespond to the actual grain number (in an EBSD scan for instance).
    A PoleFigure object is then created using this microstructure and the pole figures
    (both direct and inverse) are drawn by calling the plot_pole_figures() method.
    '''
    micro = Microstructure(name='Au_6grains')
    micro.grains.append(Grain(1158, Orientation.from_euler(np.array([344.776, 52.2589, 53.9933]))))
    micro.grains.append(Grain(1349, Orientation.from_euler(np.array([344.899, 125.961, 217.330]))))
    micro.grains.append(Grain(1585, Orientation.from_euler(np.array([228.039, 57.4791, 143.171]))))
    micro.grains.append(Grain(1805, Orientation.from_euler(np.array([186.741, 60.333, 43.311]))))
    micro.grains.append(Grain(1833, Orientation.from_euler(np.array([151.709, 55.0406, 44.1051]))))
    micro.grains.append(Grain(2268, Orientation.from_euler(np.array([237.262, 125.149, 225.615]))))

    # create pole figure (both direct and inverse)
    pf = PoleFigure(hkl='111', axis='Z', proj='stereo', microstructure=micro)
    pf.mksize = 100
    pf.set_map_field('grain_id')
    pf.pflegend = True  # this works well for a few grains
    pf.plot_pole_figures(plot_sst=True, display=False, save_as='png')

    image_name = os.path.splitext(__file__)[0] + '.png'
    print('writting %s' % image_name)
Пример #19
0
 def load(file_path='experiment.txt'):
     with open(file_path, 'r') as f:
         dict_exp = json.load(f)
     sample = Sample()
     sample.set_name(dict_exp['Sample']['Name'])
     sample.set_position(dict_exp['Sample']['Position'])
     if 'Geometry' in dict_exp['Sample']:
         sample_geo = ObjectGeometry()
         sample_geo.set_type(dict_exp['Sample']['Geometry']['Type'])
         sample.set_geometry(sample_geo)
     if 'Material' in dict_exp['Sample']:
         a, b, c = dict_exp['Sample']['Material']['Lengths']
         alpha, beta, gamma = dict_exp['Sample']['Material']['Angles']
         centering = dict_exp['Sample']['Material']['Centering']
         symmetry = Symmetry.from_string(
             dict_exp['Sample']['Material']['Symmetry'])
         material = Lattice.from_parameters(a,
                                            b,
                                            c,
                                            alpha,
                                            beta,
                                            gamma,
                                            centering=centering,
                                            symmetry=symmetry)
         sample.set_material(material)
     if 'Microstructure' in dict_exp['Sample']:
         micro = Microstructure(
             dict_exp['Sample']['Microstructure']['Name'])
         for i in range(len(
                 dict_exp['Sample']['Microstructure']['Grains'])):
             dict_grain = dict_exp['Sample']['Microstructure']['Grains'][i]
             grain = Grain(
                 dict_grain['Id'],
                 Orientation.from_euler(
                     dict_grain['Orientation']['Euler Angles (degrees)']))
             grain.position = np.array(dict_grain['Position'])
             grain.volume = dict_grain['Volume']
             micro.grains.append(grain)
         sample.set_microstructure(micro)
     exp = Experiment()
     exp.set_sample(sample)
     source = XraySource()
     source.set_position(dict_exp['Source']['Position'])
     if 'Min Energy (keV)' in dict_exp['Source']:
         source.set_min_energy(dict_exp['Source']['Min Energy (keV)'])
     if 'Max Energy (keV)' in dict_exp['Source']:
         source.set_max_energy(dict_exp['Source']['Max Energy (keV)'])
     exp.set_source(source)
     for i in range(len(dict_exp['Detectors'])):
         dict_det = dict_exp['Detectors'][i]
         if dict_det['Class'] == 'Detector2d':
             det = Detector2d(size=dict_det['Size (pixels)'])
             det.ref_pos = dict_det['Reference Position (mm)']
         if dict_det['Class'] == 'RegArrayDetector2d':
             det = RegArrayDetector2d(size=dict_det['Size (pixels)'])
             det.pixel_size = dict_det['Pixel Size (mm)']
             det.ref_pos = dict_det['Reference Position (mm)']
             if 'Binning' in dict_det:
                 det.set_binning(dict_det['Binning'])
             det.u_dir = np.array(dict_det['u_dir'])
             det.v_dir = np.array(dict_det['v_dir'])
             det.w_dir = np.array(dict_det['w_dir'])
         exp.add_detector(det)
     return exp
Пример #20
0
 def set_microstructure(self, microstructure):
     if microstructure is None:
         microstructure = Microstructure()
     self.microstructure = microstructure
Пример #21
0
import os, numpy as np
from pymicro.crystal.texture import PoleFigure
from pymicro.crystal.microstructure import Microstructure, Grain, Orientation
from matplotlib import pyplot as plt

if __name__ == '__main__':
    """
    A pole figure plotted using contours.

    .. note::

      Use this example carefully since this is just using a matplotlib contourf 
      function, and has not been tested properly.
    """
    euler_list = np.genfromtxt('../data/pp100', usecols=(0, 1, 2))
    micro = Microstructure(name='test', autodelete=True)
    micro.add_grains(euler_list)

    pf = PoleFigure(hkl='111', proj='stereo', microstructure=micro)
    pf.mksize = 40
    fig = plt.figure(1, figsize=(12, 5))
    ax1 = fig.add_subplot(121, aspect='equal')
    ax2 = fig.add_subplot(122, aspect='equal')
    pf.create_pf_contour(ax=ax1, ang_step=20)
    pf.plot_pf(ax=ax2)
    image_name = os.path.splitext(__file__)[0] + '.png'
    print('writting %s' % image_name)
    plt.savefig(image_name, format='png')

    from matplotlib import image
Пример #22
0
import os, numpy as np
from pymicro.crystal.texture import PoleFigure
from pymicro.crystal.microstructure import Microstructure, Grain, Orientation
from matplotlib import pyplot as plt, colors, colorbar, cm
'''
An inverse pole figure with symboled colored by the grain size.
'''
eulers = Orientation.read_orientations('../data/EBSD_20grains.txt',
                                       data_type='euler',
                                       usecols=[1, 2, 3])
grain_sizes = np.genfromtxt('../data/EBSD_20grains.txt', usecols=[9])
micro = Microstructure(name='test')
for i in range(20):
    micro.grains.append(Grain(i + 1, eulers[i + 1]))
    micro.get_grain(i + 1).volume = grain_sizes[i]

# build a custom pole figure
pf = PoleFigure(microstructure=micro, hkl='001')  #, lattice=Ti7Al)
#pf.resize_markers = True
pf.mksize = 100
pf.set_map_field('strain',
                 grain_sizes,
                 field_min_level=0.0,
                 field_max_level=1000.,
                 lut='jet')
fig = plt.figure(figsize=(8, 5))
ax1 = fig.add_axes([0.05, 0.05, 0.8, 0.9], aspect='equal')
pf.plot_sst(ax=ax1, mk='o')
ax1.set_title('%s-axis SST inverse %s projection' % (pf.axis, pf.proj))

# to add the color bar
Пример #23
0
 def load(file_path='experiment.txt'):
     with open(file_path, 'r') as f:
         dict_exp = json.load(f)
     name = dict_exp['Sample']['Name']
     sample = Sample(name=name)
     sample.data_dir = dict_exp['Sample']['Data Dir']
     sample.set_position(dict_exp['Sample']['Position'])
     if 'Geometry' in dict_exp['Sample']:
         sample_geo = ObjectGeometry()
         sample_geo.set_type(dict_exp['Sample']['Geometry']['Type'])
         sample.set_geometry(sample_geo)
     if 'Material' in dict_exp['Sample']:
         a, b, c = dict_exp['Sample']['Material']['Lengths']
         alpha, beta, gamma = dict_exp['Sample']['Material']['Angles']
         centering = dict_exp['Sample']['Material']['Centering']
         symmetry = Symmetry.from_string(
             dict_exp['Sample']['Material']['Symmetry'])
         material = Lattice.from_parameters(a,
                                            b,
                                            c,
                                            alpha,
                                            beta,
                                            gamma,
                                            centering=centering,
                                            symmetry=symmetry)
         sample.set_material(material)
     if 'Microstructure' in dict_exp['Sample']:
         micro = Microstructure(
             name=dict_exp['Sample']['Microstructure']['Name'],
             file_path=os.path.dirname(file_path))
         # crystal lattice
         if 'Lattice' in dict_exp['Sample']['Microstructure']:
             a, b, c = dict_exp['Sample']['Microstructure']['Lattice'][
                 'Lengths']
             alpha, beta, gamma = dict_exp['Sample']['Microstructure'][
                 'Lattice']['Angles']
             centering = dict_exp['Sample']['Microstructure']['Lattice'][
                 'Centering']
             symmetry = Symmetry.from_string(
                 dict_exp['Sample']['Microstructure']['Lattice']
                 ['Symmetry'])
             lattice = Lattice.from_parameters(a,
                                               b,
                                               c,
                                               alpha,
                                               beta,
                                               gamma,
                                               centering=centering,
                                               symmetry=symmetry)
             micro.set_lattice(lattice)
         grain = micro.grains.row
         for i in range(len(
                 dict_exp['Sample']['Microstructure']['Grains'])):
             dict_grain = dict_exp['Sample']['Microstructure']['Grains'][i]
             grain['idnumber'] = int(dict_grain['Id'])
             euler = dict_grain['Orientation']['Euler Angles (degrees)']
             grain['orientation'] = Orientation.from_euler(euler).rod
             grain['center'] = np.array(dict_grain['Position'])
             grain['volume'] = dict_grain['Volume']
             #                if 'hkl_planes' in dict_grain:
             #                    grain.hkl_planes = dict_grain['hkl_planes']
             grain.append()
         micro.grains.flush()
         sample.set_microstructure(micro)
         sample.microstructure.autodelete = True
     # lazy behaviour, we load only the grain_ids path, the actual array is loaded in memory if needed
     sample.grain_ids_path = dict_exp['Sample']['Grain Ids Path']
     exp = Experiment()
     exp.set_sample(sample)
     source = XraySource()
     source.set_position(dict_exp['Source']['Position'])
     if 'Min Energy (keV)' in dict_exp['Source']:
         source.set_min_energy(dict_exp['Source']['Min Energy (keV)'])
     if 'Max Energy (keV)' in dict_exp['Source']:
         source.set_max_energy(dict_exp['Source']['Max Energy (keV)'])
     exp.set_source(source)
     for i in range(len(dict_exp['Detectors'])):
         dict_det = dict_exp['Detectors'][i]
         if dict_det['Class'] == 'Detector2d':
             det = Detector2d(size=dict_det['Size (pixels)'])
             det.ref_pos = dict_det['Reference Position (mm)']
         if dict_det['Class'] == 'RegArrayDetector2d':
             det = RegArrayDetector2d(size=dict_det['Size (pixels)'])
             det.pixel_size = dict_det['Pixel Size (mm)']
             det.ref_pos = dict_det['Reference Position (mm)']
             if 'Min Energy (keV)' in dict_exp['Detectors']:
                 det.tilt = dict_det['Tilts (deg)']
             if 'Binning' in dict_det:
                 det.set_binning(dict_det['Binning'])
             det.u_dir = np.array(dict_det['u_dir'])
             det.v_dir = np.array(dict_det['v_dir'])
             det.w_dir = np.array(dict_det['w_dir'])
         exp.add_detector(det)
     return exp
Пример #24
0
 def test_add_grains(self):
     micro = Microstructure(name='test', autodelete=True)
     self.assertEqual(micro.get_number_of_grains(), 0)
     micro.add_grains(self.test_eulers)
     self.assertEqual(micro.get_number_of_grains(), 3)
     del micro