2

I want to compile this function:

fun = With[{a = Range[-300, -200]}, 
        Compile[{{t, _Integer}, {window, _Integer, 2}}, 
          Pick[a + t, #, 1] & /@ window, 
        CompilationTarget -> "C", RuntimeOptions -> "Speed"]];

but

CompilePrint[fun]

returns MainEvaluate at Pick. Is there a workaround and is Pick not compilable in C?

edit: window is a sparse array and fun is actually a more complicated function that contains Pick.

Baran Cimen
  • 1,184
  • 1
  • 8
  • 18
  • Here's a discussion of compilable functions: https://mathematica.stackexchange.com/questions/1096/list-of-compilable-functions – Roman Feb 01 '19 at 14:11
  • 1
    Also Pick with packed arrays is already extremely fast, especially when the filtering function is optimized for packed arrrays, like Unitize, UnitStep etc. Compiling it would not give much boost. – Marius Ladegård Meyer Feb 01 '19 at 14:18
  • I'm using Pick inside a more complicated function, but the only point it evaluates at the main kernel is Pick so that's how I phrased the question. – Baran Cimen Feb 01 '19 at 14:29
  • You cannot use sparse array in Compile. – Henrik Schumacher Feb 01 '19 at 15:10

1 Answers1

3

Neither Pick nor SparseArrays can be used in compiled function. But the following shows you how to achieve the desired operation more quickly without Compile, just by SparseArray techniques:

a = Range[-300, -200];
n = 100000;
m = 1000000;
i = RandomInteger[{1, n}, m];
j = RandomInteger[{1, Length[a]}, m];
vals = RandomInteger[{-2, 2}, m];
window = SparseArray[Transpose[{i, j}] -> vals, {n, Length[a]}];
t = RandomInteger[100];

result0 = Table[Pick[a + t, w, 1], {w, window}]; // AbsoluteTiming // First

result = With[{A = SparseArray[ Clip[window, {0, 1}, {0, 0}].DiagonalMatrix[SparseArray[a + t]]]},
     Internal`PartitionRagged[A["NonzeroValues"], Differences[A["RowPointers"]]]
     ]; // AbsoluteTiming // First
result0 == result

0.63127

0.048193

True

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309