Skip to main content

meta programming - Macro functions in GeneralUtilities?


Questions have been asked about the Macros package before (e.g., (83815)), but I'm interested if anyone has some examples of using the macro related functions in GeneralUtilities:


In[2397]:= Names["GeneralUtilities`*Macro*"]

Out[2397]= {"DefineLiteralMacro", "DefineMacro", "MacroEvaluate", \
"MacroExpand", "MacroExpandList", "MacroPanic", "MacroRules", \
"UseMacros", "$MacroDebugMode"}


I find their docstrings a bit cryptic:


enter image description here



Answer



The only official information about the Macro functions I am aware of can be found in a short segment in this presentation, which describes the "Macro System" as an essential part of the next compiler generation. However, the CreateMExpr shown there isn't included in Mathematica 10.4.1. (But maybe someone can find parts of it digging deeper into it?)


Nevertheless, one can already apply the Macro System practically (while being aware that this is an undocumented functionality with all the consequences involved) outside of that next generation compiler context.


First let's load the GeneralUtilities package and see what Macro functions are available as of version 10.4.1.


Needs["GeneralUtilities`"]
Names["*Macro*"]



{"DefineLiteralMacro", "DefineMacro", "MacroEvaluate", "MacroExpand", "MacroExpandList", 
"MacroPanic", "MacroRules", "UseMacros", $MacroDebugMode"}

First


?MacroRules

MacroRulesUsage


can be used to see how macros are defined within Mathematica. The most illustrating example is


MacroRules[DoWhile]


DoWhileMacro


One can get an overview of all predefined macros (that I found) using


MacroRules /@ List @@ GeneralUtilities`Control`PackagePrivate`$MacroHeadsPattern //
Grid[#, Frame -> All, Alignment -> Left] &

The Panels are how Quoted code is displayed in the Front End.


?Quoted

Quoded_Usage




Let's assume we don't like the common Increment syntax and want to use an incr function instead.


DefineMacro[incr, incr[n_] := Quoted[n++]]

incrMacro


incr itself doesn't have any DownValues, therefore


counter = 0;
Table[incr[counter], 5]


{incr[0], incr[0], incr[0], incr[0], incr[0]}




The macro can be applied using


MacroEvaluate@Table[incr[counter], 5]


{0, 1, 2, 3, 4}



To see what the macro does, one can use


MacroExpand@Table[incr[counter], 5]


MacroExpand_incr


and


MacroExpandList@Table[incr[counter], 5]

MacroExpandList_incr



Let's say we have some code that contains some Table expressions in the form Table[expr, n] and we want to replace them with Array and add 1 to every expr. To do this a macro can be defined in the following way:


DefineMacro[macro1, macro1[Table[expr_, n_?IntegerQ]] := Quoted[Array[1 + expr &, n]]]

macro1



Just applying macro1 to a Table does nothing special


macro1[Table[RandomReal[], 5]]


macro1[{0.0977249, 0.987251, 0.484049, 0.712003, 0.358444}]



but


MacroEvaluate@macro1@Table[RandomReal[], 5]



{1.60094, 1.53355, 1.49432, 1.74318, 1.648}



does make use of the macro.


MacroExpand[macro1[Table[RandomReal[], 5]]]

MacroExpand_macro1


MacroExpandList[macro1[Table[RandomReal[], 5]]]

MacroExpandList_macro1


If one tries to apply this macro to a Table having a different syntax pattern a Failure message is created.



MacroExpand[macro1[Table[RandomReal[], {i, 5}]]]

FailureMessage


Using replacement rules instead of a macro is less convenient, as the syntax is more complex.


Unevaluated@
Table[RandomReal[], 5] /. {Verbatim[Table][expr_, n_?IntegerQ] :> Array[1 + expr &, n],
___ -> $Failed}


{1.14275, 1.55058, 1.13318, 1.05475, 1.75428}





Let's assume we have defined a function


f[n_] := Table[RandomReal[], n]

and now we realize that for big integers n this implementation does perform much worse than RandomReal[{0, 1}, n]. A macro can be used to refactor our code.


DefineMacro[f, f[n_] := Quoted[RandomReal[{0, 1}, n] + 1]]

(The + 1 is just added to directly judge by the output, if the macro has been applied.)


For small n the overhead of using the Macro System does outweigh the performance increase of not using Table,



Table[RandomReal[], 10]; // AbsoluteTiming
RandomReal[{0, 1}, 10]; // AbsoluteTiming
RandomReal[{0, 1}, 10] + 1; // AbsoluteTiming
MacroEvaluate[f[10]]; // AbsoluteTiming


{0.0000126977, Null}
{8.35374*10^-6, Null}
{0.0000110269, Null}
{0.00018278, Null}


but becomes neglectable for big n.


f[1000000]; // AbsoluteTiming
MacroEvaluate[f[1000000]]; // AbsoluteTiming


{0.0549422, Null}
{0.0149402, Null}

One interesting thing to note is that the macro gets automatically applied when f is used to define an other function. For example



g[m_] := f[m]

DownValues@g


{HoldPattern[g[m_]] :> RandomReal[{0, 1}, m] + 1}



That this will be happening in other cases too becomes evident by looking at


 ?? f


Using the Macro System is also very helpful in conjunction with Compile.


cf = MacroEvaluate@Compile[{{n, _Integer, 0}},
f[n]
]

CompilePrint@cf

CompilePrint@cf


Here using MacroEvaluate has two effects:




  1. The macro for f gets applied and therefore the more efficient version is compiled.

  2. f[n] can directly been put into Compile.


Without the Macro System directly using f[n] inside Compile results in a call to MainEvaluate.


Compile[{{n, _Integer, 0}},
f[n]
] // CompilePrint

CompilePrint


Comments

Popular posts from this blog

mathematical optimization - Minimizing using indices, error: Part::pkspec1: The expression cannot be used as a part specification

I want to use Minimize where the variables to minimize are indices pointing into an array. Here a MWE that hopefully shows what my problem is. vars = u@# & /@ Range[3]; cons = Flatten@ { Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; Minimize[{Total@((vec1[[#]] - vec2[[u[#]]])^2 & /@ Range[1, 3]), cons}, vars, Integers] The error I get: Part::pkspec1: The expression u[1] cannot be used as a part specification. >> Answer Ok, it seems that one can get around Mathematica trying to evaluate vec2[[u[1]]] too early by using the function Indexed[vec2,u[1]] . The working MWE would then look like the following: vars = u@# & /@ Range[3]; cons = Flatten@{ Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; NMinimize[ {Total@((vec1[[#]] - Indexed[vec2, u[#]])^2 & /@ R...

functions - Get leading series expansion term?

Given a function f[x] , I would like to have a function leadingSeries that returns just the leading term in the series around x=0 . For example: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x)] x and leadingSeries[(1/x + 2 + (1 - 1/x^3)/4)/(4 + x)] -(1/(16 x^3)) Is there such a function in Mathematica? Or maybe one can implement it efficiently? EDIT I finally went with the following implementation, based on Carl Woll 's answer: lds[ex_,x_]:=( (ex/.x->(x+O[x]^2))/.SeriesData[U_,Z_,L_List,Mi_,Ma_,De_]:>SeriesData[U,Z,{L[[1]]},Mi,Mi+1,De]//Quiet//Normal) The advantage is, that this one also properly works with functions whose leading term is a constant: lds[Exp[x],x] 1 Answer Update 1 Updated to eliminate SeriesData and to not return additional terms Perhaps you could use: leadingSeries[expr_, x_] := Normal[expr /. x->(x+O[x]^2) /. a_List :> Take[a, 1]] Then for your examples: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x), x] leadingSeries[Exp[x], x] leadingSeries[(1/x + 2 + (1 - 1/x...

What is and isn't a valid variable specification for Manipulate?

I have an expression whose terms have arguments (representing subscripts), like this: myExpr = A[0] + V[1,T] I would like to put it inside a Manipulate to see its value as I move around the parameters. (The goal is eventually to plot it wrt one of the variables inside.) However, Mathematica complains when I set V[1,T] as a manipulated variable: Manipulate[Evaluate[myExpr], {A[0], 0, 1}, {V[1, T], 0, 1}] (*Manipulate::vsform: Manipulate argument {V[1,T],0,1} does not have the correct form for a variable specification. >> *) As a workaround, if I get rid of the symbol T inside the argument, it works fine: Manipulate[ Evaluate[myExpr /. T -> 15], {A[0], 0, 1}, {V[1, 15], 0, 1}] Why this behavior? Can anyone point me to the documentation that says what counts as a valid variable? And is there a way to get Manpiulate to accept an expression with a symbolic argument as a variable? Investigations I've done so far: I tried using variableQ from this answer , but it says V[1...