-
Notifications
You must be signed in to change notification settings - Fork 122
/
CrystalFieldMultiSpectrum.cpp
483 lines (450 loc) · 19.6 KB
/
CrystalFieldMultiSpectrum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#include "MantidCurveFitting/Functions/CrystalFieldMultiSpectrum.h"
#include "MantidCurveFitting/Functions/CrystalElectricField.h"
#include "MantidCurveFitting/Functions/CrystalFieldHeatCapacity.h"
#include "MantidCurveFitting/Functions/CrystalFieldMagnetisation.h"
#include "MantidCurveFitting/Functions/CrystalFieldMoment.h"
#include "MantidCurveFitting/Functions/CrystalFieldPeakUtils.h"
#include "MantidCurveFitting/Functions/CrystalFieldPeaks.h"
#include "MantidCurveFitting/Functions/CrystalFieldSusceptibility.h"
#include "MantidAPI/FunctionFactory.h"
#include "MantidAPI/IConstraint.h"
#include "MantidAPI/IFunction1D.h"
#include "MantidAPI/IPeakFunction.h"
#include "MantidAPI/MultiDomainFunction.h"
#include "MantidAPI/ParameterTie.h"
#include "MantidKernel/Exception.h"
#include "MantidKernel/Logger.h"
#include <boost/regex.hpp>
namespace Mantid::CurveFitting::Functions {
using namespace CurveFitting;
using namespace Kernel;
using namespace API;
DECLARE_FUNCTION(CrystalFieldMultiSpectrum)
namespace {
Kernel::Logger g_log("CrystalFieldMultiSpectrum");
// Regex for the FWHMX# type strings (single-site mode)
const boost::regex FWHMX_ATTR_REGEX("FWHMX([0-9]+)");
const boost::regex FWHMY_ATTR_REGEX("FWHMY([0-9]+)");
/// Define the source function for CrystalFieldMultiSpectrum.
/// Its function() method is not needed.
class Peaks : public CrystalFieldPeaksBase, public API::IFunctionGeneral {
public:
Peaks() : CrystalFieldPeaksBase() {}
std::string name() const override { return "Peaks"; }
size_t getNumberDomainColumns() const override {
throw Exception::NotImplementedError("This method is intentionally not implemented.");
}
size_t getNumberValuesPerArgument() const override {
throw Exception::NotImplementedError("This method is intentionally not implemented.");
}
void functionGeneral(const API::FunctionDomainGeneral & /*domain*/, API::FunctionValues & /*values*/) const override {
throw Exception::NotImplementedError("This method is intentionally not implemented.");
}
std::vector<size_t> m_IntensityScalingIdx;
std::vector<size_t> m_PPLambdaIdxChild;
std::vector<size_t> m_PPLambdaIdxSelf;
std::vector<size_t> m_PPChi0IdxChild;
std::vector<size_t> m_PPChi0IdxSelf;
/// Declare the intensity scaling parameters: one per spectrum.
void declareIntensityScaling(size_t nSpec) {
m_IntensityScalingIdx.clear();
m_PPLambdaIdxChild.resize(nSpec, -1);
m_PPLambdaIdxSelf.resize(nSpec, -1);
m_PPChi0IdxChild.resize(nSpec, -1);
m_PPChi0IdxSelf.resize(nSpec, -1);
for (size_t i = 0; i < nSpec; ++i) {
auto si = std::to_string(i);
try { // If parameter has already been declared, don't declare it.
declareParameter("IntensityScaling" + si, 1.0, "Intensity scaling factor for spectrum " + si);
} catch (std::invalid_argument &) {
}
m_IntensityScalingIdx.emplace_back(parameterIndex("IntensityScaling" + si));
}
}
/// Declare the Lambda parameter for susceptibility
void declarePPLambda(size_t iSpec) {
if (m_PPLambdaIdxSelf.size() <= iSpec) {
m_PPLambdaIdxSelf.resize(iSpec + 1, -1);
m_PPLambdaIdxChild.resize(iSpec + 1, -1);
m_PPChi0IdxSelf.resize(iSpec + 1, -1);
m_PPChi0IdxChild.resize(iSpec + 1, -1);
}
auto si = std::to_string(iSpec);
try { // If parameter has already been declared, don't declare it.
declareParameter("Lambda" + si, 0.0, "Effective exchange coupling of dataset " + si);
} catch (std::invalid_argument &) {
}
try { // If parameter has already been declared, don't declare it.
declareParameter("Chi0" + si, 0.0, "Effective exchange coupling of dataset " + si);
} catch (std::invalid_argument &) {
}
m_PPLambdaIdxSelf[iSpec] = parameterIndex("Lambda" + si);
m_PPChi0IdxSelf[iSpec] = parameterIndex("Chi0" + si);
}
};
} // namespace
/// Constructor
CrystalFieldMultiSpectrum::CrystalFieldMultiSpectrum() : FunctionGenerator(IFunction_sptr(new Peaks)) {
declareAttribute("Temperatures", Attribute(std::vector<double>(1, 1.0)));
declareAttribute("Background", Attribute("FlatBackground", true));
declareAttribute("PeakShape", Attribute("Lorentzian"));
declareAttribute("FWHMs", Attribute(std::vector<double>(1, 0.0)));
declareAttribute("FWHMX0", Attribute(std::vector<double>()));
declareAttribute("FWHMY0", Attribute(std::vector<double>()));
declareAttribute("FWHMVariation", Attribute(0.1));
declareAttribute("NPeaks", Attribute(0));
declareAttribute("FixAllPeaks", Attribute(false));
declareAttribute("PhysicalProperties", Attribute(std::vector<double>(1, 0.0)));
}
void CrystalFieldMultiSpectrum::init() {
try {
buildTargetFunction();
} catch (std::runtime_error const &ex) {
g_log.error(ex.what());
}
}
size_t CrystalFieldMultiSpectrum::getNumberDomains() const {
if (!m_target) {
buildTargetFunction();
if (!m_target) {
throw std::runtime_error("Failed to build target function.");
}
}
return m_target->getNumberDomains();
}
std::vector<IFunction_sptr> CrystalFieldMultiSpectrum::createEquivalentFunctions() const {
checkTargetFunction();
std::vector<IFunction_sptr> funs;
auto &composite = dynamic_cast<CompositeFunction &>(*m_target);
for (size_t i = 0; i < composite.nFunctions(); ++i) {
funs.emplace_back(composite.getFunction(i));
}
return funs;
}
/// Perform custom actions on setting certain attributes.
void CrystalFieldMultiSpectrum::setAttribute(const std::string &name, const Attribute &attr) {
boost::smatch match;
if (name == "Temperatures") {
// Define (declare) the parameters for intensity scaling.
const auto nSpec = attr.asVector().size();
dynamic_cast<Peaks &>(*m_source).declareIntensityScaling(nSpec);
m_nOwnParams = m_source->nParams();
m_fwhmX.resize(nSpec);
m_fwhmY.resize(nSpec);
std::vector<double> new_fwhm = getAttribute("FWHMs").asVector();
const auto nWidths = new_fwhm.size();
if (nWidths != nSpec) {
new_fwhm.resize(nSpec);
if (nWidths > nSpec) {
for (size_t iSpec = nWidths; iSpec < nSpec; ++iSpec) {
new_fwhm[iSpec] = new_fwhm[0];
}
}
}
Attribute newVal = attr;
newVal.setVector(new_fwhm);
FunctionGenerator::setAttribute("FWHMs", newVal);
for (size_t iSpec = 0; iSpec < nSpec; ++iSpec) {
const auto suffix = std::to_string(iSpec);
// try to declare attribute, if already exists, set attribute.
try {
declareAttribute("FWHMX" + suffix, Attribute(m_fwhmX[iSpec]));
} catch (const std::invalid_argument &) {
setAttribute("FWHMX" + suffix, Attribute(m_fwhmX[iSpec]));
}
try {
declareAttribute("FWHMY" + suffix, Attribute(m_fwhmY[iSpec]));
} catch (const std::invalid_argument &) {
setAttribute("FWHMY" + suffix, Attribute(m_fwhmY[iSpec]));
}
}
} else if (name == "PhysicalProperties") {
const auto physpropId = attr.asVector();
const auto nSpec = physpropId.size();
auto &source = dynamic_cast<Peaks &>(*m_source);
for (size_t iSpec = 0; iSpec < nSpec; ++iSpec) {
const auto suffix = std::to_string(iSpec);
const auto pptype = static_cast<int>(physpropId[iSpec]);
switch (pptype) {
case MagneticMoment: // Hmag, Hdir, inverse, Unit, powder
declareAttribute("Hmag" + suffix, Attribute(1.0));
// fall through
case Susceptibility: // Hdir, inverse, Unit, powder
declareAttribute("inverse" + suffix, Attribute(false));
// fall through
case Magnetisation: // Hdir, Unit, powder
declareAttribute("Hdir" + suffix, Attribute(std::vector<double>{0., 0., 1.}));
declareAttribute("Unit" + suffix, Attribute("bohr"));
declareAttribute("powder" + suffix, Attribute(false));
break;
}
if (pptype == Susceptibility) {
source.declarePPLambda(iSpec);
m_nOwnParams = m_source->nParams();
}
}
} else if (boost::regex_match(name, match, FWHMX_ATTR_REGEX)) {
auto iSpec = std::stoul(match[1]);
if (m_fwhmX.size() > iSpec) {
m_fwhmX[iSpec].clear();
} else {
throw std::invalid_argument("Temperatures must be defined before resolution model");
}
} else if (boost::regex_match(name, match, FWHMY_ATTR_REGEX)) {
auto iSpec = std::stoul(match[1]);
if (m_fwhmY.size() > iSpec) {
m_fwhmY[iSpec].clear();
} else {
throw std::invalid_argument("Temperatures must be defined before resolution model");
}
}
FunctionGenerator::setAttribute(name, attr);
}
/// Uses source to calculate peak centres and intensities
/// then populates m_spectrum with peaks of type given in PeakShape attribute.
void CrystalFieldMultiSpectrum::buildTargetFunction() const {
m_dirty = false;
auto fun = new MultiDomainFunction;
m_target.reset(fun);
DoubleFortranVector en;
ComplexFortranMatrix wf;
ComplexFortranMatrix ham;
ComplexFortranMatrix hz;
int nre = 0;
auto &peakCalculator = dynamic_cast<Peaks &>(*m_source);
peakCalculator.calculateEigenSystem(en, wf, ham, hz, nre);
ham += hz;
// Get the temperatures from the attribute
m_temperatures = getAttribute("Temperatures").asVector();
if (m_temperatures.empty()) {
throw std::runtime_error("Vector of temperatures cannot be empty.");
}
// Get the FWHMs from the attribute and check for consistency.
m_FWHMs = getAttribute("FWHMs").asVector();
if (m_FWHMs.empty()) {
throw std::runtime_error("Vector of FWHMs cannot be empty.");
} else if (m_FWHMs.size() != m_temperatures.size()) {
if (m_FWHMs.size() == 1) {
auto fwhm = m_FWHMs.front();
m_FWHMs.resize(m_temperatures.size(), fwhm);
} else {
throw std::runtime_error("Vector of FWHMs must either have same size as "
"Temperatures (" +
std::to_string(m_temperatures.size()) + ") or have size 1.");
}
}
const auto nSpec = m_temperatures.size();
// Get a list of "spectra" which corresponds to physical properties
const auto physprops = getAttribute("PhysicalProperties").asVector();
if (physprops.empty()) {
m_physprops.resize(nSpec, 0); // Assume no physical properties - just INS
} else if (physprops.size() != nSpec) {
if (physprops.size() == 1) {
auto physprop = static_cast<int>(physprops.front());
m_physprops.resize(nSpec, physprop);
} else {
throw std::runtime_error("Vector of PhysicalProperties must have same "
"size as Temperatures or size 1.");
}
} else {
m_physprops.clear();
m_physprops.reserve(physprops.size());
std::transform(physprops.cbegin(), physprops.cend(), std::back_inserter(m_physprops),
[](auto elem) { return static_cast<int>(elem); });
}
// Create the single-spectrum functions.
m_nPeaks.resize(nSpec);
if (m_fwhmX.empty()) {
m_fwhmX.resize(nSpec);
m_fwhmY.resize(nSpec);
}
for (size_t i = 0; i < nSpec; ++i) {
if (m_physprops[i] > 0) {
// This "spectrum" is actually a physical properties dataset.
fun->addFunction(buildPhysprop(nre, en, wf, ham, m_temperatures[i], i));
} else {
if (m_fwhmX[i].empty()) {
auto suffix = std::to_string(i);
m_fwhmX[i] = IFunction::getAttribute("FWHMX" + suffix).asVector();
m_fwhmY[i] = IFunction::getAttribute("FWHMY" + suffix).asVector();
}
fun->addFunction(buildSpectrum(nre, en, wf, m_temperatures[i], m_FWHMs[i], i));
}
fun->setDomainIndex(i, i);
}
}
/// Calculate excitations at given temperature
void CrystalFieldMultiSpectrum::calcExcitations(int nre, const DoubleFortranVector &en, const ComplexFortranMatrix &wf,
double temperature, FunctionValues &values, size_t iSpec) const {
IntFortranVector degeneration;
DoubleFortranVector eEnergies;
DoubleFortranMatrix iEnergies;
const double de = getAttribute("ToleranceEnergy").asDouble();
const double di = getAttribute("ToleranceIntensity").asDouble();
DoubleFortranVector eExcitations;
DoubleFortranVector iExcitations;
calculateIntensities(nre, en, wf, temperature, de, degeneration, eEnergies, iEnergies);
calculateExcitations(eEnergies, iEnergies, de, di, eExcitations, iExcitations);
const size_t nSpec = m_nPeaks.size();
// Get intensity scaling parameter "IntensityScaling" + std::to_string(iSpec)
// using an index instead of a name for performance reasons
auto &source = dynamic_cast<Peaks &>(*m_source);
double intensityScaling;
if (source.m_IntensityScalingIdx.empty()) {
intensityScaling = getParameter(m_nOwnParams - nSpec + iSpec);
} else {
intensityScaling = getParameter(source.m_IntensityScalingIdx[iSpec]);
}
const auto nPeaks = eExcitations.size();
values.expand(2 * nPeaks);
for (size_t i = 0; i < nPeaks; ++i) {
values.setCalculated(i, eExcitations.get(i));
values.setCalculated(i + nPeaks, iExcitations.get(i) * intensityScaling);
}
}
/// Build a function for a single spectrum.
API::IFunction_sptr CrystalFieldMultiSpectrum::buildSpectrum(int nre, const DoubleFortranVector &en,
const ComplexFortranMatrix &wf, double temperature,
double fwhm, size_t iSpec) const {
FunctionValues values;
calcExcitations(nre, en, wf, temperature, values, iSpec);
m_nPeaks[iSpec] = CrystalFieldUtils::calculateNPeaks(values);
const auto fwhmVariation = getAttribute("FWHMVariation").asDouble();
const auto peakShape = IFunction::getAttribute("PeakShape").asString();
auto bkgdShape = IFunction::getAttribute("Background").asUnquotedString();
const size_t nRequiredPeaks = IFunction::getAttribute("NPeaks").asInt();
const bool fixAllPeaks = getAttribute("FixAllPeaks").asBool();
if (!bkgdShape.empty() && bkgdShape.find("name=") != 0 && bkgdShape.front() != '(') {
bkgdShape = "name=" + bkgdShape;
}
auto spectrum = new CompositeFunction;
auto background = API::FunctionFactory::Instance().createInitialized(bkgdShape);
spectrum->addFunction(background);
if (fixAllPeaks) {
background->fixAll();
}
m_nPeaks[iSpec] = CrystalFieldUtils::buildSpectrumFunction(
*spectrum, peakShape, values, m_fwhmX[iSpec], m_fwhmY[iSpec], fwhmVariation, fwhm, nRequiredPeaks, fixAllPeaks);
return IFunction_sptr(spectrum);
}
API::IFunction_sptr CrystalFieldMultiSpectrum::buildPhysprop(int nre, const DoubleFortranVector &en,
const ComplexFortranMatrix &wf,
const ComplexFortranMatrix &ham, double temperature,
size_t iSpec) const {
switch (m_physprops[iSpec]) {
case HeatCapacity: {
IFunction_sptr retval = IFunction_sptr(new CrystalFieldHeatCapacity);
auto &spectrum = dynamic_cast<CrystalFieldHeatCapacity &>(*retval);
spectrum.setEnergy(en);
return retval;
}
case Susceptibility: {
IFunction_sptr retval = IFunction_sptr(new CrystalFieldSusceptibility);
auto &spectrum = dynamic_cast<CrystalFieldSusceptibility &>(*retval);
spectrum.setEigensystem(en, wf, nre);
const auto suffix = std::to_string(iSpec);
spectrum.setAttribute("Hdir", getAttribute("Hdir" + suffix));
spectrum.setAttribute("inverse", getAttribute("inverse" + suffix));
spectrum.setAttribute("powder", getAttribute("powder" + suffix));
dynamic_cast<Peaks &>(*m_source).m_PPLambdaIdxChild[iSpec] = spectrum.parameterIndex("Lambda");
dynamic_cast<Peaks &>(*m_source).m_PPChi0IdxChild[iSpec] = spectrum.parameterIndex("Chi0");
return retval;
}
case Magnetisation: {
IFunction_sptr retval = IFunction_sptr(new CrystalFieldMagnetisation);
auto &spectrum = dynamic_cast<CrystalFieldMagnetisation &>(*retval);
spectrum.setHamiltonian(ham, nre);
spectrum.setAttributeValue("Temperature", temperature);
const auto suffix = std::to_string(iSpec);
spectrum.setAttribute("Unit", getAttribute("Unit" + suffix));
spectrum.setAttribute("Hdir", getAttribute("Hdir" + suffix));
spectrum.setAttribute("powder", getAttribute("powder" + suffix));
return retval;
}
case MagneticMoment: {
IFunction_sptr retval = IFunction_sptr(new CrystalFieldMoment);
auto &spectrum = dynamic_cast<CrystalFieldMoment &>(*retval);
spectrum.setHamiltonian(ham, nre);
const auto suffix = std::to_string(iSpec);
spectrum.setAttribute("Unit", getAttribute("Unit" + suffix));
spectrum.setAttribute("Hdir", getAttribute("Hdir" + suffix));
spectrum.setAttribute("Hmag", getAttribute("Hmag" + suffix));
spectrum.setAttribute("inverse", getAttribute("inverse" + suffix));
spectrum.setAttribute("powder", getAttribute("powder" + suffix));
return retval;
}
}
throw std::runtime_error("Physical property type not understood");
}
/// Update m_spectrum function.
void CrystalFieldMultiSpectrum::updateTargetFunction() const {
if (!m_target) {
buildTargetFunction();
return;
}
m_dirty = false;
DoubleFortranVector en;
ComplexFortranMatrix wf;
ComplexFortranMatrix ham;
ComplexFortranMatrix hz;
int nre = 0;
auto &peakCalculator = dynamic_cast<Peaks &>(*m_source);
peakCalculator.calculateEigenSystem(en, wf, ham, hz, nre);
ham += hz;
auto &fun = dynamic_cast<MultiDomainFunction &>(*m_target);
try {
for (size_t i = 0; i < m_temperatures.size(); ++i) {
updateSpectrum(*fun.getFunction(i), nre, en, wf, ham, m_temperatures[i], m_FWHMs[i], i);
}
fun.checkFunction();
} catch (std::out_of_range &) {
buildTargetFunction();
return;
}
}
/// Update a function for a single spectrum.
void CrystalFieldMultiSpectrum::updateSpectrum(API::IFunction &spectrum, int nre, const DoubleFortranVector &en,
const ComplexFortranMatrix &wf, const ComplexFortranMatrix &ham,
double temperature, double fwhm, size_t iSpec) const {
switch (m_physprops[iSpec]) {
case HeatCapacity: {
auto &heatcap = dynamic_cast<CrystalFieldHeatCapacity &>(spectrum);
heatcap.setEnergy(en);
break;
}
case Susceptibility: {
auto &suscept = dynamic_cast<CrystalFieldSusceptibility &>(spectrum);
suscept.setEigensystem(en, wf, nre);
auto &source = dynamic_cast<Peaks &>(*m_source);
suscept.setParameter(source.m_PPLambdaIdxChild[iSpec], getParameter(source.m_PPLambdaIdxSelf[iSpec]));
suscept.setParameter(source.m_PPChi0IdxChild[iSpec], getParameter(source.m_PPChi0IdxSelf[iSpec]));
break;
}
case Magnetisation: {
auto &magnetisation = dynamic_cast<CrystalFieldMagnetisation &>(spectrum);
magnetisation.setHamiltonian(ham, nre);
break;
}
case MagneticMoment: {
auto &moment = dynamic_cast<CrystalFieldMoment &>(spectrum);
moment.setHamiltonian(ham, nre);
break;
}
default:
const auto fwhmVariation = getAttribute("FWHMVariation").asDouble();
const auto peakShape = IFunction::getAttribute("PeakShape").asString();
const bool fixAllPeaks = getAttribute("FixAllPeaks").asBool();
FunctionValues values;
calcExcitations(nre, en, wf, temperature, values, iSpec);
auto &composite = dynamic_cast<API::CompositeFunction &>(spectrum);
m_nPeaks[iSpec] = CrystalFieldUtils::updateSpectrumFunction(composite, peakShape, values, 1, m_fwhmX[iSpec],
m_fwhmY[iSpec], fwhmVariation, fwhm, fixAllPeaks);
}
}
} // namespace Mantid::CurveFitting::Functions