Community RSS Feed
https://community.wolfram.com
RSS Feed for Wolfram Community showing any discussions in tag sorted by activeCreate custom component with custom formula or transfer function?
https://community.wolfram.com/groups/-/m/t/1687073
How can I create a custom component with custom equation of transfer function? I have an equation for a low pass filter as shown below
L(t)= exp(-t/tau)/tau
ThanksLakshmi Rajagopalan2019-05-20T19:29:03Zregistering wolframscript behind a firewall
https://community.wolfram.com/groups/-/m/t/1688559
How do I set the proxy, so I can register wolframscript behind a fire wall?Steven Craighead2019-05-23T00:39:36ZWhat function provides Recurrence relations?
https://community.wolfram.com/groups/-/m/t/1686424
WolframAlpha finds for some sequences Recurrence relations:
- The input of [2732,2728,1368,680,344,168,88,40,24,8,8,0,4][1] provides
the Recurrence relation a(n+2)=a(n)/2-a(n+1)/2.
- The input of [5460,5464,2728,1368,680,344,168,88,40,24,8,8,0,4][2]
provides the same Recurrence relation a(n+2)=a(n)/2-a(n+1)/2.
The Guide [Recurrence and Sum Functions][3] is obviously intended as a comprehensive list of Recurrence and Sum Functions. But what function provides the result of WolframAlpha?
- FindLinearRecurrence[{2732,2728,1368,680,344,168,88,40,24,8,8,0,4}]
simlpy repeats the input in the output.
- FindSequenceFunction[{2732,2728,1368,680,344,168,88,40,24,8,8,0,4},n]
provides DifferenceRoot[Function[... . It's not a Recurrence
relation.
- FindGeneratingFunction[{2732,2728,1368,680,344,168,88,40,24,8,8,0,4},n]
provides -((4 (1366+2047 n+683 n^2))/(-2-n+n^2)) . It's also not a
Recurrence relation.
Is there no function what provides the Recurrence relation that WolframAlpha does provide or is the Guide [Recurrence and Sum Functions][3] simply incomplete?
Thanks.
[1]: https://www.wolframalpha.com/input/?i=2732,2728,1368,680,344,168,88,40,24,8,8,0,4
[2]: https://www.wolframalpha.com/input/?i=5460,5464,2728,1368,680,344,168,88,40,24,8,8,0,4
[3]: https://reference.wolfram.com/language/guide/RecurrenceAndSumFunctions.html
[4]: https://reference.wolfram.com/language/guide/RecurrenceAndSumFunctions.htmUwe Galle2019-05-19T19:59:44ZPerspective Anamorphosis in a Square Trihedral Corner
https://community.wolfram.com/groups/-/m/t/1687864
Perspective anamorphosis is when you need a specific viewpoint to observe an image correctly and any other viewpoint will give a deformed image.
Inspired by [Ewan Gedge's Inspiration on Pinterest][1], (left) I made a project of creating 3D perspective anamorphosis images using Mathematica. Here is "Lena from ExampleData " in a "square trihedral corner" (right).
![introduction pics][2]
To create a similar perspective anamorphism for viewing purposes only is quite simple in Mathematica using PlotStyle with Texture and a TextureCoordinateFunction. Some time ago, I uploaded the Wolfram Demonstration [Perspective Anamorphosis of Photographic Images][3] which can be used to make GIFs like these when adapted to a [trihedron][4]:
![lena trihedral][5]![enter image description here][6]
However, these GIFs make nice images but are hardly usable to make a real, printable object. What follows is how I made a printable and "make-able" trihedral perspective anamorphism.
We want to look from infinity toward the 3 faces of a trihedron in the direction of its main diagonal and see an image undeformed.
We first create a **vertically upright trihedron**. Then, find the necessary rotation angles \[Alpha] and \[Beta] around the x- and y-axes, and the derived rotation matrix to set the diagonal vector (1,1,1) of a unit cube vertically upright at (0,0,Sqrt(3))
Solve[RotationMatrix[\[Alpha], {1, 0, 0}].RotationMatrix[\[Beta], {0, 1, 0}].{1, 1, 1} == {0, 0, Sqrt[3]}, {\[Alpha], \[Beta]}] /.
C[1] -> 0 /. C[2] -> 0;
rMat = Simplify[
Last[RotationMatrix[\[Alpha], {1, 0,
0}].RotationMatrix[\[Beta], {0, 1, 0}] /. %]];
(PolygonCoordinates[#1] + 1/2 &) /@ PolyhedronData["Cube", "Polygons"];
triHedron =
Map[rMat.#1 &,
Polygon /@ %[[Position[%, {0, 0, 0}][[All, 1]]]], {3}];
We first will make a setup similar to the rectangle in a corner of Ewan Gredge [above][7]. To simulate our viewing of the rectangle, we intersect the trihedron with a cuboid that has the desired rectangle as a base:
is = RegionIntersection[Cuboid[{-4, -5, 0}, {4, 4, 100}], #] & /@
triHedron;
Graphics3D[{FaceForm[], EdgeForm[Thick], is},
PlotRange -> .65 {{-10, 10}, {-10, 10}, {0, 16}}, Boxed -> False]
![trihedron][8]
To proceed, we need a 2D drawing of the three faces by selecting view directions perpendicular to the faces of the trihedron:
(*3 viewvectors*)
Take[SortBy[DeleteDuplicates[Flatten[PolygonCoordinates /@ is, 1]],
EuclideanDistance[{0, 0, 0}, #] &], {2, 4}];
GraphicsRow@
MapThread[
Graphics3D[{FaceForm[], EdgeForm[AbsoluteThickness[4]], is[[#1]]},
Boxed -> False, ViewPoint -> %[[#2]]] &, {Range[3], {2, 1, 3}}]
![3 faces printout][9]
This is a makeshift setup of this using masking tape in a rectangular trihedral corner (of the kitchen):
![taped trihedron][10]
To get into more complex projects, we need a function that will map a point P in the x-y plane to the intersection Q of the vertical through P with the trihedron and then rotated around axis r, s or t back to the x-y plane as R.
![geometry][11]
From P to Q: computing the z-values of Q for each trihedral face:
Flatten[Solve[{{x, y, z} \[Element]
Line[{{x, y, 0}, {x, y, z}}], {x, y, z} \[Element]
RegionUnion @@ triHedron}, z] /.
Rule[z, ConditionalExpression[value_, region_]] :> value] //
FullSimplify;
(*{-Sqrt[2] y,(-Sqrt[3] x+y)/Sqrt[2],(Sqrt[3] x+y)/Sqrt[2]}*)
From Q to R: rotation around the appropriate axis in the x-y plane:
sector[pt : {x_, y_}] := Module[{\[Alpha]}, \[Alpha] = ArcTan @@ pt;
Which[-\[Pi]/6 <= \[Alpha] < \[Pi]/2,
1, -5 \[Pi]/6 <= \[Alpha] < -\[Pi]/6, 3, True, 2]]
trihedronPerspectiveMap[pt : {x_, y_}, \[Phi]_: - ArcSec[Sqrt[3]]] :=
Module[{z},
z = Switch[sector@pt, 1, (Sqrt[3] x + y)/Sqrt[2],
2, (-Sqrt[3] x + y)/Sqrt[2], 3, -Sqrt[2] y, True, 0];
Chop@Switch[sector@pt, 3,
RotationMatrix[\[Phi], {-1, 0, 0.}].{x, y, z}, 2,
RotationMatrix[\[Phi], {1, Sqrt[3], 0.}].{x, y, z}, 1,
RotationMatrix[\[Phi], {1, -Sqrt[3], 0.}].{x, y, z}, _, {0, 0}]]
We can try out the function *trihedronPerspectiveMap* on a GraphicsComplex from one of the many "Popular Curves":
The parametric curve of Bugs Bunny is obtained using Interpreter. We extract the coordinates and apply the function *trihedronPerspectiveMap* to them. This is used to create a printable set of the 3 faces. When glued together, they make up a trihedral image.
![flow bunnies][12]
Interpreter[
Restricted["PopularCurve",
EntityClass["PopularCurve", "LooneyTunes"]]]["bugs bunny curve"]
bugsbunnyPrimitives =
First[ParametricPlot[%["ParametricEquations"][t], {t, 0,
40 \[Pi]}]] /. {x_?NumericQ, y_?NumericQ} :> {x + 189, y + 150}/
650;
allPts = Cases[
bugsbunnyPrimitives /. Line -> Identity, {x_?NumericQ,
y_?NumericQ}, \[Infinity]];
Animate[Module[{tbl, pt}, pt = AngleVector[{0, -.1}, {.2, \[Phi]}];
tbl = (pt + #1 &) /@ (+allPts);
Grid[{{"original", "2D printout view",
"3D perspectiveview"}, {Graphics[{Blue, AbsolutePointSize[1.],
Point /@ tbl}, Axes -> True, Ticks -> None, PlotRange -> .75],
Graphics[{{Blue, AbsolutePointSize[1.],
Point[ParallelMap[Most[trihedronPerspectiveMap[#1]] &,
tbl, {1}]]}, {FaceForm[{White, Opacity[.85]}],
EdgeForm[
Thin], (Triangle[{{0, 0}, AngleVector[{10, #1 - \[Pi]/12}],
AngleVector[{10, #1 + \[Pi]/12}]}] &) /@ {-(\[Pi]/
6), \[Pi]/2, (7 \[Pi])/6}}}, PlotRange -> 1.185],
Graphics3D[{triHedron, {Blue, AbsolutePointSize[2],
Point[ParallelMap[trihedronPerspectiveMap[#1, 0.] &,
tbl, {1}]]}}, PlotRange -> .7 {{-1, 1}, {-1, 1}, {0, 2}},
ViewAngle -> 0.175, ViewCenter -> {0.65, 0.5`, 1},
ViewPoint -> {1.434, 0.34, 5.94},
ViewVertical -> {.2, 0.24, 0.95}, Boxed -> False,
Lighting -> {{"Ambient", White}}]}}]], {\[Phi], 0, 2 \[Pi]}]
![bunny open-close][13]
![bunny 3D][14]
Finally, we want to test our function on a photographic image. Mapping the function pixel by pixel would be a solution. However, it is easier to create 3 perspective transformation functions and apply them to the complete image.
This is "Lena" with the projection of the triHedron on top, dividing the image in 3 sectors.
ImageCrop[
ImageAdjust@
ColorConvert[
ImageResize[ExampleData[{"TestImage", "Lena"}], {300}],
"Grayscale"], {200, 242}];
data = ImageData[%]; img =
Image[Show[{ListDensityPlot[Reverse@data,
DataRange -> {{-.7, .7}, {-.85, .85}},
ColorFunction -> GrayLevel, AspectRatio -> Automatic],
Graphics[{FaceForm[], EdgeForm[Black],
triHedron /. {x_?NumericQ, y_?NumericQ, z_} :> {x, y}}]},
FrameStyle -> Thick, FrameTicks -> None], ImageResolution -> 200,
ImageSize -> 200]
![enter image description here][15]
We take 3 reference (base) points in each of the 3 sectors and compute their perspective map with the function *trihedronPerspectiveMap*. We then find the necessary transformation function that converts the base points into the perspective points and apply the 3 transformation functions to our image.
basePoints =
Table[Map[RotationMatrix[\[Alpha]].# &,
CirclePoints[{.05, -.35}, .2, 3]], {\[Alpha], {0, 2 \[Pi]/3,
4 \[Pi]/3}}];
perspectivePoints =
Table[Map[Most@trihedronPerspectiveMap[#] &, p], {p, basePoints}];
transfoFunctions =
MapThread[
Chop@Last@FindGeometricTransform[#1, #2] &, {perspectivePoints,
basePoints}];
ImagePerspectiveTransformation[ima, #, 300, DataRange -> Full,
PlotRange -> All, Resampling -> "Nearest"] & /@ {tf1, tf2, tf3}
![enter image description here][16]
After cropping out the necessary parts and rotating:
![enter image description here][17]
After assembling into a trihedron, the result looks like this:
![enter image description here][18]
This is the same method used with another image, showing the 3 trihedron faces in 2D and the assembled trihedron.
![enter image description here][19] ![enter image description here][20]
[1]: https://www.pinterest.com/pin/366691594652008593/
[2]: https://community.wolfram.com//c/portal/getImageAttachment?filename=combiintro.png&userId=68637
[3]: http://demonstrations.wolfram.com/PerspectiveAnamorphosisOfPhotographicImages/
[4]: http://mathworld.wolfram.com/Trihedron.html
[5]: https://community.wolfram.com//c/portal/getImageAttachment?filename=lenatrihedral-1.gif&userId=68637
[6]: https://community.wolfram.com//c/portal/getImageAttachment?filename=chessboard-2.gif&userId=68637
[7]: https://www.pinterest.com/pin/366691594652008593/
[8]: https://community.wolfram.com//c/portal/getImageAttachment?filename=4292trihedronframe.png&userId=68637
[9]: https://community.wolfram.com//c/portal/getImageAttachment?filename=91253facesprintout.png&userId=68637
[10]: https://community.wolfram.com//c/portal/getImageAttachment?filename=tapedtrihedron.jpg&userId=68637
[11]: https://community.wolfram.com//c/portal/getImageAttachment?filename=1357geometryfun.png&userId=68637
[12]: https://community.wolfram.com//c/portal/getImageAttachment?filename=3bunniesflow.png&userId=68637
[13]: https://community.wolfram.com//c/portal/getImageAttachment?filename=5329ezgif.com-optimize.gif&userId=68637
[14]: https://community.wolfram.com//c/portal/getImageAttachment?filename=9271ScreenShottwinbunnies.png&userId=68637
[15]: https://community.wolfram.com//c/portal/getImageAttachment?filename=7603lenaraw.png&userId=68637
[16]: https://community.wolfram.com//c/portal/getImageAttachment?filename=3lenassmall.png&userId=68637
[17]: https://community.wolfram.com//c/portal/getImageAttachment?filename=3lenaslarge.png&userId=68637
[18]: https://community.wolfram.com//c/portal/getImageAttachment?filename=3lenas3D.png&userId=68637
[19]: https://community.wolfram.com//c/portal/getImageAttachment?filename=sandy2D.jpg&userId=68637
[20]: https://community.wolfram.com//c/portal/getImageAttachment?filename=sandy3D-5.jpg&userId=68637Erik Mahieu2019-05-21T14:52:15Z[GIF] Pathways (Some random paths on the sphere)
https://community.wolfram.com/groups/-/m/t/1686259
![Some random paths on the sphere][1]
**Pathways**
This was inspired by some [very cool pieces by Caleb Ogg][2].
The basic setup is that I choose 20 random points on the sphere...
spherepoints = Normalize /@ RandomVariate[NormalDistribution[], {20, 3}];
...and 2 random rotation axes...
n = Normalize /@ RandomVariate[NormalDistribution[], {2, 3}];
...and then rotate around both axes at different rates. Here's the code:
With[{cols = RGBColor /@ {"#fd5f00", "#76b39d", "#05004e"}},
Manipulate[
Graphics3D[
{Thickness[.006],
Line[#,
VertexColors ->
Table[Directive[Blend[cols[[;; 2]], t/33], Opacity[1 - t/50]], {t, 0, 50}]]
& /@ Transpose[
Table[
spherepoints.RotationMatrix[2 θ, n[[1]]].RotationMatrix[3 θ, n[[2]]],
{θ, -s, π/2 - s, π/100}]]},
Background -> cols[[-1]], ImageSize -> 540, Boxed -> False,
SphericalRegion -> True, PlotRange -> 1.1, ViewAngle -> π/10],
{s, 0, 2 π}]
]
If you want to use the exact points and axes used to produce the animation, here they are:
n = {{0.3728141055805563, 0.6721175529008367, 0.6397402893071225},
{-0.10208165334304724, -0.6120577359476601, -0.7841968272808646}};
spherepoints = {{-0.10799106985352425, -0.4160584039226773,
0.9029027264092216}, {0.15157900537807614, -0.5578647580382791,
0.8159722525107612}, {-0.3907113954330362, -0.5122140334828592,
0.764840760800567}, {0.9730729495569006, -0.21261435696902062,
0.089017807495373}, {0.05688278789414075, -0.9809950827315541,
0.18550740173346517}, {-0.4021137935203268, -0.3483613122969294,
0.8467283467296068}, {-0.6190979467900267, 0.6365973432675175,
0.45984949149163135}, {0.9284570780710303, -0.30562860674878534,
0.2110891018423282}, {-0.02111841597881698, -0.6807852829904154,
-0.7321785376328684}, {0.19282461280624952, -0.6222904436398903,
-0.7586654548947043}, {-0.47354875944631875, -0.8700494995707841,
0.13698700932380656}, {-0.49852600855636126, 0.8644855768934002,
0.06431567566424101}, {-0.3016842794402542, 0.23403999944393247,
-0.9242358325659629}, {0.5083619289119673, 0.06303537237490779,
-0.8588333313643925}, {0.16849837994835584, 0.19647359703572312,
0.9659225753768382}, {0.7430004401900321, 0.6651325623033352,
-0.07449174747056579}, {0.16245182018285645, 0.8928343037536511,
-0.4200670329364233}, {0.290783587893684, 0.39701839696616603,
0.870529320288577}, {-0.4909586596128248, -0.8633143801147486,
-0.1168241226727844}, {0.21102565308351864, 0.4447293257316856,
0.8704504584265061}};
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=path5srq.gif&userId=610054
[2]: https://www.instagram.com/p/BxXPRSmnc5S/Clayton Shonkwiler2019-05-19T21:18:57ZStraightness via Image Processing
https://community.wolfram.com/groups/-/m/t/1688698
I have a continuously moving piece of product that I am trying to measure the straightness of via (computer) visual observation. The set up I have includes a camera pointed at the material which is moving past a marked background. The camera is connected to a computer, on which I would like to run Wolfram code that will analyze the material (edge detection?) and determine the overall straightness of the material (based on differences of the edge against the marked background).
I feel this will be easiest to accomplish with Wolfram, I just am new to the code / syntax. Any suggestions to get me going will be appreciated.
Thanks in advance.Paul Huter2019-05-22T21:40:49ZHelping Mathematica to recognize the norm of a vector (Assumptions?)
https://community.wolfram.com/groups/-/m/t/1688648
Hi,
in my recent calculations for theoretical physics homework I have to do some bigger matrix multiplikations. It would be nice if Mathematice could recognise for example `Sqrt[b1^2+b2^2+b3^2]` as the norm of my vector `B` or some other name I gave it an advance.
I tried working with Assumptions and (Full-)Simplify but it didn't help in any way.
Thank you for some help!
NicolaiNicolai Anger2019-05-22T18:36:33ZFind Fit a function
https://community.wolfram.com/groups/-/m/t/1686848
Hello, I'm trying to use Mathematica to fit a function, but have an error, can someone tell me what the problem is?
I first define the data table that will be fitted.
xmdatapar =
ReadList["/home/roberto/Fśica/Pesquisa/<X^m>/kaon/lib/pares/xm_\
pares.dat", {Number}];
xmpardata = Table[{xmdatapar[[i, 1]]}, {i, 1, Length[xmdatapar]}]
{{0.243098}, {0.127303}, {0.0834994}, {0.0609518}, {0.0473757}, \
{0.0384113}, {0.0320716}, {0.027407}, {0.0237647}, {0.020894}, \
{0.0185901}, {0.0167308}, {0.0151393}, {0.013839}, {0.0127182}, \
{0.0117066}, {0.0108577}, {0.0101237}, {0.00948312}, {0.00887854}, \
{0.00834716}, {0.00788257}, {0.00746653}, {0.00705183}, {0.00669624}}
in the second place the function with the variables that I want to fit.
\[Phi]par[x_] :=
Npar*(x (1 - x))^
aRL\[Alpha]par (1 + \[Alpha]2RLpar*
GegenbauerC[2, \[Alpha]RLpar, (2 x - 1)]);
and finally I make the fit
fitpar = FindFit[
xmpardata, \[Phi]par, {Npar, aRL\[Alpha]par, \[Alpha]2RLpar}, x]
FindFit::fitc: Number of coordinates (0) is not equal to the number of variables (1).
FindFit[{{0.243098}, {0.127303}, {0.0834994}, {0.0609518}, \
{0.0473757}, {0.0384113}, {0.0320716}, {0.027407}, {0.0237647}, \
{0.020894}, {0.0185901}, {0.0167308}, {0.0151393}, {0.013839}, \
{0.0127182}, {0.0117066}, {0.0108577}, {0.0101237}, {0.00948312}, \
{0.00887854}, {0.00834716}, {0.00788257}, {0.00746653}, {0.00705183}, \
{0.00669624}}, \[Phi]par, {Npar, aRL\[Alpha]par, \[Alpha]2RLpar}, x]
Thanks.roberto correa da silveira2019-05-20T10:52:02ZFind left side of definitions?
https://community.wolfram.com/groups/-/m/t/1687954
How do I find the left side of the sets as the following example?
o = {3, 2};
g = {9};
z = {5, 7};
f = {8, 11};
I'd like the result to be:
![enter image description here][1]
I would like a code to do this even if I change or add more definitions to the sets list freely, for example adding two more sets or renaming some.
My attempt to accomplish this (although believe that must have a much easier way):
ClearAll["Global`*"]
o = {3, 2};
g = {9};
z = {5, 7};
f = {8, 11};
FromLetterNumber[
Select[Flatten[
Table[If[
Length[Flatten[
Take[Position[
Table[If[
FromDigits[
Flatten[
Take[Alphabet[] // ToExpression, {ii}]]] \[Element]
Reals, 1], {ii, 1, 26}], 1], {ii}]]] < 2,
Take[Position[
Table[If[
FromDigits[
Flatten[
Take[Alphabet[] // ToExpression, {ii}]]] \[Element] Reals,
1], {ii, 1, 26}], 1], {ii}]], {ii, 1, 26}]], NumberQ]]
![enter image description here][2]
My achievement was partial, because the answer is not organized correctly in a way that I want (instead, it was in alphabetic sort). Is there any way to do that with a smarter code? Would someone please know how to help me?
Thanks.
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=6683ima1.png&userId=1316061
[2]: https://community.wolfram.com//c/portal/getImageAttachment?filename=9796ima2.png&userId=1316061Claudio Chaib2019-05-21T16:24:35ZAchieve a proper display of WSM-Diagrams in Mathematica?
https://community.wolfram.com/groups/-/m/t/1686643
Hi everyone,
I just noted that the icons for some components I have created are not properly visualized when having them displayed in Mathematica using `SytemModel["model"]["Diagram"]`. Here is a very short minimal example for the behavior:
model DemoIconDisplay
partial model UnidirectionalFlow "Icon for unidirectional flow classes"
annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, lineColor = {0, 128, 0}, fillColor = {255, 255, 255}, fillPattern = FillPattern.Solid, lineThickness = 5, extent = {{-100, -100}, {100, 100}}), Rectangle(visible = true, lineColor = {0, 128, 0}, fillColor = {255, 255, 255}, fillPattern = FillPattern.Solid, lineThickness = 5, extent = {{-100, -100}, {100, 100}}), Line(visible = true, origin = {-2.596, -11.973}, points = {{-72.3, 0}, {72.3, 0}}, color = {0, 128, 0}, thickness = 5), Line(visible = true, origin = {-1.216, 11.777}, points = {{-73.637, 0}, {73.637, 0}}, color = {0, 128, 0}, thickness = 5), Polygon(visible = true, origin = {72.114, -0.25}, rotation = -450, lineColor = {0, 128, 0}, fillColor = {0, 128, 0}, fillPattern = FillPattern.Solid, points = {{-22.295, -7.943}, {22.191, -7.943}, {0.104, 15.886}}), Text(visible = true, origin = {-73.452, 37.479}, textColor = {0, 128, 0}, extent = {{-13.452, -20}, {13.452, 20}}, textString = "A"), Text(visible = true, origin = {73.452, -43.134}, textColor = {0, 128, 0}, extent = {{-13.452, -20}, {13.452, 20}}, textString = "B"), Ellipse(visible = true, origin = {1.899, 0}, lineColor = {0, 128, 0}, fillColor = {0, 128, 0}, fillPattern = FillPattern.Solid, lineThickness = 5, extent = {{-15.107, -15.107}, {15.107, 15.107}}), Text(visible = true, origin = {2.487, 1}, textColor = {255, 255, 255}, extent = {{-16.513, -12.307}, {16.513, 12.307}}, textString = "X", textStyle = {TextStyle.Bold})}), Diagram(coordinateSystem(extent = {{-148.5, -105}, {148.5, 105}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})));
end UnidirectionalFlow;
partial model Interaction "Icon for interactional flow classes"
annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, lineColor = {0, 128, 0}, fillColor = {255, 255, 255}, fillPattern = FillPattern.Solid, lineThickness = 5, extent = {{-100, -100}, {100, 100}}), Line(visible = true, origin = {-1.596, -11.973}, points = {{-71, 0}, {71, 0}}, color = {0, 128, 0}, thickness = 5), Line(visible = true, origin = {-0.216, 11.777}, points = {{-73, 0}, {73, 0}}, color = {0, 128, 0}, thickness = 5), Polygon(visible = true, origin = {72.114, -0.25}, rotation = -450, lineColor = {0, 128, 0}, fillColor = {0, 128, 0}, fillPattern = FillPattern.Solid, points = {{-22.295, -7.943}, {22.191, -7.943}, {0.104, 15.886}}), Text(visible = true, origin = {-73.452, 37.479}, textColor = {0, 128, 0}, extent = {{-13.452, -20}, {13.452, 20}}, textString = "A"), Text(visible = true, origin = {73.452, -43.134}, textColor = {0, 128, 0}, extent = {{-13.452, -20}, {13.452, 20}}, textString = "B"), Polygon(visible = true, origin = {-72.424, 0}, rotation = 450, lineColor = {0, 128, 0}, fillColor = {0, 128, 0}, fillPattern = FillPattern.Solid, points = {{22.295, -7.943}, {-22.191, -7.943}, {-0.104, 15.886}}), Rectangle(visible = true, origin = {40.723, 0.173}, lineColor = {0, 128, 0}, fillColor = {0, 128, 0}, fillPattern = FillPattern.Solid, extent = {{-26.573, -12.251}, {26.573, 12.251}}), Ellipse(visible = true, origin = {1.899, 0}, lineColor = {255, 255, 255}, fillColor = {0, 128, 0}, fillPattern = FillPattern.Solid, lineThickness = 5, extent = {{-15.107, -15.107}, {15.107, 15.107}}), Text(visible = true, origin = {2.487, 0}, textColor = {255, 255, 255}, extent = {{-16.513, -12.307}, {16.513, 12.307}}, textString = "X", textStyle = {TextStyle.Bold}), Text(visible = true, origin = {74.452, -0.51}, textColor = {255, 255, 255}, extent = {{-13.452, -20}, {13.452, 20}}, textString = "+", fontSize = 72), Text(visible = true, origin = {-74.548, -0.51}, textColor = {255, 255, 255}, extent = {{-13.452, -20}, {13.452, 20}}, textString = "+", fontSize = 72)}), Diagram(coordinateSystem(extent = {{-148.5, -105}, {148.5, 105}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})));
end Interaction;
replaceable Interaction interaction1 annotation(Placement(visible = true, transformation(origin = {-30, 10}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
replaceable UnidirectionalFlow unidirectionalFlow1 annotation(Placement(visible = true, transformation(origin = {10, 10}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
annotation(Diagram(coordinateSystem(extent = {{-150, -90}, {150, 90}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})), Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, lineColor = {0, 114, 195}, fillColor = {255, 255, 255}, extent = {{-100, -100}, {100, 100}}, radius = 25), Text(visible = true, textColor = {64, 64, 64}, extent = {{-150, 110}, {150, 150}}, textString = "%name")}));
end DemoIconDisplay;
Now in a Mathematica notebook I can read in the model or enter it as a string (escaping the quotes and backlashes to appear verbatim) `model = ImportString[ " <paste code here> ", "mo" ]`.
model = SystemModel["DemoIconDisplay"] (* or model = ImportString[ " <paste code here> ", "mo" ] *)
![ModelRepresentation][1]
The model representation already does not look too good being very coarsely rendered. Let's look at the individual components' icons:
Through[ model["Children"]["ModelicaIcon"] ]
![IconView][2]
That is exactly how the components' icons look in System Model and in System Modeler Diagrams (using Version 12.0). All is nice and crisp.
But now, let's have a look at a model diagram, where the partial models have been instantiated. Again, in Mathematica, we do:
model["Diagram"]
![DiagramView][3]
The display is "broken" and looks rather ugly. Unfortunately, there are even worse examples.
What can be done about this?
Regards,
Guido
EDIT:
While the above is a minimal example, I feel like giving more explicit examples to demonstrate, that the display of diagrams (i.e. `SystemModel["model"]["Diagram"]` ) in its present form is rather completely useless:
Example1 (WSM Model Center):
![Example1_Original][4]
Example1 (Mathematica):
![Example1][5]
Example2 (WSM Model Center):
![Example2_Original][6]
Example2 (Mathematica):
![Example2][7]
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=model.PNG&userId=566944
[2]: https://community.wolfram.com//c/portal/getImageAttachment?filename=IconView.PNG&userId=566944
[3]: https://community.wolfram.com//c/portal/getImageAttachment?filename=DiagramView.PNG&userId=566944
[4]: https://community.wolfram.com//c/portal/getImageAttachment?filename=Example1_Original.PNG&userId=566944
[5]: https://community.wolfram.com//c/portal/getImageAttachment?filename=Example1.png&userId=566944
[6]: https://community.wolfram.com//c/portal/getImageAttachment?filename=Example2_Original.PNG&userId=566944
[7]: https://community.wolfram.com//c/portal/getImageAttachment?filename=Example2.png&userId=566944Guido Wolf Reichert2019-05-20T09:53:03ZMultivariable derivative rule
https://community.wolfram.com/groups/-/m/t/1685571
When we consider multivariable derivatives related to same variable with different values, there can be a simplification of the manner to calculate a derivative that gives rise to the possibility to calculate by other means the la grangian point at which the total volume mass time expression between two celestial bodies equals , a point at which the distance gives rise to a certain value that express the limit of the derivative to zero and that is equivalent to a distance between the bodies where the value of gravity time multiple is equal meaning that the bodie is pulled in equal terms of proportion.
![proof for the rule of aplied proportion][1]
r1= RandomReal[6471000,{200}] radius of earth in meters
r2=RandomReal[695510000,{200}] radius of the sun in meters
s=RandomReal[149600000000,{200}] distance from the sun in meters
g1=RandomReal[9.86,{200}] gravity of earth
g2=RandomReal[274,{200}] gravity of sun
s2=(g2*r1*s)/(2*r2*g1) interrelated equation to obtain an intermediate distance from earth to the sun
s1=s-s2
a=(r1*s1)/g1 total space mass time relation to earth
b=(r2*s2)/g2 total space mass time relation to sun; both equals each other at a given distance
y=(g2*r1*s1)/(g1*r2*s2) third variable obtained from a rule of proportion that equals the aplication of the theorem for the limit of a derivative
ListPlot[a]
ListPlot[b]
ListPolarPlot[s2]
ListPolarPlot[y]
data=Table[Mod[s2,y],{s2,0,Pi,Pi},{y,0,Pi,Pi}]
ListPlot[data,InterpolationOrder->3, ColorFunction->{s2->Yellow,y->Blue,s1->Green}]
ContourPlot3D[Sin[s2*s1/y] ,{s2,-Pi,Pi},{s1,-Pi,Pi},{y,-Pi,Pi}]
Run the program and notice that the simple proportion between two analogus functions alows to obtain a third variable that is related to the applied principle of limit of a derivative. Notice that a and b have equal values for a certain distance from the sun and from earth expressed in space per mass per second. the distance at this point makes the bodie there located to be in the same relative position.
r1= RandomReal[6471000,{200}]
r2=RandomReal[695510000,{200}]
s=RandomReal[149600000000,{200}]
g1=RandomReal[9.86,{200}]
g2=RandomReal[274,{200}]
s2=(g2*r1*s)/(2*r2*g1)
s1=s-s2
a=(r1*s1)/g1
b=(r2*s2)/g2
y=(g2*r1*s1)/(g1*r2*s2)
ListPlot[a]
ListPlot[b]
ListPolarPlot[s2]
ListPolarPlot[y]
data=Table[Mod[s2,y],{s2,0,Pi,Pi},{y,0,Pi,Pi}]
ListPlot[data,InterpolationOrder->3, ColorFunction->{s2->Yellow,y->Blue,s1->Green}]
ContourPlot3D[Sin[s2*s1/y] ,{s2,-Pi,Pi},{s1,-Pi,Pi},{y,-Pi,Pi}]
tahnk you , feel free to aply the rule to any other object distance gravity related condition: black holes for instance.
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=DERIVADADEMASSENAMISIEC.jpg&userId=1147177Luis Felipe Massena Misiec2019-05-18T16:57:31Z[✓] Access elements of a QuantityArray?
https://community.wolfram.com/groups/-/m/t/1687732
Hi,
How do I access the individual elements of a QuantityArray? For example, if I initialize an array:
temps=QuantityArray[ConstantArray[0,5],"Kelvins"]
and then I'd like to change the third element of temps to 273 K.
Thanks,
TonyTony Marino2019-05-21T19:49:57Z[WSS17] Mathematica connection to NI - Data Acquisition (DAQ) cards
https://community.wolfram.com/groups/-/m/t/1137025
## [WSS17] Mathematica connection to NI - Data Acquisition (DAQ) cards ##
I have controlled hardware devices through serial ports, GPIB ports, USB ports using SerialRead/Write and NI - VISA from Mathematica. Here at WSS17, I wanted to control NI - DAQ cards using Mathematica. Through all these device communication protocols, large number of devices can be controlled which enables me to run my experiments efficiently using Mathematica.
DAQ cards are used for efficient measurements as they are compact and occupy less space than traditional devices. NI-DAQmx is an efficient driver to control NI-DAQ cards. In WSS17, I developed Mathematica-DAQmx Link ("DAQmxLink"), which links NI-DAQ cards with Mathematica through the communication between Mathematica NETLink and NI-DAQmx .
![Project structure][1]
You can find the detailed code [Git link][2]
## Further Reading on DAQmx ##
More on [DAQmx .NET object][3]
## NI - DAQ - Test ##
usb6000 = DeviceOpen["DAQmx"]
![enter image description here][4]
ListPlot[DeviceReadBuffer[usb6000, 10000, "source"]]
![enter image description here][5]
I can read the individual data too.
Table[DeviceRead[usb6000], {i, 1, 10}]
![enter image description here][6]
This is the basic connectivity between Mathematica and NI DAQmx.
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=final.jpg&userId=1122758
[2]: https://github.com/sumanban/HW_submit/blob/master/HW_suman%20_fin.nb
[3]: http://zone.ni.com/reference/en-XX/help/370473H-01/mstudiowebhelp/html/a648a297/
[4]: http://community.wolfram.com//c/portal/getImageAttachment?filename=output1.jpg&userId=1122758
[5]: http://community.wolfram.com//c/portal/getImageAttachment?filename=output2.jpg&userId=1122758
[6]: http://community.wolfram.com//c/portal/getImageAttachment?filename=out3.jpg&userId=1122758Suman Banerjee2017-07-05T21:10:28ZInvert a 2x2 matrix with 2x2 matrix elements?
https://community.wolfram.com/groups/-/m/t/1651695
If this is my matrix a as follows:
a00 a01
a10 a11
Element a00 would be comprised of a matrix b as follows:
b00 b01
b10 b11
And so on ...
I want to solve my A matrix using Mathematica algorithm.
Thanks for your help.
Stanstan gianzero2019-04-07T16:35:03Z[✓] Avoid Manipulate causing CPU loop?
https://community.wolfram.com/groups/-/m/t/1685676
Hello
I am looking for a better understanding of the behavior of Manipulate when using a Module. I know this is a larger topic but I have a specific question.
I will post my code at the end for reference.
I have a function defined inside Manipulate and all is working as expected however Mathematica pegs one of my CPUs to 100% even after the results are calculated and returned.
I read an article saying a function inside Manipulate will be continuously reevaluated even when sliders are not being changed. The article suggested placing the function inside a Module to prevent reevaluation by Manipulate unless something changes like a Slider value.
My question is – Why is this necessary? Why does Mathematica loop the function causing constant CPU usage? I almost understand why using Module resolves the problem but am I confused why this is the default behavior of Manipulate.
If I remove the Module below the CPU loop returns.
Code is below. This is a SpiroGraph emulator I am fooling around with.
Manipulate[Module[{Cx,Cy,Fx,Fy},
l=p/r; (* Drawing hole radius as a percent of drawing disk radius *)
k=r/R0;(* Drawing disk radius as a percent of stationary outer ring radius *)
Cx[t_]:=R0*Sin[t]; (* X coordinate of stationary outer ring *)
Cy[t_]:=R0*Cos[t];(* Y coordinate of stationary outer ring *)
Fx[t_]:=R0*((1-k)*Cos[t]+(l*k*Cos[((1-k)/k)*t]));
Fy[t_]:=R0*((1-k)*Sin[t]-(l*k*Sin[((1-k)/k)*t]));
ParametricPlot[{{Fx[t1],Fy[t1]},{Cx[t1],Cy[t1]}},{t1,0,R Pi}]],
{{R0,32,"Stationary ring inner radius"},10,200,10,Appearance->"Labeled"},
{{r,IntegerPart[R0/2]-1,"Drawing disk radius"},1,R0,1,Appearance->"Labeled"},
{{p,IntegerPart[r/2]-1,"Drawing hole radius"},1,r,1,Appearance->"Labeled"},
{{R,30,"Number of rotations"},1,100,10,Appearance->"Labeled"}
]Albert Cattani2019-05-18T22:58:55ZUse Simpson2D rule?
https://community.wolfram.com/groups/-/m/t/1684536
I want to know how to use Simpson2D rule. I got confused, because on
http://mathfaculty.fullerton.edu/mathews/n2003/simpsons2Drule/SimpsonsRule2DMod/Links/SimpsonsRule2DMod_lnk_5.html
it gives the rule as Simpson2D[a,b,c,d,m,n] where c, d are lower and upper limits of the integration dx, and a, b are lower and upper limits of the integration dy. From the context it seems the function must be in the form of f(x,y). However, when I use the rule, to find out
va1=Simpson[a,b, c. d,m, n],
a=0, b=1.26, c=0.17,d=0.44, m=10,n=10
I got an answer
Smpson2D[1, 1.2, 0.17, 0.44, 10, 10]
I want to know: 1. how to specify the function, does it have to have the form f(x,y) 2. How to write the syntax. For example, if f(x,y)= Sin[x] Cos[y], integrate from x=0 to 1, from y=0.1 to 0.2. how to write the syntax so that I can get a numerical answer answer.
This is my actual file. Only the last 6 entries deals with the use of Simpson2D
Your help will be much appreciated.
Hong-Yee Chiu, hongychiu@gmail.comHong-Yee Chiu2019-05-16T20:17:34ZWhy can't a parameter be used to set the unit-attribute?
https://community.wolfram.com/groups/-/m/t/1684057
Hi everybody,
The following minimal example does compile without any problems in WSM 4.3 and 5.1. But it will cause an error in WSM 12.0 all of a sudden:
model UnitErrorModel
MyComponent c( hasUnit = "myUnit" );
block MyComponent
parameter String hasUnit = "1";
output Real y( unit = hasUnit );
equation
y = 10;
end MyComponent;
end UnitErrorModel;
So the global model will have a component *c* that modifies a parameter *hasUnit* which is used by the component to set the *unit*-attribute of its output *y*.
In Mathematica [12.0.0 for Microsoft Windows (64-bit) (April 6, 2019)] I observe this:
model = Import[ "UnitErrorModel.mo" ];
SystemModelSimulate[ model, { 0, 10 } ]
> SystemModelSimulate::bldl
> Internal error: Codegen.getValueString: Non-constant expression:c.hasUnit
What has changed in WSM that this is causing an error? Why can't a parameter (note, that making the modification *final* will not resolve the issue) be used to set the unit-attribute - after all it is known at runtime when compiling the model?
Best regards,
Guido
Note: I cross-posted an extended question on [StackOverflow][1].
Background:
I am developing a library for (acausal) System Dynamics modeling. Since SD is very low level (e.g. stocks and flows) working with “hard-wired” SI-units is not helpful for modeling managerial or economical problems. Yet, unit checking is very useful and widely embraced in the SD community. Thus, having a flexible way to use parameters to assign units to output (and input) connectors wouldmbe very helpful; this is also how most dedicated SD tools go about it.
[1]: https://stackoverflow.com/q/56154630/5363743Guido Wolf Reichert2019-05-15T17:39:35ZHandle top-level parameters in WSM?
https://community.wolfram.com/groups/-/m/t/1687373
Hi,
I found these recommendations for handling parameters at the top-level of models for Dymola:
[Handling of Modelica Model's Parameters][1]
Would these also be best-practice recommendations for the System Modeler or are there notable deviations?
Regards,
Guido
[1]: https://www.claytex.com/blog/handling-of-modelica-models-parameter-values-in-dymola/Guido Wolf Reichert2019-05-20T18:59:55ZHow can I get to new lists?
https://community.wolfram.com/groups/-/m/t/1685871
Dear All,
How do I able to reach to new lists as follow:
![enter image description here][1]
m = {2, "*", 4, "*"}
n = {8, "*", 7, 9}
mNEW = {2, 4}
nNEW = {8, 7}
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=2202Untitled.png&userId=943918
Thank you very much.M.A. Ghorbani2019-05-19T10:58:14ZFix issues with Machine Precision in NMaximize?
https://community.wolfram.com/groups/-/m/t/1675910
I am having daily problems with the new Machine Precision standard from V11.3 and now in V12.
Please suggest a quick fix that will work for all functions/procedures.
I will not be able to use Mathematica in the future if this problem is not fixed.Christian Damgaard2019-05-04T09:35:01ZTranscendental Spheres
https://community.wolfram.com/groups/-/m/t/1678098
One of the most beautiful equations in the whole of mathematics is the identity (and its derivation):
![enter image description here][1]
I recently came across another beautiful mathematical concept that likewise relates the two transcendental numbers e and Pi.
We begin by reviewing the concept of a unit sphere, which in 3-dimensional space is the region of points described by the equation:
![enter image description here][2]
We can some generate random coordinates in Mathematica that satisfy the equation, to produce the expected result:
![enter image description here][3]
The equation above represents a 3-D unit sphere using the standard Euclidean Norm. It can be generalized to produce a similar formula for an n-dimensional hyper-sphere:
![enter image description here][4]
Another way to generalize the concept is by extending the Euclidean distance measure with what are referred to as p-Norms, or L-p spaces:
![enter image description here][5]
The shape of a unit sphere in L-p space can take many different forms, including some that have “corners”. Here are some examples of 2-dimensional spheres for values of p varying in the range { 0.25, 4}:
![enter image description here][6]
which can also be explored in the complex plane:
![enter image description here][7]
Reverting to the regular Euclidean metric, let’s focus on the n-dimensional unit hypersphere, whose volume is given by:
![enter image description here][8]
To see this, note that the volume of the unit sphere in 2-D space is just the surface area of a unit circle, which has area V(2) = π. Furthermore:
![enter image description here][9]
This is the equation for the volume of the unit hypersphere in n dimensions. Hence we have the following recurrence relationship:
![enter image description here][10]
This recursion allows us to prove the equation for the volume of the unit hypersphere, by induction.
The function V(n) take a maximal value of 5.26 for n = 5 dimensions, thereafter declining rapidly towards zero:
![enter image description here][11]
![enter image description here][12]
In the limit, the volume of the n-dimensional unit hypersphere tends to zero:
![enter image description here][13]
Now, consider the sum of the volumes of unit hypersphere in even dimensions, i.e. for n = 0, 2, 4, 6,…. For example, the first few terms of the sum are:
![enter image description here][14]
These are the initial terms of a well-known McClaurin expansion, which in the limit produces the following remarkable result:
![enter image description here][16]
In other words, the infinite sum of the volumes of n-dimensional unit hyperspheres evaluates to a power relationship between the two most famous transcendental numbers. The result, known as Gelfond’s constant, is itself a transcendental number:
![enter image description here][15]
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=EiPi.png&userId=773999
[2]: https://community.wolfram.com//c/portal/getImageAttachment?filename=UnitSphereEqn.png&userId=773999
[3]: https://community.wolfram.com//c/portal/getImageAttachment?filename=SpherePoints.png&userId=773999
[4]: https://community.wolfram.com//c/portal/getImageAttachment?filename=HypershereEqn.png&userId=773999
[5]: https://community.wolfram.com//c/portal/getImageAttachment?filename=P-Norms.png&userId=773999
[6]: https://community.wolfram.com//c/portal/getImageAttachment?filename=unitcircles.gif&userId=773999
[7]: https://community.wolfram.com//c/portal/getImageAttachment?filename=complexplots.gif&userId=773999
[8]: https://community.wolfram.com//c/portal/getImageAttachment?filename=VnEqn.png&userId=773999
[9]: https://community.wolfram.com//c/portal/getImageAttachment?filename=recurrenceeqn.png&userId=773999
[10]: https://community.wolfram.com//c/portal/getImageAttachment?filename=recurrence2.png&userId=773999
[11]: https://community.wolfram.com//c/portal/getImageAttachment?filename=VnValues.png&userId=773999
[12]: https://community.wolfram.com//c/portal/getImageAttachment?filename=VnChart.png&userId=773999
[13]: https://community.wolfram.com//c/portal/getImageAttachment?filename=LimitVn.png&userId=773999
[14]: https://community.wolfram.com//c/portal/getImageAttachment?filename=VnSum.png&userId=773999
[15]: https://community.wolfram.com//c/portal/getImageAttachment?filename=Gelfond.png&userId=773999
[16]: https://community.wolfram.com//c/portal/getImageAttachment?filename=EPi.png&userId=773999Jonathan Kinlay2019-05-07T19:45:51Z[WSS18] Reinforcement Q-Learning for Atari Games
https://community.wolfram.com/groups/-/m/t/1380007
## Introduction ##
This project aims to create a neural network agent that plays Atari games. This agent is trained using Q-Learning. The agent will not have any priori knowledge of the game. It is able to learn by playing the game and only being told when it loses.
##What is reinforcement learning? ##
Reinforcement learning is an area under the general machine Learning, inspired by behavioral psychology. The agent learns what to do, given a situation and a set of possible actions to choose from, in order to maximize a reward. Therefore, to model a problem to reinforcement learning problem, the game should have a set of states, a set of actions that able to transfer one state into another and a set of reward corresponding to each state. The mathematical formulation of reinforcement learning problem is called Markov Decision Process (MDP).
![An visual representation of reinforcement learning problem][1]
Image From:https://medium.freecodecamp.org/diving-deeper-into-reinforcement-learning-with-q-learning-c18d0db58efe
## Markov Decision Process ##
Before apply Markov decision process to the problem, we need to make sure the problem satisfy the Markov property which is that the current state completely represents the state of the environment. For short, the future depends only on the present.
An MDP can be defined by **(S,A,R,P,γ)** where:
- S — set of possible states
- A — set of possible actions
- R — probability distribution of reward given (state, action) pair
- P — probability distribution over how likely any of the states is to
be the new states, given (state, action) pair. Also known as
transition probability.
- γ — reward discount factor
At initial state $S_{0}$, the agent chooses action $A_{0}$. Then the environment gives reward $R_{0}=R(.|S_{0}, A_{0})$ and next state $S_{1}=P(.|S_{0},A_{0})$. Repeats till the environment ends.
##Value Network##
In value-based RL, the input will be the current state or a combination of few recent states, and the output will be the estimated future reward of every possible action at this state. The goal will be to optimize the value function so that the prediction value is close to the actual reward. In the following graph, each number in the box represents the distance from current box to the goal.
![Value network example][2]
Image From:https://medium.freecodecamp.org/diving-deeper-into-reinforcement-learning-with-q-learning-c18d0db58efe
## Deep Q-Learning ##
Deep Q-learning is the algorithm that I used to construct my agent. The basic idea of Q function is to get the state and action then output the corresponding sum of rewards till the end of the game. In deep Q-learning, we use a neural network as the Q function therefore we can use one state as input and let neural network to generate the prediction for all possible actions.
The Q function is stated as following.
$Q(S_{t},A) = R_{t+1}+\gamma maxQ(S_{t+1},A)\\Where:\\Q(S_{t},A)\,\,\,\,\,\,\,\,\,\,\,\,\, = The \,predicted\,sum \,of rewards \,given\, current\,state\,and\,selected\,action\\R_{t+1} \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,= Reward\,received\,after\,taking\,action\\\gamma \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,= Discount\,factor\\maxQ(S_{t+1},A) = The\,prediction\,of\,next\,state$
As we can see that given current state and action, Q function outputs the reward of current plus the max value of the predictions of next state. This function will iteratively predicts the reward till the end of the game where Q[S,A] = R. Therefore we can calculate the loss by minus the prediction of current state with the sum of the reward and the prediction of the next state. When loss equals to 0, the function will able to perfectly predicts the reward of all actions. In another sense that the Q function is predicting the future value of its own prediction. People might ask how could this function be ever converge? Yes, this function is usually hard to converge but when it converges, the performance is really well. There are a lot of techniques that can be used to speed up the converge of the Q function. I will talk about a few techniques I used in this project.
## Experience Replay ##
Experience replay means that the agent will remember the states that it has experienced and learn from those experience when training. It gives more efficient way of using generated data which is by learning it for multiple times. It is important when gaining experience is expensive to agent. Since the Q function usually don't converge in a short time which means a lot of the outcomes from the experience are usually similar, multiple passes on the same data is useful.
## Decaying Random Factor ##
Random Factor is the possibility for the agent to choose a random action instead of the best predicted action. It allows the agent to start with random player to increase the diversity of the sample. The random factor decreases with the more game plays therefore the agent is able to be reinforced on its own action pattern.
## Combine Multiple Observations As Input ##
The following image shows a single frame took out from Atari game BreakOut. From this image, the agent is able to capture information about the location of the ball, the location of the board, etc. But several important information is not shown. If you play as the agent, this image is shown to you, what action you will choose? Feel something is missing? Is the ball going right or left? Is the ball going up or down?
![breakout frame1][3]
Generated Using openAI Gym
The following images are two continuous frames took out from the game BreakOut. From these two images that agent is able to capture the information on the direction of the ball and also the speed of the ball. A lot of people tends to forget this since processing recent memories during playing a game is like a nature to us but not to an reinforcement agent.
![breakout frame1][4]![frame 2][5]
Generated Using openAI Gym
## Agent Play in CartPole environment ##
The main environment for agent to learn and tested is CartPole environment. This environment is consist of two movable parts. One is the cart which is controlled by the agent, has two possible action every state which is moving left or right. The other one is pole. This environment simulate the effect of gravity on pole which makes it fall to left or right due to its orientation with the horizon. For this environment to be considered as solved, the average episodes that the agent able to get in 100 games is over 195. Following graph is a visual representation of the environment. The blue rectangle represents the pole. The black box is the cart. The black line is the horizon.
![cart pole sample][6]
First, let's create an environment
$env = RLEnvironmentCreate["WLCartPole"]
Then, initialize a network for this environment and a generator
policyNet =
NetInitialize@
NetChain[{LinearLayer[128], Tanh, LinearLayer[128], Tanh,
LinearLayer[2]}, "Input" -> 8,
"Output" -> NetDecoder[{"Class", {0, 1}}]];
generator := creatGenerator[$env, 20, 10000, False, 0.98, 1000, 0.95, False]
The generator function plays the game and generates input-output pairs to train the network.
Inside the generator, it initialize the replay buffer which is processed, reward list is used to record the performance, best is to record the peak performance.
If[#AbsoluteBatch == 0,
processed = <|"action"->{},"observation"->{},"next"->{},"reward"->{}|>;
$rewardList = {};
$env=env;
best = 0;
];
Then the environment data are being generated from game function and being preprocessed. At the start of training, the generator will produce more data to fill the replay buffer.
If[#AbsoluteBatch == 0,
experience = preprocess[game[start,maxEp,#Net, render, Power[randomDiscount,#AbsoluteBatch], $env], nor]
,
experience = preprocess[game[1,maxEp,#Net, render, Power[randomDiscount,#AbsoluteBatch],$env], nor]
];
The game function is below, it is joining current observation and next observation as the input to the network.
game[ep_Integer,st_Integer,net_NetChain,render_, rand_, $env_, end_:Function[False]]:= Module[{
states, list,next,observation, punish,choiceSpace,
state,ob,ac,re,action
},
choiceSpace = NetExtract[net,"Output"][["Labels"]];
states = <|"observation"->{},"action"->{},"reward"->{},"next"->{}|>;
Do[
state["Observation"] = RLEnvironmentReset[$env]; (* reset every episode *)
ob = {};
ac = {};
re = {};
next = {};
Do[
observation = {};
observation = Join[observation,state["Observation"]];
If[ob=={},
observation = Join[observation,state["Observation"]]
,
observation = Join[observation, Last[ob][[;;Length[state["Observation"]]]]]
];
action = If[RandomReal[]<=Max[rand,0.1],
RandomChoice[choiceSpace]
,
net[observation]
];
(*Print[action];*)
AppendTo[ob, observation];
AppendTo[ac, action];
state = RLEnvironmentStep[$env, action, render];
If[Or[state["Done"], end[state]],
punish = - Max[Values[net[observation,"Probabilities"]]] - 1;
AppendTo[re, punish];
AppendTo[next, observation];
Break[]
,
AppendTo[re, state["Reward"]];
observation = state["Observation"];
observation = Join[observation, ob[[-1]][[;;Length[state["Observation"]]]]];
AppendTo[next, observation];
]；
,
{step, st}];
AppendTo[states["observation"], ob];
AppendTo[states["action"], ac];
AppendTo[states["reward"], re];
AppendTo[states["next"], next];
,
{episode,ep}
];
(* close the $environment when done *)
states
]
Preprocess function flatten the input and has an option on if normalizing the observation
preprocess[x_, nor_:False] := Module[{result},(
result = <||>;
result["action"] = Flatten[x["action"]];
If[nor,
result["observation"] = N[Normalize/@Flatten[x["observation"],1]];
result["next"] = N[Normalize/@Flatten[x["next"],1]];
,
result["observation"] = Flatten[x["observation"],1];
result["next"] = Flatten[x["next"],1];
];
result["reward"] = Flatten[x["reward"]];
result
)]
Let's continue with generator, after getting the data from the game, generator measures the performance and records it.
NotebookDelete[temp];
reward = Length[experience["action"]];
AppendTo[$rewardList,reward];
temp=PrintTemporary[reward];
Records the net with best performance
If[reward>best,best = reward;bestNet = #Net];
Add these experience to the replay buffer
AppendTo[processed["action"],#]&/@experience["action"];
AppendTo[processed["observation"],#]&/@experience["observation"];
AppendTo[processed["next"],#]&/@experience["next"];
AppendTo[processed["reward"],#]&/@experience["reward"];
Make sure the total size of replay buffer does not exceed the limit
len = Length[processed["action"]] - replaySize;
If[len > 0,
processed["action"] = processed["action"][[len;;]];
processed["observation"] = processed["observation"][[len;;]];
processed["next"] = processed["next"][[len;;]];
processed["reward"] = processed["reward"][[len;;]];
];
Add input of the network to the result
pos = RandomInteger[{1,Length[processed["action"]]},#BatchSize];
result = <||>;
result["Input"] = processed["observation"][[pos]];
Calculates the out put based on the next state and reward and add to the result
predictionsOfCurrentObservation = Values[#Net[processed["observation"][[pos]],"Probabilities"]];
rewardsOfAction = processed["reward"][[pos]];
maxPredictionsOfNextObservation = gamma*Max[Values[#]]&/@#Net[processed["next"][[pos]],"Probabilities"];
temp = rewardsOfAction + maxPredictionsOfNextObservation;
MapIndexed[
(predictionsOfCurrentObservation[[First@#2,(#1+1)]]=temp[[First@#2]])&,(processed["action"][[pos]]-First[NetExtract[net,"Output"][["Labels"]]])
];
result["Output"] = out;
result
In the end, we can start training
trained =
NetTrain[policyNet, generator,
LossFunction -> MeanSquaredLossLayer[], BatchSize -> 32,
MaxTrainingRounds -> 2000]
## Performance of the agent ##
![enter image description here][7]
The graph above show the performance of the agent in 1000 games in cart pole environment. The agent starts with random play which has a low number of episodes lasted. The performance stay low till 800 games. But after 800 games, the performance starts to increase exponentially. In the end of the training, the performance jumps from 3k to 10k which is the maximal number of episode per game in 4 games. This proves that although the Q function is hard to converge, but when it converges, the performance is very well.
##Future Directions##
The current agent uses the classical DQN as its major structure. Other techniques like Noisy Net, DDQN, Prioritized Reply, etc can help the Q function to converge in a shorter time. Other algorithms like Rainbow Algorithm which is based on Q learning will be the next step of this project.
code can be found on [github link][8]
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=rl.png&userId=1363029
[2]: http://community.wolfram.com//c/portal/getImageAttachment?filename=vn.png&userId=1363029
[3]: http://community.wolfram.com//c/portal/getImageAttachment?filename=breakout1.png&userId=1363029
[4]: http://community.wolfram.com//c/portal/getImageAttachment?filename=breakout1.png&userId=1363029
[5]: http://community.wolfram.com//c/portal/getImageAttachment?filename=breakout2.png&userId=1363029
[6]: http://community.wolfram.com//c/portal/getImageAttachment?filename=cp.png&userId=1363029
[7]: http://community.wolfram.com//c/portal/getImageAttachment?filename=performance.png&userId=1363029
[8]: https://github.com/ianfanx/wss2018ProjectIan Fan2018-07-11T20:52:09Z[✓] Perform a non-linear fitting?
https://community.wolfram.com/groups/-/m/t/1687041
hi, i'm a new to the mathematica,need some advice on how i do a fitting to this kind of data,try to fitt to gaussian model but end up to nowhere,please anyone can give me a suggestion on how i suppose to to a fitting,tq
data4 = {{1, 0.7908237678805172`}, {2, 0.7923540508123751`}, {3, 0.79741355834688`}, {4, 0.8075308378102534`}, {5, 0.82630159208019`}, {6, 0.8617959376912471`}, {6.5`,0.9311495289477106`}, {6.75`, 0.9858878062075014`}, {7,
1.0183233500654116`}, {7.5`, 1.052535900411738`}, {7.75`,
1.1139261047524773`}, {7.85`, 1.1322647992772223`}, {8,
1.1359323690995655`}, {8.25`, 1.1370214756148385`}, {9,
1.1271031295853728`}, {10, 1.0397067038571146`}, {11,
0.9209408678283771`}, {12, 0.854055093889399`}, {13,
0.8189527427776097`}, {14, 0.7993224779484722`}, {15,
0.7874811068946352`}, {16, 0.7798540751147963`}, {17,
0.7709924536766344`}, {18, 0.7682869474772277`}, {19,
0.7662377379751114`}, {20, 0.7646469190983587`}};
nlm = NonlinearModelFit[data4, 1 E^-(x - a)^2/2 c^2, {{a, 1}, {c, 3}},
x]joe jill2019-05-20T17:44:20ZIs Version 12 Tetrahedron Bottomless?
https://community.wolfram.com/groups/-/m/t/1686088
Consider the following code:
In[1]:= Minimize[z, {x, y, z} \[Element] Tetrahedron[]]
Dur
ing evaluation of In[1]:= Minimize::natt: The minimum is not attained at any point satisfying the given constraints.
Out[1]= {-\[Infinity], {x -> Indeterminate, y -> Indeterminate,
z -> Indeterminate}}Frank Kampas2019-05-19T17:54:50ZFunction Suggestions
https://community.wolfram.com/groups/-/m/t/1685310
Very interestingly Mathematica 12.0 now has some cool shorthand notations for some functions. A good example is `ReverseSortBy`.
Almost a year ago I suggest some [shorthands][1] like that if anyone is interested. One that I find myself using quite a lot is `TallySortByFirst`.
I hope Mathematica can improve and increase the number of functions like that.
[1]: https://github.com/ThalesFernandes/FunctionConcatenationThales Fernandes2019-05-17T13:57:24ZCounting Trailing Zeros Of Factorials
https://community.wolfram.com/groups/-/m/t/1670775
##Introduction##
You may have noticed that the factorial function for integers generates a lot of trailing zeros at the end e.g. 100! evaluates to
9332621544394415268169923885626670049071596826438162146859296389521759\
9993229915608941463976156518286253697920827223758251185210916864000000\
000000000000000000
That's 24 zeros right there. Maybe you would like to figure out how to calculate the exact number for arbitrary input integers? And then maybe for any chosen radix as well i.e. not using the decimal representation? I don't want to spoil the fun for you, so please go chew away at this nice little mathematical diversion. The asymptotic "TZF" function for large integers is really compute-friendly, so for "easy" large integers you will be able to do the algebra just using a simple rule.
Well and then it is always possible I have made a mistake, so I include my notebook on this problem for you to compare.
Have fun!
![enter image description here][1]
In the seventies when I got my first TI pocket calculator in school I developed a certain fascination for the factorial function. It was basically the most dangerous function around because if you entered any integer larger than 69 it would blow up with an error because it could not calculate numbers with more than two digits in the base-10 exponent and for most of them it could of course only show the first few most significant digits.
So it took me almost 40 years and the mind-boggling capacity of WL to handle arbitrary-sized integers (well almost) to ask the following question: What is the number of trailing zeros in $n$ factorial? As a short reminder n! is the mathematical notation for the product of all positive integers less or equal to n.
As you can easily see from an example there are plenty of trailing zeros in the factorial of reasonably-sized integers:
100!
> `9332621544394415268169923885626670049071596826438162146859296389521759\
9993229915608941463976156518286253697920827223758251185210916864000000\
000000000000000000`
Well to answer the question above we reformulate it as the number of sought zeros is equal to how many times n factorial can be divided (meaning integer division) by ten without getting a remainder. But for getting a factor of 10 there needs to be a corresponding factor of 5 and one factor of 2 in the prime factorization of $n$ factorial. Since every other number contains at least a factor of 2 in its prime factorization we can safely count only the factors of 5 in the factorization of the first n integers so we get a first (very functional and "pattern matchy" way to calculate the trailing zero function TZF:
TZF1[n_] :=
Flatten[FactorInteger[Range[n]] , 1] // Cases[{5, a_} -> a] // Total
ListPlot[Table[TZF1[n], {n, 100}], Joined -> True, ImageSize -> Large,
PlotRange -> All]
![enter image description here][2]
Well it looks pretty step-like with regular intervals so let's plot the differences:
ListPlot[Differences[Table[TZF1[n], {n, 100}]], Joined -> True,
ImageSize -> Large, PlotRange -> All]
![enter image description here][3]
Aha! For each $5^i$ we get i new trailing zeros, but that is then equal to just summing the integer quotients of dividing n by increasing powers of $5^i$. So we have another candidate for the trailing zeros which definitely looks much more procedural:
TZF2[n_] := Module[{i = 1, result = 0}, While[5^i <= n, result += Quotient[n, 5^i]; i++]; result]
And finally we might always have done a mistake so let's just see how long the last group of digits is for any n larger than 4, which is the brute force way to get the answer:
TZF3[n_] := If[n < 5, 0, IntegerDigits[Factorial[n]] // SplitBy[#, 1] & // Part[#, -1] & // Length]
m = 150; ListPlot[{Table[TZF1[n], {n, m}], Table[TZF2[n], {n, m}],
Table[TZF3[n], {n, m}]}, Joined -> True, ImageSize -> Large, PlotRange -> All]
![enter image description here][4]
All well it seems, of course not everything worked out right at first trial, but now that all three seem to coincide, it seems pretty watertight right?
So then let's see which form might be most efficient to calculate the TZF function:
n = 10000;
Timing[TZF1[n]]
Timing[TZF2[n]]
Timing[TZF3[n]]
{0.041059, 2499}
{0.000055, 2499}
{0.043205, 2499}
So you see functional is not always faster unfortunately, but it is also surprising to see that taking the long detour to calculate the whole factorial does equally well roughly as the first variant which only factorizes rather small numbers.
But back to the original question we can see that we answer the original question pretty accurately by calculating the TZF function divided by n as a geometric sum:
n =.;
Sum[1/5^i, {i, 1, \[Infinity]}]
> 1/4
So the trailing number of zeros of n factorial is approximately $n/4$ for large n (to be more accurate take one less). So if you get the question at the next party "how many trailing zeros are there in 10000 factorial?" just say "2499 of course"!
So what about other radices (plural for radix or base of the integer digit representation)? To find an the answer we have to consider the prime factorization of the radix which then of course can have more (or less) than two prime factors and each with a separate multiplicity to form the radix as a product. So for each of these prime factors of the radix $p^k$ we then have to calculate how many times p appears in the positive integer numbers smaller or equal to n and find the integer quotient when dividing by k. The smallest of these is then our trailing zeros count.
TZF4[n_, r_] := Quotient[Total[ Cases[Flatten[FactorInteger[Range[n]] , 1] , {#[[1]], a_} ->
a]], #[[2]]] & /@ FactorInteger[r] // Min
TZF5[n_, r_] :=
Module[{f = FactorInteger[r], q = Table[0, Length[FactorInteger[r]]],
i, p, q0},
Do[i = 1; p = f[[j, 1]]; q0 = 0;
While[p^i <= n, q0 += Quotient[n, p^i]; i++];
q[[j]] = q0
, {j, Length[f]}];
If[Min[q] > 0, Min[Quotient[q, f[[;; , 2]]]], 0]
]
TZF6[n_, r_] :=
IntegerDigits[Factorial[n], r] // SplitBy[#, 1] & //
If[Part[#, -1][[1]] == 0, Length[Part[#, -1]], 0] &
Let's see if these agree to iron out obvious mistakes by feeding random samples. But beware, the factorial is still dangerous and will exhaust your physical memory if you throw in too big numbers or too small radices.
Table[{n = RandomInteger[10000], r = RandomInteger[{5, 30}],
TZF4[n, r], TZF5[n, r], TZF6[n, r]}, 10] // TableForm
![enter image description here][5]
Table[{n = RandomInteger[10000], TZF1[n], TZF2[n], TZF3[n],
TZF4[n, 10], TZF5[n, 10], TZF6[n, 10]}, 10] // TableForm
![enter image description here][6]
In order to get asymptotic values of the trailing zeros you now need to divide n by $(p-1) k$. You have to do this only with the prime factor that results in the largest value of $(p-1) k$ of course. Then you round down again and you will be mostly very accurate. So let's do an example:
TZF5[10000, 72]
> 2498
For radix 72 the prime decomposition is $2^3 3^2$, so again it's a division by four (from the first factor) but now we'd actually would have to subtract 2 to get the right number. If you end up with a tricky radix decomposition for the party trick you might actually have to consult the pocket calculator on your smartphone for the division. To close out I have to confess that I still own a working HP-15C, an icon of computation devices and a testament to solid engineering:
Well I am looking forward to the day when we are going to have hardware that durable again and being able to run WL from it.
If you liked this piece and want to explore further, why not generalizing the TZF functions above to mixed radix representations or make your own variant of them to optimize code, memory or performance.
![enter image description here][7]
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=42551.png&userId=20103
[2]: https://community.wolfram.com//c/portal/getImageAttachment?filename=65422.png&userId=20103
[3]: https://community.wolfram.com//c/portal/getImageAttachment?filename=64973.png&userId=20103
[4]: https://community.wolfram.com//c/portal/getImageAttachment?filename=78994.png&userId=20103
[5]: https://community.wolfram.com//c/portal/getImageAttachment?filename=54855.png&userId=20103
[6]: https://community.wolfram.com//c/portal/getImageAttachment?filename=44026.png&userId=20103
[7]: https://community.wolfram.com//c/portal/getImageAttachment?filename=44607.png&userId=20103Fabian Wenger2019-04-27T18:17:05ZInconsistent simulation outcomes?
https://community.wolfram.com/groups/-/m/t/1687358
Please find attached two in principle identical kinds of simulating the one-sided exact Fisher-test of obtaining at least 86 successes in 129 draws in a population of size 299 containing 167 successes. 1st Version is rather slow and yields too large a probability. 2nd Version is fast and its result is pretty similar to the theoretical probability. Does this possibly indicate bugs in the RandomVariate and/or Hypergeometric functions or mechanisms?Hagen Scherb2019-05-20T18:46:56ZReactiveX for Wolfram Language?
https://community.wolfram.com/groups/-/m/t/1687123
In [ReactiveX][1] website one can see that its ideas about asynchronous programming are implemented in many programming languages including:
- Java: RxJava
- JavaScript: RxJS
- C#: Rx.NET & UniRx
- Scala: RxScala
- Clojure: RxClojure
- C++: RxCpp
- Lua: RxLua
- Ruby: Rx.rb
- Python: RxPY
- Go: RxGo
- Groovy: RxGroovy
- JRuby: RxJRuby
- Kotlin: RxKotlin
- Swift: RxSwift
- PHP: RxPHP
- Elixir: reaxive
- Dart: RxDart
Any opinions about the viability of implementing these ideas in the Wolfram Language? I am considering this for handling live streams of data for dashboards.
[1]: http://reactivex.ioGustavo Delfino2019-05-20T16:14:41ZUS Climate Change at the County Level
https://community.wolfram.com/groups/-/m/t/1671437
![US County century-scale climate change][3]
(Edited 4/29/2019) Continuing my efforts to visualize climate change in the US, I found that the US National Oceanic and Atmospheric Administration (NOAA) maintains a dataset of monthly average temperatures for every county in the 48 contiguous US States from 1895 to the present. To avoid burdening the server during testing, I downloaded the file to my computer, but it is available [here][1]. On the NOAA ftp site the file will have the name climdiv-tmpccy-v1.0.0-YYYYMMDD, where YYYY, MM and DD correspond to the year, month and date when the file was updated. When I downloaded the file its name was climdiv-tmpccy-v1.0.0-20190408.
It takes some time to read in all 388,375 lines of this file:
cdata = SemanticImport["climdiv-tmpccy-v1.0.0-20190408.txt",
PadRight[{"String"}, 13, "Real"]];
The dataset consists of 13 columns: the first is a string of digits encoding the year and something that is almost -- but not quite -- the FIPS code for the county. The next 12 are the monthly average temperatures in degrees Fahrenheit in that county for January through December of that year. For clarity, I like to add column headers first:
cdata = cdata[All,
AssociationThread[
Prepend[Table[
DateString[d, "MonthNameShort"], {d,
DateRange[{0, 1}, {0, 12}, "Month"]}], "Code"], Range[13]]];
To correct the FIPS codes, we require the FIPS codes for the 48 contiguous States:
stateFIPS =
EntityValue[
EntityList[
EntityClass["AdministrativeDivision", "ContinentalUSStates"]],
"FIPSCode"];
Now we can add a column containing the correct FIPS code for each county. While we're at it we add a column for the year:
cdata = cdata[
All, <|"FIPS" ->
stateFIPS[[ToExpression[StringTake[#Code, 2]]]] <>
StringTake[#Code, {3, 5}],
"Year" -> ToExpression[StringTake[#Code, -4]], #|> &];
Then I build an association of FIPS codes and entity values for the corresponding counties:
counties =
EntityList[
EntityClass["AdministrativeDivision", "USCountiesAllCounties"]];
massoc = AssociationThread[EntityValue[counties, "FIPSCode"],
counties];
With this association, we can add a column to the dataset corresponding to the entity value of each county. In the same statement I also add a column for the average annual temperature:
cdata = cdata[
All, <|"County" -> massoc[#FIPS], #,
"Tavg" ->
Mean[WeightedData[{#Jan, #Feb, #Mar, #Apr, #May, #Jun, #Jul, \
#Aug, #Sep, #Oct, #Nov, #Dec}, {31, 28 + Boole[LeapYearQ[#Year]], 31,
30, 31, 30, 31, 31, 30, 31, 30, 31}]]|> &];
The file includes data for the first couple of months of 2019, so I strip that out:
cdata = cdata[Select[#Year <= 2018 &]];
I tried several different ways of smoothing the temperatures and decided on an moving average of the past 10 years:
s = cdata[GroupBy["County"],
With[{ma = MovingAverage[#, 10]},
Last[ma] - ma[[-100]]] &, "Tavg"];
I experimented with the color functions available in Mathematica, but decided to build my own using a color pallette from the [ColorBrewer][2] website.
col1 = RGBColor[{255, 245, 240}/255];
col2 = RGBColor[{254, 224, 210}/255];
col3 = RGBColor[{252, 187, 161}/255];
col4 = RGBColor[{252, 146, 114}/255];
col5 = RGBColor[{251, 106, 74}/255];
col6 = RGBColor[{239, 59, 44}/255];
col7 = RGBColor[{203, 24, 29}/255];
col8 = RGBColor[{165, 15, 21}/255];
col9 = RGBColor[{103, 0, 13}/255];
qq = Values[s];
zz = Table[Min[qq] + i*(Max[qq] - Min[qq])/9, {i, 9}];
cfunc[x_?NumericQ] := Which[
x <= zz[[1]], col1,
x <= zz[[2]], col2,
x <= zz[[3]], col3,
x <= zz[[4]], col4,
x <= zz[[5]], col5,
x <= zz[[6]], col6,
x <= zz[[7]], col7,
x <= zz[[8]], col8,
x <= zz[[9]], col9]
Then it's just a matter of building the legend and displaying the map:
legend = SwatchLegend[{col1, col2, col3, col4, col5, col6, col7, col8,
col9}, {"-0.30 - 0.28", " 0.28 - 0.87", " 0.87 - 1.45",
" 1.45 - 2.04", " 2.04 - 2.62", " 2.62 - 3.21", " 3.21 - 3.79",
" 3.79 - 4.38", " 4.38 - 4.96"},
LegendMarkers ->
Graphics[{EdgeForm[Black], Opacity[1], Rectangle[]}],
LegendLabel -> "\[CapitalDelta]T(\[Degree]F)",
LegendFunction -> (Framed[#, RoundingRadius -> 5] &),
LegendMargins -> 5];
climvis =
GeoRegionValuePlot[s, Frame -> True, FrameTicks -> None,
FrameLabel -> {"Change in Mean Annual Temperature for US Counties, \
1919-2018"}, LabelStyle -> Larger,
PlotLegends -> Placed[legend, Right], ColorFunction -> cfunc,
ColorFunctionScaling -> False,
PlotStyle -> Directive[EdgeForm[{Thin, White}]],
GeoBackground -> None,
GeoProjection -> {"LambertAzimuthal",
"Centering" -> GeoPosition[{30, -195/2}]},
PlotRange -> {{-0.37, 0.38}, {-0.13, 0.38}}, ImageSize -> 800,
PlotLegends -> Placed[legend, Right]]
And finally here is the result. This is of course just a "proof of concept" exercise. There are any number of ways to analyze this dataset and visualize the results.
![US County century-scale climate change][3]
[1]: http://ftp://ftp.ncdc.noaa.gov/pub/data/cirs/climdiv/
[2]: http://colorbrewer2.org
[3]: https://community.wolfram.com//c/portal/getImageAttachment?filename=figmean.jpg&userId=66744John Shonder2019-04-28T15:26:25ZSyntax to compute probability for a continuous distribution?
https://community.wolfram.com/groups/-/m/t/1684668
All:
I know this is a newbie question, but I'm struggling to find documentation and/or an example on how to do this. :(
If I have a `UniformDistribution[0,1]` what is the syntax to compute the probability that `P(U <= 2/3)`?
From what I was able to find I think the command should be something like this:
PDF[UniformDistribution[{0,1}], {x, 2/3, 0}]
I've tried a number of variations of that to no avail so far. Can some one please give me a pointer to some documentation that describes how to calculate probabilities for uniform distributions and/or a few examples?
Many thanks!Nathan Rasch2019-05-16T16:58:16Z[✓] Find surface normal and intersection from any arbitrary shape?
https://community.wolfram.com/groups/-/m/t/1686810
I wish to find the surface normal, and intersection from any arbitrary shape. I can do this using the `Gaphics3D` shapes as follows:
I have a constraint function which finds logic to give the allowed values which are along the line and is on one of the surfaces, but not within any two shapes. So, the function to do create the logic is called `constraints[]` and `intersection[]` which then just uses `NSolve[]` to find the solution with the line, i.e.
*NSolve[{x, y, z} \[Element] line && (surfaceequations1 || surfaceequations2 || surfaceequations3) && ! (volumeequation1 && volumeequation2) && ! (volumeequation2 && volumeequation3) && ! (volumeequation1 && volumeequation3), {x, y, z}]*
constraints[shapes__] :=
And[## & @@ (Not /@
Through[(RegionMember[RegionIntersection@##] & @@@
Subsets[{shapes}, {2}])@#]),
RegionMember[RegionUnion @@ (RegionBoundary /@ {shapes})]@#] &
intersections[l_, s__] :=
NSolve[{x, y, z} \[Element] l && constraints[s][{x, y, z}], {x, y, z}]
shape1 = Cuboid[{5, 5, 1}, {6, 25, 3}];
shape2 = Cuboid[{6, 5, 1}, {21, 6, 3}];
shapes = {shape1, shape2};
line = InfiniteLine[{{5.5, 10.5, 0.5}, {5.5, 10.5, 1}}];
intersection = intersections[line, ##] & @@ shapes;
intersection = DeleteDuplicates[intersection];
points = {x, y, z} /. intersection;
Graphics3D[{line, shapes, {Red, PointSize[0.05], Point[points]}}]
This works
![enter image description here][1]
I can also find the surface normals of the shapes as follows
shape1 = Cuboid[{5, 5, 1}, {15, 15, 4/3}];
shapes = {shape1};
standardize[a_ <= b_] := a - b;
standardize[a_ >= b_] := b - a;
regnormal[reg_, {x_, y_, z_}] :=
Module[{impl},
impl = LogicalExpand@
Simplify[
RegionMember[reg, {x, y, z}], {x, y, z} \[Element] Reals];
If[Head@impl === Or, impl = List @@ impl, impl = List@impl];
impl = Replace[impl, {Verbatim[And][a___] :> {a}, e_ :> {e}}, 1];
Piecewise[
Flatten[Function[{component},
Table[{D[standardize[component[[i]]], {{x, y, z}}],
Simplify[(And @@ Drop[component, {i}] /. {LessEqual -> Less,
GreaterEqual ->
Greater}) && (component[[i]] /. {LessEqual -> Equal,
GreaterEqual -> Equal}),
TransformationFunctions -> {Automatic,
Reduce[#, {}, Reals] &}]}, {i, Length@component}]] /@
impl, 1], Indeterminate]];
normals = regnormal[RegionUnion[##] & @@ shapes, {x, y, z}]
But I wish to do it with more complex shapes, i.e. ones I may have designed in a modelling package, for instance, the Example Data helicopter.
image = Import["ExampleData/helicopter.dxf.gz"]
![enter image description here][2]
How can I find the surface normals, and the intersection with a line with shapes like this? Mathematica must be doing it for the Graphics plots. Any ideas?
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=Screenshot2019-05-20at09.45.45.png&userId=1686596
[2]: https://community.wolfram.com//c/portal/getImageAttachment?filename=Screenshot2019-05-20at09.49.44.png&userId=1686596Tomi B2019-05-20T08:48:32ZUse wolframclient api package in python and wolfram engine in a PC?
https://community.wolfram.com/groups/-/m/t/1686783
I installed the wolframclient api package in python, wolfram engine in the PC, and call the kernel in the way accoring to the guidance. While the code "session.evaluate" always lead to error information "Failed to communicate with kernel".
Do I need to install other packages, or purchase licence to let it work?yang haah2019-05-20T12:31:31ZIs Mathematica 11 compatible with Mac OS Mojave
https://community.wolfram.com/groups/-/m/t/1479746
any problem with Mojave before I switch to it?michel2018-09-26T02:01:06ZComparisons between procedural and functional programming
https://community.wolfram.com/groups/-/m/t/1681993
I would like to know (for teaching purposes) of examples where the efficiency of functional programming is overwhelmingly greater than procedural programming.Tomas Garza2019-05-14T00:46:01ZSolve a simple nonlinear equation numerically?
https://community.wolfram.com/groups/-/m/t/1682567
I am trying to solve a simple nonlinear equation numerically. it is Tangent[alpha]+alpha=0 It is embedded in an "If" statement. So the the pertinent parts of the input and output are
input: Tan[alpha]+alpha=0 along with my algorithm where alpha zero is 2.02 to start out with.
Output Tan[2.02 + 0.5 (2.02 - 1. \[Alpha][-1.])] is part of the algorithm to solve for alpha's
The problem is with the output. The square bracket at the end of the out put belongs next to the number "2.02" (the way I typed) and instead it has included "+ 0.5 (2.02 - 1. \[Alpha][-1.])" which is part of the "If " statement that I'm using to calculate the eigenvalues (or alpha's). I don't know why it is doing this or how to fix it. I tried too post a file but could not do it. I am using Mathematica 11.2 I am sure there are bugs in my algorithm but can not do anything until I fix this prolbem.Michael Bernthal2019-05-13T19:48:27ZChange the permissions of a cloud notebook?
https://community.wolfram.com/groups/-/m/t/1674806
I have a notebook, e. g. "190427 Drei Hunde.nb", stored within the Wolfram cloud. It has Permissions Private as I can see from Details.
But I cannot change that Permissions to Public. Neither from the browser cloud interface, nor programmatically from within the notebook opened in the web interface "http://lab.wolframcloud.com/app/objects/wernergg/190427%20Drei%20Hunde.nb"
I think from within the notebook I should do something like
co=CloudObject[...[Notebook[]]]
SetOptions[co,Permissions->"Public"]
but I cannot find out how to create a CloudObject from the current notebook.Werner Geiger2019-05-02T12:19:48ZInternal dosimetry: BIOKMOD WEB expanded including ICRP I30/134/137 models
https://community.wolfram.com/groups/-/m/t/1685662
I inform people interesting in Internal Dosimetry and Health Physics used in Radiation Protection that BIOKMOD WEB (a web application developed using web Mathematica ) has been expanded to include the newest ICRP 130/134/137 biokinetic models. It can be used to internal dosimetry and bioassay evaluation. According to my knowledges it is the only web application that use the ICRP 130/134/137 biokinetic models to bioassay evalution. Apart from Single or Acute intake, chronic and chronic that cease intake can be assumed.
Visit: http://oed.usal.es/webMathematica/Biokmod/ :> ICRP 130/134/137 models.
Please, If you have some comments send me an e-mail: guillermo2046(at)gmail.com.
http://diarium.usal.es/guillermo
Guillermo SánchezGuillermo Sanchez2019-05-18T16:00:49ZSimplify this equation in terms of function and coefficients?
https://community.wolfram.com/groups/-/m/t/1684972
I have two fourth order differential equations and I have solved both equations on Dsolve to get the final solution but it gives me a very large output. I need the result in the form of function (Y) and constant coefficient (let say p1,p2,p3 and so on). So how can I transform it into a simplified form?
Here are the equations.
X''''[Y] - A6*X''[Y] + (B1*Bi)/(k*Um)*(Upm) -
B1/(k*Um)*(D[C1*Sinh[A0*Y] + C2*Cosh[A0*Y] + Da, {Y, 2}]) - (
Bi*Br*Da)/(
k*Um^2)*(1/Da*(Upm)^2 +
1/\[Epsilon]*(D[
C1*Sinh[A0*Y] + C2*Cosh[A0*Y] + Da, {Y, 1}])^2) + (Br*Da)/(
Um^2*k)*(1/
Da*(D[(C1*Sinh[A0*Y] + C2*Cosh[A0*Y] + Da)^2, {Y, 2}]) +
1/\[Epsilon]*(D[(A0 (C1 Cosh[A0 Y] + C2 Sinh[A0 Y]))^2, {Y,
2}])) == 0
Z''''[Y] -
A6*Z''[Y] + (B1*Bi)/(k*Um)*(Upm) - (Bi*Br*Da)/(
k*Um^2)*(1/Da*(Upm)^2 +
1/\[Epsilon]*(D[
C1*Sinh[A0*Y] + C2*Cosh[A0*Y] + Da, {Y, 1}])^2) == 0
Boundary Conditions
X''[0] == B4, Z''[0] == 0, X[0] == 0, Z[0] == 0, X''[t] == B3,
Z''[t] == 0, X[t] == Z[t], B2 == -k*X'[t] - Z'[t]Mirza Farrukh Baig2019-05-17T08:09:41ZImport a downloaded Cactus Graph program from a web?
https://community.wolfram.com/groups/-/m/t/1618730
Hellow everyone
I downloaded a notebook about Cactus Graph downloaded from *http://mathworld.wolfram.com/CactusGraph.html.* **I want to get all cacti Graph of order 8.**
But I don't know how to **use** the program from it. what should I do ?
thanksLicheng Zhang2019-02-23T05:36:44ZHide input boxes / display only output boxes?
https://community.wolfram.com/groups/-/m/t/1684575
Hello,
I am a newbie on Wolfram Desktop and I am having trouble finding any documentation on the following: I'd like to be able to export a notebook to PDF or HTML but hide the Wolfram Language code displayed on Input Boxes and only display their results on the OutputBoxes.
That's because my audience are of non-programmers and they would be confused by the source code.
Any help is appreciated,
QuenioQuenio dos Santos2019-05-16T21:43:53ZWriting a Book with Mathematica
https://community.wolfram.com/groups/-/m/t/1672656
#Cross-Post from [here](https://b3m2a1.github.io/writing-books-in-mathematica.html)
---
As part of a [continuing](https://b3m2a1.github.io/making-docs-with-easyide.html) [series](https://b3m2a1.github.io/making-a-website-with-easyide.html) on [my new IDE](https://b3m2a1.github.io/easyide-an-ide-for-mathematica.html) and in particular a series that has focused on publishing—e.g., docs, websites—today we're gonna look at a new little extension to EasyIDE to work with creating books/tutorials in Mathematica. Obviously making a true book in Mathematica is something of a fool's errand, given that it doesn't have the detailed layout control of LaTeX or the grammar check/toolkit of Word, but making many chapter, many chapter PDFs, notebooks, and websites is entirely reasonable. Many people have done this over the years, [myself included](https://mresources.github.io/tutorial/) . With this new IDE work, though, this becomes even easier.
## Getting Started
I won't repeat the instructions for getting started with EasyIDE altogether here, as they are in [the](https://b3m2a1.github.io/easyide-an-ide-for-mathematica.html) [previous](https://b3m2a1.github.io/making-docs-with-easyide.html) [posts](https://b3m2a1.github.io/making-a-website-with-easyide.html) . We will need to get started with our new book, though. Here's a video showing the entire process:
[![HnLuP](https://i.stack.imgur.com/HnLuP.png)](https://www.youtube.com/watch?v=p1WRvwepdvI&feature=youtu.be)
###Creating the Book Structure
The book-content layout borrows directly from my general website building structure. We're just gonna add a few more points of metadata to it. To make this process more streamlined I've included a new Authoring toolbar that you can open by going to `Window ▸ Add Toolbar` in the menus. Once you have the toolbar open you can hit `Initialize Book` to get a dialog for making the new book.
###Creating a Book Chapter
Next we need to make a chapter for our content to live under. To do this we just hit the `New Chapter` button in the bar and give our chapter a name. It's important that we do this before making a section, as every section needs a chapter.
###Creating a Book Section
This is where we'll actually write the content. To make one of these we hit `New Section` , pick a chapter to file the section under, and then provide a name for the section. The new notebook will open up and we can put whatever content we have there.
###Pulling Content of StackExchange
To create a sample book I'm gonna pull a number of answers off StackExchange, say from the [common pitfalls question](https://mathematica.stackexchange.com/questions/18393/what-are-the-most-common-pitfalls-awaiting-new-users/) and the [good examples](https://mathematica.stackexchange.com/questions/18/where-can-i-find-examples-of-good-mathematica-programming-practice) question. The way I'll do this is via a Markdown → Notebook converter I wrote up as a generalization of my old Markdown → XML converter.
To pull an answer we can either get its Markdown via the Edit mechanism or we can use the API. For reasons of efficiency I'm going to choose the latter. If you don't have my StackExchange service connection [ you can get it off the paclet server](https://paclets.github.io/PacletServer/serviceconnectionstackexchange.html) . Once we have that we load the connection:
$so = ServiceConnect["StackExchange"]
(*Out:*)
![post31-3058623906089846253](https://b3m2a1.github.io/img/post31-3058623906089846253.png)
I can never remember my requests or parameters, so we'll look those up:
$so@"Requests"//Select[StringContainsQ["Question"]]
(*Out:*)
{"AnswerQuestion","LinkedQuestions","MyQuestions","MyTopQuestions","MyTopQuestionTags","NoAnswerQuestions","QuestionAnswers","QuestionComments","Questions","QuestionTimeline","RelatedQuestions","RenderQuestions","UnansweredQuestions","UserQuestions","UserTopQuestions","UserTopQuestionTags"}
$so["RequestParameters", "r"->"QuestionAnswers"]
(*Out:*)
<|"Parameters"->{"id","site","page","pagesize","fromdate","todate","order","min","max","sort","filter","preview"},"Required"->{"site"}|>
Then we pull the question ID off SE:
$qid = 18393;
And finally pull our data, using a filter that returns the `"body_markdown"` field to get the Markdown out:
$filter = "!YOKGPNvvbIpDIehANcVbZ*)Cv2";
ans = $so["QuestionAnswers", "id" -> $qid, "site" -> "Mathematica",
"filter" -> $filter];
Now we can look at one of these bodies:
ans[1, "body_markdown"]//Snippet[#, 5]&
<pre><code>(*Out:*)
##What the @#%^&amp;*?! do all those funny signs mean?##
Questions frequently arise about the meaning of the basic operators, and I hope
it will prove useful to have a sort of index for them. It would be nice to have</code></pre>
Unfortunately HTML elements are baked into this so we'll need to clean out those:
ImportString["", "HTML"];
getmd[ans_, n_] :=
StringReplace[{
ent : ("&#" ~~ NumberString ~~ ";") :>
ImportString[ent, "HTML"],
"\r" -> ""
}]@
Nest[
StringReplace[System`Convert`HTMLImportDump`fromEntities],
ans[n, "body_markdown"],
2
]
We'll also define a post-processing function to insert links where necessary:
ppLinks[tag_, body_]:=
(* Automatic invokes the default post-processor *)
Automatic[tag,
Replace[body,
s_String:>
Sequence@@
StringReplace[
s,
l:("http"~~(Except[WhitespaceCharacter]..)):>
Automatic["Link", {l, StringSplit[l, "//", 2][[2]]}]
],
1]
]
And then we can turn this into a `Notebook` using BTools:
<< BTools`Web`
MarkdownToNotebook[
getmd[ans, 1],
"PostProcessor" -> ppLinks
] // CreateDocument
![post31-3108498676653567781](https://b3m2a1.github.io/img/post31-3108498676653567781.png)
There's maybe a little bit of clean up work to do (say those two `##` ) but it's a very small amount. We can then do with this `Notebook` as we will...in particular we can copy it into a section notebook.
## Making a Book
Once we've gotten enough content ported over we have three options for how to proceed. At this point, we can either make a notebook, a PDF, or a website (or all three). Each of these is also quite straightforward once we have the EasyIDE structure.
###Making a Book Notebook
This distribution mechanism allows us to compile a single Notebook that we can send to our friends and coworkers that they can click through and is chaptered and easily navigable. All we have to do for this is go to our toolbar and hit `Create Book` (if it's been some time since we updated the table of contents we probably want to hit `Create TOC` first). Once we're done we get something like this:
[![https://i.stack.imgur.com/FqHIE.png](https://i.stack.imgur.com/FqHIE.png)](https://youtu.be/drLc4dNo8SI)
###Making a PDF
We can also build a PDF with this. There is a `Create PDF` button provided that does exactly this. Admittedly, this can be a bit finnicky as the front-end can't always export a notebook to a PDF cleanly. On the other hand, this just operates by calling `Export` on the constructed book notebook, so one can always use the system-level `Print... ▸ Save as PDF` mechanism (on Mac at least).
###Making a Website
This is the most heavy-duty but most customizable distribution mechanism. All of the book/tutorial mechanisms are also designed to make it easy to create a website from them. For this we go to `Plugins ▸ SiteBuilder ▸ Build Site` and choose our build settings. I'd turn off `Generate Aggregations` as these pages are not exposed in the default theme. If you modify the theme obviously it makes sense to turn the aggregation pages back on.
After the build we get something like this:
*landing page*
![post31-7698137239929577745](https://b3m2a1.github.io/img/post31-7698137239929577745.png)
*nav menu open*
![post31-4847562609283534597](https://b3m2a1.github.io/img/post31-4847562609283534597.png)
*sample article*
![post31-4404605020778869542](https://b3m2a1.github.io/img/post31-4404605020778869542.png)
And then you can publish it wherever you like. If you'd like an easy place to publish to, I provided some info on something I set up to make that easy [here](https://b3m2a1.github.io/making-a-website-with-easyide.html#wlsitesgithubio) .b3m2a1 2019-04-30T01:33:49ZGet drawing tools in V12.0.0.0?
https://community.wolfram.com/groups/-/m/t/1684985
How to get graphics menu & Drawing tools in mathematica online version 12.0.0.0?CHITHRA Raj2019-05-17T10:52:33ZRemove "Powered by Wolfram Cloud" Footer?
https://community.wolfram.com/groups/-/m/t/1303976
Hello,
I'd like to publish a web page publicly, but the "Powered by Wolfram Cloud" footer is rendered at the bottom of the page.
Is there a way to remove it? In order to do that, do I need a specific type of license?
Thanks,
QuenioQuenio dos Santos2018-03-18T11:25:05ZGet right result with FindIndependentVertexSet[g,{n}] ？
https://community.wolfram.com/groups/-/m/t/1684840
Hi！
I konw the function **FindIndependentVertexSet[g, {n}l]** which
finds an independent vertex set with exactly n vertices. We konw 4- Path graph, every single vertex is its 1- indepent vertex set . but we use the function FindIndependentVertexSet[g, {1}l],it returns empty set {}. **It may return {{1},{2},{3},{4}}.**
The following text give out all of the original code proceedings. it is strange，How to solve it.
path4 = Graph[{{1, 2}, {2, 3}, {3, 4}}, VertexLabels -> All]
FindIndependentVertexSet[path4, {1}, All]
IndependentVertexSetQ[path,{1}]
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=findindepentindex.png&userILicheng Zhang2019-05-17T06:47:13ZWhere is the scrollbar on step-by-step solutions W|A?
https://community.wolfram.com/groups/-/m/t/1559973
I don't know if I'm missing something obvious, but on my tablet I can't scroll when Wolfram Alpha gives me step-by-step solutions. This is consistent across all queries, so I can only ever see the first step. Sorry if this has been asked, but Google is giving me nothing.
![Problem][1]
[1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=Capture.PNG&userId=1559959Jordan M2018-11-26T20:10:17ZMeaning of "[EXPERIMENTAL]"?
https://community.wolfram.com/groups/-/m/t/1670556
Dear all,
the title says it already: With MM v12.0 again we see a wealth of new functions (and to me this always feels a bit like Xmas) . What strikes me is that there seem to be surprisingly many functions qualified as "[EXPERIMENTAL]". What specifically does that mean?
Regard -- HenrikHenrik Schachner2019-04-26T19:01:13ZGet W|A functionality in Mathematica?
https://community.wolfram.com/groups/-/m/t/1684481
Hi All,
If I process the following line in Wolfram Alpha
`t-test mu0=60, xbar=58.5, s=3, n=20`
I get back useful information without reference to the actual sample. Not expecting plots or tables, but is there a way to do something similar in Mathematica?
thanks,
WhiffeeWhiffee Bollenbach2019-05-16T20:38:50ZExport Notebooks to HTML?
https://community.wolfram.com/groups/-/m/t/1684566
Hello,
I'm a newbie in Wolfram Desktop and I am having a hard time finding documentation that shows how to export notebooks to HTML. I was able to export PDFs like like this:
```
nbFile = FileNameJoin[{ $HomeDirectory, "optimization", "production-optimization.nb"}]
nb = Get[nbFile];
pdfFile = FileNameJoin[{ $HomeDirectory, "optimization", "production-optimization.pdf"}]
NotebookPrint[NotebookPut[nb, Visible -> False], pdfFile]
```
But replacing the ".pdf" extension with the ".html" extension does not render the notebook in HTML as I expected; instead, it continues to render a PDF.
I have also tried the Export[] function unsuccessfully.
Any help is appreciated,
QuenioQuenio dos Santos2019-05-16T21:39:40ZUse OutputResponse in WM 12?
https://community.wolfram.com/groups/-/m/t/1684701
Hello
I am trying to simulate a third order system using OutputResponse. Here are the commands I used for the simulation
OutputResponse[TransferFunctionModel[k 1/(s (s + 1)^2 + k), s],
UnitStep[t], t]
Plot[% /. {k -> 1}, {t, 0, 100}]
Almost a copy of the example shown in the help page for OutputResponse.
Problems I have encountered are:
a) WM takes a long time to output the answer. To be honest, I don't remember being that slow when using the same example in WM 11 (Unfortunately I have deleted the old version to give room to the new one).
b) Rather intricate output - Again I don't recall WM 11 using RootSum in this particular problem. It is a third order polynomial.
c) For k=1, the system is stable and the output of Plot is a response of an unstable system. It seems right up to t=20 but after WM 12 loses it completely. Numerical problems?
My plan was to encapsulate the commands above in a manipulate loop for different values of k, but unfortunately I don't see how. I have tried different values of k and the output was not the one expected for any of them.
Any help will be much appreciated.
Ed
Ps. I have tried alternatives such as defining a function resp[t_,k_] with = and := but to no avail.Eduardo Mendes2019-05-16T15:43:32ZRun following simulation with large number of iterations?
https://community.wolfram.com/groups/-/m/t/1682317
When I tried to run the following simulation for say 5 times, it runs successfully but when I tried to run it for 50 or 200 times it never terminates or produces results. I tried to limit the accuracy goal and precision goal in the 'FindDistributionParameters', it did not work. I thought that IntegerQ? needs to be inserted some place in the definition of the distribution very first line. I tried but that did not work either. Thanks.
ClearAll[a0, d0]
ExpoWeibull[sigma_, alpha_, theta_] :=
ProbabilityDistribution[
alpha theta/
sigma (1 - Exp[-(x/sigma)^alpha])^(theta - 1) Exp[-(x/sigma)^
alpha ]*(x/sigma)^(alpha - 1), {x, 0, Infinity},
Assumptions -> sigma > 0 && alpha > 0 && theta > 0];
DistributionParameterAssumptions[ExpoWeibull[sigma, alpha, theta]];
TruncatedEW[sigma_, alpha_, theta_, c_] :=
TruncatedDistribution[{c, \[Infinity]},
ExpoWeibull[sigma, alpha, theta]];
mydata = Sort[RandomVariate[ExpoWeibull[15, 2, 4], 50]];
myp = Values[
FindDistributionParameters[mydata, ExpoWeibull[a0, 2, d0]]];
myLeftCensoredData = Take[mydata, -40];
Table[myinitalParameters =
Values[FindDistributionParameters[mydata, ExpoWeibull[a0, 2, d0]] //
FullSimplify];
myTruncatedData :=
Sort[RandomVariate[
TruncatedDistribution[{0, Min[myLeftCensoredData]},
ExpoWeibull[myinitalParameters[[1]], 2,
myinitalParameters[[2]]]], 10]];
myPseudoCompleteData := Join[myLeftCensoredData, myTruncatedData];
mydata = myPseudoCompleteData;
myinitalParameters, {i, 1, 20}]Nutan Mishra2019-05-13T22:09:00Z