Debian Codegraph @

examples/R/sig.R

raw
1 #Takes a path in R^d given by an array of n points with dims c(d,n)
2 #and returns its signature up to level m excluding level 0
3 #e.g. path=array(c(1,1,3,10,20,30),c(3,2))
4 #Note that the order of path's dimensions is the other
5 #way around from iisignature.sig.
6 sig=function(path,m, flat=TRUE){
7 n=dim(path)[2]
8 d=dim(path)[1]
9 diffs=path[,-1,drop=FALSE]-path[,-n,drop=FALSE]
10 if (n<2){
11 o=sapply(1:m,function(x)rep(0,d**x))
12 if (flat) return (do.call(c,o))
13 return (o)
14 }
15 r=lapply(1:(n-1),function(x)Reduce(kronecker,rep(list(diffs[,x]),m),accumulate=TRUE))
16 facts=lapply(1:m,factorial)
17 r=lapply(r,function(x)mapply("/",x,facts))
18 chen=function(x,y) c(list(x[[1]]+y[[1]]),
19 lapply(2:m,
20 function(z)x[[z]]+y[[z]]
21 +Reduce("+",mapply(kronecker,x[1:z-1],rev(y[1:z-1]),
22 SIMPLIFY=FALSE))))
23 o=Reduce(chen,r)
24 if (flat) return (do.call(c,o))
25 o
26 }
27