What is going on? Its definitely outputting the same expression, but in one case Mathematica is saying its the wrong rank, the other its correct.
Became Hot Network Question
What is going on?
What is going on? Its definitely outputting the same expression, but in one case Mathematica is saying its the wrong rank, the other its correct.
Using Total to evaluate row sums of a matrix inside Compile
I have some code that evaluates a a large function of the strengths and degrees of a bipartite adjacency matrix. It takes a while to evaluate it, so I tried compiling it:
Qgreen = RandomReal[{0, 1}, {2000, 2000}]; len = Dimensions[Qgreen][[1]]; len2 = Dimensions[Qgreen][[2]]; strength1 = Total /@ Qgreen; strength2 = Total /@ Transpose[Qgreen]; deg1 = Count[#, _?(# > 0 &)] & /@ Qgreen; deg2 = Count[#, _?(# > 0 &)] & /@ Transpose[Qgreen]; b = Table[1, {i, len}]; y = Table[1, {i, len}]; d = Table[1, {i, len2}]; e = Table[1, {i, len2}]; degA = N@deg1; strA = N@strength1; degB = N@deg2; strB = N@strength2; compiledObjective = Compile[{{b, _Real, 1}, {y, _Real, 1}, {d, _Real, 1}, {e, _Real, 1}, {degA, _Real, 1}, {strA, _Real, 1}, {degB, _Real, 1}, {strB, _Real, 1}}, Module[{expMat, sumMat, denomMat, p1, p2, p3, p4, f}, expMat = Outer[Exp[-(#1 + #2)] &, b, d]; sumMat = Outer[#1 + #2 &, y, e]; denomMat = sumMat + expMat; t1 = expMat/denomMat; t1b = expMat/(denomMat*sumMat); t2 = Transpose[expMat/denomMat]; t2b = Transpose[expMat/(denomMat*sumMat)]; Total[((Total[#] & /@ (t1)) - degA)^2] + Total[((Total[#] & /@ (t1b)) - strA)^2] + Total[((Total[#] & /@ (t2)) - degB)^2] + Total[((Total[#] & /@ (t2b)) - strB)^2] ], CompilationTarget -> "C", RuntimeOptions -> "Speed", Parallelization -> True]; result = compiledObjective[b, y, d, e, degA, strA, degB, strB]; Print["Objective function value: ", result]; There is clearly something slow about the line
Total[((Total[#] & /@ (t1)) - degA)^2] + Total[((Total[#] & /@ (t1b)) - strA)^2] + Total[((Total[#] & /@ (t2)) - degB)^2] + Total[((Total[#] & /@ (t2b)) - strB)^2] But! If I use the faster
Total[(Total[expMat/denomMat, {2}] - degA)^2] + Total[(Total[expMat/(denomMat*sumMat), {2}] - strA)^2] + Total[(Total[expMat/denomMat, {1}] - degB)^2] + Total[(Total[expMat/(denomMat*sumMat), {1}] - strB)^2]; I am getting an error:
CompiledFunction::cfte: Compiled expression {65.9832,65.9832,363.422,65.9832,65.9832,65.9832,363.422,65.9832,65.9832,65.9832,<<3115>>} should be a rank 2 tensor of machine-size real numbers. What is going on?
lang-mma