Suppose I would like to speed up the function in FindMinimum[function[variables],startingPoint] by compiling function
I've constructed a minimal working example to describe what I would like to do.
Here is the code without compile (Minimizing some spring energy between several points)
p is a list of points.
springEnergy[p_] :=
Total@Total[(DistanceMatrix[p,
DistanceFunction -> EuclideanDistance] - 1)^2]
positions = CirclePoints[4];
variables = p[#] & /@ Range[Length[positions]]
startingPoint = MapThread[{#1, #2} &, {variables, positions}]
This works:
FindMinimum[
springEnergy[variables], startingPoint
]
I'd like to do the same thing, but with a compiled springEnergy. I believe this is functionally the same as springEnergy:
fc = FunctionCompile[
Function[Typed[pos, TypeSpecifier["NumericArray"]["Real64", 2]],
Module[{
adm =
Typed[
KernelFunction[
DistanceMatrix], {TypeSpecifier["NumericArray"]["Real64",
2]} -> TypeSpecifier["NumericArray"]["Real64", 2]][pos] -
Typed[KernelFunction[ConstantArray],
{"Integer32", {"Integer32", "Integer32"}} ->
TypeSpecifier["NumericArray"]["Real64", 2]][
1, {Length[pos], Length[pos]}]
},
Total[Total[adm^2]]
]
]
]
fc[NumericArray[N@positions]] == springEnergy[N@positions]
(True)
However,
FindMinimum[
fc[NumericArray[variables]], startingPoint
]
complains because--I think--FindMinimum calls the initial point symbolically. Normally, I get around that by specifying _?NumericQ on the calling function. I tried to so something like that with a wrapper function:
wrapper[variables_NumericArray] := fc[variables]
But, that doesn't prevent the initial symbolic call by FindMinimum:
FindMinimum[
wrapper[variables], startingPoint
]
wrapper[variables_?MatrixQ] := fc[variables]; FindMinimum[wrapper[variables], startingPoint]– Simon Woods Mar 18 '22 at 19:49FindMinimum[Inactivate@fc[variables], startingPoint]also works – Simon Woods Mar 18 '22 at 20:13