I'd like to find the points of a time-series that are a certain distance away (in value, not in time) from the previous maximum, which I consider a reversal.
For example, for {1, 2, 3, 5, 10, 8, 6, 3}
with a threshold of 4
, the reversal point would be 6
, since it's 4
units away from the previous maximum of 10
.
I want to find all such reversal points, but at each one I need to reset the running maximum (or split the list and start again on the new list).
Here is some code to find the first reversal. It computes the distance from each element to a rolling maximum, then looks for the first difference bigger than the threshold.
ts = {1, 2, 3, 5, 10, 8, 6, 3};
rollmax = FoldList[Max, First[ts], Rest[ts]];
delta = rollmax - ts;
sel = Map[# >= 4 &, delta];
index = Position[sel, True, 1, 1]
I can do this in a procedural way, but it's probably not the preferred way. I'm new to functional programming and I don't quite know what sort of patterns are available that would help me here.
And if there was a better way of writing the above code, please let me know.
Answer
You seem to be on the right track. If I understand your question I believe this will help:
f = If[#2 + 4 <= #, -∞, Max[##]] &;
FoldList[f, ts]
Position[%, -∞, {1}]
(See Shorter syntax for Fold and FoldList? regarding FoldList[f, ts]
.)
The above assumes that you want to reset the new maximum to the value after the reversal (3).
If you want to reset it to the reversal point value itself, try this:
f = If[#2 + 4 <= Max@#, {#2}, Max[##]] &;
FoldList[f, ts]
Position[%, {_}, {1}]
I argue the superiority of the FoldList
method over Module
/MapIndexed
. The latter introduces a variable that it does not need to, it is longer, and it is slower.
SeedRandom[1]
ts = RandomInteger[20, 50000];
Timing[
r1 =
Module[{max = -∞},
MapIndexed[(max = Max[max, #1];
If[max - #1 >= 4, Sow[#2]; max = -∞;]) &, ts];] //
Reap // Last // Flatten;
]
{0.1966, Null}
f = If[#2 + 4 <= #, -∞, Max[##]] &;
Timing[
r2 = Join @@ Position[FoldList[f, #, {##2}] & @@ ts, -∞, 1];
]
{0.0874, Null}
r1 === r2
True
Comments
Post a Comment