inspy-conv 0.2.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
inspy/__init__.py ADDED
@@ -0,0 +1,32 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Thu Jan 30 13:27:29 2020
4
+ @author: dgc
5
+ """
6
+
7
+
8
+ from __future__ import absolute_import
9
+ import sys
10
+ import warnings
11
+ import pkg_resources
12
+
13
+ from . import constants
14
+ from . import instrument
15
+ from .crystal import Lattice
16
+ from .crystal import Material
17
+ from .crystal import Sample
18
+ from .crystal import symmetry
19
+ #from .data import Data
20
+ from .energy import Energy
21
+ from .instrument import TripleAxisSpectr, TimeOfFlightSpectr, tools
22
+ from .insfit import FitConv
23
+ try:
24
+ from .gui.main_gui import main
25
+ except ImportError:
26
+ warnings.warn('QtPy not found, cannot run Resolution GUI')
27
+
28
+ __version__ = pkg_resources.require("inspy")[0].version
29
+
30
+ if sys.version_info[:2] == (2, 6) or sys.version_info[:2] == (3, 3):
31
+ warnings.warn('Support for Python 2.6 and Python 3.3 is depreciated and will be dropped in inspy 0.1.0',
32
+ DeprecationWarning)
inspy/constants.py ADDED
@@ -0,0 +1,57 @@
1
+ # -*- coding: utf-8 -*-
2
+ # This file is adapted from neutronpy
3
+
4
+ """
5
+ Useful constants for neutron scattering calculations, including:
6
+
7
+ * ``magnetic_form_factors()`` : Magnetic Ion j-values
8
+ * ``periodic_table()`` : Periodic table values
9
+ * ``scattering_lengths()`` : Neutron scattering lengths
10
+ * ``symmetry()`` : Space group information
11
+ * ``JOULES_TO_MEV`` : Joules-to-meV conversion factor
12
+ * ``BOLTZMANN_IN_MEV_K`` : Boltzmann constant in meV/K
13
+ * ``N_A`` : Avogadro constant
14
+ * ``neutron_mass`` : Mass of a neutron in grams
15
+ * ``e`` : Electric charge of an electron in Coulombs
16
+ """
17
+
18
+
19
+ import json
20
+ import os
21
+
22
+ def magnetic_ion_j():
23
+ #Loads j values for Magnetic ions.
24
+ #Returns: ion_j values : dict
25
+ with open(os.path.join(os.path.dirname(__file__),
26
+ "database/magnetic_form_factors.json"), 'r') as infile:
27
+ return json.load(infile)
28
+
29
+ def periodic_table():
30
+ #Loads periodic table database. mass, and long-form name.
31
+ #Returns atom information dict, including mass, atomic number, density, mass, and name
32
+ with open(os.path.join(os.path.dirname(__file__),
33
+ "database/periodic_table.json"), 'r') as infile:
34
+ return json.load(infile)
35
+
36
+ def scattering_lengths():
37
+ #Loads neutron scattering lengths.
38
+ #Returns: scattering_lengths : dict
39
+
40
+ with open(os.path.join(os.path.dirname(__file__),
41
+ "database/scattering_lengths.json"), 'r') as infile:
42
+ return json.load(infile)
43
+
44
+ def symmetry():
45
+ #Loads crystal lattice space groups.
46
+ #Returns lattice_space_groups : dict Database of 230 crystal lattice space groups and their generators
47
+ with open(os.path.join(os.path.dirname(__file__),
48
+ "database/symmetry.json"), 'r') as infile:
49
+ return json.load(infile)
50
+
51
+
52
+ JOULES_TO_MEV = 1. / 1.6021766208e-19 * 1.e3 # Joules to meV
53
+ BOLTZMANN_IN_MEV_K = 8.6173303e-05 * 1.e3 # Boltzmann constant in meV/K
54
+ N_A = 6.022140857e+23
55
+ neutron_mass = 1.674927211e-24 # mass of a neutron in grams
56
+ hbar = 1.054571628e-34 # hbar in m2 kg / s
57
+ e = 1.602176487e-19 # coulombs
@@ -0,0 +1,7 @@
1
+ from .atom import Atom, MagneticAtom
2
+ from .lattice import Lattice
3
+ from .material import Material
4
+ from .sample import Sample
5
+ from .symmetry import SpaceGroup
6
+ from .structure_factors import MagneticFormFactor, MagneticStructureFactor, NuclearStructureFactor
7
+ from . import symmetry
inspy/crystal/atom.py ADDED
@@ -0,0 +1,51 @@
1
+ # -*- coding: utf-8 -*-
2
+ # This file is adapted from neutronpy
3
+
4
+
5
+ import numpy as np
6
+ from ..constants import periodic_table, scattering_lengths
7
+
8
+
9
+ class Atom(object):
10
+ #Class for adding atoms to the Material class.
11
+
12
+ def __init__(self, ion, pos, occupancy=1., Mcell=None, massNorm=False, Uiso=0, Uaniso=np.zeros((3, 3))):
13
+ self.ion = ion
14
+ self.pos = np.array(pos)
15
+ self.occupancy = occupancy
16
+ self.Mcell = Mcell
17
+ self.Uiso = Uiso
18
+ self.Uaniso = np.matrix(Uaniso)
19
+
20
+ if isinstance(scattering_lengths()[ion]['Coh b'], list):
21
+ b = complex(*scattering_lengths()[ion]['Coh b'])
22
+ else:
23
+ b = scattering_lengths()[ion]['Coh b']
24
+
25
+ if massNorm is True:
26
+ self.mass = periodic_table()[ion]['mass']
27
+
28
+ self.b = (b * self.occupancy * self.Mcell / np.sqrt(self.mass))
29
+ else:
30
+ self.b = b / 10.
31
+
32
+ self.coh_xs = scattering_lengths()[ion]['Coh xs']
33
+ self.inc_xs = scattering_lengths()[ion]['Inc xs']
34
+ self.abs_xs = scattering_lengths()[ion]['Abs xs']
35
+
36
+ def __repr__(self):
37
+ return "Atom('{0}')".format(self.ion)
38
+
39
+
40
+ class MagneticAtom(object):
41
+ #Class for adding magnetic atoms to the Material class.
42
+
43
+
44
+ def __init__(self, ion, pos, moment, occupancy):
45
+ self.ion = ion
46
+ self.pos = np.array(pos)
47
+ self.moment = moment
48
+ self.occupancy = occupancy
49
+
50
+ def __repr__(self):
51
+ return "MagneticAtom('{0}')".format(self.ion, self.pos, self.moment, self.occupancy)
@@ -0,0 +1,244 @@
1
+ # -*- coding: utf-8 -*-
2
+ # This file is adapted from neutronpy
3
+
4
+ # Handles lattice geometries to find rotations and transformations
5
+
6
+ import numpy as np
7
+
8
+ class Lattice(object):
9
+ #Class to describe a generic lattice system defined by lattice six parameters.
10
+
11
+
12
+ def __init__(self, a, b, c, alpha, beta, gamma):
13
+ self.abc = [a, b, c]
14
+ self.abg = [alpha, beta, gamma]
15
+
16
+ def __repr__(self):
17
+ return "Lattice({0}, {1}, {2}, {3}, {4}, {5})".format(self.a, self.b, self.c, self.alpha, self.beta, self.gamma)
18
+
19
+ @property
20
+ def a(self):
21
+
22
+ return self.abc[0]
23
+
24
+ @a.setter
25
+ def a(self, a):
26
+ self.abc[0] = a
27
+
28
+ @property
29
+ def b(self):
30
+
31
+ return self.abc[1]
32
+
33
+ @b.setter
34
+ def b(self, b):
35
+ self.abc[1] = b
36
+
37
+ @property
38
+ def c(self):
39
+
40
+ return self.abc[2]
41
+
42
+ @c.setter
43
+ def c(self, c):
44
+ self.abc[2] = c
45
+
46
+ @property
47
+ def alpha(self):
48
+
49
+ return self.abg[0]
50
+
51
+ @alpha.setter
52
+ def alpha(self, alpha):
53
+ self.abg[0] = alpha
54
+
55
+ @property
56
+ def beta(self):
57
+
58
+ return self.abg[1]
59
+
60
+ @beta.setter
61
+ def beta(self, beta):
62
+ self.abg[1] = beta
63
+
64
+ @property
65
+ def gamma(self):
66
+
67
+ return self.abg[2]
68
+
69
+ @gamma.setter
70
+ def gamma(self, gamma):
71
+ self.abg[2] = gamma
72
+
73
+ @property
74
+ def alpha_rad(self):
75
+
76
+ return self.abg_rad[0]
77
+
78
+ @property
79
+ def beta_rad(self):
80
+
81
+ return self.abg_rad[1]
82
+
83
+ @property
84
+ def gamma_rad(self):
85
+
86
+ return self.abg_rad[2]
87
+
88
+ @property
89
+ def astar(self):
90
+
91
+ return self.b * self.c * np.sin(self.alpha_rad) / self.volume * 2 * np.pi
92
+
93
+ @property
94
+ def bstar(self):
95
+
96
+ return self.a * self.c * np.sin(self.beta_rad) / self.volume * 2 * np.pi
97
+
98
+ @property
99
+ def cstar(self):
100
+
101
+ return self.a * self.b * np.sin(self.gamma_rad) / self.volume * 2 * np.pi
102
+
103
+ @property
104
+ def alphastar_rad(self):
105
+
106
+ return np.arccos((np.cos(self.beta_rad) * np.cos(self.gamma_rad) -
107
+ np.cos(self.alpha_rad)) /
108
+ (np.sin(self.beta_rad) * np.sin(self.gamma_rad)))
109
+
110
+ @property
111
+ def betastar_rad(self):
112
+
113
+ return np.arccos((np.cos(self.alpha_rad) *
114
+ np.cos(self.gamma_rad) -
115
+ np.cos(self.beta_rad)) /
116
+ (np.sin(self.alpha_rad) * np.sin(self.gamma_rad)))
117
+
118
+ @property
119
+ def gammastar_rad(self):
120
+
121
+ return np.arccos((np.cos(self.alpha_rad) * np.cos(self.beta_rad) -
122
+ np.cos(self.gamma_rad)) /
123
+ (np.sin(self.alpha_rad) * np.sin(self.beta_rad)))
124
+
125
+ @property
126
+ def alphastar(self):
127
+
128
+ return np.rad2deg(self.alphastar_rad)
129
+
130
+ @property
131
+ def betastar(self):
132
+
133
+ return np.rad2deg(self.betastar_rad)
134
+
135
+ @property
136
+ def gammastar(self):
137
+
138
+ return np.rad2deg(self.gammastar_rad)
139
+
140
+ @property
141
+ def reciprocal_abc(self):
142
+
143
+ return [self.astar, self.bstar, self.cstar]
144
+
145
+ @property
146
+ def reciprocal_abg(self):
147
+
148
+ return [self.alphastar, self.betastar, self.gammastar]
149
+
150
+ @property
151
+ def reciprocal_abg_rad(self):
152
+
153
+ return [self.alphastar_rad, self.betastar_rad, self.gammastar_rad]
154
+
155
+ @property
156
+ def abg_rad(self):
157
+
158
+ return np.deg2rad(self.abg)
159
+
160
+ @property
161
+ def lattice_type(self):
162
+
163
+ if len(np.unique(self.abc)) == 3 and len(np.unique(self.abg)) == 3:
164
+ return 'triclinic'
165
+ elif len(np.unique(self.abc)) == 3 and self.abg[1] != 90 and np.all(np.array(self.abg)[:3:2] == 90):
166
+ return 'monoclinic'
167
+ elif len(np.unique(self.abc)) == 3 and np.all(np.array(self.abg) == 90):
168
+ return 'orthorhombic'
169
+ elif len(np.unique(self.abc)) == 1 and len(np.unique(self.abg)) == 1 and np.all(
170
+ np.array(self.abg) < 120) and np.all(np.array(self.abg) != 90):
171
+ return 'rhombohedral'
172
+ elif len(np.unique(self.abc)) == 2 and self.abc[0] == self.abc[1] and np.all(np.array(self.abg) == 90):
173
+ return 'tetragonal'
174
+ elif len(np.unique(self.abc)) == 2 and self.abc[0] == self.abc[1] and np.all(np.array(self.abg)[0:2] == 90) and \
175
+ self.abg[2] == 120:
176
+ return 'hexagonal'
177
+ elif len(np.unique(self.abc)) == 1 and np.all(np.array(self.abg) == 90):
178
+ return 'cubic'
179
+ else:
180
+ raise ValueError('Provided lattice constants and angles do not resolve to a valid Bravais lattice')
181
+
182
+ @property
183
+ def volume(self):
184
+
185
+ return np.sqrt(np.linalg.det(self.G))
186
+
187
+ @property
188
+ def reciprocal_volume(self):
189
+
190
+ return np.sqrt(np.linalg.det(self.Gstar))
191
+
192
+ @property
193
+ def G(self):
194
+ #Metric tensor of the real space lattice
195
+
196
+
197
+ a, b, c = self.abc
198
+ alpha, beta, gamma = self.abg_rad
199
+
200
+ return np.matrix([[a ** 2, a * b * np.cos(gamma), a * c * np.cos(beta)],
201
+ [a * b * np.cos(gamma), b ** 2, b * c * np.cos(alpha)],
202
+ [a * c * np.cos(beta), b * c * np.cos(alpha), c ** 2]], dtype=float)
203
+
204
+ @property
205
+ def Gstar(self):
206
+ #Metric tensor of the reciprocal lattice
207
+
208
+ return np.linalg.inv(self.G) * 4 * np.pi ** 2
209
+
210
+ @property
211
+ def Bmatrix(self):
212
+ #Cartesian basis matrix in reciprocal units such that Bmatrix*Bmatrix.T = Gstar
213
+
214
+
215
+ return np.matrix([[self.astar, self.bstar * np.cos(self.gammastar_rad), self.cstar * np.cos(self.betastar_rad)],
216
+ [0, self.bstar * np.sin(self.gammastar_rad), -self.cstar * np.sin(self.betastar_rad) * np.cos(self.alpha_rad)],
217
+ [0, 0, self.cstar * np.sin(self.betastar_rad) * np.sin(self.alphastar_rad)]], dtype=float)
218
+
219
+ def get_d_spacing(self, hkl):
220
+ #Returns the d-spacing of a given reciprocal lattice vector.
221
+
222
+ hkl = np.array(hkl)
223
+
224
+ return float(1 / np.sqrt(np.dot(np.dot(hkl, self.Gstar / 4 / np.pi ** 2), hkl)))
225
+
226
+ def get_angle_between_planes(self, v1, v2):
227
+ #Returns the angle :math:`\phi` between two reciprocal lattice vectors
228
+
229
+ v1, v2 = np.array(v1), np.array(v2)
230
+
231
+ return float(np.rad2deg(np.arccos(np.inner(np.inner(v1, self.Gstar), v2) /
232
+ np.sqrt(np.inner(np.inner(v1, self.Gstar), v1)) /
233
+ np.sqrt(np.inner(np.inner(v2, self.Gstar), v2)))))
234
+
235
+ def get_two_theta(self, hkl, wavelength):
236
+ #Returns the detector angle for a given reciprocal lattice vector and incident wavelength.
237
+
238
+ return 2 * np.rad2deg(np.arcsin(wavelength / 2 /
239
+ self.get_d_spacing(hkl)))
240
+
241
+ def get_q(self, hkl):
242
+ #Returns the magnitude of *Q* for a given reciprocal lattice
243
+
244
+ return 2 * np.pi / self.get_d_spacing(hkl)
@@ -0,0 +1,174 @@
1
+ # -*- coding: utf-8 -*-
2
+ # This file is adapted from neutronpy
3
+
4
+ # Material constructor
5
+
6
+ import inspy.constants as const
7
+ import numpy as np
8
+
9
+ from .atom import Atom, MagneticAtom
10
+ from .sample import Sample
11
+ from .structure_factors import MagneticStructureFactor, NuclearStructureFactor
12
+ from .symmetry import SpaceGroup
13
+
14
+ # from ..scattering.pattern import HKLGenerator
15
+
16
+
17
+ class MagneticUnitCell(Sample):
18
+ # defining a magnetic unit cell
19
+
20
+ def __init__(self, unit_cell):
21
+ if 'chirality' not in unit_cell:
22
+ self.chirality = 0
23
+ if 'ph' not in unit_cell:
24
+ self.phase = 0
25
+ self.atoms = []
26
+ if 'space_group' in unit_cell:
27
+ self.space_group = SpaceGroup(unit_cell['space_group'])
28
+ for atom in unit_cell['atoms']:
29
+ symmetrized_positions = self.space_group.symmetrize_position(atom['pos'])
30
+ for pos in symmetrized_positions:
31
+ self.atoms.append(MagneticAtom(atom['ion'],
32
+ pos,
33
+ atom['moment'],
34
+ atom['occupancy']))
35
+ else:
36
+ for atom in unit_cell['atoms']:
37
+ self.atoms.append(MagneticAtom(atom['ion'],
38
+ atom['pos'],
39
+ atom['moment'],
40
+ atom['occupancy']))
41
+
42
+ self.propagation_vector = unit_cell['propagation_vector']
43
+
44
+ a, b, c = unit_cell['lattice']['abc']
45
+ alpha, beta, gamma = unit_cell['lattice']['abg']
46
+ super(MagneticUnitCell, self).__init__(a, b, c, alpha, beta, gamma)
47
+
48
+ def __repr__(self):
49
+ return "MagneticUnitCell('{0}')".format(self.propagation_vector)
50
+
51
+
52
+ class Material(Sample, NuclearStructureFactor, MagneticStructureFactor):
53
+ #Class for the Material being supplied for the structure factor calculation
54
+
55
+
56
+ def __init__(self, crystal):
57
+ self.name = crystal['name']
58
+
59
+ if 'formulaUnits' not in crystal:
60
+ crystal['formulaUnits'] = 1.
61
+
62
+ self.muCell = 0.
63
+ for item in crystal['composition']:
64
+ if 'occupancy' not in item:
65
+ item['occupancy'] = 1.
66
+ self.muCell += const.periodic_table()[item['ion']]['mass'] * item['occupancy']
67
+
68
+ self.Mcell = self.muCell * crystal['formulaUnits']
69
+
70
+ if 'lattice' in crystal:
71
+ a, b, c = crystal['lattice']['abc']
72
+ alpha, beta, gamma = crystal['lattice']['abg']
73
+
74
+ if 'wavelength' in crystal:
75
+ self.wavelength = crystal['wavelength']
76
+ else:
77
+ self.wavelength = 2.359
78
+
79
+ if 'space_group' in crystal:
80
+ self.space_group = SpaceGroup(crystal['space_group'])
81
+ self.atoms = []
82
+ for atom in crystal['composition']:
83
+ if 'Uiso' not in atom:
84
+ atom['Uiso'] = 0
85
+ if 'Uaniso' not in item:
86
+ atom['Uaniso'] = np.matrix(np.zeros((3, 3)))
87
+ if 'occupancy' not in item:
88
+ atom['occupancy'] = 1.
89
+ symmetrized_positions = self.space_group.symmetrize_position(atom['pos'])
90
+ for pos in symmetrized_positions:
91
+ self.atoms.append(Atom(atom['ion'],
92
+ pos,
93
+ atom['occupancy'],
94
+ self.Mcell,
95
+ crystal['massNorm'],
96
+ atom['Uiso'],
97
+ atom['Uaniso']))
98
+ else:
99
+ self.atoms = []
100
+ for item in crystal['composition']:
101
+ if 'Uiso' not in item:
102
+ item['Uiso'] = 0
103
+ if 'Uaniso' not in item:
104
+ item['Uaniso'] = np.matrix(np.zeros((3, 3)))
105
+ if 'occupancy' not in item:
106
+ item['occupancy'] = 1.
107
+ self.atoms.append(Atom(item['ion'],
108
+ item['pos'],
109
+ item['occupancy'],
110
+ self.Mcell,
111
+ crystal['massNorm'],
112
+ item['Uiso'],
113
+ item['Uaniso']))
114
+
115
+ if 'magnetic_unit_cell' in crystal:
116
+ self.magnetic_unit_cell = MagneticUnitCell(crystal['magnetic_cell'])
117
+
118
+ if 'mosaic' not in crystal:
119
+ crystal['mosaic'] = None
120
+ if 'vmosaic' not in crystal:
121
+ crystal['vmosaic'] = None
122
+ if 'u' not in crystal:
123
+ crystal['u'] = None
124
+ if 'v' not in crystal:
125
+ crystal['v'] = None
126
+ if 'dir' not in crystal:
127
+ crystal['dir'] = 1
128
+
129
+ super(Material, self).__init__(a, b, c, alpha, beta, gamma, crystal['mosaic'], crystal['vmosaic'],
130
+ crystal['dir'], crystal['u'], crystal['v'])
131
+
132
+ def __repr__(self):
133
+ return "Material('{0}')".format(self.name)
134
+
135
+ @property
136
+ def total_scattering_cross_section(self):
137
+ r"""Returns total scattering cross-section of unit cell
138
+ """
139
+ total = 0
140
+ for atom in self.atoms:
141
+ total += (atom.coh_xs + atom.inc_xs)
142
+ return total
143
+
144
+ def N_atoms(self, mass):
145
+ #Number of atoms in the defined Material, given the mass of the sample.
146
+
147
+ return const.N_A * mass / self.muCell
148
+
149
+ def calc_optimal_thickness(self, energy=25.3, transmission=1 / np.exp(1)):
150
+ #Calculates the optimal sample thickess to avoid problems with
151
+ #extinction, multiple coherent scattering and absorption.
152
+
153
+
154
+ sigma_coh = np.sum([atom.occupancy * atom.coh_xs for atom in self.atoms])
155
+ sigma_inc = np.sum([atom.occupancy * atom.inc_xs for atom in self.atoms])
156
+ sigma_abs = np.sum([atom.occupancy * atom.abs_xs for atom in self.atoms])
157
+
158
+ sigma_T = (sigma_coh + sigma_inc + sigma_abs * np.sqrt(25.3 / energy)) / self.volume
159
+
160
+ return -np.log(transmission) / sigma_T
161
+
162
+ def calc_incoh_elas_xs(self, mass=None):
163
+ #Calculates the incoherent elastic cross section.
164
+
165
+
166
+ INC_XS = 0
167
+ for atom in self.atoms:
168
+ INC_XS += atom.inc_xs * np.exp(-8 * np.pi ** 2 * atom.Uiso * np.sin(
169
+ np.deg2rad(self.get_two_theta(atom.pos, self.wavelength) / 2.)) ** 2 / self.wavelength ** 2)
170
+
171
+ if mass is not None:
172
+ return self.N_atoms(mass) / (4 * np.pi) * INC_XS
173
+ else:
174
+ return INC_XS / (4 * np.pi)