|
standard library package SampledFunctions { |
|
doc |
|
|
|
|
|
|
|
|
|
private import Base::Anything; |
|
private import ScalarValues::Positive; |
|
private import Collections::KeyValuePair; |
|
private import Collections::OrderedMap; |
|
private import SequenceFunctions::size; |
|
private import ControlFunctions::forAll; |
|
private import ControlFunctions::collect; |
|
private import ControlFunctions::select; |
|
|
|
attribute def SamplePair :> KeyValuePair { |
|
doc |
|
|
|
|
|
|
|
|
|
attribute domainValue :>> key; |
|
attribute rangeValue :>> val; |
|
} |
|
|
|
attribute def SampledFunction :> OrderedMap { |
|
doc |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
attribute samples: SamplePair[0..*] ordered :>> elements; |
|
|
|
assert constraint { |
|
|
|
(1..size(samples)-1)->forAll { in i; (samples.domainValue#(i) < samples.domainValue#(i+1)) } or |
|
(1..size(samples)-1)->forAll { in i; (samples.domainValue#(i) > samples.domainValue#(i+1)) } |
|
} |
|
} |
|
|
|
calc def Domain { |
|
doc |
|
|
|
|
|
|
|
|
|
in fn : SampledFunction; |
|
return : Anything[0..*] = fn.samples.domainValue; |
|
} |
|
|
|
calc def Range { |
|
doc |
|
|
|
|
|
|
|
|
|
in fn : SampledFunction; |
|
return : Anything[0..*] = fn.samples.rangeValue; |
|
} |
|
|
|
calc def Sample { |
|
doc |
|
|
|
|
|
|
|
|
|
in calc calculation { in x; } |
|
in attribute domainValues [0..*]; |
|
return sampling = SampledFunction ( |
|
samples = domainValues->collect { in x; SamplePair(x, calculation(x)) } |
|
); |
|
} |
|
|
|
calc def Interpolate { |
|
doc |
|
|
|
|
|
|
|
|
|
|
|
in attribute fn : SampledFunction; |
|
in attribute value; |
|
return attribute result; |
|
} |
|
|
|
calc interpolateLinear : Interpolate { |
|
doc |
|
|
|
|
|
|
|
|
|
in attribute fn : SampledFunction; |
|
in attribute value; |
|
|
|
private attribute domainValues = Domain(fn); |
|
private attribute index : Positive[0..1] = |
|
(1..size(domainValues))->select { in i : Positive; domainValues#(i) <= value }#(1); |
|
|
|
private calc def Linear { |
|
in attribute lowerSample : SamplePair; |
|
in attribute upperSample : SamplePair; |
|
in attribute value; |
|
private attribute f = (value - lowerSample.domainValue) / (lowerSample.domainValue - upperSample.domainValue); |
|
return result = upperSample.rangeValue + f * (lowerSample.rangeValue - upperSample.rangeValue); |
|
} |
|
|
|
return result [0..1] = |
|
if index == null or index == size(domainValues)? null |
|
else if domainValues#(index) < domainValues#(index+1)? Linear(fn.samples#(index), fn.samples#(index+1), value) |
|
else Linear(fn.samples#(index+1), fn.samples#(index), value); |
|
} |
|
|
|
} |