# Compile succeeds and then fails with a simple change.

Posted 9 years ago
5815 Views
|
4 Replies
|
4 Total Likes
|
 The following works just fine: positions = RandomReal[{-200, 200}, {1000, 2}]; example1 = Compile[{{positions, _Real, 2}}, Block[{distanceMat, distanceMatCubed, differenceMat, ret}, differenceMat = Outer[Subtract, N[positions], N[positions], 1] ; distanceMat = Map[#.# &, differenceMat, {2}] + IdentityMatrix[Length[positions]]; distanceMatCubed = distanceMat^3; (*{ Total[-12 differenceMat ( 1-distanceMatCubed)/distanceMat^7], Total[(1-2distanceMatCubed)/distanceMat^6] }*) Total[-12 differenceMat ( 1 - distanceMatCubed)/distanceMat^7] ] ] Timing[example1[positions];] However, this doesn't: example2 = Compile[{{positions, _Real, 2}}, Block[{distanceMat, distanceMatCubed, differenceMat, ret}, differenceMat = Outer[Subtract, N[positions], N[positions], 1] ; distanceMat = Map[#.# &, differenceMat, {2}] + IdentityMatrix[Length[positions]]; distanceMatCubed = distanceMat^3; { Total[-12 differenceMat ( 1 - distanceMatCubed)/distanceMat^7], Total[(1 - 2 distanceMatCubed)/distanceMat^6] } ] ] Timing[example2[positions];] Looking at the CompilePrint, the offending line appears to be:MainEvaluate[ Hold[List][ T(R2)6, T(R1)12]]Where T(R2)6 = Total[ T(R3)11, I12]] and T(R1)12 = Total[ T(R2)11, I12]] appear to be valid results.Perhaps, I need to coerce the final result type... but I am not sure how to do this. Any advice? Thanks, Craig
4 Replies
Sort By:
Posted 9 years ago
 It fails because the two totals do not have compatible dimensions, so creating that final List involves an object that is not a proper tensor. Compile gets upset when handling nontensorial objects. Very, very upset.
Posted 9 years ago
 btw, you meant to write example[particles] and not example[positions]As for the problem, it seems relating to the list at the end. Simply putting Flatten at the end, removes the error and not it works.  particles = RandomReal[{-200, 200}, {1000, 2}]; example = Compile[{{positions, _Real, 2}}, Block[{distanceMat, distanceMatCubed, differenceMat, ret}, differenceMat = Outer[Subtract, N[positions], N[positions], 1]; distanceMat = Map[#.# &, differenceMat, {2}] + IdentityMatrix[Length[positions]]; distanceMatCubed = distanceMat^3; Flatten@{Total[-12 differenceMat (1 - distanceMatCubed)/distanceMat^7], Total[(1 - 2 distanceMatCubed)/distanceMat^6]} ] ] example[particles] 
Posted 9 years ago
 Thanks Nassar, I've fixed the particles and positions typo in the original post. Your solution will work: I suppose that I can Partition the result. However, the Dimensions of the two Lists that are getting Flattened are different, but it is doable. Thanks. However, I am still curious as to why it fails. Thanks, CraigPS: I believe that my N[positions] in the compile statement is redundant...
Posted 9 years ago
 I do not know why it fails when the compile result is multi-dimensions list.