numass-framework/numass-main/src/main/java/inr/numass/models/ModularSpectrum.java

249 lines
9.4 KiB
Java
Raw Normal View History

2015-12-18 16:20:47 +03:00
/*
* Copyright 2015 Alexander Nozik.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package inr.numass.models;
import hep.dataforge.functions.AbstractParametricFunction;
import hep.dataforge.functions.ParametricFunction;
import hep.dataforge.names.NamedUtils;
2016-05-31 20:05:15 +03:00
import hep.dataforge.values.NamedValueSet;
import hep.dataforge.values.ValueProvider;
2015-12-18 16:20:47 +03:00
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.analysis.BivariateFunction;
import org.slf4j.LoggerFactory;
/**
* Modular spectrum for any source spectrum with separate calculation for
* different transmission components
*
* @author Darksnake
*/
public class ModularSpectrum extends AbstractParametricFunction {
private static final String[] list = {"X", "trap"};
private LossCalculator calculator;
List<NamedSpectrumCaching> cacheList;
2016-05-25 12:18:43 +03:00
NamedSpectrumCaching trappingCache;
2015-12-18 16:20:47 +03:00
BivariateFunction resolution;
RangedNamedSetSpectrum sourceSpectrum;
2016-05-25 12:18:43 +03:00
BivariateFunction trappingFunction;
2016-07-07 20:40:43 +03:00
boolean caching = false;
2015-12-18 16:20:47 +03:00
double cacheMin;
double cacheMax;
/**
*
* @param source
* @param resolution
* @param cacheMin - нижняя граница кэширования. Должна быть с небольшим
* запасом по отношению к данным
* @param cacheMax - верхняя граница кэширования.
*/
public ModularSpectrum(RangedNamedSetSpectrum source, BivariateFunction resolution, double cacheMin, double cacheMax) {
super(NamedUtils.combineNamesWithEquals(list, source.namesAsArray()));
if (cacheMin >= cacheMax) {
throw new IllegalArgumentException();
}
this.cacheMin = cacheMin;
this.cacheMax = cacheMax;
this.resolution = resolution;
this.calculator = LossCalculator.instance();
this.sourceSpectrum = source;
setupCache();
}
public ModularSpectrum(RangedNamedSetSpectrum source, BivariateFunction resolution) {
this(source, resolution, Double.NaN, Double.NaN);
}
/**
*
* @param source
* @param resA - относительная ширина разрешения
* @param cacheMin - нижняя граница кэширования. Должна быть с небольшим
* запасом по отношению к данным
* @param cacheMax - верхняя граница кэширования, может быть без запаса.
*/
public ModularSpectrum(RangedNamedSetSpectrum source, double resA, double cacheMin, double cacheMax) {
this(source, new ResolutionFunction(resA), cacheMin, cacheMax);
}
2016-05-25 12:18:43 +03:00
2015-12-18 16:20:47 +03:00
public ModularSpectrum(RangedNamedSetSpectrum source, double resA) {
this(source, new ResolutionFunction(resA));
2016-05-25 12:18:43 +03:00
}
2015-12-18 16:20:47 +03:00
2016-05-25 12:18:43 +03:00
public void setTrappingFunction(BivariateFunction trappingFunction) {
this.trappingFunction = trappingFunction;
2016-06-04 20:12:40 +03:00
LoggerFactory.getLogger(getClass()).info("Recalculating modular spectrum cache");
setupCache();
2016-05-25 12:18:43 +03:00
}
2015-12-18 16:20:47 +03:00
/**
* Отдельный метод нужен на случай, если бета-спектр(FSS) или разрешение
* будут меняться в процессе
*/
private void setupCache() {
//обновляем кэши для трэппинга и упругого прохождения
2016-05-25 12:18:43 +03:00
//Using external trappingCache function if provided
BivariateFunction trapFunc = trappingFunction != null ? trappingFunction : LossCalculator.getTrapFunction();
2015-12-18 16:20:47 +03:00
BivariateFunction trapRes = new LossResConvolution(trapFunc, resolution);
ParametricFunction elasticSpectrum = new TransmissionConvolution(sourceSpectrum, resolution, sourceSpectrum);
ParametricFunction trapSpectrum = new TransmissionConvolution(sourceSpectrum, trapRes, sourceSpectrum);
/**
* обнуляем кэш рассеяния
*/
cacheList = new ArrayList<>();
//добавляем нулевой порядок - упругое рассеяние
TritiumSpectrumCaching elasticCache = new TritiumSpectrumCaching(elasticSpectrum, cacheMin, cacheMax);
elasticCache.setCachingEnabled(caching);
cacheList.add(elasticCache);
2016-05-25 12:18:43 +03:00
this.trappingCache = new TritiumSpectrumCaching(trapSpectrum, cacheMin, cacheMax);
this.trappingCache.setCachingEnabled(caching);
2015-12-18 16:20:47 +03:00
}
/**
* Обновляем кэш рассеяния если требуемый порядок выше, чем тот, что есть
*
* @param order
*/
private void updateScatterCache(int order) {
if (order >= cacheList.size()) {
LoggerFactory.getLogger(getClass())
.debug("Updating scatter cache up to order of '{}'", order);
// здесь можно сэкономить вызовы, начиная с cacheList.size(), но надо это?
for (int i = 1; i < order + 1; i++) {
BivariateFunction loss = calculator.getLossFunction(i);
BivariateFunction lossRes = new LossResConvolution(loss, resolution);
ParametricFunction inelasticSpectrum = new TransmissionConvolution(sourceSpectrum, lossRes, sourceSpectrum);
TritiumSpectrumCaching spCatch = new TritiumSpectrumCaching(inelasticSpectrum, cacheMin, cacheMax);
spCatch.setCachingEnabled(caching);
spCatch.setSuppressWarnings(true);
//TODO сделать пороверку
cacheList.add(i, spCatch);
}
}
}
@Override
2016-05-31 20:05:15 +03:00
public double derivValue(String parName, double U, NamedValueSet set) {
2015-12-18 16:20:47 +03:00
if (U >= sourceSpectrum.max(set)) {
return 0;
}
double X = this.getX(set);
switch (parName) {
case "X":
List<Double> probDerivs = calculator.getLossProbDerivs(X);
updateScatterCache(probDerivs.size() - 1);
double derivSum = 0;
for (int i = 0; i < probDerivs.size(); i++) {
derivSum += probDerivs.get(i) * cacheList.get(i).value(U, set);
}
return derivSum;
case "trap":
2016-05-25 12:18:43 +03:00
return this.trappingCache.value(U, set);
2015-12-18 16:20:47 +03:00
default:
if (sourceSpectrum.names().contains(parName)) {
List<Double> probs = calculator.getLossProbabilities(X);
updateScatterCache(probs.size() - 1);
double sum = 0;
for (int i = 0; i < probs.size(); i++) {
sum += probs.get(i) * cacheList.get(i).derivValue(parName, U, set);
}
2016-05-25 12:18:43 +03:00
sum += this.getTrap(set) * this.trappingCache.derivValue(parName, U, set);
2015-12-18 16:20:47 +03:00
return sum;
} else {
return 0;
}
}
}
2016-05-31 20:05:15 +03:00
private double getTrap(ValueProvider set) {
return set.getDouble("trap");
2015-12-18 16:20:47 +03:00
}
2016-05-31 20:05:15 +03:00
private double getX(ValueProvider set) {
return set.getDouble("X");
2015-12-18 16:20:47 +03:00
}
@Override
public boolean providesDeriv(String name) {
return sourceSpectrum.providesDeriv(name);
}
/**
* Set the boundaries and recalculate cache
2016-05-25 12:18:43 +03:00
*
2015-12-18 16:20:47 +03:00
* @param cacheMin
2016-05-25 12:18:43 +03:00
* @param cacheMax
2015-12-18 16:20:47 +03:00
*/
2016-05-25 12:18:43 +03:00
public void setCachingBoundaries(double cacheMin, double cacheMax) {
2015-12-18 16:20:47 +03:00
this.cacheMin = cacheMin;
this.cacheMax = cacheMax;
setupCache();
}
2016-05-25 12:18:43 +03:00
2015-12-18 16:20:47 +03:00
public final void setCaching(boolean caching) {
2016-05-25 12:18:43 +03:00
if (caching && (cacheMin == Double.NaN || cacheMax == Double.NaN)) {
2015-12-18 16:20:47 +03:00
throw new IllegalStateException("Cahing boundaries are not defined");
}
2016-05-25 12:18:43 +03:00
2015-12-18 16:20:47 +03:00
this.caching = caching;
2016-05-25 12:18:43 +03:00
this.trappingCache.setCachingEnabled(caching);
2016-06-29 19:01:10 +03:00
this.cacheList.stream().forEach((sp) -> {
2015-12-18 16:20:47 +03:00
sp.setCachingEnabled(caching);
2016-06-29 19:01:10 +03:00
});
2015-12-18 16:20:47 +03:00
}
2016-06-02 18:41:34 +03:00
/**
* Suppress warnings about cache recalculation
* @param suppress
*/
2015-12-18 16:20:47 +03:00
public void setSuppressWarnings(boolean suppress) {
2016-05-25 12:18:43 +03:00
this.trappingCache.setSuppressWarnings(suppress);
2016-06-02 18:41:34 +03:00
this.cacheList.stream().forEach((sp) -> {
2015-12-18 16:20:47 +03:00
sp.setSuppressWarnings(suppress);
2016-06-02 18:41:34 +03:00
});
2015-12-18 16:20:47 +03:00
}
@Override
2016-05-31 20:05:15 +03:00
public double value(double U, NamedValueSet set) {
2015-12-18 16:20:47 +03:00
if (U >= sourceSpectrum.max(set)) {
return 0;
}
double X = this.getX(set);
List<Double> probs = calculator.getLossProbabilities(X);
updateScatterCache(probs.size() - 1);
double res = 0;
for (int i = 0; i < probs.size(); i++) {
res += probs.get(i) * cacheList.get(i).value(U, set);
}
2016-05-25 12:18:43 +03:00
res += this.getTrap(set) * this.trappingCache.value(U, set);
2015-12-18 16:20:47 +03:00
return res;
}
}