vectorizing the integrate function

classic Classic list List threaded Threaded
10 messages Options
Reply | Threaded
Open this post in threaded view
|

vectorizing the integrate function

R help mailing list-2
Hi all,I am having some difficulties in vectorizing the integrate function. Let me explain with an example.
a <- 10; b <- 3; c <- 4
f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
integrate(f,0,Inf) # works fine

My difficulties start when I want to vectorize.

# attempts to vectorize fail
a <- seq(from=0,to=1,by=0.5)
b <- seq(from=5,to=10,by=1)
m <- seq(from=10,to=20,by=5)
f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
fv <- Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)

I want the result as a 3-d array with dimensions of the lengths of a, b and c. I have tried several variants but am not having much luck. Will appreciate any help that I can get.
Thanks,Ravi Sutradhara




        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: vectorizing the integrate function

Bert Gunter-2
Ravi:

First of all, you're calling Vectorize incorrectly. The first argument must
be a function *name*, not a function call. Here's what you need to do (and
thanks for the reprex -- wouldn't have been able to help without it!):

f2 <- function(a,b,c)integrate(function(x){exp(-a*x^3-b*x^2-c*x)},lower
=0,upper = Inf)
fv <- Vectorize(f2,vectorize.args=c("a","b","c"),SIMPLIFY=TRUE)

Second of all, as you may realize, the vectorization uses mapply() and so
vectorizes the c(a,b,c) triplet "in parallel," which will "recycle" shorter
arguments to the length of longer. Hence you will get 6 results from your
example:

> fv(a,b,m)
             [,1]         [,2]         [,3]        [,4]         [,5]
  [,6]
value        0.09207851   0.0635289    0.04837997  0.08856628   0.06224138
  0.04777941
abs.error    3.365173e-08 3.108388e-06 1.00652e-09 3.284876e-09
1.796619e-08 6.348142e-09
subdivisions 2            1            2           2            2
 2
message      "OK"         "OK"         "OK"        "OK"         "OK"
  "OK"
call         Expression   Expression   Expression  Expression   Expression
  Expression

Cheers,
Bert

Bert Gunter

"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Sat, Aug 10, 2019 at 10:20 AM ravi via R-help <[hidden email]>
wrote:

> Hi all,I am having some difficulties in vectorizing the integrate
> function. Let me explain with an example.
> a <- 10; b <- 3; c <- 4
> f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
> integrate(f,0,Inf) # works fine
>
> My difficulties start when I want to vectorize.
>
> # attempts to vectorize fail
> a <- seq(from=0,to=1,by=0.5)
> b <- seq(from=5,to=10,by=1)
> m <- seq(from=10,to=20,by=5)
> f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
> fv <-
> Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
>
> I want the result as a 3-d array with dimensions of the lengths of a, b
> and c. I have tried several variants but am not having much luck. Will
> appreciate any help that I can get.
> Thanks,Ravi Sutradhara
>
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: vectorizing the integrate function

R help mailing list-2
 Bert,Thanks a lot for your help. I have a few follow-up questions (shown in the comment lines).  Numerical values and error for a (i) vector and (ii) array.

a <- seq(from=0,to=1,by=0.5)
b <- seq(from=5,to=10,by=1)
m <- seq(from=10,to=20,by=5)

f2 <- function(a,b,m)integrate(function(x){exp(-a*x^3-b*x^2-m*x)},lower=0,upper = Inf)
fv <- Vectorize(f2,vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)

r1 <- fv(a,b,m)
# How to get just the numerical results as an array
# for scalar values of a,b and m, I can get it with

#s <- integrate(f,0,Inf)$value
# How do I get this for a vector

# Finally, if I want an array for all the values of a, b and m, how should I proceed?
r <- array(0,c(3,6,3))
r.error <- array(0,c(3,6,3))
# I want the results of the vectorized integrate function in the above arrays. How do I extract these values?

Thanks,Ravi


    On Saturday, 10 August 2019, 20:03:22 CEST, Bert Gunter <[hidden email]> wrote:  
 
 Ravi:
First of all, you're calling Vectorize incorrectly. The first argument must be a function *name*, not a function call. Here's what you need to do (and thanks for the reprex -- wouldn't have been able to help without it!):
f2 <- function(a,b,c)integrate(function(x){exp(-a*x^3-b*x^2-c*x)},lower =0,upper = Inf)
fv <- Vectorize(f2,vectorize.args=c("a","b","c"),SIMPLIFY=TRUE)
Second of all, as you may realize, the vectorization uses mapply() and so vectorizes the c(a,b,c) triplet "in parallel," which will "recycle" shorter arguments to the length of longer. Hence you will get 6 results from your example:
> fv(a,b,m)
             [,1]         [,2]         [,3]        [,4]         [,5]         [,6]        
value        0.09207851   0.0635289    0.04837997  0.08856628   0.06224138   0.04777941  
abs.error    3.365173e-08 3.108388e-06 1.00652e-09 3.284876e-09 1.796619e-08 6.348142e-09
subdivisions 2            1            2           2            2            2          
message      "OK"         "OK"         "OK"        "OK"         "OK"         "OK"        
call         Expression   Expression   Expression  Expression   Expression   Expression 

Cheers,Bert
Bert Gunter

"The trouble with having an open mind is that people keep coming along and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Sat, Aug 10, 2019 at 10:20 AM ravi via R-help <[hidden email]> wrote:

Hi all,I am having some difficulties in vectorizing the integrate function. Let me explain with an example.
a <- 10; b <- 3; c <- 4
f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
integrate(f,0,Inf) # works fine

My difficulties start when I want to vectorize.

# attempts to vectorize fail
a <- seq(from=0,to=1,by=0.5)
b <- seq(from=5,to=10,by=1)
m <- seq(from=10,to=20,by=5)
f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
fv <- Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)

I want the result as a 3-d array with dimensions of the lengths of a, b and c. I have tried several variants but am not having much luck. Will appreciate any help that I can get.
Thanks,Ravi Sutradhara




        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

 
        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: vectorizing the integrate function

Rui Barradas
Hello,

The following code might not be the best way of computing the integrals
for all combinations of the arguments but it gets the job done and I
believe it's readable code.


f2 <- function(a, b, c){
   integrate(function(x) {exp(-a*x^3 - b*x^2 - c*x)},
             lower = 0, upper = Inf)
}

f2_all_args <- function(a, b, c){
   lapply(a, function(.a)
     lapply(b, function(.b)
       lapply(c, function(.c)
         f2(.a, .b, .c)[1:2]
       )
     )
   )
}

a <- seq(from = 0, to = 1, by = 0.5)
b <- seq(from = 5, to = 10, by = 1)
m <- seq(from = 10, to = 20, by = 5)

res <- f2_all_args(a, b, m)

r <- array(0, c(3, 6, 3))
r.error <- array(0, c(3, 6, 3))

for(i in seq_along(a)){
   res_i <- res[[i]]
   for(j in seq_along(b)){
     res_i_j <- res_i[[j]]
     for(k in seq_along(m)){
       r[i, j, k] <- res_i_j[[k]]$value
       r.error[i, j, k] <- res_i_j[[k]]$abs.error
     }
   }
}


Hope this helps,

Rui Barradas


Às 21:14 de 10/08/19, ravi via R-help escreveu:

>   Bert,Thanks a lot for your help. I have a few follow-up questions (shown in the comment lines).  Numerical values and error for a (i) vector and (ii) array.
>
> a <- seq(from=0,to=1,by=0.5)
> b <- seq(from=5,to=10,by=1)
> m <- seq(from=10,to=20,by=5)
>
> f2 <- function(a,b,m)integrate(function(x){exp(-a*x^3-b*x^2-m*x)},lower=0,upper = Inf)
> fv <- Vectorize(f2,vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
>
> r1 <- fv(a,b,m)
> # How to get just the numerical results as an array
> # for scalar values of a,b and m, I can get it with
>
> #s <- integrate(f,0,Inf)$value
> # How do I get this for a vector
>
> # Finally, if I want an array for all the values of a, b and m, how should I proceed?
> r <- array(0,c(3,6,3))
> r.error <- array(0,c(3,6,3))
> # I want the results of the vectorized integrate function in the above arrays. How do I extract these values?
>
> Thanks,Ravi
>
>
>      On Saturday, 10 August 2019, 20:03:22 CEST, Bert Gunter <[hidden email]> wrote:
>  
>   Ravi:
> First of all, you're calling Vectorize incorrectly. The first argument must be a function *name*, not a function call. Here's what you need to do (and thanks for the reprex -- wouldn't have been able to help without it!):
> f2 <- function(a,b,c)integrate(function(x){exp(-a*x^3-b*x^2-c*x)},lower =0,upper = Inf)
> fv <- Vectorize(f2,vectorize.args=c("a","b","c"),SIMPLIFY=TRUE)
> Second of all, as you may realize, the vectorization uses mapply() and so vectorizes the c(a,b,c) triplet "in parallel," which will "recycle" shorter arguments to the length of longer. Hence you will get 6 results from your example:
>> fv(a,b,m)
>               [,1]         [,2]         [,3]        [,4]         [,5]         [,6]
> value        0.09207851   0.0635289    0.04837997  0.08856628   0.06224138   0.04777941
> abs.error    3.365173e-08 3.108388e-06 1.00652e-09 3.284876e-09 1.796619e-08 6.348142e-09
> subdivisions 2            1            2           2            2            2
> message      "OK"         "OK"         "OK"        "OK"         "OK"         "OK"
> call         Expression   Expression   Expression  Expression   Expression   Expression
>
> Cheers,Bert
> Bert Gunter
>
> "The trouble with having an open mind is that people keep coming along and sticking things into it."
> -- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
>
>
> On Sat, Aug 10, 2019 at 10:20 AM ravi via R-help <[hidden email]> wrote:
>
> Hi all,I am having some difficulties in vectorizing the integrate function. Let me explain with an example.
> a <- 10; b <- 3; c <- 4
> f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
> integrate(f,0,Inf) # works fine
>
> My difficulties start when I want to vectorize.
>
> # attempts to vectorize fail
> a <- seq(from=0,to=1,by=0.5)
> b <- seq(from=5,to=10,by=1)
> m <- seq(from=10,to=20,by=5)
> f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
> fv <- Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
>
> I want the result as a 3-d array with dimensions of the lengths of a, b and c. I have tried several variants but am not having much luck. Will appreciate any help that I can get.
> Thanks,Ravi Sutradhara
>
>
>
>
>          [[alternative HTML version deleted]]
>
> ______________________________________________
> [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>    
> [[alternative HTML version deleted]]
>
> ______________________________________________
> [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: vectorizing the integrate function

Bert Gunter-2
Cleaner, I think, is to use ?expand.grid and ?do.call, noting that any
n-column data frame is also an n-component list.

Using your example as before:

> f2 <- function(a,b,m)integrate(function(x){exp(-a*x^3-b*x^2-m*x)},lower
=0,upper = Inf)
> fv <- Vectorize(f2,vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)

## Now use expand.grid to get all combinations of a,b, and m in a data frame

> allvals <- expand.grid(a=a, b=b, m=m)
## Here's what it looks like (note the **named** columns to avoid problems)
> head(allvals)
    a b  m
1 0.0 5 10
2 0.5 5 10
3 1.0 5 10
4 0.0 6 10
5 0.5 6 10
6 1.0 6 10
## etc.  3 x 6 x 3 = 54 rows in all

## now use do.call to do fv() on these three column vectors (considered as
a list of 3 components)

> results <- do.call(fv, allvals)

## So what does results look like?
> class(results)
[1] "matrix"
> dim(results)
[1]  5 54
> dimnames(results)[[1]]
[1] "value"        "abs.error"    "subdivisions" "message"      "call"

## So the first row of the matrix contains the values. If you extract them
by results[1, ],
## you'll find, however, that it's a list of 54 components, each of which
is a vector with
## one value. So unlist it first to avoid this:

> vals <- unlist(results[1,])
> vals
 [1] 0.09207851 0.09193111 0.09178672 0.09083412 0.09070066 0.09056960
0.08966646 0.08954474
 [9] 0.08942499 0.08856628 0.08845459 0.08834454 0.08752598 0.08742295
0.08732131 0.08653926
[17] 0.08644379 0.08634949 0.06403081 0.06398995 0.06394947 0.06356740
0.06352890 0.06349075
[25] 0.06312099 0.06308463 0.06304856 0.06269028 0.06265583 0.06262164
0.06227409 0.06224138
[33] 0.06220891 0.06187141 0.06184029 0.06180937 0.04883372 0.04881874
0.04880384 0.04861813
[41] 0.04860372 0.04858939 0.04840766 0.04839378 0.04837997 0.04820203
0.04818865 0.04817532
[49] 0.04800099 0.04798808 0.04797521 0.04780433 0.04779185 0.04777941

You can either convert this into an array or just add it as a column to
allvals. The results are listed in
the order given there.

Cheers,
Bert
Bert Gunter

"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Sat, Aug 10, 2019 at 3:03 PM Rui Barradas <[hidden email]> wrote:

> Hello,
>
> The following code might not be the best way of computing the integrals
> for all combinations of the arguments but it gets the job done and I
> believe it's readable code.
>
>
> f2 <- function(a, b, c){
>    integrate(function(x) {exp(-a*x^3 - b*x^2 - c*x)},
>              lower = 0, upper = Inf)
> }
>
> f2_all_args <- function(a, b, c){
>    lapply(a, function(.a)
>      lapply(b, function(.b)
>        lapply(c, function(.c)
>          f2(.a, .b, .c)[1:2]
>        )
>      )
>    )
> }
>
> a <- seq(from = 0, to = 1, by = 0.5)
> b <- seq(from = 5, to = 10, by = 1)
> m <- seq(from = 10, to = 20, by = 5)
>
> res <- f2_all_args(a, b, m)
>
> r <- array(0, c(3, 6, 3))
> r.error <- array(0, c(3, 6, 3))
>
> for(i in seq_along(a)){
>    res_i <- res[[i]]
>    for(j in seq_along(b)){
>      res_i_j <- res_i[[j]]
>      for(k in seq_along(m)){
>        r[i, j, k] <- res_i_j[[k]]$value
>        r.error[i, j, k] <- res_i_j[[k]]$abs.error
>      }
>    }
> }
>
>
> Hope this helps,
>
> Rui Barradas
>
>
> Às 21:14 de 10/08/19, ravi via R-help escreveu:
> >   Bert,Thanks a lot for your help. I have a few follow-up questions
> (shown in the comment lines).  Numerical values and error for a (i) vector
> and (ii) array.
> >
> > a <- seq(from=0,to=1,by=0.5)
> > b <- seq(from=5,to=10,by=1)
> > m <- seq(from=10,to=20,by=5)
> >
> > f2 <-
> function(a,b,m)integrate(function(x){exp(-a*x^3-b*x^2-m*x)},lower=0,upper =
> Inf)
> > fv <- Vectorize(f2,vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
> >
> > r1 <- fv(a,b,m)
> > # How to get just the numerical results as an array
> > # for scalar values of a,b and m, I can get it with
> >
> > #s <- integrate(f,0,Inf)$value
> > # How do I get this for a vector
> >
> > # Finally, if I want an array for all the values of a, b and m, how
> should I proceed?
> > r <- array(0,c(3,6,3))
> > r.error <- array(0,c(3,6,3))
> > # I want the results of the vectorized integrate function in the above
> arrays. How do I extract these values?
> >
> > Thanks,Ravi
> >
> >
> >      On Saturday, 10 August 2019, 20:03:22 CEST, Bert Gunter <
> [hidden email]> wrote:
> >
> >   Ravi:
> > First of all, you're calling Vectorize incorrectly. The first argument
> must be a function *name*, not a function call. Here's what you need to do
> (and thanks for the reprex -- wouldn't have been able to help without it!):
> > f2 <- function(a,b,c)integrate(function(x){exp(-a*x^3-b*x^2-c*x)},lower
> =0,upper = Inf)
> > fv <- Vectorize(f2,vectorize.args=c("a","b","c"),SIMPLIFY=TRUE)
> > Second of all, as you may realize, the vectorization uses mapply() and
> so vectorizes the c(a,b,c) triplet "in parallel," which will "recycle"
> shorter arguments to the length of longer. Hence you will get 6 results
> from your example:
> >> fv(a,b,m)
> >               [,1]         [,2]         [,3]        [,4]         [,5]
>       [,6]
> > value        0.09207851   0.0635289    0.04837997  0.08856628
> 0.06224138   0.04777941
> > abs.error    3.365173e-08 3.108388e-06 1.00652e-09 3.284876e-09
> 1.796619e-08 6.348142e-09
> > subdivisions 2            1            2           2            2
>      2
> > message      "OK"         "OK"         "OK"        "OK"         "OK"
>     "OK"
> > call         Expression   Expression   Expression  Expression
> Expression   Expression
> >
> > Cheers,Bert
> > Bert Gunter
> >
> > "The trouble with having an open mind is that people keep coming along
> and sticking things into it."
> > -- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
> >
> >
> > On Sat, Aug 10, 2019 at 10:20 AM ravi via R-help <[hidden email]>
> wrote:
> >
> > Hi all,I am having some difficulties in vectorizing the integrate
> function. Let me explain with an example.
> > a <- 10; b <- 3; c <- 4
> > f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
> > integrate(f,0,Inf) # works fine
> >
> > My difficulties start when I want to vectorize.
> >
> > # attempts to vectorize fail
> > a <- seq(from=0,to=1,by=0.5)
> > b <- seq(from=5,to=10,by=1)
> > m <- seq(from=10,to=20,by=5)
> > f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
> > fv <-
> Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
> >
> > I want the result as a 3-d array with dimensions of the lengths of a, b
> and c. I have tried several variants but am not having much luck. Will
> appreciate any help that I can get.
> > Thanks,Ravi Sutradhara
> >
> >
> >
> >
> >          [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
> >
> >       [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
>

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: vectorizing the integrate function

R help mailing list-2
In reply to this post by Bert Gunter-2
 Rui,Thanks for your help in getting the result with for loops. That is useful, but I have a complicated integral and I am interested in improving the performance with the benefit of vectorization.
In the solution from Bert, I would like to know how I can extract the numerical vector from the function fv. That is, extract the fv$value as a vector. I can then perhaps try to improvise and extend it to arrays.Thanks,Ravi

    On Saturday, 10 August 2019, 20:03:22 CEST, Bert Gunter <[hidden email]> wrote:  
 
 Ravi:
First of all, you're calling Vectorize incorrectly. The first argument must be a function *name*, not a function call. Here's what you need to do (and thanks for the reprex -- wouldn't have been able to help without it!):
f2 <- function(a,b,c)integrate(function(x){exp(-a*x^3-b*x^2-c*x)},lower =0,upper = Inf)
fv <- Vectorize(f2,vectorize.args=c("a","b","c"),SIMPLIFY=TRUE)
Second of all, as you may realize, the vectorization uses mapply() and so vectorizes the c(a,b,c) triplet "in parallel," which will "recycle" shorter arguments to the length of longer. Hence you will get 6 results from your example:
> fv(a,b,m)
             [,1]         [,2]         [,3]        [,4]         [,5]         [,6]        
value        0.09207851   0.0635289    0.04837997  0.08856628   0.06224138   0.04777941  
abs.error    3.365173e-08 3.108388e-06 1.00652e-09 3.284876e-09 1.796619e-08 6.348142e-09
subdivisions 2            1            2           2            2            2          
message      "OK"         "OK"         "OK"        "OK"         "OK"         "OK"        
call         Expression   Expression   Expression  Expression   Expression   Expression 

Cheers,Bert
Bert Gunter

"The trouble with having an open mind is that people keep coming along and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Sat, Aug 10, 2019 at 10:20 AM ravi via R-help <[hidden email]> wrote:

Hi all,I am having some difficulties in vectorizing the integrate function. Let me explain with an example.
a <- 10; b <- 3; c <- 4
f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
integrate(f,0,Inf) # works fine

My difficulties start when I want to vectorize.

# attempts to vectorize fail
a <- seq(from=0,to=1,by=0.5)
b <- seq(from=5,to=10,by=1)
m <- seq(from=10,to=20,by=5)
f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
fv <- Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)

I want the result as a 3-d array with dimensions of the lengths of a, b and c. I have tried several variants but am not having much luck. Will appreciate any help that I can get.
Thanks,Ravi Sutradhara




        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

 
        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: vectorizing the integrate function

R help mailing list-2
In reply to this post by Bert Gunter-2
 Bert,Thanks a lot. This meets all my expectations for the moment. Thanks.Ravi

    On Sunday, 11 August 2019, 00:52:02 CEST, Bert Gunter <[hidden email]> wrote:  
 
 Cleaner, I think, is to use ?expand.grid and ?do.call, noting that any n-column data frame is also an n-component list.
Using your example as before:
> f2 <- function(a,b,m)integrate(function(x){exp(-a*x^3-b*x^2-m*x)},lower =0,upper = Inf)
> fv <- Vectorize(f2,vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
 ## Now use expand.grid to get all combinations of a,b, and m in a data frame
> allvals <- expand.grid(a=a, b=b, m=m)## Here's what it looks like (note the **named** columns to avoid problems)> head(allvals)
    a b  m
1 0.0 5 10
2 0.5 5 10
3 1.0 5 10
4 0.0 6 10
5 0.5 6 10
6 1.0 6 10## etc.  3 x 6 x 3 = 54 rows in all
## now use do.call to do fv() on these three column vectors (considered as a list of 3 components)
> results <- do.call(fv, allvals)
## So what does results look like?
> class(results)
[1] "matrix"
> dim(results)
[1]  5 54
> dimnames(results)[[1]]
[1] "value"        "abs.error"    "subdivisions" "message"      "call"     

## So the first row of the matrix contains the values. If you extract them by results[1, ],
## you'll find, however, that it's a list of 54 components, each of which is a vector with
## one value. So unlist it first to avoid this:
> vals <- unlist(results[1,])
> vals
 [1] 0.09207851 0.09193111 0.09178672 0.09083412 0.09070066 0.09056960 0.08966646 0.08954474
 [9] 0.08942499 0.08856628 0.08845459 0.08834454 0.08752598 0.08742295 0.08732131 0.08653926
[17] 0.08644379 0.08634949 0.06403081 0.06398995 0.06394947 0.06356740 0.06352890 0.06349075
[25] 0.06312099 0.06308463 0.06304856 0.06269028 0.06265583 0.06262164 0.06227409 0.06224138
[33] 0.06220891 0.06187141 0.06184029 0.06180937 0.04883372 0.04881874 0.04880384 0.04861813
[41] 0.04860372 0.04858939 0.04840766 0.04839378 0.04837997 0.04820203 0.04818865 0.04817532
[49] 0.04800099 0.04798808 0.04797521 0.04780433 0.04779185 0.04777941
You can either convert this into an array or just add it as a column to allvals. The results are listed in
the order given there.
Cheers,BertBert Gunter

"The trouble with having an open mind is that people keep coming along and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Sat, Aug 10, 2019 at 3:03 PM Rui Barradas <[hidden email]> wrote:

Hello,

The following code might not be the best way of computing the integrals
for all combinations of the arguments but it gets the job done and I
believe it's readable code.


f2 <- function(a, b, c){
   integrate(function(x) {exp(-a*x^3 - b*x^2 - c*x)},
             lower = 0, upper = Inf)
}

f2_all_args <- function(a, b, c){
   lapply(a, function(.a)
     lapply(b, function(.b)
       lapply(c, function(.c)
         f2(.a, .b, .c)[1:2]
       )
     )
   )
}

a <- seq(from = 0, to = 1, by = 0.5)
b <- seq(from = 5, to = 10, by = 1)
m <- seq(from = 10, to = 20, by = 5)

res <- f2_all_args(a, b, m)

r <- array(0, c(3, 6, 3))
r.error <- array(0, c(3, 6, 3))

for(i in seq_along(a)){
   res_i <- res[[i]]
   for(j in seq_along(b)){
     res_i_j <- res_i[[j]]
     for(k in seq_along(m)){
       r[i, j, k] <- res_i_j[[k]]$value
       r.error[i, j, k] <- res_i_j[[k]]$abs.error
     }
   }
}


Hope this helps,

Rui Barradas


Às 21:14 de 10/08/19, ravi via R-help escreveu:

>   Bert,Thanks a lot for your help. I have a few follow-up questions (shown in the comment lines).  Numerical values and error for a (i) vector and (ii) array.
>
> a <- seq(from=0,to=1,by=0.5)
> b <- seq(from=5,to=10,by=1)
> m <- seq(from=10,to=20,by=5)
>
> f2 <- function(a,b,m)integrate(function(x){exp(-a*x^3-b*x^2-m*x)},lower=0,upper = Inf)
> fv <- Vectorize(f2,vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
>
> r1 <- fv(a,b,m)
> # How to get just the numerical results as an array
> # for scalar values of a,b and m, I can get it with
>
> #s <- integrate(f,0,Inf)$value
> # How do I get this for a vector
>
> # Finally, if I want an array for all the values of a, b and m, how should I proceed?
> r <- array(0,c(3,6,3))
> r.error <- array(0,c(3,6,3))
> # I want the results of the vectorized integrate function in the above arrays. How do I extract these values?
>
> Thanks,Ravi
>
>
>      On Saturday, 10 August 2019, 20:03:22 CEST, Bert Gunter <[hidden email]> wrote:
>   
>   Ravi:
> First of all, you're calling Vectorize incorrectly. The first argument must be a function *name*, not a function call. Here's what you need to do (and thanks for the reprex -- wouldn't have been able to help without it!):
> f2 <- function(a,b,c)integrate(function(x){exp(-a*x^3-b*x^2-c*x)},lower =0,upper = Inf)
> fv <- Vectorize(f2,vectorize.args=c("a","b","c"),SIMPLIFY=TRUE)
> Second of all, as you may realize, the vectorization uses mapply() and so vectorizes the c(a,b,c) triplet "in parallel," which will "recycle" shorter arguments to the length of longer. Hence you will get 6 results from your example:
>> fv(a,b,m)
>               [,1]         [,2]         [,3]        [,4]         [,5]         [,6]
> value        0.09207851   0.0635289    0.04837997  0.08856628   0.06224138   0.04777941
> abs.error    3.365173e-08 3.108388e-06 1.00652e-09 3.284876e-09 1.796619e-08 6.348142e-09
> subdivisions 2            1            2           2            2            2
> message      "OK"         "OK"         "OK"        "OK"         "OK"         "OK"
> call         Expression   Expression   Expression  Expression   Expression   Expression
>
> Cheers,Bert
> Bert Gunter
>
> "The trouble with having an open mind is that people keep coming along and sticking things into it."
> -- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
>
>
> On Sat, Aug 10, 2019 at 10:20 AM ravi via R-help <[hidden email]> wrote:
>
> Hi all,I am having some difficulties in vectorizing the integrate function. Let me explain with an example.
> a <- 10; b <- 3; c <- 4
> f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
> integrate(f,0,Inf) # works fine
>
> My difficulties start when I want to vectorize.
>
> # attempts to vectorize fail
> a <- seq(from=0,to=1,by=0.5)
> b <- seq(from=5,to=10,by=1)
> m <- seq(from=10,to=20,by=5)
> f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
> fv <- Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
>
> I want the result as a 3-d array with dimensions of the lengths of a, b and c. I have tried several variants but am not having much luck. Will appreciate any help that I can get.
> Thanks,Ravi Sutradhara
>
>
>
>
>          [[alternative HTML version deleted]]
>
> ______________________________________________
> [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>   
>       [[alternative HTML version deleted]]
>
> ______________________________________________
> [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

 
        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: vectorizing the integrate function

Bert Gunter-2
In reply to this post by R help mailing list-2
Ravi:

I believe you are under a misconception. The Vectorize() function
vectorizes the function call, **but it does not vectorize the computation
by moving loops down to the C level**, which is typically what is meant
when it is recommended that R users use inbuilt vectorized functions when
possible to move looping from the interpreted (R) level to the compiled (C
level) code. That is, mapply() -- and thus Vectorize, which is just a
wrapper for mapply -- is still looping at the interpreted level and
therefore is essentially the same as explicit iterative or *apply loops. It
may be a bit faster or slower, depending, but not the orders of magnitude
faster that one can get with true vectorized (at the C level) code.

Finally, if you want to just add the integration results to the allvals
list, here's a
slightly different one-liner to do it:

> allvals$vals <- unlist(with(allvals,fv(a,b,m))[1,])
> head(allvals)
    a b  m       vals
1 0.0 5 10 0.09207851
2 0.5 5 10 0.09193111
3 1.0 5 10 0.09178672
4 0.0 6 10 0.09083412
5 0.5 6 10 0.09070066
6 1.0 6 10 0.09056960

or the one liner using the previous do.call() construction that just
extracts the vector of values:

> vals <- unlist(do.call(fv,allvals)[1,])
Cheers,
Bert


Bert Gunter

"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Sat, Aug 10, 2019 at 3:56 PM ravi <[hidden email]> wrote:

> Rui,
> Thanks for your help in getting the result with for loops. That is useful,
> but I have a complicated integral and I am interested in improving the
> performance with the benefit of vectorization.
>
> In the solution from Bert, I would like to know how I can extract the
> numerical vector from the function fv. That is, extract the fv$value as a
> vector. I can then perhaps try to improvise and extend it to arrays.
> Thanks,
> Ravi
>
> On Saturday, 10 August 2019, 20:03:22 CEST, Bert Gunter <
> [hidden email]> wrote:
>
>
> Ravi:
>
> First of all, you're calling Vectorize incorrectly. The first argument
> must be a function *name*, not a function call. Here's what you need to do
> (and thanks for the reprex -- wouldn't have been able to help without it!):
>
> f2 <- function(a,b,c)integrate(function(x){exp(-a*x^3-b*x^2-c*x)},lower
> =0,upper = Inf)
> fv <- Vectorize(f2,vectorize.args=c("a","b","c"),SIMPLIFY=TRUE)
>
> Second of all, as you may realize, the vectorization uses mapply() and so
> vectorizes the c(a,b,c) triplet "in parallel," which will "recycle" shorter
> arguments to the length of longer. Hence you will get 6 results from your
> example:
>
> > fv(a,b,m)
>              [,1]         [,2]         [,3]        [,4]         [,5]
>   [,6]
> value        0.09207851   0.0635289    0.04837997  0.08856628   0.06224138
>   0.04777941
> abs.error    3.365173e-08 3.108388e-06 1.00652e-09 3.284876e-09
> 1.796619e-08 6.348142e-09
> subdivisions 2            1            2           2            2
>    2
> message      "OK"         "OK"         "OK"        "OK"         "OK"
>   "OK"
> call         Expression   Expression   Expression  Expression   Expression
>   Expression
>
> Cheers,
> Bert
>
> Bert Gunter
>
> "The trouble with having an open mind is that people keep coming along and
> sticking things into it."
> -- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
>
>
> On Sat, Aug 10, 2019 at 10:20 AM ravi via R-help <[hidden email]>
> wrote:
>
> Hi all,I am having some difficulties in vectorizing the integrate
> function. Let me explain with an example.
> a <- 10; b <- 3; c <- 4
> f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
> integrate(f,0,Inf) # works fine
>
> My difficulties start when I want to vectorize.
>
> # attempts to vectorize fail
> a <- seq(from=0,to=1,by=0.5)
> b <- seq(from=5,to=10,by=1)
> m <- seq(from=10,to=20,by=5)
> f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
> fv <-
> Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
>
> I want the result as a 3-d array with dimensions of the lengths of a, b
> and c. I have tried several variants but am not having much luck. Will
> appreciate any help that I can get.
> Thanks,Ravi Sutradhara
>
>
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: vectorizing the integrate function

Linus Chen
In reply to this post by R help mailing list-2
Dear ravi,

In your example, the function "f" is linear to a, b, and c.
Is this the general case in your task?

If it is, you can save  *lots* of computation taking advantage of the linearity.

Lei


On Sat, 10 Aug 2019 at 19:20, ravi via R-help <[hidden email]> wrote:

>
> Hi all,I am having some difficulties in vectorizing the integrate function. Let me explain with an example.
> a <- 10; b <- 3; c <- 4
> f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
> integrate(f,0,Inf) # works fine
>
> My difficulties start when I want to vectorize.
>
> # attempts to vectorize fail
> a <- seq(from=0,to=1,by=0.5)
> b <- seq(from=5,to=10,by=1)
> m <- seq(from=10,to=20,by=5)
> f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
> fv <- Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
>
> I want the result as a 3-d array with dimensions of the lengths of a, b and c. I have tried several variants but am not having much luck. Will appreciate any help that I can get.
> Thanks,Ravi Sutradhara
>
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: vectorizing the integrate function

R help mailing list-2
 Hi all,I would like to thank every one who has responded to my question. I have received valuable help.Linus, the function that I gave here is just a toy function. I think that is possible even to find an analytical solution. I chose that just to include many constant parameters. I wanted to find out how I can vectorize. I have obtained nice answers from Bert and I appreciate the help. I knew even previously that the vectorizing primarily improves the readability of the code. Thanks Bert for making it crystal clear that the looping is still at the interpreted level of R.Thanks,Ravi
    On Sunday, 11 August 2019, 12:24:43 CEST, Linus Chen <[hidden email]> wrote:  
 
 Dear ravi,

In your example, the function "f" is linear to a, b, and c.
Is this the general case in your task?

If it is, you can save  *lots* of computation taking advantage of the linearity.

Lei


On Sat, 10 Aug 2019 at 19:20, ravi via R-help <[hidden email]> wrote:

>
> Hi all,I am having some difficulties in vectorizing the integrate function. Let me explain with an example.
> a <- 10; b <- 3; c <- 4
> f <- function(x) {exp(-a*x^3-b*x^2-c*x)}
> integrate(f,0,Inf) # works fine
>
> My difficulties start when I want to vectorize.
>
> # attempts to vectorize fail
> a <- seq(from=0,to=1,by=0.5)
> b <- seq(from=5,to=10,by=1)
> m <- seq(from=10,to=20,by=5)
> f2 <- function(x,a,b,c) {exp(-a*x^3-b*x^2-m*x)}
> fv <- Vectorize(integrate(f2,0,Inf),vectorize.args=c("a","b","m"),SIMPLIFY=TRUE)
>
> I want the result as a 3-d array with dimensions of the lengths of a, b and c. I have tried several variants but am not having much luck. Will appreciate any help that I can get.
> Thanks,Ravi Sutradhara
>
>
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
 
        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.