5

I tried to create Graphics primitives using the techniques in this, found problems with parallel rasterization

SetAttributes[createPrimitive,HoldAll];

createPrimitive[patt_,expr_]:=TypesetMakeBoxes[p:patt,fmt_,Graphics]:=TypesetMakeBoxes[Interpretation[expr,p],fmt,Graphics];

createPrimitive[face[x_:0.1],{Circle[{0,0},1],Circle[{-0.3,0.5},x],Circle[{0.3,0.5},x],Line[{{-0.4,-0.2},{0.4,-0.2}}]}];

ParallelTable[Graphics[{face[i]},ImageSize->Tiny],{i,0,0.3,0.3/5}] ParallelTable[Rasterize@Graphics[{face[i]},ImageSize->Tiny],{i,0,0.3,0.3/5}]

enter image description here

Is there any way to fix this?

xzczd
  • 65,995
  • 9
  • 163
  • 468
expression
  • 5,642
  • 1
  • 19
  • 46

1 Answers1

5

I think this is probably related to Parallel evaluation of Image and Rasterize problem. Briefly, Rasterize is not done by the kernel but by the front-end.

For example, when you don't include rasterization, the output of ParallelTable is still Graphics[{face[...]}], and it is then the main front-end that afterwards converts this to your shapes.

ParallelTable[InputForm@Graphics[{face[i]}, ImageSize -> Tiny], {i, {0, .2}}]
(* {Graphics[{face[0]}, ImageSize -> Tiny],
    Graphics[{face[0.2]}, ImageSize -> Tiny]} *)

ParallelTable[ToBoxes@Graphics[{face[i]}, ImageSize -> Tiny], {i, {0, .2}}] (* {GraphicsBox[{face[0]}, ImageSize -> Tiny], GraphicsBox[{face[0.2]}, ImageSize -> Tiny]}

Therefore, you need to somehow get your definitions to the front-ends that are initiated by the subkernels. DistributeDefinitions doesn't work, but ParallelEvaluate seems to do the job. Maybe there are also some other viable solutions.

ParallelEvaluate[
 SetAttributes[createPrimitive, HoldAll];
 createPrimitive[patt_, expr_] := 
  Typeset`MakeBoxes[p : patt, fmt_, Graphics] := 
   Typeset`MakeBoxes[Interpretation[expr, p], fmt, Graphics];
 createPrimitive[
  face[x_ : 0.1], {Circle[{0, 0}, 1], Circle[{-0.3, 0.5}, x], 
   Circle[{0.3, 0.5}, x], Line[{{-0.4, -0.2}, {0.4, -0.2}}]}];];

ParallelTable[Rasterize@Graphics[{face[i]}, ImageSize -> Tiny], {i, 0, 0.3, 0.3/5}]

enter image description here

Domen
  • 23,608
  • 1
  • 27
  • 45
  • 1
    This is surprising. BTW it's worth mentioning that DistributedContexts->All doesn't work, either. (+1, of course. ) – xzczd Apr 26 '23 at 12:24