Skip to main content

options - Inline documentation of "Properties"


Context


I find the documentation has become a bit of a maze, in particular given the more recent convention of having keywords has strings rather than Mathematica Keywords.


For instance,


?PrecisionGoal


produced before


Mathematica graphics


But now if we use a more recent function such as


 ComponentMeasurements[u1, "Properties"]

I get this list


  {AdjacentBorderCount,AdjacentBorders,Area,AreaRadiusCoverage,AuthalicRadius,BoundingBox,BoundingBoxArea,BoundingDiskCenter,BoundingDiskCoverage,BoundingDiskRadius,CaliperElongation,CaliperLength,CaliperWidth,Centroid,Circularity,Complexity,ConvexArea,ConvexCount,ConvexCoverage,ConvexPerimeterLength,ConvexVertices,Count,Data,Dimensions,Eccentricity,Elongation,EmbeddedComponentCount,EmbeddedComponents,EnclosingComponentCount,EnclosingComponents,Energy,Entropy,EquivalentDiskRadius,EulerNumber,ExteriorNeighborCount,ExteriorNeighbors,FilledCircularity,FilledCount,Fragmentation,Holes,IntensityCentroid,IntensityData,InteriorNeighborCount,InteriorNeighbors,Label,LabelCount,Length,Mask,Max,MaxCentroidDistance,MaxIntensity,MaxPerimeterDistance,Mean,MeanCaliperDiameter,MeanCentroidDistance,MeanIntensity,Median,MedianIntensity,Medoid,Min,MinCentroidDistance,MinimalBoundingBox,MinIntensity,NeighborCount,Neighbors,Orientation,OuterPerimeterCount,PerimeterCount,PerimeterLength,PolygonalLength,Rectangularity,SemiAxes,Skew,StandardDeviation,StandardDeviationIntensity,Total,TotalIntensity,Width}

and we don't know what each option does without scanning the documentation (where I typically get lost but that's another issue).


Question




Would it be possible to design a function which, given the Keyword ComponentMeasurements and the String "PerimeterCount", would return "number of elements on the perimeter" as documented here:



Mathematica graphics



Or if this is too complicated, how can I get mathematica open the relevant documentation?



Update


One could hack the FullOptions function so that FullOptions[ComponentMeasurements] would return these?



Answer




Yes, it is possible:



enter image description here





The idea is to look at the underlying cell expressions in the documentation for those string property tables. As I said already in my comment above, basically we have two different situations here:



  • the trend since Mathematica V6 that many options are not symbols any more but rather strings.

  • function arguments, that are given as strings



This leads to a documentation shift, because while e.g. all Options of Graphics have their own reference page, this is not that case for the properties of ComponentMeasurements and you can neither look at their usage message nor do they have a separate documentation page.


My implementation will make no difference between an option and a property, but it will let you access them easily.


Implementation notes


The provides StringProperties function requires at least a symbol. It will try to open the documentation notebook-expression for this and extract all the key-value pairs that look like this



Mathematica graphics



It will store the information in a association at gives you the chance to access them easily. The extracted values are persistent for your session, so that repeated calls will run in no-time. All information is stored in the module-variable $db so that it won't clash with any other symbol and hides the data from the user (I guess in javascript this is called a closure).


The important part of the functionality is hidden in the definition of $db[...]:=.., so you should start there. At the end of this function, an Association is created where the keys are string-properties (or options) and the values are the explanation extracted from the documentation page.


Another probably interesting part is the creation of the output as usage cell. Beware that this is only hacked. So when cells are not displayed properly, the cause is most likely in there.



Usages


There are 3 different call patterns. To extract all string-property-names found on the help-page you can use


StringProperties[ColorData]
(* {"Gradients", "Indexed", "Named", "Physical",
"ColorFunction", "ColorList", "ColorRules", "Image", "Name", "Panel",
"ParameterCount", "Range"} *)

To extract the explanation of one, just put the property-name as second argument



Mathematica graphics




Or if think you can handle it, then simply call e.g.


StringProperties[ComponentMeasurements, All]

Limitations


Always remember, that the extraction relies on the structure of the help page. If the WRI stuff screwed this, it won't work. Additionally, I have found that some string properties are not only strings. For ColorData for instance, there exists an entry


{"Range",i} range of possible values for the i^th parameter

which can currently not be handled and is excluded.


Another thing is, that there seem to be cells that cannot simply be wrapped in a usage-style cell:




Mathematica graphics



Code


StringProperties::notfound = 
"Documentation for symbol `` could not be found.";
SetAttributes[StringProperties, {HoldFirst}];

Module[{$db},
StringProperties[func_Symbol] :=

With[{name = SymbolName[Unevaluated[func]]},
Keys[$db[name]]
];
StringProperties[func_Symbol, prop_String] :=
Module[{name = SymbolName[Unevaluated[func]], doc},
doc = $db[name][prop];
With[{res = If[Head[doc] === Cell, doc, "Missing"]}, CellPrint[{
Cell[BoxData[
RowBox[{
StyleBox[prop <> ": ", FontWeight -> Bold],

res}]], "Print", "PrintUsage"]}]
]
];

StringProperties[func_Symbol, All] :=
(StringProperties[func, #] & /@ StringProperties[func];);

$db[func_String] := $db[func] = Module[{file, nb, cells, entries},
file = Documentation`ResolveLink[func];
If[FileBaseName[file] =!= func,

Message[StringProperties::notfound, func]; Abort[]];
nb = Import[file, "Notebook"];
cells = Cases[nb, Cell[a_, "2ColumnTableMod", __] :> a, Infinity];
entries = cells /. BoxData[GridBox[content_]] :> content;
If[entries === {},
Association[],
Association@
Cases[entries, {_, key_String,
value_Cell} :> (ToExpression[key] -> value), {2}]]
];

];

Edit


Chris asked



would it be possible to modify your answer so that it takes wildcards? Such as StringProperties[NonlinearModelFit, "Table"] which would be the equivalent of ?Table ?



You have to decide how you want this to be incorporated into the existing framework, but in general, yes this is easily possible. To give you a head-start: Let's assume you are using StringExpressions like __~~"Table~~__ as wildcards, then an additional definition could look like this


StringProperties[func_Symbol, strExpr_StringExpression] := With[
{

keys = Flatten@StringCases[StringProperties[func], strExpr]
},
Do[StringProperties[func, k], {k, keys}]
]

and you are now able to do



Mathematica graphics



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...