Community RSS Feed
http://community.wolfram.com
RSS Feed for Wolfram Community showing any discussions in tag Graphics and Visualization sorted by activeHow to print indented vertex based on depth from DepthFirstScan?
http://community.wolfram.com/groups/-/m/t/1246810
DepthFirstScan[
{"A" <-> "B", "A" <-> "C", "B" <-> "D", "B" <-> "E", "C" <-> "F", "C" <-> "G"},
"A",
{"PrevisitVertex" -> (Print[#] &)}
];
produces
A
B
D
E
C
F
G
How could one visualize this tree indented by its depth as
A
B
D
E
C
F
G
I am experimenting to visualize our Messaging infrastructure having thousands of vertices. Each vertex is a queue name so printing the graph would need a way to enlarge it to at least paper size A0 or allowing to print it on multiple A3 size papers.
That is why I am experimenting to visualize the graph vertically indented by its depth.
I plan to use specific icons for different components and adding the edges aside colored by its type.
Any help is much appreciated.
Many thanks.
MarkusMarkus Sonderegger2017-12-16T11:42:04ZComputing change in water level via processing of satellite images
http://community.wolfram.com/groups/-/m/t/1232351
Inspired by [Planet's][1] guide on [calculating change in water level][2], I wanted to re-create their visual analysis environment from within the Wolfram Language.
Using the Planet API
====================
The Planet API is easily leveraged from their quickstart python [here][3].
Browsing the [Planet Explorer][4] we can find some cool assets, note their names, and store to variables:
idList = {"20160804_180723_0e26", "20160820_180756_0e30"}; (*id of image*)
itemType = "PSScene4Band"; (*Type of satellite/image *)
assetType = "analytic"; (*analytic = cool multi spectrum image, visual = visible spectrum image*)
path = "images/"; (*where you want to output the images*)
The new `ExternalEvaluate` will allow us to write an easy wrapper to access the APIs functionality:
session=StartExternalSession[<|"System"->"Python","Version"->"2.7.12 :: Anaconda 4.2.0 (x86_64)", "ReturnType"->"String"|>];
(*change working directory and add the api key to the environment*)
ExternalEvaluate[session,"import os; os.chdir('/Users/peter/Downloads')"]
ExternalEvaluate[session,"os.environ['PLANET_API_KEY'] = "~~PersistentValue["PLANETAPIKEY"]]
(*overload an uninitialized global reference*)
ExternalEvaluate[session,
"class dummy:
download = 'downloading images'"]
ExternalEvaluate[session, "args = dummy()"]
(*Load full download script, downloaded from *)
ExternalEvaluate[session,File["/Users/peterro/Downloads/download.py" ]]
convertToJSON[strAr_] := ExportString[strAr,"JSON", "Compact"->True];
inputArgs = <|"idList"->idList,"itemType"-> itemType, "assetType"->assetType |>;
activateArgs = Join[inputArgs,<|"activateOrCheck"->"activate"|>];
checkArgs = Join[inputArgs,<|"activateOrCheck"->"activate"|>];
downloadArgs = Join[inputArgs,<|"path"->path|>];
processActivation = StringTemplate["process_activation(activate, `idList`, `itemType`, `assetType`, `activateOrCheck`)"];
processDownload = StringTemplate["process_download(`path`, `idList`, `itemType`, `assetType`, '')"];
(*activate the assets*)
ExternalEvaluate[session,processActivation[convertToJSON /@ activateArgs]];
obj=SessionSubmit[ScheduledTask[
(*check if the assets are active*)
If[ImportString[Last@StringSplit[ExternalEvaluate[session,processActivation[convertToJSON /@ checkArgs]],"\n"]] != "[True, True]" ,
Module[{},
Print["Assets active, downloading"];
TaskRemove[$CurrentTask];
(*download the assets*)
Print[ExternalEvaluate[session,processDownload[convertToJSON /@ downloadArgs]]];
DeleteObject[session];
Print["Download Complete"];
]
,
Print["Waiting for download: " ~~ DateString[]]
],{10,10}]];
This will asynchronously download the images from the Planet servers when they are prepared for download.
## Process the Images ##
Import:
img820 = ImageResize[First@Import["20160820_180756_0e30_analytic.tif"], Scaled[.4]];
img804 = ImageResize[First@Import["20160804_180723_0e26_analytic.tif"], Scaled[.4]];
![Initial Import][5]
These look weird because we're viewing the stacked {R,G,B,IR} channels. For the purposes of calculating water level change, I wanted to use the IR channel:
infra820 = ImageAdjust[ColorCombine[ColorSeparate[img820][[{4}]]]];
infra804 = ImageAdjust[ColorCombine[ColorSeparate[img804][[{4}]]]];
![IR chan adjusted][6]
Next, we'll binarize the image using thresholds derived from the image histogram:
![img histogram][7]
binarized820 = MorphologicalBinarize[infra820, {0.172, 0.896}];
binarized804 = MorphologicalBinarize[infra804, {0.172, 0.896}];
![binarized][8]
These images are hard to work with because they are rotated and not cropped so we can use some [cool image rotation][9] to correct that
First identify the lines:
lines820=ImageLines[GradientFilter[binarized820,1], MaxFeatures->5];
lines804=ImageLines[GradientFilter[binarized804,1], MaxFeatures->5];
Show[#,ImageSize->Large]&/@ {HighlightImage[binarized820,{Orange,Line/@lines}],HighlightImage[binarized804,{Orange,Line/@lines2}]}
![bin with lines][10]
Rotate and crop:
rotateCrop820 = ColorNegate@ImagePad[ImageCrop[ImageRotate[binarized820,Median[Select[-ArcTan[(#[[2,2]]-#[[1,2]])/(#[[2,1]]-#[[1,1]])]&/@
ImageLines[GradientFilter[binarized820,1]],#<20/360 2 \[Pi]&&#>-20/360 2 \[Pi]&]]]],-20]
![rotated and cropped 820][11]
Next we'll use the overlapping key points to create a comparable area between the two images:
crops= { rotateCrop804,rotateCrop820};
matches = ImageCorrespondingPoints[Sequence@@crops, KeypointStrength->.01] ;
{matches804,matches820} = matches;
Column@MapThread[Show[#1,Graphics[{Blue,MapIndexed[Inset[#2[[1]],#1]& ,#2]}], ImageSize->Large]&,{crops,matches}]
![labels][12]
Use the bounding regions to create the masks:
![bounding region][13]
Tie it all together and measure the change in water level
waterPixels820 = Total@Flatten@ImageData@ImageTrim[rotateCrop820,Round /@ BoundingRegion[matches820] /. Cuboid->List]
waterPixels804 = Total@Flatten@ImageData@ImageTrim[rotateCrop804,Round /@ BoundingRegion[matches804] /. Cuboid->List]
We get **575304** and **597415** meaning the water level decreased by **3.7%** over these days.
[1]: https://www.planet.com/
[2]: https://www.planet.com/docs/guides/quickstart-water_level_change/
[3]: https://www.planet.com/docs/api-quickstart-examples/examples/download.py
[4]: http://https%20:%20//%20www.planet.com/explorer/
[5]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-11-27at7.20.28PM.png&userId=1231150
[6]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-11-27at7.23.59PM.png&userId=1231150
[7]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-11-27at7.25.55PM.png&userId=1231150
[8]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-11-27at7.28.42PM.png&userId=1231150
[9]: https://mathematica.stackexchange.com/questions/152445
[10]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-11-27at7.31.59PM.png&userId=1231150
[11]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-11-27at7.34.30PM.png&userId=1231150
[12]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-11-27at7.39.14PM.png&userId=1231150
[13]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-11-27at7.41.08PM.png&userId=1231150Peter Roberge2017-11-28T03:53:48ZPack NonConvex Curve Into An Ellipse
http://community.wolfram.com/groups/-/m/t/1242150
Set Up Functions Describing Ellipse and Cassini Oval
rule to translate and rotate coordinates
rottransrl[{xc_, yc_, \[Theta]_}, {x_, y_}] =
Thread[{x, y} -> RotationMatrix[-\[Theta]].{x - xc, y - yc}];
function describing an ellipse with axes {a,b}, center {xc,yc} and orientation \[Theta]
ell[{a_, b_}, {xc_, yc_, \[Theta]_}] = (x/a)^2 + (y/b)^2 - 1 /.
rottransrl[{xc, yc, \[Theta]}, {x, y}];
function describing a Cassini oval with axes {a,b}, center {xc,yc} and orientation \[Theta]
oval[{a_, b_}, {xc_, yc_, \[Theta]_}] = ((x - a)^2 + y^2) ((x + a)^2 + y^2) -
b^4 /. rottransrl[{xc, yc, \[Theta]}, {x, y}];
Generate Regions for Elllipse and Cassini Oval
ellipse region with axes {a,b}, center {xc,yc} and orientation \[Theta]
el = ImplicitRegion[ell[{a, b}, {xc, yc, \[Theta]}] <= 0, {x, y}];
Cassini oval region with axes {1,5/4}, centered at {1/7,0} and rotated by \[Pi]/10
ov = ImplicitRegion[oval[{1, 5/4}, {1/7, 0, \[Pi]/10}] <= 0, {x, y}];
Attempt to find smallest area ellipse with oval contained in it, Using RegionWithin and NMinimze
TimeConstrained[
sln = NMinimize[{a*b, RegionWithin[el, ov], a >= 0, b >= 0}, {a, b, xc,
yc, \[Theta]}, Method -> {"NelderMead", "PostProcess" -> False}], 360]
$Aborted
Reformulate Problem Using Lagrange Multipliers
function to generate Lagrange multiplier equations for finding extreme values for function describing curve1 for points on curve2.
curveWithinLagMults[curve1_, curve2_, vars_List] :=
Join[Thread[D[curve1 == \[Lambda]*curve2, {vars}]], {curve2 == 0,
curve1 == r}]
use NSolve to find the solutions to the Lagrange multiplier equations
curveWithinNSolve[curve1_, curve2_, vars_List] :=
NSolve[curveWithinLagMults[curve1, curve2, vars], Join[vars, {\[Lambda], r}],
Reals]
function to find the maximum value of ellipse function for points on the Cassini oval
f[a_?NumericQ, b_?NumericQ, xc_?NumericQ, yc_?NumericQ, \[Theta]_?NumericQ] :=
Max[r /. curveWithinNSolve[ell[{a, b}, {xc, yc, \[Theta]}],
oval[{1, 5/4}, {1/7, 0, \[Pi]/10}], {x, y}]]
find the minimum area ellipse containing the Cassini oval
AbsoluteTiming[
sln = NMinimize[{a*b, f[a, b, xc, yc, \[Theta]] <= 0, a >= 0, b >= 0}, {a, b,
xc, yc, \[Theta]}, Method -> {"NelderMead", "PostProcess" -> False}]]
NMinimize::incst: NMinimize was unable to generate any initial points satisfying the inequality constraints {f[a,b,xc,yc,\[Theta]]<=0}. The initial region specified may not contain any feasible points. Changing the initial region or specifying explicit initial points may provide a better solution.
NMinimize::nosat: Obtained solution does not satisfy the following constraints within Tolerance -> 0.001`: {f[a,b,xc,yc,\[Theta]]<=0}.
{95.9544, {1.61441, {a -> 1.62478, b -> 0.993618, xc -> 0.145382,
yc -> -0.000172813, \[Theta] -> 0.305791}}}
plot the result
p = ContourPlot[{oval[{1, 5/4}, {1/7, 0, \[Pi]/10}] ==
0, (ell[{a, b}, {xc, yc, \[Theta]}] /. sln[[2]]) == 0}, {x, -2,
2}, {y, -2, 2}, ImageSize -> Small];
find the extremum points
pts = curveWithinNSolve[(ell[{a, b}, {xc, yc, \[Theta]}] /. sln[[2]]),
oval[{1, 5/4}, {1/7, 0, \[Pi]/10}], {x, y}]
{{x -> -1.34479, y -> 0.0336357, \[Lambda] -> 0.155498,
r -> -0.0117827}, {x -> 1.63088, y -> -0.0328177, \[Lambda] -> 0.154844,
r -> -0.0186086}, {x -> -0.0933478, y -> 0.711853, \[Lambda] -> 0.324496,
r -> -0.428871}, {x -> 1.6821, y -> 0.433738, \[Lambda] -> 0.121384,
r -> -0.0326298}, {x -> -1.39363, y -> -0.445365, \[Lambda] -> 0.121615,
r -> -0.0267585}, {x -> 0.38161, y -> -0.711032, \[Lambda] -> 0.323676,
r -> -0.431725}, {x -> -1.01925, y -> -0.913277, \[Lambda] -> 0.161002,
r -> 0.00116534}, {x -> 1.29604, y -> 0.91782, \[Lambda] -> 0.162165,
r -> -0.00179309}}
show the result with the extremum points
Show[p, Graphics @ Point[{x, y} /. pts]]
![enter image description here][1]
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=cassini_oval_in_ellipse.jpg&userId=29126Frank Kampas2017-12-09T15:51:13ZFinding the Classifier Boundary Function For Method->LogisticRegression
http://community.wolfram.com/groups/-/m/t/1245216
Here' s a diagram we often see in machine learning. I want to construct something like it using the Wolfram Language and Classify, at least when the method is logistic regression. Here's how I go about it.
![Boundary Drawing][1]
Let' s generate some simple data.
SeedRandom[121217];
trainx = RandomReal[{0, 1}, {20, 2}];
trainy = Map[
If[LogisticSigmoid[{-2.7, 1.4}.# +
RandomVariate[NormalDistribution[0.3, 0.5]]] > 0.5, 1, 0] &,
trainx];
If our classification task does not require much complexity, we can use LogitModelFit and some algebra to find the boundary.
boundaryExpression[fm_FittedModel] :=
y /. Quiet@First@Solve[fm[x, y] == 1/2, y] // Expand;
boundaryExpression[lomf]
We find it is y=-3.69718 + 10.2671 x
We can now visualize the boundary and get a picture like the one above with the following code.
With[{be = boundaryExpression[lomf]},
Show[ListPlot[
KeySort[GroupBy[
MapThread[List, {trainx, trainy}], (ToString[Last[#]] &) ->
First]], PlotMarkers -> {{"-", 18}, {"+", 18}}, Axes -> False,
Frame -> True],
Plot[be, {x, 0, 1}, PlotStyle -> {Thick, Dashed, Black}]]
But all of that is using LogitModelFit. Sometimes we need regularization or other features of Classify. So, here's how we generate a similar picture using Classify.
cl = Classify[trainx -> trainy, Method -> {"LogisticRegression", "L1Regularization" -> 0,
"L2Regularization" -> 0}, TrainingProgressReporting -> None];
We get the probabilities for each class.
ci = ClassifierInformation[cl, "ProbabilitiesFunction"]
This generates a function that produces an Association:
Association[{0 -> (0.0307046 E^(8.58421 #1))/(
0.0307046 E^(0. + 8.58421 #1) + 0.675585 E^(0.836087 #2)),
1 -> 1./(1. + 0.0454489 E^(8.58421 #1 - 0.836087 #2))}] &
We can again use a little algebra to find the boundary.
boundaryExpression[a_Function] :=
y /. Quiet@
First@Simplify[Solve[Equal @@ a[x, y], y, Reals],
x \[Element] Reals];
boundaryExpression[cl_ClassifierFunction] :=
boundaryExpression[
ClassifierInformation[cl, "ProbabilitiesFunction"]]
We can now use this function to make a plot quite similar to the one above.
With[{be = boundaryExpression[cl]},
Show[ListPlot[
KeySort[GroupBy[
MapThread[List, {trainx, trainy}], (ToString[Last[#]] &) ->
First]], PlotMarkers -> {{"-", 18}, {"+", 18}}, Axes -> False,
Frame -> True],
Plot[be, {x, 0, 1}, PlotRange -> {{0, 1}, {0, 1}},
PlotStyle -> {Dashed, Black}]
]
]
Here's another way that does not require use of algebra. Instead we rely on RegionPlot and Ordering.
Show[ListPlot[
KeySort[GroupBy[
MapThread[List, {trainx, trainy}], (ToString[Last[#]] &) ->
First]], PlotMarkers -> {{"-", 18}, {"+", 18}}, Axes -> False,
Frame -> True],
RegionPlot[
Ordering[ci[x, y], -1][[1]] == 1, {x, 0 - 1, 2}, {y, -1, 2},
PlotRange -> {{0, 1}, {0, 1}}, BoundaryStyle -> {Dashed, Black},
PlotStyle -> {Opacity[0], White}]
]
By using RegionPlot we can readily extend the production of boundary diagrams to situations involving more than two classes.
cl3 = Classify[trainx -> trainy2,
Method -> {"LogisticRegression", "L1Regularization" -> 0,
"L2Regularization" -> 0}, TrainingProgressReporting -> None];
ci3 = ClassifierInformation[cl3, "ProbabilitiesFunction"];
c3plot = Show[
ListPlot[KeySort[
GroupBy[MapThread[List, {trainx, trainy2}], (ToString[Last[#]] &) ->
First]], PlotMarkers -> {{"-", 18}, {"+", 18}, {"2", 18}},
Axes -> False, Frame -> True],
RegionPlot[{Ordering[ci3[x, y], -1][[1]] == 1,
Ordering[ci3[x, y], -1][[1]] == 2, Ordering[ci3[x, y], -1][[1]] == 3}, {x,
0 - 1, 2}, {y, -1, 2}, PlotRange -> {{0, 1}, {0, 1}},
BoundaryStyle -> {{Dotted, Black}}, PlotStyle -> {Opacity[0.05]}]
]
![Boundaries with three classes][2]
I attach a notebook that recapitulates this post and adds an animation.
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=classificationboundary.png&userId=20849
[2]: http://community.wolfram.com//c/portal/getImageAttachment?filename=classificationboundary3.png&userId=20849Seth Chandler2017-12-14T15:27:16ZPlot for a solution of the following equation?
http://community.wolfram.com/groups/-/m/t/1244489
I have run a command of Plot for a solution of an equation. However, the graph is always empty. I don't know what's wrong with my code. Could anyone help me to figure it out?
My code is following:
![enter image description here][1]
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=code.jpg&userId=1232269Tim Zhang2017-12-12T23:57:12Z[✓] Get plot with just axes crossing at the origin?
http://community.wolfram.com/groups/-/m/t/1242000
Hi, when I plot (3D) a 2 variable scalar function in wolfram Mathemática I always get the function in a box formed by the axis. How could I get rid of that box and just see the surface I´m plotting and the three ortogonal axis crossing at the origin??Victor Gutierrez2017-12-09T11:01:10ZI’m okay with making name tags with Mathematica
http://community.wolfram.com/groups/-/m/t/1244333
*This post was originally published at [Ultimaker][1].*
----------
Pioneer Chris Hanusa led a Mathematica and 3D printing workshop where he shared resources to help attendees get up and running with the program and 3D printing. At the end of the information-rich workshop, attendees learned how to to use Mathematica to create several 3D printable objects, including name tags.
In October, at my invitation, Assistant Professor Chris Hanusa of the Math Department at Queens College led an Introduction to 3D printing with Mathematica workshop for educators at [NYU’s ITP][2] in New York City. Chris is a mathematician and a designer who creates beautiful objects inspired by math (you can see his work on his website [hanusadesign][3]). Chris creates his objects and shares the math behind them on his site. He has also written several tutorials on his [blog mathzorro.com][4] about how to use Mathematica to create 3D objects. There is a great deal to learn about Mathematica before one can start designing printable 3D objects, and during the workshop Chris worked to provide the attendees with enough information to be just a little bit dangerous. Without a question, Mathematica is the kind of application that one needs to see in action, and then spend quite a bit of time with processing the information and doing further exploration on one’s own.
Chris’s teaching style encourages independence. He shows his college students how to rely on Mathematica’s extensive documentation, and he provides well-scaffolded tutorials to follow so that his students develop their understanding and confidence.
[Mathematica][5] is not a CAD package, nor was it created with 3D printing in mind. However, one can use Mathematica’s programing language to create printable 3D objects, basically watertight, mesh files and export them as STLs or OBJs. Like other programming languages (Processing, Openscad, OpenGL) that can create 3D objects with code, you don’t have the ability to drag and drop shapes. Basically, you create statements that generate nodes or vertices in 3D space. By specifying coordinates, you can then apply rotate, scale and translate transformations. You can use parametric curves, vector functions, and trigonometry to create your geometric objects. Remember when you asked in Trig class "When will ever use this?" Well, you’ll use your trig in Mathematica to create 3D printable objects. Math class would have been very different for me if I had access to both Mathematica and 3D printing back when I was in high school.
What I like about Mathematica (and Processing and OpenSCAD) is the algorithmic approach to generating objects. While Processing uses a sketch metaphor and OpenSCAD employs an editing window, Mathematica uses notebooks. For each of these options, programmers start with a general idea of a task for their computers to perform. Programmers then flesh out their general ideas into complete, unambiguous, step-by-step procedures to carry out their tasks. Such procedures are called algorithms. An algorithm is not the same thing as a program. A program is written in some particular programming language, like C, Java, Python, or the Wolfram Language. An algorithm is more like the idea behind the program. An algorithm can be expressed in any language, including English.
When you know what you want your program to do, many programmers find it helpful to write a description of the task or tasks. That description can then be used as an outline for their algorithm. As a programmer refines and elaborates on their description, gradually adding more details, they eventually end up with a complete algorithm that can be translated directly into a programming language. This method is called stepwise refinement, and it is a type of top-down design. As you proceed through the stages of stepwise refinement, you write out descriptions of your algorithm in pseudo-code, the informal instructions that imitate the structure of your program without complete details or the perfect syntax of actual code. Pseudo-code is where you figure out what kinds of data your program needs and what kind of data it returns. This is also the step where you think about the best way to solve the problems that you're going to run into during the project, and to you get to figure out solutions to try before even starting to write code.
Think of programming as a process of logical problem-solving. Your two big challenges are a) learning the syntax, and b) applying your logical problem-solving skills to an unfamiliar domain. When I taught programming at [Saint Ann’s School][6] in Brooklyn, NY, I told my students who were learning a new language to break things down into four areas:
- Code-reading—be able to look at code and figure out what it’s doing. Code-reading means two things:
- Being able to understand what a particular line of code is doing -
understanding the syntax of the program.
- It also means understanding something called the control flow of the program: when the program executes a line of code, what will it execute next?
- Pseudo-code—This is where you do a lot of thinking and not a lot of
writing code. Because most projects start with a vague idea, or an
English description, this step helps turn your project into something
that is approachable as a program. It forces you to define and
explain what you're trying to do very precisely.
- Code-writing—It can be intimidating to try and figure out how to
express what you're trying to do with an unfamiliar syntax of a
programming language. However, if you've done a good job with the
pseudo-code, writing your code should be in some ways the simplest
step. You’re performing a translation from the precise and clear
concepts you've figured out to the syntax of the programming language
in question. As you write the code, you'll figure out some issues
that your original design or pseudo-code didn't address. You'll
improvise, double back, and sometimes change your entire design. But
the more you separate the simple writing of code from the hard work
of figuring out what you want the code to do, the happier you will be
in the long run.
- Debugging—This is the process of testing and fixing the problems in a
program that you've already written. Unfortunately, this is the step
that will generally take most of your time. While occasionally you
will be able to write a program that's bug-free, generally your
program will either not work immediately or it will do something
completely unexpected. Learning techniques for figuring out what's
wrong (and even more important, solving the problem) is important.
The more code you write and the longer your programs become, the
harder problems become to track down and deal with.
Start small, modify, test and build incrementally. When you work in Mathematica, instead of modifying code that works, make a copy and modify the copy. This way you’ll have a record of what you started with that you can always return to at a later date.
Mathematica is also capable of nested commands. But ease into this. Until you know how each command works (what information a command takes and what it returns) you may want to consider separating the commands out. As you become more experienced, nest away with confidence.
During the workshop, Chris pointed out a few things that were helpful to keep in mind:
- Mathematica is case sensitive.
- All built-in Mathematica functions are spelled, capitalized, and
follow CamelCase rules.
- It is important to distinguish between parentheses (), brackets [],
and braces {}: Parentheses (): Used to group mathematical
expressions, such as (3+4)/(5+7). Brackets []: Used when calling
functions, such as N[Pi]. Braces {}: Used when making lists, such as
{i,1,20}.
- To calculate an expression, use Shift-Return.
- To find the options of a given function, highlight it in the notebook
and then press Command+Shift+F.
- A semicolon can be used to suppress output.
- Mathematica has four types of equals: =, ==, :=, and ===.
- Assignment: To define a variable to store it in memory, use =. For example, to define z to be 3, write z=3.
- Test for equality: Use == to check for equality. For example, 1-1==0 will evaluate to True and 1==0 will evaluate to False.
- Set Delay: Use := when you want to evaluate the function when it is called rather than when it is assigned . (This is advanced.)
- SameQ: Use === to test whether two expressions are identically the same.
- Adding comments to your notebook will help you remember what your intentions were when you look back on your notebook months later. Comments are also invaluable for other people who are navigating through your notebook. To write a sentence, create a new text cell by clicking below a cell. When the cursor turns horizontal type Option-7, or right click and navigate to Insert New Cell > Text.
- Use the documentation. If you are having trouble with a certain
function, use the ? command to ask for help. For example enter ?
Table and the output will be a yellow box with a quick synopsis of
the command. For more detailed information, click the blue >> at the
bottom right of this yellow box. This will open the Documentation
Center which gives examples of using the command in action, available
options for this command, and anything else you might want to know
about the command.
The following three statements represent a sphere, a cuboid and a cone:
Sphere[{0, 0, 0}, .28]
Cuboid[{-.05, -.05, .26}, {.05, .05, .35}]
Cone[{{0, 0, 0}, {0, 0, -1}}, .3]
You can also combine them using a list
Graphics3D[{
Sphere[{0, 0, 0}, .28],
Cuboid[{-.05, -.05, .26}, {.05, .05, .35}],
Cone[{{0, 0, 0}, {0, 0, -1}}, .3]
}]
They are combined, but if you press Shift Return, I suspect you may not get what you expect.
In order to see all the objects combined you have to pass these objects from Graphics3D[] to Show[]:
sphere = Graphics3D[Sphere[{0, 0, 0}, .28]]
cuboid = Graphics3D[Cuboid[{-.05, -.05, .26}, {.05, .05, .35}]]
cone = Graphics3D[Cone[{{0, 0, 0}, {0, 0, -1}}, .3]]
Show[sphere, cuboid, cone]
Like other programming languages, there's often more than one way to do do the same thing:
shapes = {
Sphere[{0, 0, 0}, .28],
Cuboid[{-.05, -.05, .26}, {.05, .05, .35}],
Cone[{{0, 0, 0}, {0, 0, -1}}, .3]}
Map[Graphics3D, shapes]
Show[Map[Graphics3D, shapes]]
Graphics3D[Table[Sphere[{i, 0, 0}, .2], {i, 0, 10}]]
To get the workshop attendees started, Chris created a [Mathematica Basics Crash Course][7] and a [3D Graphics in Mathematica][8] notebook.
If you're new to Mathematica, open Chris’s notebooks and execute each command by placing your cursor at the end of the line and pressing Shift+RETURN. Not everything will make sense right away, and that’s okay. Mathematica is packed with information and functionality. At the beginning just try to appreciate what it is doing, and then marvel at what might be possible when you have more experience.
Mathematica has a large number (195) of built-in polyhedra that you can create, export and print. They are accessible using the command PolyhedronData[]. How do I know how many polyhedra Mathematica can represent? Execute the following statement:
Length[PolyhedronData[All]]
To find out the properties associated with PolyheronData[] execute the following command:
PolyhedronData["Properties"]
And here is a handy statement to explore all the polyhedra:
Manipulate[
Column[{PolyhedronData[g], PolyhedronData[g, p]}], {g,
PolyhedronData[All]}, {p,
Complement @@ PolyhedronData /@ {"Properties", "Classes"}}]
Here how to create a 3D object that you can see and then export:
myShape = Graphics3D[PolyhedronData["Icosahedron", "Faces"]]
![enter image description here][9]
Save your notebook. Then to export the object as an STL file :
Export[NotebookDirectory[] <> "myFile.stl", myShape]
And then to see the STL:
Import[NotebookDirectory[] <> "myFile.stl"]
#Back to name tags#
Name tags or nameplates often seem to me to be the Hello World of 3D printing. They are generally pretty simple to create with a CAD package and they provide an easy introduction to 3D space. There is nothing inherently wrong with creating name tags or nameplates, but I think 3D printing is capable of so much more, and I try to advocate for finding the real potential for 3D printing in education. Yet here I am, encouraging you to use Mathematica to create a name tag. Why? Because I think it is helpful to start off with a familiar object in an unfamiliar context. Remember, Mathematica won’t let you click and drag. You are going to have to build a name tag from the ground up, and in the process, you’re going to become familiar with some of Mathematica’s mesh commands.
At it’s simplest, to make a name tag, you’re going to need a base and then a top. Remember that an STL file is a watertight mesh. That means that where the base and the top meet you will need to eliminate the top surface on the base and the bottom surface of the top. Let’s start with some text:
Text[Style["Ultimaker", Bold, FontFamily -> "Futura", FontSize -> 50]]
![enter image description here][10]
You now need to convert this text to a 2D mesh. To do that you use the command DiscretizeGraphics[]:
meshText2d = DiscretizeGraphics[
Text[Style["Ultimaker", Bold, FontFamily -> "Futura",
FontSize -> 50]], _Text]
![enter image description here][11]
To make the 2D mesh 3D use RegionProduct[] with the mesh and a vertical line:
RegionProduct[meshText2d, Line[{{0.}, {5.}}]]
![enter image description here][12]
Next you’ll create a 2D mesh of a polygon to act as the base:
base = DiscretizeGraphics[Graphics[{RegularPolygon[8]}]]
![enter image description here][13]
To see the two meshes together:
Show[{RegionResize[base, 1.3], RegionResize[meshText2d, 1]}]
![enter image description here][14]
Next you need to remove the surfaces where the two meshes intersect (RegionDifference[]) and make the base big enough to support the text (RegionResize[]):
polygon = RegionResize[base, 1.3];
text = RegionResize[meshText2d, 1];
intersection = RegionDifference[polygon, text]
![enter image description here][15]
Now you need to create boundaries from the two regions so that you can create walls:
bdrypolygon = RegionBoundary[polygon]
bdrytext = RegionBoundary[text]
![enter image description here][16]
![enter image description here][17]
Now you need to build the actual mesh. You’ll need to create 3 levels: the floor, the top of the base and the top of the text (You must use a floating point number):
level0 = 0.;
level1 = 0.1;
level2 = 0.15;
Now it’s time to put all the parts together:
Show[{
RegionProduct[polygon, Point[{{level0}}]],
RegionProduct[bdrypolygon, Line[{{level0}, {level1}}]],
RegionProduct[intersection, Point[{{level1}}]],
RegionProduct[bdrytext, Line[{{level1}, {level2}}]],
RegionProduct[text, Point[{{level2}}]]
}]
![enter image description here][18]
Export and Import. You can use the % as shorthand for the last thing you created:
Export[NotebookDirectory[] <> "nametag.stl", %]
Import[NotebookDirectory[] <> "nametag.stl"]
![enter image description here][19]
If the export doesn’t work, it could be that your notebook hasn’t been saved yet. Save the notebook, then export and import.
But what if you want to use a logo instead of text? No problem. Start with an image, convert it to a 2D mesh, resize it, convert to 3D, create a base, eliminate the surface where the meshes intersect, create boundaries, establish level values, and then put them all together.
Find a black and white image online, copy it, and then create a variable to hold it. Use the semicolon to suppress the output:
![enter image description here][20]
To convert a bitmap to a mesh first negate the color then use ImageMesh[] instead of DiscretizeGraphics[]:
catMesh=ImageMesh[ColorNegate[cat]]
![enter image description here][21]
Next, you need to scale the image:
scaledCat = RegionResize[catMesh, {{-.8, .8}, {-.6, .6}}]
![enter image description here][22]
Lets use a disk for the base. You’ll need to convert it to a mesh and make it slightly larger than 1 unit. (Remember you just scaled your image to be slightly smaller than the unit length:
base = DiscretizeGraphics[Graphics[{Disk[{0, 0}, 1.1]}]]
![enter image description here][23]
Let’s make a hole in the base:
hole = DiscretizeGraphics[Graphics[{Disk[{0, .9}, .1]}]]
To make sure everything fits:
Show[{base, hole, scaledCat}, PlotRange -> All]
![enter image description here][24]
Let’s first make the hole in the base:
base = RegionDifference[base, hole]
![enter image description here][25]
Now find the intersection:
intersection=RegionDifference[base, scaledCat]
![enter image description here][26]
Now you need to get the boundary of the 2D mesh:
bdryCat = RegionBoundary[scaledCat]
bdryBase = RegionBoundary[base]
![enter image description here][27]
![enter image description here][28]
Create the levels:
level0 = 0.;
level1 = 0.15;
level2 = 0.25;
And now to put it all together:
Show[{
RegionProduct[base, Point[{{level0}}]],
RegionProduct[bdryBase, Line[{{level0}, {level1}}]],
RegionProduct[intersection, Point[{{level1}}]],
RegionProduct[bdryCat, Line[{{level1}, {level2}}]],
RegionProduct[scaledCat, Point[{{level2}}]]
}]
![enter image description here][29]
Export and print!
There you have it: a name tag in Mathematica. Not only did you get to learn a little about Mathematica, but you also got to see how meshes from two shapes are constructed. Where does Mathematica and 3D printing fit in the curriculum? Math class is an obvious answer, but it’s also well suited for a programming class, and with access to computers, patience and time, why not bring Mathematica and 3D printing to the art studio?
Here’s a challenge: Try [Mathematica][30] for 15 days and see what you can do with it. Upload your 3D models to [Youmagine][31] and tag them #MathematicaAnd3DPrinting.
[1]: https://ultimaker.com/en/blog/51553-im-okay-with-making-name-tags-with-mathematica
[2]: https://tisch.nyu.edu/itp
[3]: http://hanusadesign.com/
[4]: http://blog.mathzorro.com/
[5]: https://www.wolfram.com/mathematica/
[6]: http://saintannsny.org/
[7]: https://qcpages.qc.cuny.edu/~chanusa/mathematica/Basics.nb
[8]: https://qcpages.qc.cuny.edu/~chanusa/mathematica/GraphicsObjects.nb
[9]: http://community.wolfram.com//c/portal/getImageAttachment?filename=2084polyhedra.png&userId=20103
[10]: http://community.wolfram.com//c/portal/getImageAttachment?filename=text.png&userId=20103
[11]: http://community.wolfram.com//c/portal/getImageAttachment?filename=01_mathematica_text.png&userId=20103
[12]: http://community.wolfram.com//c/portal/getImageAttachment?filename=02_mathematica_3D.png&userId=20103
[13]: http://community.wolfram.com//c/portal/getImageAttachment?filename=312203_polygon.png&userId=20103
[14]: http://community.wolfram.com//c/portal/getImageAttachment?filename=713504_base_text_together.png&userId=20103
[15]: http://community.wolfram.com//c/portal/getImageAttachment?filename=672905_intersection.png&userId=20103
[16]: http://community.wolfram.com//c/portal/getImageAttachment?filename=326906_boundary_base.png&userId=20103
[17]: http://community.wolfram.com//c/portal/getImageAttachment?filename=943207_boundary_text.png&userId=20103
[18]: http://community.wolfram.com//c/portal/getImageAttachment?filename=08_mesh.png&userId=20103
[19]: http://community.wolfram.com//c/portal/getImageAttachment?filename=09_stl.png&userId=20103
[20]: http://community.wolfram.com//c/portal/getImageAttachment?filename=10_cat.png&userId=20103
[21]: http://community.wolfram.com//c/portal/getImageAttachment?filename=11_remove_color.png&userId=20103
[22]: http://community.wolfram.com//c/portal/getImageAttachment?filename=12_resize.png&userId=20103
[23]: http://community.wolfram.com//c/portal/getImageAttachment?filename=488713_base.png&userId=20103
[24]: http://community.wolfram.com//c/portal/getImageAttachment?filename=14_show.png&userId=20103
[25]: http://community.wolfram.com//c/portal/getImageAttachment?filename=719215_hole.png&userId=20103
[26]: http://community.wolfram.com//c/portal/getImageAttachment?filename=16_intersection.png&userId=20103
[27]: http://community.wolfram.com//c/portal/getImageAttachment?filename=735417_boundary_cat.png&userId=20103
[28]: http://community.wolfram.com//c/portal/getImageAttachment?filename=668918_boundary_base.png&userId=20103
[29]: http://community.wolfram.com//c/portal/getImageAttachment?filename=19_mesh.png&userId=20103
[30]: https://www.wolfram.com/mathematica/trial/
[31]: http://youmagine.com/Lizabeth Arum2017-12-12T18:51:20ZFind intersection points of lines using ListPlot?
http://community.wolfram.com/groups/-/m/t/1242003
Hello, I am trying to find the intersection points of the two horizontal solid lined with the dashed line. I would like to label each point as for example point a and the second point as b. I would also like to display the value of the intersecting point. Note that I am aiming to find the x value of the intersecting point since I know y. I find it easier with function and using Plot function. I tried with this one but it didn't work.
Thank you
list1 = {0, 1};
list2 = {0, 5};
ListLinePlot[Transpose[{list1, list2}], PlotStyle -> {Thick, Dashed},
PlotRange -> {{0, 5}, {0, 5}},
GridLines -> {None, {{2, {Black, Thick}}, {4, {Green, Thick}}}}]Joeseph A2017-12-08T18:27:16ZBSplineFunction not evaluating as expected in RevolutionPlot3D?
http://community.wolfram.com/groups/-/m/t/1242827
Hello,
Why does the code (shown below) give this error?
> Dot::rect: Nonrectangular tensor encountered.
And how might this code be modified to produce the desired plot?
controlPoints = {{0., 1.48195}, {0.151384, 1.49651}, {0.330883, 1.39382}, {0.488076, 1.2461}, {0.575162, 1.06331}, {0.599079, 0.886118}, {0.547864,
0.698224}, {0.46997, 0.542705}, {0.386957, 0.404801}, {0.285357, 0.28673}, {0.314028, -0.0307762}, {0.202299, -0.0181826}, {0., 0.}};
RevolutionPlot3D[BSplineFunction[controlPoints][t], {t, 0, 1}]Rian Shams2017-12-11T04:51:43Z[GIF] Lean In
http://community.wolfram.com/groups/-/m/t/1242836
![Spheres in projective space][1]
_Lean In_
A similar idea to [_Fall Out_][2], one dimension up. Now I have a 2-sphere in the 3-sphere which I map to 3-space by extending the line containing a point until it intersects the $w=1$ hyperplane, then inverting in the unit sphere and reflecting through the origin.
The underlying object is just the standard equatorial 2-sphere $(x,y,z,0)$ with $x^2+y^2+z^2=1$, which then gets rotated by $\pi/4$ in the plane spanned by $\cos s (0,0,1,0) + \sin s (1,0,0,0)$ and $(0,0,0,1)$ as $s$ varies from $0$ to $2\pi$.
Here's the code:
inversion[p_] := p/Norm[p]^2;
With[{n = 50, m = 31, d = .01,
cols = Darker[RGBColor[#]] & /@ {"#43DDE6", "#FC5185", "#364F6B"}},
Manipulate[
Graphics3D[
{Sphere[#, .02] & /@
Flatten[
Table[
i * inversion[#1[[1 ;; -2]]/#1[[-1]]] &[
RotationMatrix[π/4, {Cos[s] {0, 0, 1, 0} + Sin[s] {1, 0, 0, 0}, {0, 0, 0, 1}}]
.{Sqrt[1 - z^2] Cos[θ], Sqrt[1 - z^2] Sin[θ], z, 0}],
{i, {-1, 1}}, {θ, 0., 2 π - 2 π/n,
2 π/n}, {z, -1., 1, 2/m}], 2]},
PlotRange -> 1.2, Boxed -> False, ViewPoint -> {0, 5, 0},
ImageSize -> 540, Background -> cols[[-1]],
Lighting -> {{"Point", cols[[1]], 1/2 {Sin[s], 0, Cos[s]}},
{"Point", cols[[2]], 1/2 {-Sin[s], 0, -Cos[s]}}, {"Ambient", cols[[-1]], {0, 5, 0}}}],
{s, 0, 2 π}]
]
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=projective5gc.gif&userId=610054
[2]: http://community.wolfram.com/groups/-/m/t/1239487Clayton Shonkwiler2017-12-11T05:12:17ZEdge detect code gives different outputs
http://community.wolfram.com/groups/-/m/t/1242353
I have often noticed that examples of the past when done in newer versions of Mathematica generate inconsistent results. A prime example related to the following post (Character edge finding):
pic = Thinning@Binarize[GradientFilter[Rasterize[Style["\[Euro]",
FontFamily -> "Times"], ImageSize -> 200] // Image, 1]];
pdata = Position[ImageData[pic], 1];
lcp = ListCurvePathPlot[pdata];
This simple piece of code gives different results in Mathematica 9.0, 10.4 and 11.2 with default options. I have posted the results on StackExchange
(click the [link][1] to see).
Note: this is not the only example where I have seen differences.
**To the WRI quality assurance department**:
Can you kindly check why similar functions do not behave the same across different versions ?? I think it is more crucial to establish whether
the built-in functions are working properly rather than releasing more and more functions without appropriate checks.
[1]: https://mathematica.stackexchange.com/questions/161667Ali Hashmi2017-12-09T19:32:04Z[✓] Plot for numerical integration?
http://community.wolfram.com/groups/-/m/t/1240835
How can I plot a graph and interval table for the following function?
NIntegrate[0.00159155/(x^2 + 0.000025^2), {x, -10, 10, 0.2}, Method ->
{"MultiPanelRule", Method -> {"TrapezoidalRule", "Points" -> 2, "RombergQuadrature" -> False},
"Panels" -> 50}, MaxRecursion -> 0] // QuietMujtaba Mozumder2017-12-06T13:19:59Z