User Reb.Cabin - Mathematica Stack Exchange most recent 30 from mathematica.stackexchange.com 2019-10-15T22:10:20Z https://mathematica.stackexchange.com/feeds/user/387 https://creativecommons.org/licenses/by-sa/4.0/rdf https://mathematica.stackexchange.com/questions/6497/-/207026#207026 1 Answer by Reb.Cabin for How can I implement object oriented programming in Mathematica? Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-09-28T20:26:10Z 2019-09-28T21:16:43Z <p>Data abstraction is one aspect of object-oriented programming, in my opinion, the most important aspect. I frequently use a schema abstracted, I hope in a very obvious way, from the following example, to implement data abstraction. I can just keyboard new 'classes' according to this schema without thinking much at all. My answer ignores many aspects of "object-oriented programming," such as namespace control (all my symbols must be free of global definitions), polymorphism (it's not straightforward to inherit from my 'class' simulacrum), lifetime management (I can only hope Mathematica's garbage collector does the right thing), and many other aspects, I am sure. I offer this only because it's been useful to me many times and it doesn't require any special support. And, in the hope that it is self-explantory, here it is with no further prose.</p> <pre><code>ClearAll[complex, real, imaginary, magnitude, phase, asMMA, setReal, setImaginary, setMagnitude, setPhase, setEulerian, setCartesian]; (* Constructor for 'complex' numbers stands in for the 'class' \ concept. There are no functions, here, for algebraic operations on my \ complex numbers, but I hope it's obvious how to add them. *) complex[ r : (_Real | _Integer | _Rational), i : (_Real | _Integer | _Rational)] := Module[{this,(* a perforce unique 'instance' symbol *) realPart, imaginaryPart, phasePart, magnitudePart, setEulerian, setCartesian (* closures that depend on other unique symbols *)}, (* private *) realPart = r; imaginaryPart = i; setEulerian[] := (magnitudePart = Sqrt[realPart^2 + imaginaryPart^2]; phasePart = ArcTan[realPart, imaginaryPart];); setCartesian[] := (realPart = magnitudePart*Cos[phasePart]; imaginaryPart = magnitudePart*Sin[phasePart]); (* initialize! *) setEulerian[]; (* public getters; patterns unique to the instance, but installed in the global namespace *) this@real[] := realPart; this@imaginary[] := imaginaryPart; this@magnitude[] := magnitudePart; this@phase[] := phasePart; this@asMMA[] := Complex[realPart, imaginaryPart]; (* public setters *) this@setReal[newR_] := (realPart = newR; setEulerian[];); this@setImaginary[newI_] := (imaginaryPart = newI; setEulerian[];); this@setMagnitude[newM_] := (magnitudePart = newM; setCartesian[];); this@setPhase[new\[Phi]_] := (phasePart = Mod[new\[Phi], 2 \[Pi]]; setCartesian[]); (* return 'this' instance symbols as result of constructor *) this ]; aComplexNumber = complex[42, 157]; Print[aComplexNumber@real[]]; aComplexNumber@setReal; Print[aComplexNumber@real[]]; Print[aComplexNumber@asMMA[]]; Print[N@aComplexNumber@phase[]]; Print[N@aComplexNumber@magnitude[]]; aComplexNumber@setPhase; Print[N@aComplexNumber@asMMA[]]; </code></pre> <blockquote> <pre><code>42 39 39+157 I 1.32732 161.771 161.771 +0. I </code></pre> </blockquote> https://mathematica.stackexchange.com/q/206975 2 Animate: surprise over discrete lists Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-09-27T15:25:30Z 2019-09-27T15:25:30Z <p>Consider <code>Animate[xs, {xs, {0, 1, 2}}]</code>. By my reading of <a href="https://reference.wolfram.com/language/ref/Animate.html" rel="nofollow noreferrer">the documentation</a>, </p> <pre><code>Animate[expr,{u,{u1,u2,…}}] makes u take on discrete values u1, u2, …. </code></pre> <p>my expression should produce an animation that steps from <code>0</code> to <code>1</code> to <code>2</code> and back to <code>0</code> in a loop, and, indeed it does:</p> <p><a href="https://i.stack.imgur.com/ZCXTj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZCXTj.png" alt="enter image description here"></a></p> <p>Now, consider <code>Animate[xs, {xs, {{"A", 0}, {"B", 1}, {"C", 2}}}]</code>. I would expect <code>xs</code> to take on the values <code>{"A", 0}</code>, <code>{"B", 1}</code>, and <code>{"C", 2}</code> in a loop, just as <code>xs</code> took on the values <code>0</code>, <code>1</code>, and <code>2</code> in a loop. I do not get what I expect. Instead, the display shows only <code>"A"</code>, <code>"B"</code>, <code>"C"</code> and the slider has a small excursion from 0 to 1 and a large excursion from 1 to 2:</p> <p><a href="https://i.stack.imgur.com/uiCng.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uiCng.png" alt="enter image description here"></a></p> <p>Guessing that the second argument in each list tells Animate how long, relatively, to dwell on each frame, if I turn things around, <code>Animate[xs, {xs, {0, "A"}, {1, "B"}, {2, "C"}}]</code>, I get a frozen animator, though with no error message. </p> <p>Under that hypothesis, I get what I want as follows</p> <p><a href="https://i.stack.imgur.com/GyU6P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GyU6P.png" alt="enter image description here"></a></p> <p>or, without the hypothesis, sort-of like this:</p> <p><a href="https://i.stack.imgur.com/r4Y23.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r4Y23.png" alt="enter image description here"></a></p> <p>Did I miss something in the documentation? Did I misunderstand the documentation? Did I stumble on undocumented (albeit useful) behavior?</p> https://mathematica.stackexchange.com/q/206565 6 Stabilized Inverted Pendulum Blog Post Broken in 12.0? Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-09-20T18:34:43Z 2019-09-21T12:05:39Z <p>One of the old Wolfram blog posts that I use frequently is this demonstration of the LQR gains computation. </p> <p><a href="https://blog.wolfram.com/2011/01/19/stabilized-inverted-pendulum/" rel="nofollow noreferrer">https://blog.wolfram.com/2011/01/19/stabilized-inverted-pendulum/</a></p> <p>I've been able to trust this since version 8. It's just one of those things I "go to" without thinking too much about it when starting a controls project. </p> <p>It's now broken in ways I describe below, and despite a few hours of poking deep, I haven't found the root cause nor a workaround. This has me doubting not only Mathematica version 12 but my own sanity. I cannot trust the entire infrastructure this demo stands on.</p> <p>I downloaded a fresh copy of the CDF this morning. The notebook no longer <strong>qualitatively</strong> matches the posted videos, and it certainly used to match in earlier versions of Mathematica. </p> <p>In particular, the last two simulations are badly broken. In the penultimate demonstration, the cart does not return to center after the second bump, but drifts off to the right forever. That behavior is contrary to the video and contrary to the behavior I have observed in live notebooks since version 8. </p> <p>Something changed in version 12!</p> <p>The last demonstration fails even more dramatically. The cart does not move at all while being bumped hard. The video shows the expected behavior.</p> <p>Anyone have any insight to this? Is <code>NDSolve</code> broken? Could it be related to broken eigenvalues? <a href="https://mathematica.stackexchange.com/questions/198597/eigenvalues-broken-in-version-12-0">Eigenvalues broken in Version 12.0</a> </p> https://mathematica.stackexchange.com/q/187882 1 A little magic for the Euler-Lagrange equations? Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-12-14T01:57:09Z 2018-12-14T02:10:26Z <p>Consider a simple, one-dimensional Lagrangian:</p> <pre><code>L = m (z'[t]^2)/2 - m g z[t] </code></pre> <p>The built-in, partial-derivative operator <code>D</code> has no trouble producing the Euler-Lagrange equations of motion for this:</p> <pre><code>D[D[L, z'[t]],t] - D[L,z[t]] == 0 </code></pre> <blockquote> <pre><code>g m + m z''[t] == 0 </code></pre> </blockquote> <p>The same idea works when there are several dynamical variables, say something like </p> <pre><code>L = m (x'[t]^2 + y'[t]^2) / 2; MapThread[Function[{q, v, h}, D[D[L,v],t] - D[L,q] == h], {{x[t], y[t]}, {x'[t], y'[t]}, {fx[t], fy[t]}}] </code></pre> <blockquote> <pre><code>{m x''[t] == fx[t], m y''[t] == fy[t]} </code></pre> </blockquote> <p>This is really great and convenient and I use it a lot, but it's occurred to me that it's a little magical. I read the documentation for <code>D</code> and the second argument seems always to be just a variable like <code>x</code> or <code>t</code>, not an extended expression like <code>x[t]</code> or <code>x'[t]</code>, which is really <code>Derivative[x][t]</code> or, equivalently, <code>D[x[t],t]</code>.</p> <p>The idea does work when the second argument of <code>D</code> is an arbitrary, though unknown function:</p> <pre><code>D[exp[t]^2 / 2, exp[t]] </code></pre> <blockquote> <pre><code>exp[t] </code></pre> </blockquote> <p>But not when the second argument is a built-in:</p> <pre><code>D[Exp[t]^2 / 2, Exp[t]] </code></pre> <blockquote> <pre><code>General: Exp[t] is not a valid variable. </code></pre> </blockquote> <p>This message is hard to grok because <code>exp[t]</code> isn't exactly a valid variable either, or is it? Are expressions like <code>x[t]</code> and <code>x'[t]</code> always considered "variables" by <code>D</code>? If so, are there other kinds of expressions that <code>D</code> thinks of as variables?</p> <p>This all makes sense, in a way, but is a little surprising and made me curious. Did I miss something in the documentation? Did I not understand the documentation? Is this an under-documented feature? What are the limitations of this feature?</p> <p><strong>EDIT</strong>:</p> <p>I found, by researching "related questions," that </p> <pre><code>D[Log[x]^2 / 2, Log[x]] </code></pre> <blockquote> <pre><code>Log[x] </code></pre> </blockquote> <p>works as expected. So, it seems, <code>D</code> works on <em>some</em> built-ins. I'm more confused than ever.</p> https://mathematica.stackexchange.com/q/183771 1 Discrepancy between ReplaceList and ReplaceAll? Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-10-13T15:20:07Z 2018-10-13T15:31:34Z <p>Consider the following</p> <pre><code>ClearAll[eqv, not, neqv, p, q, r] ReplaceAll[eqv[neqv[p, q], r], neqv[p_, q_] :&gt; not[eqv[p, q]]] </code></pre> <blockquote> <p><code>eqv[not[eqv[p, q]], r]</code></p> </blockquote> <p>According to the documentation, I should expect <code>ReplaceList</code> to return (at least) this result in a list, but, instead, I am surprised to get an empty list:</p> <pre><code>ClearAll[eqv, not, neqv, p, q, r] ReplaceList[eqv[neqv[p, q], r], neqv[p_, q_] :&gt; not[eqv[p, q]]] </code></pre> <blockquote> <p><code>{}</code></p> </blockquote> <p>Again, according to the documentation, <code>ReplaceList</code> thinks there is no transformation possible, but <code>ReplaceAll</code> found one. I didn't see any indication that <code>ReplaceList</code> could be expected to return the empty list under any other circumstances. </p> <p>This is important because in some deeper and more complicated programs, I need to scan all alternative replacements, but I now fear I can't trust <code>ReplaceList</code>.</p> <p>Mathematica 11.3.0.0 Ubuntu 18.04</p> https://mathematica.stackexchange.com/questions/183322/-/183412#183412 1 Answer by Reb.Cabin for Subtle order-of-evaluation issues when pattern-matching with attributes Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-10-08T21:39:57Z 2018-10-09T00:04:16Z <p>Carl Woll's comment turned the lights on for me and cleared the fog. There are no matches when there is no <code>Flat</code>. That observation also clears up the related question <a href="https://mathematica.stackexchange.com/questions/183319/big-and-little-surprises-when-unrolling-tests-of-pattern-matching-and-attributes">Big and Little surprises when unrolling tests of pattern-matching and attributes</a>. </p> <p>Here are the only tests that make sense out of the above, now unrolled. </p> <pre><code>In:= Module[{}, ClearAll[eqv]; SetAttributes[eqv, {Flat}]; eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}] Out= {eqv[p], eqv[q, r]} In:= Module[{}, ClearAll[eqv]; SetAttributes[eqv, {Flat, OneIdentity}]; eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}] Out= {p, eqv[q, r]} In:= Module[{}, ClearAll[eqv]; SetAttributes[eqv, {Flat, Orderless}]; eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}] Out= {q, eqv[p, r]} In:= Module[{}, ClearAll[eqv]; SetAttributes[eqv, {Flat, OneIdentity, Orderless}]; eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}] Out= {p, eqv[q, r]} </code></pre> <p>The answer for <code>{Flat, Orderless}</code> seems puzzling. Usually, Mathematica sorts symbolic constants alphabetically and minimizes nesting, leading us to expect <code>{p,eqv[q,r}</code>. There are an unbounded number of correct answers, all equivalent under these attributes, however, any of which would be acceptable. Here are just a few:</p> <pre><code>In:= ClearAll[eqv]; SetAttributes[eqv, {Flat, Orderless}]; eqv[eqv[p], eqv[r, q]] === eqv[eqv[q], eqv[p, r]] === eqv[eqv[q], eqv[r, p]] === eqv[eqv[q], eqv[r, p]] === eqv[eqv[r], eqv[p, q]] === eqv[eqv[r], eqv[q, p]] === eqv[p, eqv[r, q]] === eqv[q, eqv[p, r]] === eqv[eqv[eqv[p]], eqv[q, r]] === eqv[eqv[p], q, r] Out= True </code></pre> <p>Indeed, even the result for <code>Flat</code> alone has many correct answers:</p> <pre><code>In:= ClearAll[eqv]; SetAttributes[eqv, {Flat}]; eqv[eqv[p], eqv[q, r]] === eqv[p, eqv[q, r]] === eqv[eqv[eqv[p]], eqv[q, r]] === eqv[eqv[p], q, r] Out= True </code></pre> https://mathematica.stackexchange.com/q/183322 4 Subtle order-of-evaluation issues when pattern-matching with attributes Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-10-07T18:07:12Z 2018-10-09T00:04:16Z <p>Related question concerning unrolling the tests that are shown below:</p> <p><a href="https://mathematica.stackexchange.com/questions/183319/big-and-little-surprises-when-unrolling-tests-of-pattern-matching-and-attributes">Big and Little surprises when unrolling tests of pattern-matching and attributes</a></p> <p>Questions researched before posting this one:</p> <p><a href="https://mathematica.stackexchange.com/questions/71463/orderless-pattern-matching">Orderless pattern matching</a></p> <p><a href="https://mathematica.stackexchange.com/questions/105608/combinations-of-multiple-matching-patterns">Combinations of multiple matching patterns</a></p> <p><a href="https://mathematica.stackexchange.com/questions/124372/about-oneidentity">About OneIdentity</a></p> <p><a href="https://mathematica.stackexchange.com/questions/121564/what-has-changed-in-pattern-matching-functions-with-the-orderless-attribute">What has changed in pattern matching functions with the Orderless attribute?</a></p> <p><a href="https://mathematica.stackexchange.com/questions/121535/transformation-rule-for-arbitrary-number-of-argument-expressions?noredirect=1#comment329951_121535">Transformation rule for arbitrary number of argument expressions</a></p> <p><a href="https://mathematica.stackexchange.com/questions/94432/pattern-does-not-match-with-orderless-head">Pattern does not match with Orderless head</a></p> <p>In an attempt to understand pattern-matching better, I tried some exhaustive testing of a certain substitution rule under all seven combinations of attributes, leaving out the null case of no attributes:</p> <pre><code>In:= allAtts = Flatten[Table[ Union[Sort /@ Permutations[{Flat, Orderless, OneIdentity}, {i}]], {i, 3}], 1] Out= {{Flat}, {OneIdentity}, {Orderless}, {Flat, OneIdentity}, {Flat, Orderless}, {OneIdentity, Orderless}, {Flat, OneIdentity, Orderless}} </code></pre> <p>The substitution rule attempts to match the pattern <code>eqv[x_, y_]</code> against the input <code>eqv[p, q, r]</code> to see what gets bound to <code>x</code> and <code>y</code> for each combination of attributes.</p> <p>In the first test, I define the substitution before setting the attributes. After some manual prettification of the output:</p> <pre><code>In:= Table[Module[{e = (eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}})}, ClearAll[eqv]; SetAttributes[eqv, j]; {j, First@e, Rest@e}], {j, allAtts}] Out= {{{Flat}, p, eqv[q, r]}, {{OneIdentity}, eqv[p], {eqv[q, r]}}, {{Orderless}, p, eqv[q, r]}, {{Flat, OneIdentity}, p, eqv[q, r]}, {{Flat, Orderless}, p, {eqv[q, r]}}, {{OneIdentity, Orderless}, q, {eqv[p, r]}}, {{Flat, OneIdentity, Orderless}, p, eqv[q, r]}} </code></pre> <p>The results are reasonable, plausible, interpretable.</p> <p>In a second test (not-unrolled; see cited question above), I set the attributes before defining the substitution rule. The results are subtly different.</p> <pre><code>In:= Table[Module[{e}, ClearAll[eqv]; SetAttributes[eqv, j]; e = (eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}); {j, First@e, Rest@e}], {j, allAtts}] Out= {{{Flat}, eqv[p], {eqv[q, r]}}, (* difft *) {{OneIdentity}, p, eqv[q, r]}, (* difft *) {{Orderless}, p, eqv[q, r]}, {{Flat, OneIdentity}, p, {eqv[q, r]}}, (* difft *) {{Flat, Orderless}, q, {eqv[p, r]}}, (* difft *) {{OneIdentity, Orderless}, p, eqv[q, r]}, (* difft *) {{Flat, OneIdentity, Orderless}, p, {eqv[q, r]}}} (* difft *) </code></pre> <p>My questions are:</p> <ol> <li><p>Why, exactly, are there such differences? I understand that order-of-evaluation matters quite a bit, in general, in Mathematica, but it's hard for me to understand these particular differences. Details follow in the rest of my questions:</p></li> <li><p>In the first test, with <code>Flat</code> alone, why do I get (a) <code>p</code> wrapped in <code>eqv</code>, i.e., <code>eqv[p]</code> and <code>eqv[q, r]</code> wrapped in <code>List</code>, when I set attributes before defining the substitution rule?</p></li> <li><p>In the second test, for <code>OneIdentity</code>, alone, when attributes are set before the substitution rule is defined, do I get the same results as for <code>Flat</code>, alone, when the substitution rule is defined before the attributes are set? In other words, for the two orders of attributes-setttings versus rule-defining, are the results for <code>Flat</code> alone and <code>OneIdentity</code> alone swapped?</p></li> <li><p>In the fourth test, for <code>{Flat, OneIdentity}</code>, why do I get no wrapping with <code>List</code> for the second substitution (for <code>y</code>) when the substitution rule is defined before the attributes are set, and yes wrapping with <code>List</code> when the attributes are set before the substitution rule is defined?</p></li> <li><p>In the fifth test, for <code>{Flat, Orderless}</code>, why do I get <code>p</code> for <code>x</code> when the substitution rule is defined before attributes are set, and <code>q</code> for <code>x</code> when the attributes are set before the substitution rule is defined?</p></li> <li><p>In the sixth test, for <code>{OneIdentity, Orderless}</code>, there are two differences between the two conditions (substitution rule defined before attributes set, and attributes set before substitution rule defined). The first difference (a) is that I get <code>q</code> for <code>x</code> in the first condition and <code>p</code> for <code>x</code> in the second condition. The second difference (b) is that I get <code>List</code> wrapping in the first condition and no <code>List</code> wrapping in the second condition.</p></li> </ol> <p><strong>EDIT</strong>: I missed the last difference in the original, and finding it gave me an opportunity to ask the sharpest questions:</p> <ol start="7"> <li>In the seventh test, for all three attributes, I get an extra <code>List</code> wrapping in the output in the second condition, attributes-set before substitution-defined. Why is that? Should I have been able to predict it knowing just the conditions? By what reasoning?</li> </ol> <p>I apologize for the length and complexity of this question, but I made it as short and as simple as I know how to. This question reveals that I don't know nearly as much as I thought I did about pattern-matching and attributes. Perhaps after I learn more from you-all, a much simpler form of the essential question --- hiding in here somewhere I hope --- will emerge.</p> https://mathematica.stackexchange.com/questions/183319/-/183416#183416 1 Answer by Reb.Cabin for Big and Little surprises when unrolling tests of pattern-matching and attributes Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-10-08T23:07:06Z 2018-10-08T23:42:22Z <p>Carl Woll, in a comment in the related question <a href="https://mathematica.stackexchange.com/questions/183322/subtle-order-of-evaluation-issues-when-pattern-matching-with-attributes">Subtle order-of-evaluation issues when pattern-matching with attributes</a>, provided the clue that cleared the air for me. My original tests were misleading because I failed to notice that there are no matches when there is no <code>Flat</code>. To see this, I should have returned <code>e</code> instead of <code>First[e]</code> and <code>Rest[e]</code>, because only <code>e</code> reveals that there was no match; when there is no match, <code>First[e]</code> produces <code>p</code> and <code>Rest[e]</code> produces <code>eqv[q,r]</code> and I was mislead by assuming those were the results of a match when, in fact, they are simply the ordinary deconstruction of <code>eqv[p,q,r]</code> into its first part <code>p</code> and its "rest" part <code>eqv[q,r]</code>. </p> <p>There are no differences between the case when substitution is defined (in a delayed-rule pseudo-function) before attributes are set and then case when the attributes are set before the substitution is defined, as revealed by the remaining meaningful tests below.</p> <p>It makes no sense to set attributes after a substitution rule is <em>applied</em>, as Carl points out, but there are cases where setting attributes before or after definitions makes a difference (see the "Questions researched," above). But the order does not make a difference in this case.</p> <pre><code>In:= Module[{}, ClearAll[eqv]; SetAttributes[eqv, {Flat}]; eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}] Out= {eqv[p], eqv[q, r]} In:= Module[{}, ClearAll[eqv]; SetAttributes[eqv, {Flat, OneIdentity}]; eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}] Out= {p, eqv[q, r]} In:= Module[{}, ClearAll[eqv]; SetAttributes[eqv, {Flat, Orderless}]; eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}] Out= {q, eqv[p, r]} In:= Module[{}, ClearAll[eqv]; SetAttributes[eqv, {Flat, OneIdentity, Orderless}]; eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}] Out= {p, eqv[q, r]} In:= Module[{e}, ClearAll[eqv]; e[] := eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}; SetAttributes[eqv, {Flat}]; e[]] Out= {eqv[p], eqv[q, r]} In:= Module[{e}, ClearAll[eqv]; e[] := eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}; SetAttributes[eqv, {Flat, OneIdentity}]; e[]] Out= {p, eqv[q, r]} In:= Module[{e}, ClearAll[eqv]; e[] := eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}; SetAttributes[eqv, {Flat, Orderless}]; e[]] Out= {q, eqv[p, r]} In:= Module[{e}, ClearAll[eqv]; e[] := eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}; SetAttributes[eqv, {Flat, OneIdentity, Orderless}]; e[]] Out= {p, eqv[q, r]} </code></pre> https://mathematica.stackexchange.com/q/183319 3 Big and Little surprises when unrolling tests of pattern-matching and attributes Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-10-07T17:24:59Z 2018-10-08T23:42:22Z <p>Related question concerning interpretation of the substitutions:</p> <p><a href="https://mathematica.stackexchange.com/questions/183322/subtle-order-of-evaluation-issues-when-pattern-matching-with-attributes">Subtle order-of-evaluation issues when pattern-matching with attributes</a></p> <p>Questions researched before posting this one:</p> <p><a href="https://mathematica.stackexchange.com/questions/71463/orderless-pattern-matching">Orderless pattern matching</a></p> <p><a href="https://mathematica.stackexchange.com/questions/105608/combinations-of-multiple-matching-patterns">Combinations of multiple matching patterns</a></p> <p><a href="https://mathematica.stackexchange.com/questions/124372/about-oneidentity">About OneIdentity</a></p> <p><a href="https://mathematica.stackexchange.com/questions/121564/what-has-changed-in-pattern-matching-functions-with-the-orderless-attribute">What has changed in pattern matching functions with the Orderless attribute?</a></p> <p><a href="https://mathematica.stackexchange.com/questions/121535/transformation-rule-for-arbitrary-number-of-argument-expressions?noredirect=1#comment329951_121535">Transformation rule for arbitrary number of argument expressions</a></p> <p><a href="https://mathematica.stackexchange.com/questions/94432/pattern-does-not-match-with-orderless-head">Pattern does not match with Orderless head</a></p> <p>All work done with Mathematica 11.3.0.0 on Ubuntu 18.04 (bionic)</p> <p>In an attempt to understand pattern-matching better, I tried some exhaustive testing of a certain substitution rule under all seven combinations of attributes, leaving out the null case of no attributes:</p> <pre><code>In:= allAtts = Flatten[Table[ Union[Sort /@ Permutations[{Flat, Orderless, OneIdentity}, {i}]], {i, 3}], 1] Out= {{Flat}, {OneIdentity}, {Orderless}, {Flat, OneIdentity}, {Flat, Orderless}, {OneIdentity, Orderless}, {Flat, OneIdentity, Orderless}} </code></pre> <p>The substitution rule attempts to match the pattern <code>eqv[x_, y_]</code> against the input <code>eqv[p, q, r]</code> to see what gets bound to <code>x</code> and <code>y</code> for each combination of attributes.</p> <p>In the first test, I define the substitution before setting the attributes. After some manual prettification:</p> <pre><code>In:= Table[Module[{e = (eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}})}, ClearAll[eqv]; SetAttributes[eqv, j]; {j, First@e, Rest@e}], {j, allAtts}] Out= {{{Flat}, p, eqv[q, r]}, {{OneIdentity}, eqv[p], {eqv[q, r]}}, {{Orderless}, p, eqv[q, r]}, {{Flat, OneIdentity}, p, eqv[q, r]}, {{Flat, Orderless}, p, {eqv[q, r]}}, {{OneIdentity, Orderless}, q, {eqv[p, r]}}, {{Flat, OneIdentity, Orderless}, p, eqv[q, r]}} </code></pre> <p>The results are reasonable, plausible, interpretable. I won't go into interpreting the results in this post other than to note that the results are subtly different when attributes are set before the substitution rule is parsed. The subject of this post is that unrolling the tests produce very different, not subtly different, results. Because I unroll below under both conditions --- substitution parsed before attributes set and attributes set before substitution parsed --- here are the results of the latter, subtly different:</p> <pre><code>In:= Table[Module[{e}, ClearAll[eqv]; SetAttributes[eqv, j]; e = (eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}); {j, First@e, Rest@e}], {j, allAtts}] Out= {{{Flat}, eqv[p], {eqv[q, r]}}, (* difft *) {{OneIdentity}, p, eqv[q, r]}, (* difft *) {{Orderless}, p, eqv[q, r]}, {{Flat, OneIdentity}, p, {eqv[q, r]}}, (* difft *) {{Flat, Orderless}, q, {eqv[p, r]}}, (* difft *) {{OneIdentity, Orderless}, p, eqv[q, r]}, (* difft *) {{Flat, OneIdentity, Orderless}, p, {eqv[q, r]}}} </code></pre> <p>In a separate post, I have questions about interpreting the results. I Continue here with the main question about unrolling.</p> <p>I now attempt to unroll these tests, one test for each combination of attributes rather than one table with all combinations. I get many surprises that reveal I don't really understand what's going on. I highlight these surprises below and would be grateful for explanation and clarification.</p> <p>First, here is my attempt at unrolling the tests:</p> <pre><code>In:= test32substBeforeAttrs[attrs_] := Module[{eval}, eval[] := eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}; ClearAll[eqv]; SetAttributes[eqv, attrs]; eval[]] </code></pre> <p>I try to prevent any early evaluation of the substitution by packaging it in a delayed rule named <code>eval</code>, but I do want the substitution denoted and parsed before attributes are set, which (I thought), were the same conditions as in the rolled-up test.</p> <p>Surprise number one, the <code>Flat</code> results look similar to the test where attributes are set before the substitution rule is parsed, just without a list enclosing the second binding for <code>y</code>:</p> <pre><code>In:= test32substBeforeAttrs[{Flat}] Out= {eqv[p], eqv[q, r]} </code></pre> <p>Surprise number two, we get no matches for <code>OneIdentity</code> alone and for <code>Orderless</code> alone:</p> <pre><code>In:= test32substBeforeAttrs[{OneIdentity}] Out= eqv[p, q, r] In:= test32substBeforeAttrs[{Orderless}] Out= eqv[p, q, r] </code></pre> <p>No surprises for <code>{Flat, OneIdentity}</code>:</p> <pre><code>In:= test32substBeforeAttrs[{Flat, OneIdentity}] Out= {p, eqv[q, r]} </code></pre> <p>but surprise number three for <code>{Flat, Orderless}</code>: <code>p</code> and <code>q</code> are reversed, just like the rolled-up case for <code>{OneIdentity, Orderless}</code>, except, again, no list enclosing the second binding, the binding for <code>y</code>:</p> <pre><code>In:= test32substBeforeAttrs[{Flat, Orderless}] Out= {q, eqv[p, r]} </code></pre> <p>Surprise number four: no match for unrolled <code>{OneIdentity, Orderless}</code>:</p> <pre><code>In:= test32substBeforeAttrs[{OneIdentity, Orderless}] Out= eqv[p, q, r] </code></pre> <p>No surprise for the case of all attributes.</p> <pre><code>In:= test32substBeforeAttrs[{Flat, OneIdentity, Orderless}] Out= {p, eqv[q, r]} </code></pre> <p>Now, my attempt at an unrolled setting of attributes before denoting and parsing the substitution rule. Again, I attempt to prevent early evaluation by packaging my main substitution rule in an outer, delayed substitution rule named <code>eval</code>:</p> <pre><code>In:= test32AttrsBeforeSubst[attrs_] := Module[{eval}, ClearAll[eqv]; SetAttributes[eqv, attrs]; eval[] := eqv[p, q, r] /. {eqv[x_, y_] :&gt; {x, y}}; eval[]] In:= test32AttrsBeforeSubst[{Flat}] Out= {eqv[p], eqv[q, r]} In:= test32AttrsBeforeSubst[{OneIdentity}] Out= eqv[p, q, r] In:= test32AttrsBeforeSubst[{Orderless}] Out= eqv[p, q, r] In:= test32AttrsBeforeSubst[{Flat, OneIdentity}] Out= {p, eqv[q, r]} In:= test32AttrsBeforeSubst[{Flat, Orderless}] Out= {q, eqv[p, r]} In:= test32AttrsBeforeSubst[{OneIdentity, Orderless}] Out= eqv[p, q, r] In:= test32AttrsBeforeSubst[{Flat, OneIdentity, Orderless}] Out= {p, eqv[q, r]} </code></pre> <p>The big surprise here is that the results are exactly the same as the unrolled test with substitution parsed before attributes set.</p> <p>To summarize, in addition to the four little surprises when unrolling the tests, there is a big surprise that the relative order of denoting the rule matters when the tests are rolled up and not when the tests are unrolled.</p> <p>I've managed to confuse myself mightily, here, and would be grateful for insights from those who understand both the big picture and the micro details better than I do. I apologize for the length and complexity of this question, but I made it as short and as simple as I know how to. The gist of this question is that I don't know nearly as much as I thought I did about pattern-matching and attributes. Perhaps after I learn more from you-all, a much simpler form of the essential question --- hiding in here somewhere I hope --- will emerge.</p> https://mathematica.stackexchange.com/q/182271 5 Non-breaking hyphen? Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-09-20T20:41:52Z 2018-09-20T20:48:13Z <p>I found <code>\[NonBreakingSpace]</code> but I haven't found a non-breaking hyphen (I want to use them in text mode in notebooks). I must be missing something obvious.</p> https://mathematica.stackexchange.com/q/180530 8 Adding a new GeoProjection? Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-08-23T17:26:43Z 2018-08-23T17:26:43Z <p>The documentation for <code>GeoProjectionData</code> gives a list of supported <code>GeoProjections</code>. I was not able to find any documentation on how to add a new <code>GeoProjection</code>. I have a spec for a new one in the form of equations for $x$ and $y$ as functions of lat and long, and I'd like to take advantage of Mathematica's <code>GeoGraphics</code> to display that new projection with world data. Maybe I'm missing something obvious?</p> https://mathematica.stackexchange.com/q/73016 6 Cases with Alternatives failed Reb.Cabin https://mathematica.stackexchange.com/users/387 2015-02-01T17:52:27Z 2018-08-23T15:15:41Z <p>Consider this list of rules</p> <pre><code>rules = {a -&gt; 1, b -&gt; 2, c -&gt; 3} </code></pre> <p>I'd like to fish some of the rules out of such a list using <code>Cases</code>. All is well if I hard code the <code>Alternatives</code> to fish out:</p> <pre><code>Cases[rules, HoldPattern[a|b -&gt; _]] </code></pre> <blockquote> <p>{a -> 1, b -> 2}</p> </blockquote> <p>But, if I try to dynamically generate the <code>Alternatives</code> from data, it fails:</p> <pre><code>targets = {a, b} Cases[rules, HoldPattern[Alternatives @@ targets -&gt; _]] </code></pre> <blockquote> <p>{}</p> </blockquote> <p>I've tried the following shots-in-the-dark</p> <pre><code>Cases[rules, HoldPattern[Evaluate[Alternatives @@ targets] -&gt; _]] </code></pre> <blockquote> <p>{}</p> </blockquote> <pre><code>Cases[rules, HoldPattern[ReleaseHold[Alternatives @@ targets] -&gt; _]] </code></pre> <blockquote> <p>{}</p> </blockquote> <p>MMA 10.0.2.0 on Mac Mavericks.</p> https://mathematica.stackexchange.com/q/155580 2 Interdependent SetterBars with symbolic contents Reb.Cabin https://mathematica.stackexchange.com/users/387 2017-09-12T13:29:33Z 2017-09-12T17:34:13Z <p>In <a href="https://mathematica.stackexchange.com/questions/88553/interdependent-setter-controls-in-manipulate">this question</a>, I learned how to cascade or nest interdependent <code>Setter</code> and <code>SetterBar</code> controls with numerical Ranges. The puzzle has arisen again, this time with lists containing symbols. This puzzle is not, to me, in any obvious way a duplicate of the prior one.</p> <p>Consider this miniature database of destination cities:</p> <pre><code>destinations = {SLC, DEN, OKC, MSY, ABQ}; </code></pre> <p>and this function (as a lookup table) from destination city to pair of nearby source cities:</p> <pre><code>src[SLC] = {ONT, PHX}; src[DEN] = {PHX, DFW}; src[OKC] = {DFW, SAT}; src[MSY] = {DFW, TPA}; src[ABQ] = {DFW, PHX}; </code></pre> <p>My first attempt at nested controls, allowing one to choose a destination city and then choose one of the nearby source cities, produced a surprise:</p> <pre><code>Manipulate[ {dest, source}, {dest, destinations, SetterBar}, {{source, src[dest][]}, src[dest], SetterBar}] </code></pre> <p><a href="https://i.stack.imgur.com/pALIX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pALIX.png" alt="enter image description here"></a></p> <p>Notice that, while the pair of sources for each destination are correctly pulled from the <code>src</code> function, there is no default selected item in the lower SetterBar even though I explicitly set it to the first item <code>src[dest][]</code>. The default <code>source</code> seems always to be (inexplicably) the first city in <code>destinations</code> list. The <code>source</code> SetterBar works correctly when I click in it, but its default is never set correctly.</p> <p>I can work around the problem by mapping through indices:</p> <pre><code>Manipulate[ {dest, src[dest][[source]]}, {dest, destinations, SetterBar}, {{source, 1}, {1 -&gt; src[dest][], 2 -&gt; src[dest][]}, SetterBar}] </code></pre> <p><a href="https://i.stack.imgur.com/e9qjc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e9qjc.png" alt="enter image description here"></a></p> <p>but this is not a robust solution because it requires me to hardcode the list of button labels in a set of rules. What if I wanted three sources for one of the destinations?</p> https://mathematica.stackexchange.com/q/3097 43 How to do http POST in Mathematica? Reb.Cabin https://mathematica.stackexchange.com/users/387 2012-03-16T19:33:37Z 2017-09-08T12:57:04Z <p>The Import command lets you do a HTTP GET from a URL, like this </p> <pre><code>Import @ "http://merkosoncampus.com/wp-content/uploads/2011/05/higgs-boson.jpg" </code></pre> <p>This sends an HTTP GET request to the server and presumably parses the response according to some rules for inferring the type of data, from the content or from the extension ".jpg" or whatever.</p> <p>Listening on the socket, we see something like this</p> <pre><code>GET http://merkosoncampus.com/wp-content/uploads/2011/05/higgs-boson.jpg HTTP/1.1 User-agent: Mathematica/8.0.4.0.0 PM/1.3.1 Host: merkosoncampus.com Proxy-Connection: Keep-Alive </code></pre> <p>whereas what I want is something along the lines of</p> <pre><code>POST http://foo.bar.com/myService HTTP/1.1 User-Agent: Mathematica/8.0.4.0.0 PM/1.3.1 Host: foo.bar.com Accept: */* Connection: Keep-Alive Content-Length: 76 Content-Type: application/x-www-form-urlencoded { "myJsonStuff" : {"number" : 1} } </code></pre> <p>I looked for options in <code>Import</code>, praying for something like <code>Method-&gt;"POST"</code>, but didn't find anything useful. </p> <p>I'd be grateful for clues, experience, ideas, sample code. In the mean time, I intend to work around it by writing my desired JSON to a file and using curl to POST it, but it's way sub-optimal.</p> https://mathematica.stackexchange.com/q/155113 4 Lagrangian form of Earth-Sun Kepler blows up NDSolve? Reb.Cabin https://mathematica.stackexchange.com/users/387 2017-09-05T17:30:32Z 2017-09-06T01:35:00Z <p>I've looked at <a href="https://mathematica.stackexchange.com/questions/14898/coulomb-kepler-potential-dynamics-ndsolve-breaks">this 1-D SE question</a>. That question seems to have difficulties around diverging potential functions, and I don't have that. I've looked at <a href="http://demonstrations.wolfram.com/PlanarThreeBodyProblem/" rel="nofollow noreferrer">this 2-D 3-body demonstration</a>, but that starts with equations of motion and I want to start with Lagrangians and symbolically derive the equations of motion. </p> <p>The big picture is that I am developing a generalized Lagrangian solver and sanity checking it with small, standard scenarios. I got the original idea for the solver from the Wolfram blog, in <a href="http://blog.wolfram.com/2011/03/01/stabilized-n-link-pendulum/" rel="nofollow noreferrer">this article by Moylan</a>. My version of Moylan's solver passes his scenario and passes a damped simple harmonic oscillator, but it fails on the 2-D "reduced" Kepler problem. I don't know whether I have bugs or whether I am just using Mathematica clumsily, specifically with NDSolve. </p> <p>I have checked this as much as I can visually and with cross references. For instance, the equations of motion I symbolically derive match those in <a href="http://web.mit.edu/8.01t/www/materials/modules/guide17.pdf" rel="nofollow noreferrer">this MIT courseware document</a>. </p> <p>I show all details below and will be very grateful for advice. </p> <p>I only need 2-D because all 2-body Kepler problems are planar.</p> <p>The "reduced" Kepler problem is a problem in two degrees of freedom, $r$ and $\theta$, concerning motion of a particle of "reduced mass" $m_{Earth}m_{Sun}/(m_{Earth}+m_{Sun})$ (again, see <a href="http://web.mit.edu/8.01t/www/materials/modules/guide17.pdf." rel="nofollow noreferrer">MIT</a>).</p> <p>Following <a href="http://blog.wolfram.com/2011/03/01/stabilized-n-link-pendulum/" rel="nofollow noreferrer">Moylan</a>, we write:</p> <p><a href="https://i.stack.imgur.com/ylBOs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ylBOs.png" alt="enter image description here"></a></p> <p>I hope you can see the reason for my interest in Moylan's method: the conciseness is valuable and worth generalizing to other problems. The Kepler problem doesn't have any non-conservative forces, but I have preserved that term in the code just for the purposes of that generalization. It works for a damped harmonic oscillator, for example.</p> <pre><code>coordinates = {r[τ], θ[τ]}; velocities = D[coordinates, τ]; L = 1/2 μ r'[τ]^2 + 1/2 μ r[τ]^2 θ'[τ]^2 - G M μ/r[τ]; nonConservativeForces = -{0, 0}*velocities; equations = MapThread[{q, v, h} \[Function] D[D[L, v], τ] - D[L, q] == h, {coordinates, velocities, nonConservativeForces}]; </code></pre> <p>For the rest of this post, I will paste images of a Notebook. <a href="https://gist.github.com/rebcabin/180b54ca8d7dafc25806c6d80baada39" rel="nofollow noreferrer">Self-contained code is in this gist</a> that anyone can paste into a Notebook and run.</p> <p>Mathematica finds the following equations of motion, which match the MIT reference up to units and constants:</p> <p><a href="https://i.stack.imgur.com/VfvlR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VfvlR.png" alt="enter image description here"></a></p> <p>We need numerical values, which I supply with a list of substitution rules:</p> <p><a href="https://i.stack.imgur.com/7vd3Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7vd3Q.png" alt="enter image description here"></a></p> <p>And sanity-check by comparing the gravitational force to the centripetal force with these constants:</p> <p><a href="https://i.stack.imgur.com/IDxWU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IDxWU.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/X8HZp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X8HZp.png" alt="enter image description here"></a></p> <p>Should be close enough.</p> <p>I then solve the numerical equations with the following code:</p> <p><a href="https://i.stack.imgur.com/vel28.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vel28.png" alt="enter image description here"></a></p> <p>The results plot as follows (please see the <a href="https://gist.github.com/rebcabin/180b54ca8d7dafc25806c6d80baada39" rel="nofollow noreferrer">gist</a> for the lengthy but uninformative plotting code):</p> <p><a href="https://i.stack.imgur.com/ECqYu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ECqYu.png" alt="enter image description here"></a></p> <p>OK, pretty much nothing is right. I expected $r(\tau)$ to be more-or-less constant, but it blows up. I expected $\theta(\tau)$ to be more-or-less linearly increasing, but it's not linear. Angular momentum and energy are not even slightly conserved. </p> <p>I hope this is just something dumb on my part, but I don't see it. Anyone spot a problem that's easy to fix? Or have I waded into deeper waters?</p> <p><strong>EDIT</strong>: just realized that my numerical value for <code>day</code> is off by a factor of 365.25 (oops) changing it does NOT solve the bigger problem, though. The angular momentum and energy are still not conserved. I updated <a href="https://gist.github.com/rebcabin/180b54ca8d7dafc25806c6d80baada39" rel="nofollow noreferrer">the public gist</a>.</p> https://mathematica.stackexchange.com/q/13324 15 RandomReal closed on left & open on right? Reb.Cabin https://mathematica.stackexchange.com/users/387 2012-10-19T14:34:43Z 2017-08-15T18:02:22Z <p>I have a number of algorithms that depend on uniform random reals in half-open intervals such as $[0,1)$. In particular, I need a (pseudo) random-number generator that produces machine-precision numbers in the range $0.0$ to $1-\epsilon$. It can return $0.999...$, but will never return exactly $1.0$. I haven't found in the Mathematica documentation whether Mathematica's <code>RandomReal</code> satisfies this requirement. The documentation does state that <code>RandomInteger[{xMin,xMax}]</code> produces values in the double-closed interval $[x_{min}, x_{max}]$ inclusive of both ends, but I haven't found an equally clear statement about the real-number generators. The documentation that I've read just says "between 0 and 1." I could read this as double-open, but it really isn't precise enough for me. I would be grateful for an authoritative answer.</p> https://mathematica.stackexchange.com/q/151611 6 Volumes and moments of inertia of meshes in 3D Reb.Cabin https://mathematica.stackexchange.com/users/387 2017-07-16T23:33:48Z 2017-07-21T04:32:56Z <p>I came across puzzling results for certain 3D meshes, which I reduced to a minimal case. I made a <code>1-2-3</code> cuboid in Blender, exported it to <a href="https://filebin.ca/3TcNMJskChjW/one_two_three_cuboid.obj" rel="noreferrer">this OBJ file</a>, then imported it to Mathematica, which generates a plausible result:</p> <pre><code>(rawBlenderCuboid = Import["https://filebin.ca/3TcNMJskChjW/one_two_three_cuboid.obj"]) // InputForm </code></pre> <blockquote> <pre><code>MeshRegion[{{1., -3., -2.}, {1., -3., 2.}, {-1., -3., 2.}, {-1., -3., -2.0000009536743164}, {1., 3., -1.9999990463256836}, {-1., 3., -2.}, {-1., 3., 1.9999990463256836}, {0.9999989867210388, 3., 2.0000009536743164}}, {Polygon[{{1, 3, 4}, {5, 7, 8}, {1, 8, 2}, {2, 7, 3}, {3, 6, 4}, {5, 4, 6}, {3, 1, 2}, {7, 5, 6}, {8, 1, 5}, {7, 2, 8}, {6, 3, 7}, {4, 5, 1}}]}] </code></pre> </blockquote> <p>This has no defects according to <code>FindMeshDefects</code>. It has the expected area of $88=2*(2*4+4*6+6*2)$:</p> <pre><code>Area[rawBlenderCuboid] </code></pre> <blockquote> <ol start="88"> <li></li> </ol> </blockquote> <p>Its volume, however, is zero</p> <pre><code>Volume[rawBlenderCuboid] </code></pre> <blockquote> <p>0</p> </blockquote> <p>it should be $48$, as is found for the bounding region:</p> <pre><code>Volume[BoundingRegion[rawBlenderCuboid]] </code></pre> <blockquote> <p>48.</p> </blockquote> <p>Its moment of inertia is inexplicable</p> <pre><code>MomentOfInertia[rawBlenderCuboid] </code></pre> <blockquote> <pre><code>{{541.333, 7.56979*10^-6, -0.0000177622}, {7.56979*10^-6, 242.667, -0.0000184774}, {-0.0000177622, -0.0000184774, 421.333}} </code></pre> </blockquote> <p>A hand calculation with unit density leads one to expect $(208, 80, 160)$ for the principal components of moment of inertia, which is indeed found for the bounding region:</p> <pre><code>MomentOfInertia[BoundingRegion[rawBlenderCuboid]] </code></pre> <blockquote> <pre><code>{{208., -7.10543*10^-15, -5.32907*10^-15}, {-7.10543*10^-15, 80.0001, 1.15463*10^-14}, {-5.32907*10^-15, 1.15463*10^-14, 160.}} </code></pre> </blockquote> <p>Bounding regions seem always to be cuboids, so they are not acceptable for my real examples, which are not convex. Therefore, the rather nice solutions from <a href="https://mathematica.stackexchange.com/questions/6908/how-to-calculate-volume-of-convex-hull-and-volume-of-a-3d-object">this SE post about convex hulls</a> would not serve.</p> <p>A clue comes from the fact that Mathematica does not find the mesh to be solid: </p> <pre><code>SolidRegionQ[rawBlenderCuboid] </code></pre> <blockquote> <p>False</p> </blockquote> <p>whereas the bounding region is reckoned as solid:</p> <pre><code>SolidRegionQ[BoundingRegion[rawBlenderCuboid]] </code></pre> <blockquote> <p>True</p> </blockquote> <p>Both the bounding region and the raw region are both valid regions according to <code>MeshRegionQ</code>, and they're both embedded in 3 dimensions:</p> <pre><code>RegionEmbeddingDimension[rawBlenderCuboid] </code></pre> <blockquote> <p>3</p> </blockquote> <pre><code>RegionEmbeddingDimension[BoundingRegion[rawBlenderCuboid]] </code></pre> <blockquote> <p>3</p> </blockquote> <p>so it's not easy to see the more profound differences between them.</p> <p><a href="https://mathematica.stackexchange.com/questions/56732/how-do-i-get-a-meshregion-from-an-obj-file-or-from-geometry3d">These examples from Wolfram's curated collections</a> also have zero volume and are not solid.</p> <p>I realize from <a href="https://mathematica.stackexchange.com/questions/6908/how-to-calculate-volume-of-convex-hull-and-volume-of-a-3d-object">this SE post</a> that I can fit tetrahedra and get to a volume that way, or that I could implement integrals inside polyhedra using <a href="http://www.geometrictools.com/Documentation/PolyhedralMassProperties.pdf" rel="noreferrer">a source like this one</a>. Either approach is considerable work, and I wonder whether I am just missing some really simple answer already done in Mathematica. I also think that <a href="https://mathematica.stackexchange.com/questions/85691/how-to-convert-a-surface-into-a-solid">the approaches documented here for parametric and procedurally generated meshes</a> would not be of direct help. This is my first foray into the new mesh functions, so I am a long way from mastery.</p> https://mathematica.stackexchange.com/q/58877 9 How to draw block diagrams as Graph objects? Reb.Cabin https://mathematica.stackexchange.com/users/387 2014-09-04T16:57:44Z 2017-07-03T15:21:22Z <p>In the documentation <a href="http://reference.wolfram.com/language/example/ClosedLoopResponsesWithAPIDController.html">ClosedLoopResponsesWithAPIDController</a>, There is a very nice block diagram. I want to create my own block diagrams similar to this. I clicked on the diagram and pressed "command-shift-E" to show the underlying expression. I found the expression below. While this is explicit and reasonably easy to modify and extend, For really big graphs (which I have) it will rapidly become too difficult to manage by hand. I wonder if there is an easier way to produce such graphics? Is there a tool I just don't know about for drawing and / or automatically laying out such things?</p> <pre><code>Graph[{1, 2, 3, 4, 5, 6, 7, 8, 9}, {{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {6, 2}, {8, 4}, {9, 6}}, Null}, { EdgeLabels -&gt; {DirectedEdge[8, 4] -&gt; Placed[ Style["+", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], {1, {-0.8, 0.2}}], DirectedEdge[3, 4] -&gt; Placed[ Style["+", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], 0.9], DirectedEdge[9, 6] -&gt; Placed[ Style["+", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], {1, {-0.8, 0.2}}], DirectedEdge[5, 6] -&gt; Placed[ Style["+", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], 0.9], DirectedEdge[6, 2] -&gt; Placed[ Style["-", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], {0.965, {-0.7, 0}}], DirectedEdge[1, 2] -&gt; Placed[ Style["+", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], 0.9]}, EdgeShapeFunction -&gt; {}, EdgeStyle -&gt; { GrayLevel[0, 1]}, Epilog -&gt; { Text[ Style["u", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], {2.5, 0.1}]}, ImageSize -&gt; 500, VertexCoordinates -&gt; {{0., 0.}, {0.7, 0.}, {1.8, 0.}, {2.9, 0.}, {3.9, 0.}, {5., 0.}, {5.6, 0.}, { 2.9, 0.66}, {5., 0.66}}, VertexLabels -&gt; {1 -&gt; Placed[ Style["r", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], Center], 6 -&gt; Placed[ Style["", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], Center], 9 -&gt; Placed[ Style["m", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], Center], 2 -&gt; Placed[ Style["", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], Center], 8 -&gt; Placed[ Style["d", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], Center], 7 -&gt; Placed[ Style["y", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], Center], 3 -&gt; Placed[ Style["PID controller", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], Center], 4 -&gt; Placed[ Style["", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], Center], 5 -&gt; Placed[ Style["linear system", {FontFamily -&gt; "Helvetica", GrayLevel[0, 1], 12}], Center]}, VertexShapeFunction -&gt; { 3 -&gt; "Square", 4 -&gt; "Circle", 7 -&gt; "Square", 5 -&gt; "Square", 9 -&gt; "Square", 1 -&gt; "Square", 6 -&gt; "Circle", 8 -&gt; "Square", 2 -&gt; "Circle"}, VertexSize -&gt; {8 -&gt; {0.1, 0.1}, 3 -&gt; {0.6, 0.2}, 2 -&gt; {0.125, 0.125}, 1 -&gt; {0.1, 0.1}, 9 -&gt; {0.1, 0.1}, 4 -&gt; {0.125, 0.125}, 6 -&gt; {0.125, 0.125}, 5 -&gt; {0.6, 0.2}, 7 -&gt; {0.1, 0.1}}, VertexStyle -&gt; {2 -&gt; Directive[GrayLevel, EdgeForm[{GrayLevel, AbsoluteThickness}]], 1 -&gt; Directive[Opacity, EdgeForm[{}]], 8 -&gt; Directive[Opacity, EdgeForm[{}]], 7 -&gt; Directive[Opacity, EdgeForm[{}]], 5 -&gt; Directive[GrayLevel, EdgeForm[{GrayLevel, AbsoluteThickness}]], 6 -&gt; Directive[GrayLevel, EdgeForm[{GrayLevel, AbsoluteThickness}]], 4 -&gt; Directive[GrayLevel, EdgeForm[{GrayLevel, AbsoluteThickness}]], 9 -&gt; Directive[Opacity, EdgeForm[{}]], 3 -&gt; Directive[GrayLevel, EdgeForm[{GrayLevel, AbsoluteThickness}]] }}] </code></pre> https://mathematica.stackexchange.com/q/55982 16 Backslash commands in strings? Reb.Cabin https://mathematica.stackexchange.com/users/387 2014-07-27T14:34:58Z 2017-02-01T12:28:53Z <p>I discovered by playing around that </p> <pre><code>Text[DisplayForm@SubscriptBox["λ", "k"]] </code></pre> <p>produces the same result as</p> <pre><code>Text["\*SubscriptBox[\"λ\", \"k\"]"] </code></pre> <p>and, further, that the <code>\*</code> is essential. This finding suggests that <code>\*</code> means <code>DisplayForm</code> when inside a string. After more playing around, I found that </p> <pre><code>Text["\!$$\*SubscriptBox[\"λ\", \"k\"]$$"] </code></pre> <p>produces the same result, but only if you have the bang <em>and</em> the parens, that is, that <code>\!</code> and <code>$$</code>+<code>$$</code> are <em>both</em> necessary; either construct alone will not work. </p> <p>Where can I find the documentation for this magic? I don't know what to search for because I don't know what these kinds of constructs are called.</p> https://mathematica.stackexchange.com/q/130457 3 Elegant zebra striping for Grid? Reb.Cabin https://mathematica.stackexchange.com/users/387 2016-11-05T16:24:11Z 2016-11-05T16:34:53Z <p>Some users like zebra striping in grids (see this <a href="https://ux.stackexchange.com/questions/3562/to-use-or-not-to-use-zebra-stripes-or-alternating-row-colors-for-tables">ux posting in SE</a>, whence I got the image below). </p> <p><a href="https://i.stack.imgur.com/1xs9M.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1xs9M.jpg" alt="Example of zebra-striped grid"></a></p> <p>Of course, it's easy to manually shade and style the cells of a <code>Grid</code> in Mathematica (see <a href="http://reference.wolfram.com/language/ref/Grid.html" rel="nofollow noreferrer">this documentation</a> and the image below), but the provided options are almost too general and a solution that is 'just general enough' for zebra striping didn't come to me immediately.</p> <p>Zebra striping seems like such a common practice that I was rather surprised not to see any examples or mention of it in the documentation, let alone a top-level option for it in Grid. Before diving in, I thought I'd quickly ask the community for an "elegant" solution. Of course, <em>elegant</em> is difficult to define, but you all probably know it when you see it.</p> <p><a href="https://i.stack.imgur.com/sYZxI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sYZxI.png" alt="enter image description here"></a></p> https://mathematica.stackexchange.com/q/126113 1 Evaluation conundrum: functions that call NIntegrate [duplicate] Reb.Cabin https://mathematica.stackexchange.com/users/387 2016-09-11T21:46:59Z 2016-09-11T21:52:14Z <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/18393/what-are-the-most-common-pitfalls-awaiting-new-users" dir="ltr">What are the most common pitfalls awaiting new users?</a> <span class="question-originals-answer-count"> 37 answers </span> </li> </ul> </div> <p>Consider the following function of one variable, <code>k</code>:</p> <pre><code>ClearAll[bar]; bar[k_] := NIntegrate[k t, {t, 0, 3}]; </code></pre> <p>My actual integrand is more complicated than just <code>k t</code>, of course. This one could be integrated analytically, but my real <code>bar</code> cannot (to my knowledge). I'll show it below, but this integrand is a Minimal Viable Example (MVE).</p> <p>All is well should I try to evaluate <code>bar</code> over a few values of <code>k</code>:</p> <pre><code>In:= Table[bar[k], {k, 1, 4, 0.5}] </code></pre> <blockquote> <pre><code>Out= {4.5, 6.75, 9., 11.25, 13.5, 15.75, 18.} </code></pre> </blockquote> <p>But plotting it runs into trouble:</p> <pre><code>Plot[bar[k], {k, 1, 4}] </code></pre> <blockquote> <pre><code>NIntegrate::inumr: The integrand k t has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,3}}. </code></pre> </blockquote> <p>That eventually produces a plot, but what I really need to do, <code>NMinimize</code>, does not work at all:</p> <pre><code>NMinimize[{bar[k], k &gt;= 1, k &lt;= 4, k \[Element] Reals}, k, EvaluationMonitor -&gt; Print[bar[k]]] </code></pre> <blockquote> <pre><code>NIntegrate::inumr: The integrand k t has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,3}}. NIntegrate[k t,{t,0,3}] </code></pre> </blockquote> <p>I'd appreciate any advice.</p> <p>PS: my real integrand is</p> <pre><code>(tt[r, t] - qs2[k t])^2 </code></pre> <p>where</p> <pre><code>tt[r, t] </code></pre> <p>is</p> <pre><code>Piecewise[{{1, t &gt; r}, {(r + t)/(2*r), -r &lt;= t &lt;= r}}, 0] </code></pre> <p>and </p> <pre><code>qs2[k t] </code></pre> <p>is</p> <pre><code>Piecewise[{{0, 0.5 + k*t &lt;= 0}, {E^(-(0.5 + k*t)^(-2)), 0.5 + k*t &gt; 0}}, 0]/ (Piecewise[{{0, 0.5 - k*t &lt;= 0}, {E^(-(0.5 - k*t)^(-2)), 0.5 - k*t &gt; 0}}, 0] + Piecewise[{{0, 0.5 + k*t &lt;= 0}, {E^(-(0.5 + k*t)^(-2)), 0.5 + k*t &gt; 0}}, 0]) </code></pre> <p>My real problem is to find the values of <code>k</code> that minimize the integral of this integrand from <code>t=0</code> to <code>t=3 r</code> as a function of <code>r</code> between <code>r=0.07</code> and <code>r=8</code>. It's a least-squares fit of <code>qs2[k t]</code> (non-linear mollifier) to <code>tt[r, t]</code> (clipped linear function).</p> https://mathematica.stackexchange.com/q/112550 7 Undocumented Backslash-LessThan operator in strings? [duplicate] Reb.Cabin https://mathematica.stackexchange.com/users/387 2016-04-13T20:32:22Z 2016-08-21T07:27:13Z <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/105018/what-are-and-delimiters-in-box-expressions" dir="ltr">What are &ldquo;\&lt;&rdquo; and &ldquo;\&gt;&rdquo; delimiters in box expressions?</a> <span class="question-originals-answer-count"> 3 answers </span> </li> </ul> </div> <p>I'm aware of the backslash operators in strings, as in <a href="https://mathematica.stackexchange.com/questions/55982/backslash-commands-in-strings">this SE answer</a>, but I ran across a new one. I opened a new <code>Styled Notebook ...</code> in the front-end GUI, chose <code>Standard Report</code>, saved the notebook, then opened it in Emacs. I saw the following cell:</p> <pre><code>Cell["\&lt;\ Enter text here. Enter TraditionalForm input for evaluation in a separate \ cell below:\ \&gt;", "Text"], </code></pre> <p>and didn't recognize the <code>\&lt;</code> and <code>\&gt;</code> operators. I experimented with them in another notebook, but couldn't see any difference:</p> <p><a href="https://i.stack.imgur.com/0RIur.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0RIur.png" alt="enter image description here"></a></p> <p>Anyone happen to know what they're for? Why they're there? What they're supposed or not supposed to do? Use cases for my own (automatically created) notebooks?</p> https://mathematica.stackexchange.com/questions/77659/-/121871#121871 1 Answer by Reb.Cabin for Does Mathematica support an unordered set (e.g. hashset) data structure? Reb.Cabin https://mathematica.stackexchange.com/users/387 2016-07-31T16:03:42Z 2016-07-31T16:17:00Z <p><code>DeleteDuplicates</code> is another way to build sets, or, more precisely, ordered lists with no duplicates (a friend of mine calls such things "suits," I think a brilliant name). Note the last little minitest here fails:</p> <pre><code>{DeleteDuplicates[{}], DeleteDuplicates[{1}] == DeleteDuplicates[{1, 1}], DeleteDuplicates[{2, 1, 3, 1, 2, 3, 3, 2, 2, 1}] == DeleteDuplicates[{1, 2, 3}]} </code></pre> <blockquote> <pre><code>{{}, True, False} </code></pre> </blockquote> <p>Easy to fix by composing with <code>Sort</code>:</p> <pre><code>ClearAll[set]; set = Sort@*DeleteDuplicates; {set[{}], set[{1}] == set[{1, 1}], set[{2, 1, 3, 1, 2, 3, 3, 2, 2, 1}] == set[{1, 2, 3}]} </code></pre> <blockquote> <pre><code>{{}, True, True} </code></pre> </blockquote> <p>Here's a specific implementation of the ideas in Leonid's comment:</p> <pre><code>ClearAll[set]; set[l_List] := Sort@Keys@Association@MapThread[Rule, {l, l}]; {set[{}], set[{1}] == set[{1, 1}], set[{2, 1, 3, 1, 2, 3, 3, 2, 2, 1}] == set[{1, 2, 3}]} </code></pre> <blockquote> <pre><code>{{}, True, True} </code></pre> </blockquote> <p>Keep or remove the <code>Sort</code> depending on whether you want a set or a suit. However, the <code>Sort</code> introduces more overhead, getting you away from (close to) O(1) perf, as you requested.</p> <p><strong>EDIT</strong>: The difference between set and suit can be important if you're trying to emulate a combinatorial function like <code>Permutations</code>. This function treats duplicate elements as identical, but it is also 'stable', meaning that it doesn't change the orders of inputs. If you try to emulate it using a set instead of a suit, you can get a scrambled answer. For instance, consider</p> <pre><code>Permutations[{1, 1, 1, 0, 0}] // TeXForm </code></pre> <p>\begin{array}{ccccc} 1 &amp; 1 &amp; 1 &amp; 0 &amp; 0 \\ 1 &amp; 1 &amp; 0 &amp; 1 &amp; 0 \\ 1 &amp; 1 &amp; 0 &amp; 0 &amp; 1 \\ 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0 \\ 1 &amp; 0 &amp; 1 &amp; 0 &amp; 1 \\ 1 &amp; 0 &amp; 0 &amp; 1 &amp; 1 \\ 0 &amp; 1 &amp; 1 &amp; 1 &amp; 0 \\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \\ 0 &amp; 1 &amp; 0 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 1 &amp; 1 &amp; 1 \\ \end{array}</p> <p>Let's make our own <code>permutations</code> that can take a <code>collector</code> function as an input, and try it out with <code>suit</code> to check that we get the same answer, in the same order, as with the built-in <code>Permutations</code>:</p> <pre><code>ClearAll[permutations, set, suit]; set[l_List] := Sort@Keys@Association@MapThread[Rule, {l, l}]; suit[l_List] := Keys@Association@MapThread[Rule, {l, l}]; permutations[collector_, {}] := {{}}; permutations[collector_, xs_List] := collector[ Flatten[ Table[ With[{ x = xs[[i]], plucked = Join[xs[[;; i - 1]], xs[[i + 1 ;;]]]}, Prepend[x] /@ permutations[collector, plucked]], {i, Length[xs]}], 1]]; permutations[suit, {1, 1, 1, 0, 0}] // TeXForm </code></pre> <p>\begin{array}{ccccc} 1 &amp; 1 &amp; 1 &amp; 0 &amp; 0 \\ 1 &amp; 1 &amp; 0 &amp; 1 &amp; 0 \\ 1 &amp; 1 &amp; 0 &amp; 0 &amp; 1 \\ 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0 \\ 1 &amp; 0 &amp; 1 &amp; 0 &amp; 1 \\ 1 &amp; 0 &amp; 0 &amp; 1 &amp; 1 \\ 0 &amp; 1 &amp; 1 &amp; 1 &amp; 0 \\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \\ 0 &amp; 1 &amp; 0 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 1 &amp; 1 &amp; 1 \\ \end{array}</p> <p>Now try it with <code>set</code> as the collector:</p> <pre><code>permutations[set, {1, 1, 1, 0, 0}] // TeXForm </code></pre> <p>\begin{array}{ccccc} 0 &amp; 0 &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 1 &amp; 0 &amp; 1 &amp; 1 \\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 \\ 0 &amp; 1 &amp; 1 &amp; 1 &amp; 0 \\ 1 &amp; 0 &amp; 0 &amp; 1 &amp; 1 \\ 1 &amp; 0 &amp; 1 &amp; 0 &amp; 1 \\ 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0 \\ 1 &amp; 1 &amp; 0 &amp; 0 &amp; 1 \\ 1 &amp; 1 &amp; 0 &amp; 1 &amp; 0 \\ 1 &amp; 1 &amp; 1 &amp; 0 &amp; 0 \\ \end{array}</p> https://mathematica.stackexchange.com/q/3736 24 Annoying display truncation of numerical results Reb.Cabin https://mathematica.stackexchange.com/users/387 2012-03-30T23:00:14Z 2016-06-26T16:09:02Z <p>I have a lot of data to inspect. An example of a number in my program is </p> <pre><code>123.189094 </code></pre> <p>This gets displayed as</p> <pre><code>123.189 </code></pre> <p>Unfortunately, most of my information is in the small digits, so, when visually inspecting this data, <code>123.189094</code> and <code>123.189263</code> are not distinguishable, in other words, a list like</p> <pre><code>{123.189094, 123.189263} </code></pre> <p>is displayed like</p> <pre><code>{123.189, 123.189} </code></pre> <p>and it looks like I have equal data when I don't. The only fix I have found for this is <code>FullForm</code>, but that explodes out all the structure (lists, rules, etc.) and makes the display very annoying. Imagine that my data were actually buried deep in some nested structure of lists and rules (and it is). </p> <pre><code>{123.189094, 123.189263}//FullForm (* List[123.189094,123.189263] *) </code></pre> <p>is not what I want. I would have thought <code>N[#,10]&amp;</code> or somesuch would work, but it doesn't</p> <pre><code>{123.189094, 123.189263} // N[#, 10] &amp; (* {123.189,123.189} AAACH! *) </code></pre> <p><code>StandardForm</code> doesn't do it, <code>TraditionalForm</code> doesn't do it.</p> <p>I'm stuck. As usual, will be grateful for any advice or ideas.</p> https://mathematica.stackexchange.com/q/112587 4 How to create a fully styled Notebook with a Mathematica expression? Reb.Cabin https://mathematica.stackexchange.com/users/387 2016-04-14T12:39:32Z 2016-05-14T18:23:45Z <p>I want to create a new notebook by evaluating an expression, not from the front-end GUI, and I want to specify all styles for the notebook in the expression, using only stylesheets supplied with the Mathematica installation. The use case is zero-touch installations on fresh machines, no interactions with the style GUI and no installations of user-supplied style sheets in special, magical directories. The new user walks up to the fresh machine, gets a single notebook with a single expression from me, evaluates that expression, and <em>al-a-khazam</em> gets a new notebook with all the styles that I specify.</p> <p><strong>EDIT</strong>: </p> <p>Here is an example use-case scenario (not my actual one, but very very close):</p> <p>My scenario is similar to a classroom: IT department installs stock Mathematica on stock operating systems on stock PCs, and they will not do user-specific installations. The user accounts are network accounts and the user folders don't even exist until the users log on the first time.</p> <p>The stock styles supplied by Mathematica are unacceptable for a variety of reasons. For example, Arial and Helvetica fonts are banned by our staff because their spacing on narrow letters is too condensed; but there are lots of little things like this. I got really tired of setting the styles manually in the GUI and then propagating the style sheets to the students and then teaching them about the canonical, magical, user-specific directory structure and then dealing with their mistakes on installing and using the style sheets.</p> <p>I decided to automate the distribution of notebooks with customized notebook styles. My requirements on the automation scenario are:</p> <ol> <li><p>Users must be able to create new notebooks in a style supplied by me on fresh machines that have the stock operating system and the stock installation of Mathematica, with no user-specific customizations of any kind.</p></li> <li><p>Users must NOT be required to learn and use the style GUI ("Format > Edit Stylesheet...") and must not be required to install and use a stylesheet.</p></li> <li><p>Users receive a single file from me (say from a gist or from a Dropbox folder) with the smallest possible instructions for creating properly styled notebooks. In particular, they can put this file any place they want in their folders; they don't have to put it in a special place. </p></li> </ol> <p>Users complete their assignments by filling out some work in the properly-styled notebooks and returning them to me.</p> https://mathematica.stackexchange.com/questions/112587/-/112588#112588 2 Answer by Reb.Cabin for How to create a fully styled Notebook with a Mathematica expression? Reb.Cabin https://mathematica.stackexchange.com/users/387 2016-04-14T12:39:32Z 2016-04-14T15:49:12Z <p>Here is a Mathematica expression in a meta-notebook, based on the Wolfram-supplied "StandardReport" style, as an example that creates another Notebook with all the styles set up the way I want them. I store this meta-notebook in the same place I store all my other notebooks instead of in a magical directory on my path, so it gets backed up and survives machine wipes. It could be distributed to users in a similar way, say through a gist or a Dropbox folder.</p> <p>To adapt this to your own needs, just edit and evaluate the expression! A good way to figure out how to change the expression is to create and style a notebook in the usual way, through the GUI, open it up with an ordinary text editor like vim or emacs, and find the bits that you want to copy over to your meta-notebook. I've endeavored to include samples of every element that has a style so that the newly created notebooks can be visually checked. Much easier (at least for me) than messing around with a GUI and magical directories.</p> <p>Here is a gist <a href="https://gist.github.com/rebcabin/0b9ddf27e1354cbded215594d6f59056" rel="nofollow">https://gist.github.com/rebcabin/0b9ddf27e1354cbded215594d6f59056</a></p> <p>Here is another gist with a functional refactoring (installs MMA symbols and has multiple expressions, but is a little more flexible; the gist above and the code below is just a single expression and installs only the symbol <code>myNotebook</code> in the MMA context):</p> <p><a href="https://gist.github.com/rebcabin/6ba697716ea2bcbfbe9a3253be4d1a01" rel="nofollow">https://gist.github.com/rebcabin/6ba697716ea2bcbfbe9a3253be4d1a01</a></p> <pre><code>Module[{myNotebook, myCells, myStyles, myDemoIntegral, myDemoSolution, myMathGroup, myItemGroup, myNumberedGroup, myCode, myProgramText, myMeatyContentGroup, mySectionGroup, myDocumentGroup, myFontFunction, myDefaultStyles, myNonDefaultStyles}, myDemoIntegral = RowBox[{ RowBox[{"\[Integral]", RowBox[{"x", RowBox[{"\[DifferentialD]", "x"}]}]}], "+", SqrtBox["z"]}]; myDemoSolution = RowBox[{ FractionBox[SuperscriptBox["x", "2"], "2"], "+", SqrtBox["z"]}]; myMathGroup = CellGroupData[{ Cell[BoxData[myDemoIntegral], "Input"], Cell[BoxData[myDemoSolution], "Output"]}, Open]; myItemGroup = CellGroupData[{ Cell["Item", "Item"], Cell["ItemParagraph", "ItemParagraph"], Cell[CellGroupData[{ Cell["Subitem", "Subitem"], Cell["SubitemParagraph", "SubitemParagraph"], Cell[CellGroupData[{ Cell["Subsubitem", "Subsubitem"], Cell["SubsubitemParagraph", "SubsubitemParagraph"]}, Open]]}, Open]]}, Open]; myNumberedGroup = CellGroupData[{ Cell["ItemNumbered", "ItemNumbered"], Cell["ItemParagraph", "ItemParagraph"], Cell[CellGroupData[{ Cell["SubitemNumbered", "SubitemNumbered"], Cell["SubitemParagraph", "SubitemParagraph"], Cell[CellGroupData[{ Cell["SubsubitemNumbered", "SubsubitemNumbered"], Cell["SubsubitemParagraph", "SubsubitemParagraph"]}, Open]]}, Open]]}, Open]; myCode = RowBox[{RowBox[{"fun", "[", "x_", "]"}], ":=", "1"}]; myProgramText = "\&lt;DLLEXPORT int fun(WolframLibraryData libData, mreal A1, mreal \ *Res) { mreal R0_0; mreal R0_1; R0_0 = A1; R0_1 = R0_0 * R0_0; *Res = R0_1; funStructCompile-&gt;WolframLibraryData_cleanUp(libData, 1); return 0; }\&gt;"; myMeatyContentGroup = CellGroupData[{ Cell["Subsubsection", "Subsubsection"], Cell["Text", "Text"], Cell[myMathGroup], Cell[myItemGroup], Cell[myNumberedGroup], Cell["DisplayFormula", "Text"], Cell[BoxData[FormBox[myDemoIntegral, TraditionalForm]], "DisplayFormula"], Cell[TextData[{ "InlineFormula: ", Cell[BoxData[FormBox[myDemoSolution, TraditionalForm]]], "."}], "Text"], Cell["NumberedDisplay", "Text"], Cell[BoxData[FormBox[myDemoIntegral, TraditionalForm]], "DisplayFormulaNumbered"], Cell["Code", "Text"], Cell[BoxData[myCode], "Code"], Cell["Program", "Text"], Cell[myProgramText, "Program"]}, Open]; mySectionGroup = CellGroupData[{ Cell["Section", "Section"], Cell[CellGroupData[{ Cell["Subsection", "Subsection"], Cell[myMeatyContentGroup]}, Open]]}, Open]; myDocumentGroup = CellGroupData[{ Cell["Title", "Title"], Cell["Subtitle", "Subtitle"], Cell["Subsubtitle", "Subsubtitle"], Cell["Author", "Author"], Cell["Department", "Department"], Cell["Date", "Date"], Cell["Chapter", "Chapter"], Cell["Subchapter", "Subchapter"], Cell[mySectionGroup]}, Open]; myCells = {Cell[myDocumentGroup]}; myFontFunction[siz_, fam_: "Candara", wgt_: "Plain", slt_: "Plain"] := {FontFamily -&gt; fam, FontSize -&gt; siz, FontWeight -&gt; wgt, FontSlant -&gt; slt}; myDefaultStyles = { {"Title", 44}, {"Subtitle", 24}, {"Subsubtitle", 16}, {"Author", 14}, {"Department", 11}, {"Date", 11}, {"Chapter", 34}, {"Subchapter", 28}, {"Section", 28}, {"Subsection", 20}, {"Subsubsection", 19}, {"Text", 14}, {"Item", 15}, {"ItemParagraph", 14}, {"Subitem", 13.5}, {"SubitemParagraph", 13.5}, {"Subsubitem", 13}, {"SubsubitemParagraph", 13}, {"ItemNumbered", 15}, {"SubitemNumbered", 13.5}, {"SubsubitemNumbered", 13}, {"DisplayFormula", 14}, {"DisplayFormulaNumbered", 14}}; myNonDefaultStyles = { {"InlineFormula", 12.6, "Palatino", "Plain"}, {"Code", 12, "Inconsolata", "Bold"}, {"Program", 12, "Courier", "Plain"}, {"Input", 13, "Inconsolata", "Bold"}, {"Output", 13, "Inconsolata", "Plain"}}; myStyles = { Cell[StyleData[ StyleDefinitions -&gt; FrontEnd`FileName[{"Report"}, "StandardReport.nb", CharacterEncoding -&gt; "UTF-8"]]], Sequence @@ MapThread[ Cell[StyleData[#1], myFontFunction[#2]] &amp;, Transpose[myDefaultStyles]], Sequence @@ MapThread[ Cell[StyleData[#1], myFontFunction[#2, #3, #4]] &amp;, Transpose[myNonDefaultStyles]]}; CreateDocument[ myNotebook = Notebook[ myCells, StyleDefinitions -&gt; Notebook[ myStyles, Visible -&gt; False]]]]; </code></pre> https://mathematica.stackexchange.com/q/112536 3 Undocumented "Output" alignment argument to "Column?" Reb.Cabin https://mathematica.stackexchange.com/users/387 2016-04-13T17:36:31Z 2016-04-14T06:55:05Z <p>In this SE question, <a href="https://mathematica.stackexchange.com/questions/17438/inheriting-stylesheets-when-using-createdocument">Inheriting Stylesheets when using CreateDocument</a>, I noticed the literal string argument <code>"Output"</code> to <code>Column</code>. I didn't see any documentation for this argument (see below), and I didn't see any effect of the argument: </p> <p><a href="https://i.stack.imgur.com/lUnz1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lUnz1.png" alt="enter image description here"></a></p> <p>and was curious what it does or doesn't do, or what it's supposed to do.</p> <p><strong>Silent documentation:</strong></p> <p><a href="https://i.stack.imgur.com/lvR87.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lvR87.png" alt="enter image description here"></a></p> https://mathematica.stackexchange.com/q/112543 0 Evaluating input cells in automatically created notebooks? [duplicate] Reb.Cabin https://mathematica.stackexchange.com/users/387 2016-04-13T18:31:04Z 2016-04-13T18:31:04Z <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/14113/how-to-grab-output-from-evaluating-input-cells-in-a-generated-notebook" dir="ltr">How to grab output from evaluating input cells in a generated notebook</a> <span class="question-originals-answer-count"> 1 answer </span> </li> </ul> </div> <p>I've figured out how to insert <code>Input</code> cells and <code>Text</code> cells into an automatically created notebook (and, thanks to <a href="https://mathematica.stackexchange.com/questions/112538/automatically-created-documents-dont-have-safety-dialogs-on-close">this answer</a>, how to set the closing save dialog on). Now I need to find a way to evaluate the cells in the document <em>without</em> manual intervention in the GUI, i.e., without going to the notebook and the GUI menu and selecting <code>Evaluate Notebook</code>. I can see that there might be a security hole with such an option, still, I suspect it's doable, i.e., the front end GUI is calling some API when the user does the normal thing of clicking the <code>Evaluate Notebook</code> menu item, and it's very like Wolfram to expose everything the front end can do in an API / symbol to call.</p> <p><a href="https://i.stack.imgur.com/vl5x9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vl5x9.png" alt="enter image description here"></a></p> https://mathematica.stackexchange.com/q/112538 5 Automatically Created Documents don't have safety dialogs on close? Reb.Cabin https://mathematica.stackexchange.com/users/387 2016-04-13T17:59:13Z 2016-04-13T18:07:31Z <p>If I manually open a new DocumentNotebook in the front end using the GUI, and then I put input in the document, and then try to close the document, I get a safety dialog asking me whether I want to save the document: </p> <p><a href="https://i.stack.imgur.com/C5csd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C5csd.png" alt="enter image description here"></a></p> <p>If I create a new DocumentNotebook using the <code>CreateNotebook</code> symbol, put something into it, however, I can close the notebook and I don't get the safety dialog. I want to force such automatically created notebooks to have a safety dialog. </p> <p>At first blush, it looks like the contents I'm inserting into the created notebook are not inputs (no <code>In:=</code> notation on the left). So perhaps a better question is "How can I automatically insert input into an automatically created notebook?" The key, here, is "automatically;" I want to do this without any manual interaction with the front-end GUI.</p> <p><a href="https://i.stack.imgur.com/V3kY6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V3kY6.png" alt="enter image description here"></a></p> https://mathematica.stackexchange.com/q/55526 20 MatchQ-ing Associations (MMA 10) Reb.Cabin https://mathematica.stackexchange.com/users/387 2014-07-22T04:19:07Z 2016-03-08T04:25:22Z <p>Consider</p> <pre><code>{x-&gt;1} </code></pre> <p>which has <code>FullForm</code> </p> <pre><code>List[Rule[x, 1]] </code></pre> <p>and, therefore, </p> <pre><code>MatchQ[{x-&gt;1}, List[___Rule]] </code></pre> <p>produces <code>True</code>.</p> <p>Now consider</p> <pre><code>&lt;|x-&gt;1|&gt; </code></pre> <p>which has <code>FullForm</code></p> <pre><code>Association[Rule[x, 1]] </code></pre> <p>but</p> <pre><code>MatchQ[&lt;|x-&gt;1|&gt;, Association[___Rule]] </code></pre> <p>produces <code>False</code></p> <p>In fact, </p> <pre><code>MatchQ[&lt;|x-&gt;1|&gt;, Association[___]] </code></pre> <p>produces <code>False</code>. Any ideas? (I'm trying to make some MathLink xxxxxxxx WSTP functions for serializing C structs as Associations, and this lacuna is messing me up).</p> https://mathematica.stackexchange.com/questions/206565/stabilized-inverted-pendulum-blog-post-broken-in-12-0?cid=531288 Comment by Reb.Cabin on Stabilized Inverted Pendulum Blog Post Broken in 12.0? Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-09-21T01:03:25Z 2019-09-21T01:03:25Z The cited demo (...WithFrict) <i>does</i> appear to work in V12. I will try to add some bumping to it and thereby repro Moylan&#39;s blog by this alternative approach! It also occurred to me to play around with options in <code>NDSolve</code> in the original blog. It&#39;s possible some of the defaults changed and that the breakage isn&#39;t as catastrophic as it seems at first glance. https://mathematica.stackexchange.com/questions/206565/stabilized-inverted-pendulum-blog-post-broken-in-12-0?cid=531287 Comment by Reb.Cabin on Stabilized Inverted Pendulum Blog Post Broken in 12.0? Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-09-21T00:58:23Z 2019-09-21T00:58:23Z I have contacted Moylan in the past, not about this, but to see whether he ever completed the 3D version of the same demo. He said he hadn&#39;t and also (cordially) that he wasn&#39;t able to spare the time to work on this topic since he left Wolfram Research. https://mathematica.stackexchange.com/questions/51491/fitting-points-to-tilted-off-center-ellipse?cid=512578 Comment by Reb.Cabin on Fitting points to tilted, off-center ellipse Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-05-07T03:13:06Z 2019-05-07T03:13:06Z If you can stand a bounding ellipse, the following is very fast and robust: <a href="http://stackoverflow.com/questions/1768197/bounding-ellipse">stackoverflow.com/questions/1768197/bounding-ellipse</a>. https://mathematica.stackexchange.com/questions/51491/fitting-points-to-tilted-off-center-ellipse/51517?cid=512405#51517 Comment by Reb.Cabin on Fitting points to tilted, off-center ellipse Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-05-06T04:33:11Z 2019-05-06T04:33:11Z @george2079 i found a failing case; haven&#39;t been able to debug it :( <code>{{0.17, 0.07}, {0.13, 0.15}, {0.07, 0.23}, {-0.03, 0.31}, {-0.21, 0.37}, {-0.49, 0.36}, {-0.78, 0.16}, {-0.78, -0.16}, {-0.49, -0.36}, {-0.21, -0.37}, {-0.03, -0.31}, {0.07, -0.23}, {0.13, -0.15}, {0.17, -0.07}, {0.18, 0.}}</code> https://mathematica.stackexchange.com/questions/51491/fitting-points-to-tilted-off-center-ellipse/51517?cid=512402#51517 Comment by Reb.Cabin on Fitting points to tilted, off-center ellipse Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-05-06T03:13:05Z 2019-05-06T03:13:05Z @george2079 Actually, Sow and Reap might work best in your case. https://mathematica.stackexchange.com/questions/51491/fitting-points-to-tilted-off-center-ellipse/51517?cid=512401#51517 Comment by Reb.Cabin on Fitting points to tilted, off-center ellipse Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-05-06T03:01:15Z 2019-05-06T03:01:15Z @george2079 generally when you find yourself updating global variables, a Fold is a good way to seek hygiene. https://mathematica.stackexchange.com/questions/51491/fitting-points-to-tilted-off-center-ellipse/155428?cid=512396#155428 Comment by Reb.Cabin on Fitting points to tilted, off-center ellipse Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-05-06T01:54:22Z 2019-05-06T01:54:22Z First thing I&#39;ve ever seen that made me <i>want</i> to learn something about Neural Nets. https://mathematica.stackexchange.com/questions/2245/debugging-mathematica-code?cid=502545 Comment by Reb.Cabin on Debugging Mathematica Code Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-03-11T16:48:39Z 2019-03-11T16:48:39Z I use <code>Sow</code> and <code>Reap</code> frequently to dig data out from the insides of deeply nested expressions. https://mathematica.stackexchange.com/questions/2245/debugging-mathematica-code/23239?cid=502542#23239 Comment by Reb.Cabin on Debugging Mathematica Code Reb.Cabin https://mathematica.stackexchange.com/users/387 2019-03-11T16:31:51Z 2019-03-11T16:31:51Z I&#39;d vote this up for &quot;best hack of 2013&quot; if there were such an award :) https://mathematica.stackexchange.com/questions/188246/directory-of-wolfram-language-reference-tutorials/188249?cid=491445#188249 Comment by Reb.Cabin on Directory of Wolfram Language reference tutorials Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-12-27T23:05:19Z 2018-12-27T23:05:19Z There are 1,001 tutorials (<code>getTutorialURLs[]&#47;&#47;Length</code>) ! https://mathematica.stackexchange.com/questions/112821/dynamica-package-for-mathematica?cid=490873 Comment by Reb.Cabin on Dynamica Package for Mathematica Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-12-21T00:40:28Z 2018-12-21T00:40:28Z The book but not the package is found at wolfram. <a href="http://library.wolfram.com/search/?query=dynamica&amp;collection=library&amp;x=0&amp;y=0" rel="nofollow noreferrer">library.wolfram.com/search/&hellip;</a>. Still haven&#39;t found the package files. https://mathematica.stackexchange.com/questions/112821/dynamica-package-for-mathematica?cid=490872 Comment by Reb.Cabin on Dynamica Package for Mathematica Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-12-21T00:33:19Z 2018-12-21T00:33:19Z 404 as of 20 Dec 2018. Page does not exist. Anyone willing to share a copy with me? https://mathematica.stackexchange.com/questions/134506/inlinepart-what-is-it-and-what-happened-to-it/134841?cid=490667#134841 Comment by Reb.Cabin on InlinePart. What is it and what happened to it? Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-12-19T16:08:58Z 2018-12-19T16:08:58Z In the notebook front end, if you type <code>\[In</code> you get a drop-down list of autocompletion suggestions. <code>\[InlinePart]</code> is in that list (as is <code>\[InvisibleApplication]</code>, one of my favorites. It appears that the documentation and evaluation rules of of <code>\[InlinePart]</code> have been removed, but not all traces of its existence. You will get the appropriate Unicode character and the <code>RowBox</code> result as in the originally posted question, at least in MMA 11.0.3 on Linux. https://mathematica.stackexchange.com/questions/187882/a-little-magic-for-the-euler-lagrange-equations?cid=488994 Comment by Reb.Cabin on A little magic for the Euler-Lagrange equations? Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-12-14T06:12:00Z 2018-12-14T06:12:00Z @MichaelE2 &quot;Oh what a tangled web we weave, when first we practice to deceive.&quot; I got a chuckle out of your revelation! https://mathematica.stackexchange.com/questions/187882/a-little-magic-for-the-euler-lagrange-equations?cid=488993 Comment by Reb.Cabin on A little magic for the Euler-Lagrange equations? Reb.Cabin https://mathematica.stackexchange.com/users/387 2018-12-14T06:06:16Z 2018-12-14T06:06:16Z @Alexandros (sorry no Greek keyboard installed) maybe I just stumbled on legacy. I typed in the most dumbest thing for E-L and it just worked. I know full well it&#39;s a bad pun (see Sussman and Wisdom), but I was pleasantly surprised and went with it to &quot;get stuff done.&quot; But then I started to wonder &quot;this is too easy and shouldn&#39;t work.&quot; Hence the question :)