14

I would like to learn how optim(..., hessian=TRUE) computes a Hessian, so I took a look at the function's definition. Near its end, it includes this call to .External2():

if (hessian) 
    res$hessian <- .External2(C_optimhess, res$par, fn1, 
        gr1, con)

Looks like there's a call to an external C function named C_optimhess, so I grep'd the R source directory for C_optimhess, but came up emptyhanded. There are only two occurrences of that string in R's code base, one in optim and one in optimHess. Both functions are defined in $R_SOURCE_DIR/src/library/stats/R/optim.R, and that file includes no additional hints/comments/references.

optim's help file references code on which several of the function's optimization methods were based, but doesn't (seem to) point to the source of C_optimhess.

In a case like this, where should I look to find the C code being called by .External2?

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455

1 Answers1

14

Notice that C_optimhess is an object, not a string.

> stats:::C_optimhess
$name
[1] "optimhess"

$address
<pointer: 0x266b1a0>
attr(,"class")
[1] "RegisteredNativeSymbol"

$dll
DLL name: stats
Filename: /usr/lib/R/library/stats/libs/stats.so
Dynamic lookup: FALSE

$numParameters
[1] 4

attr(,"class")
[1] "ExternalRoutine"  "NativeSymbolInfo"

So you need to grep for "optimhess" in $R_SOURCE_DIR/src/library/stats/src/:

josh@compy: $R_SOURCE_DIR/src/library/stats/src
> grep optimhess *
init.c:    EXTDEF(optimhess, 4),
optim.c:SEXP optimhess(SEXP call, SEXP op, SEXP args, SEXP rho)
statsR.h:SEXP optimhess(SEXP call, SEXP op, SEXP args, SEXP rho);
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • Great, thanks! (A line or two about this might make a nice addition to the "Functions that call compiled code" section of [your increasingly comprehensive answer to this question](http://stackoverflow.com/questions/19226816/how-can-i-view-the-source-code-for-a-function/19226817#19226817).) – Josh O'Brien Dec 18 '13 at 18:33
  • 1
    @JoshO'Brien: done; and it's finally community wiki, as it should have been from the beginning (but I wasn't allowed to mark it as CW). – Joshua Ulrich Dec 18 '13 at 18:44
  • @JoshuaUlrich: Your answer does not work for me: I dont have a `$R_SOURCE_DIR` defined. Also, `find *src*` in `R.home()` and in `dirname $(which R)` does not return any source code file or directory. How can I find the source code? – Chris Oct 03 '20 at 10:37
  • @Chris: `$R_SOURCE_DIR` isn't an actual environment variable. It's the location where you downloaded the R sources. Most R installs do not include the sources, so you need to get them yourself. You can get a [daily snapshot of R-devel](https://stat.ethz.ch/R/daily/) or clone [Winston's copy on GitHub](https://github.com/wch/r-source/) – Joshua Ulrich Oct 04 '20 at 13:48