Community RSS Feed
http://community.wolfram.com
RSS Feed for Wolfram Community showing any discussions from all groups sorted by activeIndividually apply functions in a list to the same arguments, & list the re
http://community.wolfram.com/groups/-/m/t/1358253
This does what I want:
In[688]:= #[x] & /@ {f, g}
Out[688]= {f[x], g[x]}
but is there a better way, maybe a native function particularly for this purpose? Or some pattern tricks I haven't thought of?Joe Donaldson2018-06-18T23:55:30ZHow to run a code multiple times and each time it returns a value
http://community.wolfram.com/groups/-/m/t/1357962
Hello,
I have a code that I want to run multiple times. In Matlab, I can enclose the code within a function and call the function every time I want to run the code. In each iteration, I should pass multiple values to the variables within the code and then the code runs and return multiple values. I wonder if this can be done in mathematica.
Thank youmohamed alzenad2018-06-18T22:54:23ZSemicolon-Separated Expression-Sequences: How to Control Formatting?
http://community.wolfram.com/groups/-/m/t/1357032
Here is an illustration of what I mean by semicolon-separated expression-sequence:
x1 = 0; x2 = 3; x3 = 1;
When using the notebook interface to edit my code, sometimes Mathematica allows me to sequence expressions on a single line as illustrated above, but other times Mathematica forces each expression onto its own separate line. How Mathematica decides when to force the line-breaking is obscure to me (if it is documented, I have not found where), and so Mathematica's behavior in this respect appears random and surprises me when I'm not trying to be surprised by my editor. Is it predictable? Is it controllable?Joe Donaldson2018-06-17T05:00:49ZControl a replacement step in any step and get the number of steps?
http://community.wolfram.com/groups/-/m/t/1342594
Given the following sets with names
s1={x1,x2}
x1={y1,y2}
y1 ={z1,z2}
When s1 is entered, the names would be replaced finally by all the sets. That is
Input s1
output::{{{z1,z2},y2},x2}
Question1: could we control a replacement step in any step? For example, we get
{{y1,y2},x2} so that y1 is not replaced?
Question2:: could we get the number of the replacement step, for example,to know, at step 2, we get {{y1,y2},x2}?Math Logic2018-05-21T20:20:58ZPool Noodle Spikey
http://community.wolfram.com/groups/-/m/t/1356464
I made a [compound of 5 tetrahedra](http://mathworld.wolfram.com/Tetrahedron5-Compound.html). It's surprisingly sturdy.
![noodle spikey][1]
This was built with [pool noodles](https://www.amazon.com/dp/B01BY1S2US/). Noodles are 55" (about 4.5 feet) long with a 2 3/8" diameter. Cut in half these give a Length/Diameter ratio of 11.5789. How close is that to a perfect Length/Diameter ratio?
![pool noodles][2]
First, lets build up a dodecahedron with simple vertices and an edge length of 1.23607 or $\sqrt5-1$.
From that dodecahedron, find the ten tetrahedra with edge length $2 \sqrt2 $ .
Then find five disjoint tetrahedra. The following code works.
tup=Tuples[{1,-1},{3}];
gold=Table[RotateRight[{0, \[Phi], 1/\[Phi]},n],{n,0,2}];
dodec=RootReduce[Union[Join[tup,Flatten[Table[gold[[n]] tup[[m]],{n,1,3},{m,1,8}],1]]]/.\[Phi]-> GoldenRatio];
tetra=FindClique[Graph[#[[1]]\[UndirectedEdge]#[[2]]&/@Select[Subsets[dodec,{2}],Chop[2 Sqrt[2]-EuclideanDistance@@N[#]]==0&]],{4},All];
compounds=FindClique[Graph[#[[1]]\[UndirectedEdge]#[[2]]&/@Select[Subsets[tetra,{2}],Length[Intersection[#[[1]],#[[2]]]]==0&]],{5},All];
Manipulate[Graphics3D[{
Table[{{Yellow,Red,Green,Purple,Blue}[[n]],Tube[#,thickness]&/@Subsets[compounds[[1,n]],{2}]},{n,1,k}],
Table[{{Yellow,Red,Green,Purple,Blue}[[n]],Sphere[#,thickness 2 ]&/@compounds[[1,n]]},{n,1,k}]}, Boxed-> False, SphericalRegion->True,
ViewAngle-> Pi/10, ImageSize-> 650],
Row[{Control@{{k,5, "number shown"},1,5,1, ControlType->Setter },Spacer[15],
Control@{{thickness,.11, "thickness"},.08,.20,.01, Appearance-> "Labeled" }}], SaveDefinitions->True]
![Manipulate 5 tetrahedra][3]
The "perfect" Length/Diameter ratio for rigid tubes seems to be 11.8565. The half-noodle ratio is 11.5789. Since foam is forgiving, I figured that would give a tighter figure, and that turned out to be correct.
For a regular dodecahedron with edge length 1, the inradius and circumradius are 1.11351 and 1.40125.
For an edge length of 1.23607, the inradius and circumradius are 1.37638 and 1.73204.
Based on the sizes of the tetrahedra, we can find the scaling factor of 11.4021.
Height in inches is about 31 inches tall. Distance between vertices is about 14 inches.
The notebook also has a color template. And that's how to build a spikey from pool noodles.
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=noodle5tetra.png&userId=21530
[2]: http://community.wolfram.com//c/portal/getImageAttachment?filename=noodles.png&userId=21530
[3]: http://community.wolfram.com//c/portal/getImageAttachment?filename=manipulate5tetra.png&userId=21530Ed Pegg2018-06-15T19:42:04ZImplement Mathematica in Mathematica
http://community.wolfram.com/groups/-/m/t/1357709
Has anyone written Mathematica code simulating the Mathematica evaluation process (or at least some of its basics)? A Mathematica emulator (not the heavy math stuff like integration and reduce), written Mathematica, but using a small subset of Mathematica's functions? I hope one of you thinks it is fun, because it would be far beyond my ability, but the results would at least be helpful to new users trying to understand what Mathematica does. Once you learned said small subset of functions, you could understand the emulator's code; and once you understood the emulator's code, you would understand Mathematica. I cannot pay though, so I hope this sounds fun.Joe Donaldson2018-06-17T22:41:37ZIs Defer[] like single-quote from LISP?
http://community.wolfram.com/groups/-/m/t/1355524
I have been looking for something like LISP's single-quote. Is Defer[] it?Joe Donaldson2018-06-13T19:37:49ZPlot a wave in 3d
http://community.wolfram.com/groups/-/m/t/1357311
Hello
I wish to plot the following field, in the x-y-z space:
![enter image description here][1]
It is the electric field component of an electromagnetic wave travleing in the positive x-direction.
I came [across this question][2] form Mathematica stackexchange which has a few solution to plot the very-familiar EM wave, but I am interested in this rather different field, and only in the electric field.
I am not familiar with `Module`, but familiar with `Plot3D` and `ParametricPlot3D` only up to the level seen in the Documentation.
Thanks in advance for any "simple way" suggestions.
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=1588png.latex.png&userId=1344988
[2]: https://mathematica.stackexchange.com/questions/1987/how-do-i-plot-a-plane-em-waveUdi Behar2018-06-17T17:52:58ZUpdate notebook after I changed a variable?
http://community.wolfram.com/groups/-/m/t/1357794
Hello =)
i just started with Mathematica and comming from MathCAD becouse of its poor functionality in higher math.
Now i created a new Spreadsheet and was just trying around with some functions and variables.
Becouse I want to make some big calculations, I must have the possibility to sometimes changes some variables/functions at the start. Therefore i need the option to update my whole spreadsheet with these changes, without reenter alle the later commands.
Greetings =)ha bla2018-06-18T09:42:09ZPlot a function within a circle, e.g. stresses within a loaded disk?
http://community.wolfram.com/groups/-/m/t/1356287
I wonder if anyone knows how to plot results within a circle, e.g. stresses and strains within a loaded disc?jiri havir2018-06-15T13:19:38ZDelete cases using a "Complement" that accounts for multiplicities?
http://community.wolfram.com/groups/-/m/t/1357207
Hi, I have cats, fish and dogs.
In[173]:= animals = {cat, dog , fish, dog, cat}
Out[173]= {cat, dog, fish, dog, cat}
I want to take out the fish.
In[174]:= Complement[animals, {fish}]
Out[174]= {cat, dog}
Unfortunately Mathamatica killed one of my cat and one of my dog. I want a result that looks like:
Out[173]= {cat, dog, dog, cat}
or if Mathematica really wants to sort it, then:
Out[173]= {cat, cat, dog, dog}
How can I do it and make it fast?
Thanks ahead, János
P.S. The documentation says only that the result is sorted.smile sung2018-06-17T16:07:24ZExport strings without quotes to a .csv?
http://community.wolfram.com/groups/-/m/t/1357082
Writing a file from Mathematica for use by another program.
The output file will be a comma separated file.
Content of the file will be a combination of numbers and text.
The text in the output file should **not** have quotes around it.
Below is a sample data set and what I have tried so far.
row0 = {"h1", "h2", "h3", "h4", "h5", "h6"};
row1 = {"", "", "a1", 1.01, "", ""};
row2 = {"", "", "b1", 2.02, "", ""};
row3 = {"", "", "c1", 3.03, "", ""};
data = {row0, row1, row2, row3};
Export["data.csv", data];
Export["data.txt", data];
Export["data.dat", data];
Export["data.tsv", data];
Export["data.xls", data];
A summary of the results:
- data.csv -- has quotes around the strings
- data.txt -- has quotes around the strings and curly braces around each line
- data.dat -- no quotes around the strings, but the data is separated by tabs
- data.tsv -- has quotes around the strings
- data.xls -- no quotes around strings, data in appropriate columns, but this is an Excel file, which can't be read by the other program.
**One successful work-around:**: save the files as data.xls, then from Excel export to a .csv
Is there a way to Export the data so that it does not have quotes around the strings, but is separated by commas?
(Follow-up question: how to include quotes in some of the exported text. The Excel workaround fails for this case.)Robert McHugh2018-06-17T16:03:25ZReplacing a functions and variables
http://community.wolfram.com/groups/-/m/t/1356010
Say I have $f(x,y) + \partial_x f(x,y)$ e.g.
fun = f[x,y] + D[f[x,y],x]
I would like to use the substitution $f(x,y) \rightarrow \delta^2g(\delta x, \delta y)$ to get a new function. I have tried various things such as
fun /. {f[x, y] -> \[Delta]^2 g[\[Delta] x, \[Delta]y]}
fun /. {f -> \[Delta]^2 g}
fun /. {{f -> \[Delta]^2 g}, {x -> \[Delta] x}, {y -> \[Delta] y}}
fun /. {{f[x, y] -> \[Delta]^2 g[\[Delta] x, \[Delta]y]}, {D[f[x, y],
x] -> D[\[Delta]^2 g[\[Delta] x, \[Delta] y], x]}}
none of which produce the desired output of $\delta^2g(\delta x, \delta y) + \delta^3\partial_xg(\delta x, \delta y)$. The last(4th) attempt seems to be the closest, but the output is a two element list, with each element having a correct and incorrect term.Derek Handwerk2018-06-14T21:09:53ZGet a smooth line in Spherical 3D plot?
http://community.wolfram.com/groups/-/m/t/1355288
Can any one please help me to get a smooth line in Spherical 3D plot.
I tried to get the minima of the Log of a function which is as a ring in the 3D plot, but my problem is how to make this ring smoother.
I have attached my code.
Thanks.Ghady Almufleh2018-06-13T22:11:17ZReinforcement Learning in Mathematica vs. System Modeler
http://community.wolfram.com/groups/-/m/t/1356924
Does anyone know of any links on the Wolfram site that could be used to benchmark implementing a reinforcement learning application in Mathematica vs. Wolfram System Modeler? There was one Mathematica [Reinforcement Learning Notebook][1] example but I am hoping to find a more complete example for each environment (Notebook & System Modeler) to help drive the decision on which to use to for our application.
Does anyone know of a good set of reference examples?
Thanks
[1]: http://community.wolfram.com/groups/-/m/t/1137429Robert Stephens2018-06-16T14:56:47ZDecrease a Dataset size in RAM?
http://community.wolfram.com/groups/-/m/t/1354318
Hi,
I have a question about the size of Dataset in RAM.
I have noticed that if i have a file .mx that contain a Dataset and the size on the HDD is for example 50 MB, when i import it in Mathematica the size in the RAM is about 10 times (500 MB)!
Do you know why there is so many difference between the two sizes? Is it normal?
I have noticed that if i save the same data as List and not as Dataset (without association) the size is just greater than the size in HDD.
Is there any solution that allows using the dataset without this "waste" of memory", because it is a big problem when i have to deal with a large amount of data... but the datasets are more "comfortable" than pure List.
Thank you for your help!Andrea Barresi2018-06-11T11:30:48Z[Mathematica-vs-R] Deep learning examples
http://community.wolfram.com/groups/-/m/t/1356138
# Introduction
[This MathematicaVsR at GitHub](https://github.com/antononcube/MathematicaVsR/tree/master/Projects/DeepLearningExamples) project is for the comparison of the Deep Learning functionalities in R/RStudio and Mathematica/Wolfram Language (WL).
The project is aimed to mirror and aid the talk
["Deep Learning series (session 2)"](https://www.meetup.com/Orlando-MLDS/events/250086544/)
of the meetup
[Orlando Machine Learning and Data Science](https://www.meetup.com/Orlando-MLDS).
The focus of the talk is R and Keras, so the project structure is strongly influenced by the content
of the book [Deep learning with R](https://www.manning.com/books/deep-learning-with-r),
\[[1](https://www.manning.com/books/deep-learning-with-r)\], and
the corresponding Rmd notebooks, \[[2](https://github.com/jjallaire/deep-learning-with-r-notebooks)\].
Some of Mathematica's notebooks repeat the material in \[[2](https://github.com/jjallaire/deep-learning-with-r-notebooks)\].
Some are original versions.
WL's Neural Nets framework and abilities are fairly well described in the
reference page
["Neural Networks in the Wolfram Language overview"](http://reference.wolfram.com/language/tutorial/NeuralNetworksOverview.html), \[4\],
and the [webinar talks](http://www.wolfram.com/broadcast/c?c=442) \[5\].
The corresponding documentation pages
\[[3](https://keras.rstudio.com/reference/index.html)\] (R) and
\[[6](http://reference.wolfram.com/language/guide/NeuralNetworks.html)\] (WL)
can be used for a very fruitful comparison of features and abilities.
**Remark:** With "deep learning with R" here we mean "Keras with R".
**Remark:** An alternative to R/Keras and Mathematica/MXNet is the library
[H2O](https://www.h2o.ai) (that has interfaces to Java, Python, R, Scala.) See project's directory
[R.H2O](https://github.com/antononcube/MathematicaVsR/tree/master/Projects/DeepLearningExamples/R.H2O)
for examples.
# The presentation
- [Mind map for the presentation](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/Diagrams/Deep-learning-with-Keras-in-R-mind-map.pdf).
*(Has life hyperlinks.)*
- Presentation slideshow:
[html](http://htmlpreview.github.io/?https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/R/Keras-with-R-talk-slideshow.html#/),
[Rpres](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/R/Keras-with-R-talk-slideshow.Rpres).
- ["Neural network layers primer" slideshow](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/Mathematica/Neural-network-layers-primer.pdf).
- The slideshow is part of [Sebastian Bodenstein's presentation at Wolfram U](http://www.wolfram.com/broadcast/video.php?c=442&v=2173).
*(It was separated/extracted for clarity and convenience during the meetup presentation.)*
- Recording of the presentation at YouTube:
[ORLMLDS Deep learning series (2): "Using Keras with R (... and MXNet with WL)"](https://youtu.be/AidENXetn3o).
- The info-chart
["Classification of handwritten digits by matrix factorization"](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/Diagrams/Classification-of-handwritten-digits-by-MF.pdf)
(used in the presentation.)
# The big picture
Deep learning can be used for both supervised and unsupervised learning.
***In this project we concentrate on supervised learning.***
The following diagram outlines the general, simple classification workflow we have in mind.
[![simple_classification_workflow](https://imgur.com/OT5Qkqil.png)](https://imgur.com/OT5Qkqi.png)
Here is a corresponding classification [monadic pipeline](https://en.wikipedia.org/wiki/Monad_(functional_programming))
in Mathematica:
![monadic_pipeline](https://imgur.com/zwjBynL.png)
# Code samples
R-Keras uses monadic pipelines through the library [`magrittr`](https://github.com/tidyverse/magrittr).
For example:
model <- keras_model_sequential()
model %>%
layer_dense(units = 256, activation = 'relu', input_shape = c(784)) %>%
layer_dropout(rate = 0.4) %>%
layer_dense(units = 128, activation = 'relu') %>%
layer_dropout(rate = 0.3) %>%
layer_dense(units = 10, activation = 'softmax')
The corresponding Mathematica command is:
model =
NetChain[{
LinearLayer[256, "Input" -> 784],
ElementwiseLayer[Ramp],
DropoutLayer[0.4],
LinearLayer[128],
ElementwiseLayer[Ramp],
DropoutLayer[0.3],
LinearLayer[10]
}]
# Comparison
## Installation
- Mathematica
- The neural networks framework comes with Mathematica. (No additional installation required.)
- R
- Pretty straightforward using the directions in \[3\]. (A short list.)
- Some additional Python installation is required.
## Simple neural network classifier over [MNIST data](http://yann.lecun.com/exdb/mnist/)
- Mathematica:
[Simple-neural-network-classifier-over-MNIST-data.pdf](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/Mathematica/Simple-neural-network-classifier-over-MNIST-data.pdf)
- R-Keras:
[Keras-with-R-talk-introduction.nb.html](http://htmlpreview.github.io/?https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/R/Keras-with-R-talk-introduction.nb.html),
[Keras-with-R-talk-introduction.Rmd](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/R/Keras-with-R-talk-introduction.Rmd).
## Vector classification
*TBD...*
## Categorical classification
*TBD...*
## Regression
- Mathematica:
[Predicting-house-prices-a-regression-example.pdf](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/Mathematica/Predicting-house-prices-a-regression-example.pdf).
- R-Keras:
[3.6-predicting-house-prices.nb.html](https://jjallaire.github.io/deep-learning-with-r-notebooks/notebooks/3.6-predicting-house-prices.nb.html),
[3.6-predicting-house-prices.Rmd](https://github.com/jjallaire/deep-learning-with-r-notebooks/blob/master/notebooks/3.6-predicting-house-prices.Rmd).
- *(Those are links to notebooks in \[2\].)*
## Encoders and decoders
The Mathematica encoders (for neural networks and generally for machine learning tasks) are very well designed
and with a very advanced development.
The encoders in R-Keras are fairly useful but not was advanced as those in Mathematica.
*[TBD: Encoder correspondence...]*
## Dealing with over-fitting
- Mathematica:
[Training-Neural-Networks-with-Regularization.pdf](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/Mathematica/Training-Neural-Networks-with-Regularization.pdf).
- R-Keras:
[Training-Neural-Networks-with-Regularization.nb.html](http://htmlpreview.github.io/?https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/R/Training-Neural-Networks-with-Regularization.nb.html),
[Training-Neural-Networks-with-Regularization.Rmd](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/DeepLearningExamples/R/Training-Neural-Networks-with-Regularization.Rmd).
## Repositories of pre-trained models
- Mathematica:
[Wolfram Research repository of neural networks](http://resources.wolframcloud.com/NeuralNetRepository);
can import externally trained networks in
[MXNet](http://reference.wolfram.com/language/ref/format/MXNet.html)
format.
- R-Keras: has commands loading for pre-trained models, \[[3](https://keras.rstudio.com/reference/index.html)\].
## Documentation
- Mathematica: ["Neural Networks guide"](http://reference.wolfram.com/language/guide/NeuralNetworks.html).
- R-Keras: ["Keras reference"](https://keras.rstudio.com/reference/index.html),
[cheatsheet](https://github.com/rstudio/cheatsheets/raw/master/keras.pdf).
# References
\[1\] F. Chollet, J. J. Allaire, [Deep learning with R](https://www.manning.com/books/deep-learning-with-r), (2018).
\[2\] J. J. Allaire, [Deep Learing with R notebooks](https://github.com/jjallaire/deep-learning-with-r-notebooks), (2018), GitHub.
\[3\] RStudio, [Keras reference](https://keras.rstudio.com/reference/index.html).
\[4\] Wolfram Research, ["Neural Networks in the Wolfram Language overview"](http://reference.wolfram.com/language/tutorial/NeuralNetworksOverview.html).
\[5\] Wolfram Research, ["Machine Learning Webinar Series"](http://www.wolfram.com/broadcast/c?c=442).
\[6\] Wolfram Research, ["Neural Networks guide"](http://reference.wolfram.com/language/guide/NeuralNetworks.html).Anton Antonov2018-06-15T09:24:05ZCreate a user interface and stand alone application using Wolfram Language?
http://community.wolfram.com/groups/-/m/t/1355400
Hi,
I have a question about the creation of a stand-alone application and the relative user interface.
I have created many notebooks ok Mathematica using the Button, CreateDialog, Input Field and so on, but i have noticed that the code is hard to hide... For example, if there are some errors during the computation and Mathematica Print the errors, the hidden code appear...
Here is the question:
I have created a code for signal processing and data analysis. Are there a possibility to create a stand-alone application, that uses the Mathematica Kernel obviously but that appears only with buttons, menus etc. with which the user can interact to insert data, file path etc.. and start the analysis without seeing the code, in other words, an application with graphical user interface?
I'd like to create a user-friendly software for users that haven't any knowledge of Wolfram Language.
Thank youAndrea Barresi2018-06-14T13:39:57ZAvoid trouble using: "UnitConvert & CompatibleUnitQ"?
http://community.wolfram.com/groups/-/m/t/1356668
I saw the FAQ on this website and was still not successful in getting to work (graphic attached) I am trying to use these two functions to convert things like: nautical miles to kilograms,radians to degrees or even pounds to kilograms. Any and all help is greatly appreciated!
http://community.wolfram.com//c/portal/getImageAttachment?filename=Unit_Help.JPG&userId=1255394VY HY2018-06-16T02:01:26ZSolve the brick problem/perfect box problem?
http://community.wolfram.com/groups/-/m/t/1295325
The problem of finding such a cuboid is also called the brick problem, diagonals problem, perfect box problem, perfect cuboid problem, or rational cuboid problem.
Not 100% how to put this so I will get strat to the point I have a solution for this problem but am not sure who to show
need help I am on facebook.
I find it very hard to write as I have Irlen syndrome and dyslexia I have tested it on graph paper and works.
I am struggling to put into word.
so the question is where is the best place to go?
I was going to post on here is this a no no?Aaron Cattell2018-03-03T05:57:52ZMove Notebook-Cell Brackets to the Left of the Window?
http://community.wolfram.com/groups/-/m/t/1353767
When my Mathematica-notebook window is maximized, most of the action is on the left of the window, but the cell brackets are far away on the window's right side. Is there a way to move the brackets to the left side of the window? If I find a way, I will try to include it in my default style-sheet.
Unrelated question, but small so I'll throw it in here: Is there any keyboard shortcut to move the cursor from a cell's interior to a space between cells? Or a shortcut to immediately select the cell containing the cursor (assuming the cursor is inside a cell)? These would facilitate mouse-free navigation (which is my favorite thing about Emacs).Joe Donaldson2018-06-10T14:49:24ZGenerate random points in a unit circle using a "For" loop?
http://community.wolfram.com/groups/-/m/t/1354124
I am new to Mathematica and I have a problem with the "For" statement. I am often in doubt where to place a "," or a ";".
I am stuck with the following : I want to generate random points in a unit circle with the following function :
randompunten[n_] := Module[{p = n, r, angle, lis, i},
lis = {};
For[i = 0;
r = RandomReal[],
angle = RandomReal[2 \[Pi]],
i <= p;
i++;
lis = Append[lis, Point[{r Cos[angle], r Sin[angle]]}]]]; lis]
The result is an empty lis
NB : I just found out that this is not the right way but aside of that : what am I doing wrong in the code ?
(When I do the Append statement outside the module things work fine .Chiel Geeraert2018-06-10T18:38:05ZWhere in the docs for the IFF keyboard shortcut?
http://community.wolfram.com/groups/-/m/t/1356022
When I'm thinking about math, and I need to type the if-and-only-if symbol, but esc-iff-esc doesn't work, and then I search the docs for 15 minutes, then Google, but still can't find the right key-sequence to type (what was I working on before this? can't remember offhand), where exactly in the docs should I be looking for information I need about which keys to press, please?Joe Donaldson2018-06-15T01:02:25Z2018 FIFA World Cup Football / Soccer Simulation
http://community.wolfram.com/groups/-/m/t/1354648
[![winner map][9]][9]
This June 14, 2018 starts the FIFA World Cup in Russia. After reading _El País_ predition (see ([1][1]) and ([2][2])), I wondered if I could build my own simulation using Wolfram Language. So here it is what I tried. Any new ideas on how to improve it are welcome, and let the best win!
# Introduction
I will build this simulation by blocks:
1. Base data
2. Simulation of a match
3. Simulation of the groups phase
4. Simulation of the second phase
5. All together
# 1. Base data
## 1.1. Rankings
As a base for this model, I will use the FIFA ranking. We could also do a test using other rankings (like the one generated by El País ([2][3])).
I've downloaded the ranking from [FIFA][4], and after using `Interpreter["Country"]` on all the names, I could get most of the countries properly parsed. Of course, we all know UK is not _united_ for football, so I used `Interpreter["AdministrativeDivision"]` for the _UK home nations_, and a few other cases needed special threatment (like the case of Tahiti, which is not a proper country, so I did align it with Tahiti Islands, or Congo vs Congo DR, which need special disambiguation). Here I will attach the result of that ranking, so we should just load it:
```
rankingPoints = Dispatch[Get["rankingFifaJune7.m"]]
```
## 1.2. Participants and Groups
Using the previous alignment, I took the list from [FIFA][5] and converted into a simple list of countries.
```
countries = {Entity["Country", "Russia"],
Entity["Country", "SaudiArabia"], Entity["Country", "Egypt"],
Entity["Country", "Uruguay"], Entity["Country", "Portugal"],
Entity["Country", "Spain"], Entity["Country", "Morocco"],
Entity["Country", "Iran"], Entity["Country", "France"],
Entity["Country", "Australia"], Entity["Country", "Peru"],
Entity["Country", "Denmark"], Entity["Country", "Argentina"],
Entity["Country", "Iceland"], Entity["Country", "Croatia"],
Entity["Country", "Nigeria"], Entity["Country", "Brazil"],
Entity["Country", "Switzerland"], Entity["Country", "CostaRica"],
Entity["Country", "Serbia"], Entity["Country", "Germany"],
Entity["Country", "Mexico"], Entity["Country", "Sweden"],
Entity["Country", "SouthKorea"], Entity["Country", "Belgium"],
Entity["Country", "Panama"], Entity["Country", "Tunisia"],
Entity["AdministrativeDivision", {"England", "UnitedKingdom"}],
Entity["Country", "Poland"], Entity["Country", "Senegal"],
Entity["Country", "Colombia"], Entity["Country", "Japan"]}
```
Given that it is sorted by groups, we could just use `Partition` and get the teams per group:
```
teamsByGroup = AssociationThread[CharacterRange["A", "H"] -> Partition[countries, 4]]
```
# 2. Simulation of a match
This is probably the hardest part of this problem. How to predict the outcome of a match? If it were easy, we would not even play! Well, I will use the same prediction used by other sources (like [this paper][6]), which is based on a Poisson distribution using the ration between the FIFA rankings. I'm adding also another factor that could be used to tweak more the probability (for example, Russia may not have a good ranking, but it is playing at home, that may be important!).
When it is not allowed to be a draw, instead of doing only an extra time and round of penalties if needed, I just called again the basic results to get a new result until no the tie is broken. To get an actual result we may want to call only once the Poisson distribution (for the extra time), and then maybe a binomial distribution for penalties.
```
getPossibleResult[weight1_, weight2_, lambda1_, lambda2_] :=
{RandomVariate[PoissonDistribution[lambda1 weight1/weight2]], RandomVariate[PoissonDistribution[lambda2 weight2/weight1]]};
simulateMatch[weight1_, weight2_, lambda1_, lambda2_, drawQ_] := Module[{result},
result = getPossibleResult[weight1, weight2, lambda1, lambda2];
If[!drawQ,
While[SameQ @@ result,
result = getPossibleResult[weight1, weight2, lambda1, lambda2]
];
];
result
];
simulatedMatchResults[match["Groups"][team1_, team2_]] := simulateMatch[team1 /. rankingPoints, team2 /. rankingPoints, 1, 1, True];
simulatedMatchResults[match["Knockout"][team1_, team2_]] := simulateMatch[team1 /. rankingPoints, team2 /. rankingPoints, 1, 1, False];
```
In this first model I'm using `1` for the _lambda_ values, but we could generate another dispatch list to modify for example Russia factor for playing as local, or adding more _strengh_ to our favorite team, etc. Of course, if you change too much the values, remember not to use the result for doing any bet!
# 3. Simulation of the groups phase
To simulate a each group, we will _play_ each match, and then we will compute the full table of results sorted by points, goals difference, goals done, and goals against.
```
simulateGroup[groupsTeam_] :=
Module[{matches = DeleteDuplicatesBy[Permutations[groupsTeam, {2}], Sort], matchResults, resultsTable, resultsLookup},
resultsLookup[_, _] = 0;
matchResults = {##, simulatedMatchResults[match["Groups"][##]]} & @@@ matches;
Function[{team1, team2, result},
Switch[result,
{a_, b_} /; a > b,
resultsLookup[team1, "WINS"] = resultsLookup[team1, "WINS"] + 1;
resultsLookup[team2, "LOSTS"] = resultsLookup[team2, "LOSTS"] + 1;
resultsLookup[team1, "POINTS"] = resultsLookup[team1, "POINTS"] + 3;
,
{a_, b_} /; a < b,
resultsLookup[team2, "WINS"] = resultsLookup[team2, "WINS"] + 1;
resultsLookup[team1, "LOSTS"] = resultsLookup[team1, "LOSTS"] + 1;
resultsLookup[team2, "POINTS"] = resultsLookup[team2, "POINTS"] + 3;
,
_
,
resultsLookup[team1, "DRAWS"] = resultsLookup[team1, "DRAWS"] + 1;
resultsLookup[team2, "DRAWS"] = resultsLookup[team2, "DRAWS"] + 1;
resultsLookup[team1, "POINTS"] = resultsLookup[team1, "POINTS"] + 1;
resultsLookup[team2, "POINTS"] = resultsLookup[team2, "POINTS"] + 1;
];
resultsLookup[team1, "GOL+"] = resultsLookup[team1, "GOL+"] + result[[1]];
resultsLookup[team2, "GOL+"] = resultsLookup[team2, "GOL+"] + result[[2]];
resultsLookup[team1, "GOL-"] = resultsLookup[team1, "GOL-"] + result[[2]];
resultsLookup[team2, "GOL-"] = resultsLookup[team2, "GOL-"] + result[[1]];
] @@@ matchResults;
resultsTable = Table[
{
t,
resultsLookup[t, "POINTS"],
resultsLookup[t, "WINS"],
resultsLookup[t, "LOSTS"],
resultsLookup[t, "DRAWS"],
resultsLookup[t, "GOL+"],
resultsLookup[t, "GOL-"],
resultsLookup[t, "GOL+"] - resultsLookup[t, "GOL-"]
}, {t, groupsTeam}];
SortBy[resultsTable, {-#[[2]], -#[[-1]], -#[[-3]], #[[-2]]} &]
];
selectClassified[groupResultTable_] := groupResultTable[[;;2, 1]];
simulateAllGroups[groups_] := simulateGroup /@ groups;
selectAllClassified[groupsResults_] := AssociationMap[List["1"<>#[[1]]->#[[2, 1]],"2"<>#[[1]]->#[[2, 2]]] &, selectClassified /@ groupsResults]
```
# 4. Simulation of the second phase
## 4.1. Matches schedule
First step here is to get the match schedule. Who plays against who in each knockout round? Well, that's easy to get from [FIFA][7], and as a way to store it, I will do a list of rules of `matchnumber -> {team1, team2}`, where `team1` and `team2` will be strings with the form `"1"|"2" ~~ group` or `"W"|"L" ~~ matchnumber`.
```
roundOf16 = Thread[Range[49, 56] -> {{"1C", "2D"}, {"1A", "2B"}, {"1B", "2A"}, {"1D", "2C"}, {"1E", "2F"}, {"1G", "2H"}, {"1F", "2E"}, {"1H", "2G"}}];
quarters = Thread[Range[57, 60] -> {{"W49", "W50"}, {"W53", "W54"}, {"W55", "W56"}, {"W51", "W52"}}];
semifinals = {61 -> {"W57", "W58"}, 62 -> {"W59", "W60"}};
thirdplace = {63 -> {"L61", "L62"}};
final = {64 -> {"W61", "W62"}}
```
With all this we could define the competition as a succesive group of rounds:
```
competition = {roundOf16, quarters, semifinals, Join[thirdplace, final]};
```
## 4.2. Playing the phase
Playing a round means doing a match and returning the results, to make it easier, the results will accumulate, so that we can then use `Fold` to have the total results.
```
playRound[round_, previousWL_] := Join[
previousWL,
Association@Flatten@Map[
Thread[
{"L" <> ToString[#[[1]]], "W" <> ToString[#[[1]]]} ->
#[[2]][[Ordering[simulatedMatchResults[match["Knockout"] @@ #[[2]]]]]]
] &,
round /. previousWL
]
];
playRounds[groupsResults_] := Fold[playRound[#2, #1] &, groupsResults, competition]
```
## 4.3. First basic stats
With all the results, the first stats I could think about were in which position each team finished. I only cared about the teams that actually reached at least the second phase. Of course if we run this enough times, all the teams will get into the second phase at least once... I guess.
First, let's define a function that will return the team position depending on the match they lost (or won, for third and first place):
```
posByLost = Flatten[Thread /@ {
("L" <> ToString[#] & /@ roundOf16[[All, 1]]) -> 9,
("L" <> ToString[#] & /@ quarters[[All, 1]]) -> 5,
"L63" -> 4, "W63" -> 3, "L64" -> 2, "W64" -> 1, _ -> None
}]
(posByLostFun[#1] = #2) & @@@ posByLost;
```
If we apply that function to the result of `playRounds` we can get which position each team got:
```
getPosition[globalResults_] := Reverse[Sort[DeleteCases[KeyValueMap[posByLostFun[#1] -> #2 &, globalResults], None -> _]], {2}]
```
And if we have multiple resutls of `getPosition` we would need to do a summary:
```
summaryPositions[positions_] := SortBy[
With[{n = Length[positions]},
GroupBy[Join @@ positions, First -> Last, Sort[(#1 -> N[#2/n] & @@@ Tally[#])] &]
],
-Accumulate[Lookup[#, {1, 2, 3, 4, 5, 9}, 0]] &
];
```
But, given that it is more common to talk about the winner, finalist, semifinalist, etc, let's make a function to compute that exactly, using as input the previous result:
```
accumulatePositions[pos_] := Association@
ReleaseHold[
{
"Winner" -> Hold[1],
"Finalist" -> Hold[1] + Hold[2],
"Semifinalist" -> Hold[1] + Hold[2] + Hold[3] + Hold[4],
"Quarters" -> Hold[1] + Hold[2] + Hold[3] + Hold[4] + Hold[5],
"Round16" -> Hold[1] + Hold[2] + Hold[3] + Hold[4] + Hold[5] + Hold[9]
} /. Append[pos, _Integer -> 0]
];
```
## 4.4. Other ideas for more stats
Some very custom stats could be done too, like for example, getting the most probably final, or the against which teams will play your favorite team.
# 5. All together
Now we have all the tools needed to run the world cup _n_ times:
```
simulateWC[n_] := accumulatedPositions[
summaryPositions[
Table[
getPosition[
playRounds[
selectAllClassified[
simulateAllGroups[
teamsByGroup
]
]
]
],
n
]
]
];
```
And we need to have a nice display of it:
```
displaySimulationResult[sr_] := (Dataset`$DatasetTargetRowCount = 40; Dataset[sr /. x_?NumericQ :> Quantity[100 x, "Percent"]])
```
(I know, and I always say it, `Dataset` is for much more than just displaying tables, but they look great).
## 5.1. Using it!
Now we can play with our functions, and do simulations of 10000 or 100000 or even more if you have memory and time, and get the probabilities by _just counting_.
Some results:
```
simulation100k = simulateWC[100000];
```
(This took 473 seconds in my computer, i7-4710HQ ).
And now we can display them:
```
displaySimulationResult[simulation100k]
```
![display simulation 100k][8]
### 5.1.1. Why not a map too?
Let's make a nice map of the winners probability and about reaching the second phase:
```
Labeled[GeoRegionValuePlot[Quantity[100 #["Winner"], "Percent"] & /@ simulation100k,
GeoBackground -> "CountryBorders", GeoProjection -> "Robinson", ImageSize -> 1200,
PlotLabel -> Style["Probability of winning the 2018 FIFA World Cup Russia", 24]],
Text["Using 100000 simulations based on FIFA ranking from June 7, 2018"]
]
```
![winner map][9]
```
Labeled[GeoRegionValuePlot[Quantity[100 #["Round16"], "Percent"] & /@ simulation100k,
GeoBackground -> "CountryBorders", GeoProjection -> "Robinson", ImageSize -> 1200,
PlotLabel -> Style["Probability of getting into second phase in the 2018 FIFA World Cup Russia", 24]],
Text["Using 100000 simulations based on FIFA ranking from June 7, 2018"]
]
```
![second phase map][10]
## 5.2. Desired final!
What about computing the probability of your desired final? It shouldn't be that hard given all this, it would be a matter of getting the joint probability of your teams being in first or second position simultaneously. Let's say we want a Peru-Brazil final -- and of course, expecting that Peru wins :).
We could try simply 10000 times this time:
```
Block[{n = 10000, c = 0},
Do[
c += Boole[MatchQ[Sort[{"W64", "L64"} /. playRounds[selectAllClassified[simulateAllGroups[teamsByGroup]]]], {Entity["Country", "Brazil"], Entity["Country", "Peru"]}]];
, n
];
Quantity[100.0 c/n, "Percent"]
]
```
And after doing that I got 0.85%, not as good as we would like.
# Conclusions
1. This is going to be fun!
2. This simulation is based on a given ranking, but it is easy to change it, according to different expectations and factors.
3. As a pending task remains the addition of a meaningful extra factor for each team (or even eath team pair).
[1]: https://elpais.com/deportes/2018/06/04/actualidad/1528063475_409937.html "¿Quién ganará el mundial? Así hacemos la predicción de EL PAÍS"
[2]: https://elpais.com/especiales/2018/mundial-de-futbol/pronosticos/ "¿Quién ganará el mundial?"
[3]: https://elpais.com/especiales/2018/mundial-de-futbol/pronosticos/ "¿Quién ganará el mundial?"
[4]: https://www.fifa.com/fifa-world-ranking/ranking-table/men/index.html "Ranking FIFA"
[5]: http://www.fifa.com/worldcup/groups/ "2018 FIFA WORLD CUP RUSSIA - GROUPS"
[6]: http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0101-74382015000300577 "SIMULATION-BASED METHODOLOGY FOR PREDICTING FOOTBALL MATCH OUTCOMES CONSIDERING EXPERTS' OPINIONS: THE 2010 AND 2014 FOOTBALL WORLD CUP CASES"
[7]: https://www.fifa.com/worldcup/matches/#knockoutphase "2018 FIFA WORLD CUP RUSSIA - MATCHES KNOCKOUT PHASE"
[8]: http://community.wolfram.com//c/portal/getImageAttachment?filename=displaySimulation100k.png&userId=258931
[9]: http://community.wolfram.com//c/portal/getImageAttachment?filename=winnerMapEN.png&userId=258931
[10]: http://community.wolfram.com//c/portal/getImageAttachment?filename=secondPhaseEN.png&userId=258931Francisco Rodríguez2018-06-12T06:17:23ZCode puzzles: turning docs into educational games
http://community.wolfram.com/groups/-/m/t/1032663
Teaching programing and assessing learning progress is often a very custom task. I wanted to create a completely automated "practically" infinite stream of random puzzles that guide a leaner towards improving programing skills. I think the major problem is content creation. To test whether the learner knows a programming concept, an exercise needs to be wisely designed. And it is better to have a randomized set of such exercises to definitely test the knowledge and exclude guesses and cheating and so on. Often creating such educational materials is very tedious, time consuming, and manual. Exactly like creating good documentation. I will explain one simple idea of using docs to make an educational game. This is just a barebone prototype to clearly follow the inner workings (try it out & share: https://wolfr.am/bughunter ). Please comment with feedback on how we can develop this idea further.
[![enter image description here][1]][3]
# Introduction: efficient use of resources
The docs are the finest wealth and depth of information and should be explored beyond their regular usage. Manual painstaking time consuming effort of creating good programing documentation should be used to its fullest potential. An automated game play would be a novel take on docs. We can use existing code examples in docs to randomly pull pieces of code and make programing exercises automatically. Being able to read code and find bugs is, in my experience, one of the most enlightening practices. The goal of the linked above game is to find a defect of the input code (bug) and fix it. Hence, the "bug hunter". There are just 2 possible outcomes of a single game cycle, --- and after each you can "try again":
![enter image description here][4]
# Core game code: making puzzles
Wolfram Language (WL) documentation is one of the best I've seen. It has pages and pages of examples starting from simple ones and going though the all details of the usage. Moreover the docs are written in WL itself and furthermore, WL can access docs and even has internal self-knowledge of its structure via WolframLanguageData. For instance, this is how you can show a relationship community graph for symbols related to `GatherBy`:
WolframLanguageData["GatherBy", "RelationshipCommunityGraph"]
![enter image description here][5]
We can use `WolframLanguageData` to access docs examples and then drop some parts of the code. The puzzle is then for the learner to find what is missing. For the sake of clarity designing a small working prototype lets limit test WL functions and corresponding docs' pages to some small number. So out of ~5000 (and we [just released a new addition][6]):
WolframLanguageData[] // Length
`4838`
built in symbols I just take 30
functions = {"Append", "Apply", "Array", "Cases", "Delete", "DeleteCases", "Drop", "Except",
"Flatten", "FlattenAt", "Fold", "Inner", "Insert", "Join", "ListConvolve", "Map", "MapThread",
"Nest", "Outer", "Partition", "Prepend", "ReplacePart", "Reverse", "RotateLeft", "RotateRight",
"Select", "Sort", "Split", "Thread", "Transpose"};
functions // Length
30
that are listed on a [very old but neat animated page][7] of some essential core-language collection. I will also add some "sugar syntax" to potential removable parts of code:
sugar = {"@@", "@", "/@", "@@@", "#", "^", "&"};
So, for instance, out of the following [example in docs][8] we could remove a small part to make a puzzle:
![enter image description here][9]
Here is an example of "sugar syntax" removal, which for novice programmers would be harder to solve:
![enter image description here][10]
Next step is to define a function that can check if a string is a built-in symbol (function, all 5000) or if it is some of sugar syntax we defined above:
ClearAll[ExampleHeads];
ExampleHeads[e_]:=
Select[
Cases[e,_String, Infinity],
(NameQ["System`"<>#]||MemberQ[sugar,#])&&#=!="Input"&
]
Next function essentially makes a single quiz question. First it randomly picks a function from list of 30 symbols we defined. Then it goes to the doc page of that symbol to the section called "Basic Examples". It finds a random example and removes a random part out of it:
ranquiz[]:=Module[
{ranfun=RandomChoice[functions],ranexa,ranhead},
ranexa=RandomChoice[WolframLanguageData[ranfun,"DocumentationBasicExamples"]][[-2;;-1]];
ranhead=RandomChoice[ExampleHeads[ranexa[[1]]]];
{
ReplacePart[#,Position[#,ranhead]->""]&@ranexa[[1]],
ranexa[[2]],
ranhead,
ranfun
}
]
Now we will define a few simple variables and tools.
# Image variables
I keep marveling how convenient it is that Mathematica front end can make images to be part of code. This makes notebooks a great IDE:
![enter image description here][11]
# Databin for tracking stats
It is important to have statistics of your learning game: to understand how to improve it where the education process should go. [Wolfram Datadrop][12] is an amazing tool for these purposes.
[![enter image description here][13]][14]
We define the databin as
bin = CreateDatabin[<|"Name" -> "BugHunter"|>]
# Deploy game to the web
To make an actual application usable by everyone with internet access I will use [Wolfram Development Platform][15] and [Wolfram Cloud][16]. First I define a function that will build the "result of the game" web page. It will check is answer is wrong or right and give differently designed pages accordingly.
quiz[answer_String,check_String,fun_String]:=
(
DatabinAdd[Databin["kd3hO19q"],{answer,check,fun}];
Grid[{
{If[answer===check,
Grid[{{Style["Right! You got the bug!",40,Darker@Red,FontFamily->"Chalkduster"]},{First[imgs]}}],
Grid[{{Style["Wrong! The bug got you!",40,Darker@Red,FontFamily->"Chalkduster"]},{Last[imgs]}}]
]},
{Row[
{Hyperlink["Try again","https://www.wolframcloud.com/objects/user-3c5d3268-040e-45d5-8ac1-25476e7870da/bughunter"],
"|",
hyperlink["Documentation","http://reference.wolfram.com/language/ref/"<>fun<>".html"],
"|",
hyperlink["Fun hint","http://reference.wolfram.com/legacy/flash/animations/"<>fun<>".html"]},
Spacer[10]
]},
{Style["===================================================="]},
{hyperlink["An Elementary Introduction to the Wolfram Language","https://www.wolfram.com/language/elementary-introduction"]},
{hyperlink["Fast introduction for programmers","http://www.wolfram.com/language/fast-introduction-for-programmers/en"]},
{logo}
}]
)
This function is used inside `CloudDeploy[...FormFunction[...]...]` construct to actually deploy the application. `FormFunction` builds a query form, a web user interface to formulate a question and to get user's answer. Note for random variables to function properly `Delayed` is used as a wrapper for `FormFunction`.
CloudDeploy[Delayed[
quizloc=ranquiz[];
FormFunction[
{{"code",None} -> "String",
{"x",None}-><|
"Input"->StringRiffle[quizloc[[3;;4]],","],
"Interpreter"->DelimitedSequence["String"],
"Control"->Function[Annotation[InputField[##],{"class"->"sr-only"},"HTMLAttrs"]]|>},
quiz[#code,#x[[1]],#x[[2]]]&,
AppearanceRules-> <|
"Title" -> Grid[{{title}},Alignment->Center],
"MetaTitle"->"BUG HUNTER",
"Description"-> Grid[{
{Style["Type the missing part of input code",15, Darker@Red,FontFamily->"Ayuthaya"]},
{Rasterize@Grid[{
{"In[1]:=",quizloc[[1]]},
{"Out[1]=",quizloc[[2]]}},Alignment->Left]}
}]
|>]],
"bughunter",
Permissions->"Public"
]
The result of the deployment is a cloud object at a URL:
CloudObject[https://www.wolframcloud.com/objects/user-3c5d3268-040e-45d5-8ac1-25476e7870da/bughunter]
with the short version:
URLShorten["https://www.wolframcloud.com/objects/user-3c5d3268-040e-45d5-8ac1-25476e7870da/bughunter", "bughunter"]
https://wolfr.am/bughunter
And we are done! You can go at the above URL and play.
# Further thoughts
Here are some key points and further thoughts.
## Advantages:
- Automation of content: NO new manual resource development, use existing code bases.
- Automation of testing: NO manual labor of grading.
- Quality of testing: NO multiple choice, NO guessing.
- Quality of grading: almost 100% exact detection of mistakes and correct solutions.
- Fight cheating: clear to identify question type "find missing code part" helps to ban help from friendly forums (such as this one).
- Almost infinite variability of examples if whole docs system is engaged.
- High range from very easy to very hard examples (exclusion of multiple functions and syntax can make this really hard).
## Improvements:
- Flexible scoring system based on function usage frequencies.
- Optional placeholder as hint where the code is missing.
- Using network of related functions (see above) to move smoothly through the topical domains.
- Using functions frequency to feed easier or harder exercises based on test progress.
***Please comment with your own thoughts and games and code!***
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-03-17at10.37.46AM.png&userId=11733
[2]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-03-16at6.49.58PM.png&userId=11733
[3]: https://www.wolframcloud.com/objects/user-3c5d3268-040e-45d5-8ac1-25476e7870da/bughunter
[4]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-03-16at6.58.45PM.png&userId=11733
[5]: http://community.wolfram.com//c/portal/getImageAttachment?filename=sgfq354ythwrgsf.png&userId=11733
[6]: http://blog.wolfram.com/2017/03/16/the-rd-pipeline-continues-launching-version-11-1/
[7]: http://reference.wolfram.com/legacy/flash/
[8]: http://reference.wolfram.com/language/ref/Except.html
[9]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-03-16at7.21.05PM.png&userId=11733
[10]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-03-16at7.25.52PM.png&userId=11733
[11]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-03-16at7.34.59PM.png&userId=11733
[12]: https://datadrop.wolframcloud.com/
[13]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-03-16at7.41.35PM.png&userId=11733
[14]: https://datadrop.wolframcloud.com/
[15]: https://www.wolfram.com/development-platform/
[16]: http://www.wolfram.com/cloud/Vitaliy Kaurov2017-03-17T01:13:24ZCalculation of the natural frequencies of complex mechanical systems.
http://community.wolfram.com/groups/-/m/t/1355199
Dear all,
I'm considering buying SystemModeler and Mathematica and I was wondering how easy or hard is to calculate the natural frequencies of mechanical systems. For instance, the model could be defined in SystemModeler and then it can be exported to Mathematica where additional tools are available. Is there a particular tool in Mathematica which would make this task easy?
Thank you in advance.
Regards,
Fabianoquichtli2018-06-13T21:46:32ZSemantic Image Segmentation Neural Network in Wolfram Language
http://community.wolfram.com/groups/-/m/t/1250199
Hello everyone, this is my first post in Wolfram community, so I am quite excited about it!
I got interested in the neural network functionalities, after attending a talk, right when version 11.0.0 of Mathematica was about to release (so about one and half years back). Since then, I have just been self-teaching myself about neural networks using various resources available online and Wolfram Language documentation. What really helped me with this current post (project) is the ease with which one can implement a seemingly complicated network in Wolfram Language, the level of automation which NetTrain handles behind the scenes (batch sizes, methods, learning rates, initializations... and the list can go on), and the simplicity with which we can all stitch (chain) it together and run (essentially Shift+Enter) using Wolfram Language.
So in this post, I have tried to implement SegNet ( https://arxiv.org/pdf/1511.00561.pdf ). It is a convolution neural network for a semantic pixel-wise segmentation. The encoder network is identical to the first 13 layers of the VGGNetwork, identical because each convolution layer is followed by a batch-normalization. The decoder upsamples the image obtained from the encoder, using Max pooling. (please note that this encoder, is not the same as NetEncoder and NetDecoder functionality in Wolfram Language). A snippet from the paper cited above shows the layer organization ![enter image description here][1]
So let's take a step by step approach to build this network: let's start with the encoder network. To build the networks, I directly referred to the [Caffe prototxt files][2] and tried to reproduce the same in Wolfram Language. So if we see the prototxt files that it has a structure of the layers, and these structures have a repetitive pattern. Taking use of that, we can build the encoder in a nicer neater way:
encChain[index_, nLayers_, nChannels_] := Module[{tags, names, layers},
tags = Table[ToString[index] <> "_" <> ToString[j], {j, nLayers}];
names = Append[
Flatten[{"conv" <> #, "conv" <> # <> "bn", "relu" <> #} & /@
tags], "pool" <> ToString[index]];
layers = Append[
Flatten@Table[{ConvolutionLayer[nChannels, {3, 3},
"PaddingSize" -> {1, 1}], BatchNormalizationLayer[],
ElementwiseLayer[Ramp]}, {nLayers}],
PoolingLayer[{2, 2}, "Stride" -> {2, 2}]];
AssociationThread[names -> layers]]
encoder = NetChain[Join[
encChain[1, 2, 64],
encChain[2, 2, 128],
encChain[3, 3, 256],
encChain[4, 3, 512],
encChain[5, 3, 512]],
"Input" ->
NetEncoder[{"Image", {256, 256}}]]
![enter image description here][3]
Next we can move to the decoder section of the network. This is similar to the encoder section, and it also contains the patterns which we had seen in the encoder, only now we need to add the appropriate padding, after the upsampling using a DeconvolutionLayer. Here is a decoder which is similar (if not the same) as the prototxt of the Segnet found in literature
decChain[index_, nLayersmax_, nLayersmin_, nChannels_] :=
Module[{tags, names, layers, nlayers},
nlayers = nLayersmax - nLayersmin + 1;
tags = Table[
ToString[index] <> "_" <> ToString[j] <> "_" <> "D", {j,
nLayersmax, nLayersmin, -1}];
names = Flatten@
Append[{"deconv" <> ToString[index],
"deconv" <> ToString[index] <> "pad"},
Flatten[{"conv" <> #, "conv" <> # <> "bn", "relu" <> #} & /@
tags]]; layers =
Flatten@Append[{DeconvolutionLayer[nChannels, {3, 3},
"Stride" -> 2, "PaddingSize" -> 1],
PaddingLayer[{{0, 0}, {0, 1}, {0, 1}}]},
Flatten@Table[{ConvolutionLayer[nChannels, {3, 3},
"PaddingSize" -> {1, 1}], BatchNormalizationLayer[],
ElementwiseLayer[Ramp]}, {nlayers}]];
AssociationThread[names -> layers]]
decChain2[index_, nLayersmax_, nLayersmin_, nChannels_] :=
Module[{tags, names, layers, nlayers},
nlayers = nLayersmax - nLayersmin + 1;
tags = Table[
ToString[index] <> "_" <> ToString[j] <> "_" <> "D", {j,
nLayersmax, nLayersmin, -1}];
names = Flatten[{"conv" <> #, "conv" <> # <> "bn", "relu" <> #} & /@
tags]; layers =
Flatten@Table[{ConvolutionLayer[nChannels, {3, 3},
"PaddingSize" -> {1, 1}], BatchNormalizationLayer[],
ElementwiseLayer[Ramp]}, {nlayers}];
AssociationThread[names -> layers]]
decoder = NetChain[Join[
decChain[5, 3, 1, 512],
decChain[4, 3, 2, 512],
decChain2[4, 1, 1, 256],
decChain[3, 3, 2, 256],
decChain2[3, 1, 1, 128],
decChain[2, 2, 2, 128],
decChain2[2, 1, 1, 64],
decChain[1, 2, 2, 64]]]
![enter image description here][4]
The last step would be to just put it all together, chain them with the final layer depending on the application. Since in this code (project), I just wanted to obtain a final image (pixel classified according to the object class), I kept the Output as an image.
chain = NetChain[{encoder, decoder,
ConvolutionLayer[3, {3, 3}, "PaddingSize" -> 1,
"Input" -> {64, 256, 256},
"Output" ->
NetDecoder[{"Image"}]]}]
![enter image description here][5]
Now, as a proof of concept, the network was trained on images from the EarthObject dataset: http://www2.isprs.org/potsdam-2d-semantic-labeling.html. This dataset was chosen because there was already a similar trained network in Caffe https://github.com/nshaud/DeepNetsForEO, and I just wanted to implement the same in Wolfram Language.
The dataset consists of images of dimensions {6000,6000}. They were appropriately divided into training, validation, and test images. Once done, they were imported, resized to {2048,2048} images, and partitioned into {256,256} sized images so that I could feed it into the modest-sized GPU that I had. So each image created a set of 64 images.
The final last step would be to train it, for training this network, a very modest GPU was used (just a laptop, 4GB graphics card), with Images of dimensions {256,256}, BatchSize 10.
dir = SetDirectory[NotebookDirectory[]];
trained=NetTrain[chain, traindata, ValidationSet -> valdata,
MaxTrainingRounds -> 1000, TargetDevice -> "GPU",
BatchSize -> 10,
TrainingProgressCheckpointing -> {"Directory", dir,
"Interval" -> Quantity[30, "Minutes"]}]
Once the network was trained to some extent (it was not trained completely, since the Validationloss had not plateaued yet), I was impatient to look at results (this is indeed my first neural net exploratory project).
![enter image description here][6]
The above shows roads, cars, and trees as trained by the network. The first is the actual image, second image is the trained classes, while the third is the actual label (ground truth)
I am still working on an efficient way to do error analysis. Please feel free to provide me feedback, so that I can improve on this code, do efficient error analysis, or even suggestions for other nets that I can try to code (implement) in the Wolfram Language. I am aware of the CityScapes dataset (https://www.cityscapes-dataset.com/) and Synthia dataset, which might be interesting applications of this net, and they are still work in progress (limited by the GPU availability)
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=Segnet_Architecture.PNG&userId=1124872
[2]: https://github.com/alexgkendall/SegNet-Tutorial/blob/master/Models/segnet_basic_train.prototxt
[3]: http://community.wolfram.com//c/portal/getImageAttachment?filename=Segnet_encoder.PNG&userId=1124872
[4]: http://community.wolfram.com//c/portal/getImageAttachment?filename=Segnet_decoder.PNG&userId=1124872
[5]: http://community.wolfram.com//c/portal/getImageAttachment?filename=enc_dec.PNG&userId=1124872
[6]: http://community.wolfram.com//c/portal/getImageAttachment?filename=5136trained_images2.PNG&userId=1124872Tuseeta Banerjee2017-12-19T19:44:23ZSolve the following equation with a Sum?
http://community.wolfram.com/groups/-/m/t/1355276
Consider the following code:
In[4]:= Solve[Sum[i, {i, 1, n}] == 253, n]
Out[4]= {{n -> -23}, {n -> 22}}
In[7]:= Solve[\!\(
\*UnderoverscriptBox[\(\[Sum]\), \(i = 1\), \(x\)] i\) == 253, x]
Out[7]= {{x -> -23}, {x -> 22}}
In[9]:= \!\(
\*UnderoverscriptBox[\(\[Sum]\), \(i = 1\), \(22\)]i\)
Out[9]= 253Dennis Lawler2018-06-13T21:41:52ZDisplaying Databin as a Dataset table in a FormFunction Cloud Deployment
http://community.wolfram.com/groups/-/m/t/1355333
I am trying to set up a cloud deployed FormFunction where a user can enter a public databin ID and then view the contents formatted as a dataset. I keep running into issues where the output of the form returns straight text rather than the table I am looking for.
CloudDeploy[
FormFunction[{"Databin ID:" -> <|
"Help" -> "Enter the ID of a public Databin",
"Interpreter" -> "String"|>, },
Dataset[Databin[#"Databin ID:"]] &], Permissions -> "Public"]
And here is a snippet of what I am getting in return when I try to view the databin as a dataset:
Dataset[{<|"Name" -> "Ben", "Email" -> "fake@gmail.com","Timestamp" -> DateObject[{2018, 5, 18, 12, 26, 55.98299980163574}, "Instant", "Gregorian", -7.]|><|"Name" -> "bob", "Email" -> "anotherfake@gmail.com","Timestamp" -> DateObject[{2018, 5, 18, 12, 30, 33.210999965667725}, "Instant", "Gregorian", -7.]|>.....
I can replace
Dataset[Databin[#"Databin ID:"]]&`
with this
ExportForm[Dataset[Databin[#"Databin ID:"]], "PNG"] &
and it will display an image of what I am looking for, but any other formatting option ("HTML", "WL", etc.) either fails or returns the same string of text as before
Any idea what I am missing?Ben Kickert2018-06-14T01:08:22ZExtract internals from a ParametricFunction object?
http://community.wolfram.com/groups/-/m/t/1355264
If I create a ParametricFunction object for doing ParametricIPOPTMinimize, how can extract the variables from the object?Frank Kampas2018-06-13T21:17:11ZSuggestion: mathlink.h / wstp.h shouldn't include <windows.h>
http://community.wolfram.com/groups/-/m/t/1355822
If it is at all technically feasible, it would be useful (or rather: user-friendlier) if `mathlink.h` did not include `windows.h` on Windows systems.
Recently I had a very frustrating experience where a C++ library wouldn't work on Windows when used in conjunction with MathLink. The problem turned out to be that the C++ library uses the names `IN` and `OUT` internally, but `windows.h` defines these as macros. It also defines many other macros which have a potential for conflict and difficult to debug situations.
It took quite a while to debug because the code was working fine on OS X / Linux, so at first I thought that the problem was with the Microsoft compiler. Then I realized that it was related to including `mathlink.h`, but it took some more time before I managed to find the relationship to `windows.h` and [the unexpected `IN`/`OUT` macros](https://stackoverflow.com/questions/35907493/in-and-out-macros-in-minwindef-h).
I am not experienced with Windows programming, and it is not clear to me if it is feasible to drop the `windows.h` dependency from `mathlink.h` for a future version ... I noticed two places where it was actually needed:
- For the `WinMain` function that `mprep` generates. This is not an issue as the `#include <windows.h>` can be moved to `mprep`'s output.
- For the `FAR` macro. But this has been obsolete for many many years now anyway.
[@John Fultz][at0], do you think it would be possible to remove the `#include <windows.h>` from a future version of `mathlink.h`/`wstp.h`? Or are there still-relevant technical reasons to keep it?
Does anyone else see a reason why doing this is not technically feasible?
[at0]: http://community.wolfram.com/web/jfultzSzabolcs Horvát2018-06-14T10:31:55ZAutomatically write a large binary matrix with known positions of 1?
http://community.wolfram.com/groups/-/m/t/1354213
Hi everybody! I am new to Mathematica and I have a problem that I can not find a solution to by myself. I have a script where I need to input a binary matrix, which should look like this, for example:
M = {{0, 1, 0, 0, 1, 1, 0, 0},
{1, 0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 1, 0, 0, 1, 0},
{0, 0, 1, 0, 1, 0, 1, 0},
{1, 0, 0, 1, 0, 1, 0, 0},
{1, 0, 0, 0, 1, 0, 0, 1},
{0, 0, 1, 1, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 1, 1, 0}}
However, what I actually have looks like this:
1 ZA 2 3 4 5
2 ZA 1 6 7
3 ZA 1 7 8
4 ZA 1 8 9
5 ZA 1 9 6
6 ZA 2 5 10 11
7 ZA 2 3 11 12
8 ZA 3 4 12 13
9 ZA 4 5 13 10
10 ZA 6 9 14
11 ZA 6 7 14
12 ZA 7 8 14
13 ZA 8 9 14
14 ZA 10 11 12 13
These numbers show which elements in each row should be equal to 1, while all the other elements should be equal to zero. Some of my examples contain up to 1000 rows and columns, so there is no way to write the matrix manually. Please, show me the automated way to write the matrix using the provided type of input.
Thanks in advance,
AntonAnton Savchenkov2018-06-10T21:59:40ZDraw 2D Hexagon to 3D Hexagon prism, or Thick Hexagon Mesh?
http://community.wolfram.com/groups/-/m/t/1290648
So I tried this code for 2D, but I would like to have say a slab with a defined thickness not just a plane,
The code for 2D is:
h[x_, y_] :=
Polygon[Table[{Cos[2 Pi k/6] + x, Sin[2 Pi k/6] + y}, {k, 6}]];
Graphics[{EdgeForm[Opacity[.7]], LightBlue,
Table[h[3 i + 3 ((-1)^j + 1)/4, Sqrt[3]/2 j], {i, 10}, {j, 15}]}]
I also found and modified this code [Here][1] but this is a very thin sheet , I would like to be able to define a thickness to it:
Graphics3D[
With[{hex =
Polygon[Table[{Cos[2 Pi k/6] + #, Sin[2 Pi k/6] + #2}, {k,
6}]] &},
Table[hex[3 i + 3 ((-1)^j + 1)/4, Sqrt[3]/2 j], {i, 10}, {j,
15}]] /.
Polygon[l_] :> {Red, Polygon[l], Polygon[{1, 0} # & /@ l]} /.
Polygon[l_List] :> Polygon[top @@@ l], Boxed -> False,
Axes -> False, PlotRange -> All, Lighting -> "Neutral"]
Can you help me how to convert 2D hexagonal to 3D hexagonal slab with user defined thickness?
[1]: https://mathematica.stackexchange.com/questions/77312/hexagonal-mesh-on-a-3d-surfaceArm Mo2018-02-24T02:10:32ZGet Top View of a 'toroid helix' which rotates around its circular axis?
http://community.wolfram.com/groups/-/m/t/1355507
![enter image description here][1]
![enter image description here][2]
Consider a very thin toroid helix which rotates around its circular axis (which passes through individual turns) while it is on a 'friction-full' surface. How would then the top view of the overall motion look like?
(Thin means to neglect elastic compression/elongation effects while helix rolls)
I guess it should be rotating around the center point while the individual turns are rotating around instantaneous circular axis.
An animation would be very much appropriate, kindly somebody come up with that.
(image source - https://i.stack.imgur.com/yLq6t.jpg)
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=unnamed.png&userId=1355442
[2]: http://community.wolfram.com//c/portal/getImageAttachment?filename=Movinghelix.gif&userId=1355442Anshuman Dwivedi2018-06-13T18:46:37ZAvoid errors while installing RLink?
http://community.wolfram.com/groups/-/m/t/1354724
Dear all,
when I try to install R the following error occurs:
In[1]:= Needs["RLink`"]
In[2]:= InstallR[]
During evaluation of In[2]:= InstallR::fail: Failed to install R. The following error was encountered: Unable to load dynamic libraries
Out[2]= $Failed
In[3]:= $Versiongeg fwggv2018-06-12T03:02:24ZExponential Base Radix VS Mixed Radix (non exponential)
http://community.wolfram.com/groups/-/m/t/1354888
Consider the following code:
estratti={04,23,20,11,84};
meno=1;
menouno=estratti-meno;
base=2;
radice=IntegerDigits[89,base]
cifre=Length[radice]
max=RandomInteger[{base-1,base-1},cifre]
maxn=FromDigits[max,base]
formula89=FromDigits[radice,MixedRadix[{u,v,w,x,y,z}]]
formulamax=FromDigits[max,MixedRadix[{u,v,w,x,y,z}]]
solu=Solve[{formulamax==maxn,formula89==89,{u,v,w,x,y,z}>0},{u,v,w,x,y,z},Integers];
basi={u,v,w,x,y,z}/.solu
binari=IntegerDigits[menouno,base,cifre]
coppie=Tuples[{basi,binari}];
cinquine=Partition[FromDigits[coppie[[#,2]],MixedRadix[coppie[[#,1]]]]&/@Range[1,Length[coppie]],5];
StringRiffle[Mod[cinquine,90]+meno,"\n","."]
`I explain the steps I do:
I start with 5 numbers in the range between 1 and 90.
1st step: consists of enumerating the 90 elements of my collection from 0 to 89, as we do in cryptanalysis, subtracting -1.
2nd step: I choose the numerical base (exponential).
3rd step: I find the number of digits necessary to obtain 89 with the chosen exponential base.
4th step: calculation of the maximum number (NMAX) that can be combined with the highest number of the chosen base (base-1) and the length of digits necessary to obtain 89.
5th step: calculate the possible MIXED ROOTS (non exponential) that with that number of digits can generate the maximum number (NMAX).
6th step: I solve the system by identifying the MIXED ROOT that generates both 89 and NMAX
Step 7: starting from the 5 initial numbers converted to the chosen exponential numerical base, I apply the MIXED ROOT found and calculate 5 new numbers (from 0 to 89) MOD 90.
Step 8: add +1 to get the 5 numbers in the range from 1 to 90.
well, in base 2 I need 7 digits to get 89, and the unknowns of the mixed base are 6 {u, v, w, x, y, z}.
89 base10 = 1011001 base 2.
if I wanted to do the same calculation on base 3, the number of digits LENGTH would be 5,
89 base 10 = 10022 base 3.
**MY QUESTION:**
how can I automatically generate the unknowns {u, v, w, x, y, z} and replace them with {x0, x1 ... x_Length-1}?
TNK'sMutatis Mutandis2018-06-13T08:08:58ZAvoid the following density plot artifacts?
http://community.wolfram.com/groups/-/m/t/1351515
Please run the attached code. The density plot has some artifacts on it (The light blue parts around the circle) Is there a way to resolve this issue. The density plot is showing velocity of a liquid passing through the channel. Regards.
\[CapitalOmega] =
ImplicitRegion[
0 <= x <= 2.0 &&
0 <= y <=
0.48208 && ! (x >= 1.0 && y <= 0.19) && ! (x >= 1.0 &&
y >= 0.31) && ! ((x - 0.76)^2 + (y - 0.24104)^2 <=
0.238125^2), {x, y}];
RegionPlot[\[CapitalOmega], AspectRatio -> Automatic, ImageSize -> 300]
stokesFlowOperator = {Div[({{-1, 0}, {0, -1}}.Grad[
u[x, y], {x, y}]), {x, y}] +
\!\(\*SuperscriptBox[\(w\),
TagBox[
RowBox[{"(",
RowBox[{"1", ",", "0"}], ")"}],
Derivative],
MultilineFunction->None]\)[x, y],
Div[({{-1, 0}, {0, -1}}.Grad[v[x, y], {x, y}]), {x, y}] +
\!\(\*SuperscriptBox[\(w\),
TagBox[
RowBox[{"(",
RowBox[{"0", ",", "1"}], ")"}],
Derivative],
MultilineFunction->None]\)[x, y],
\!\(\*SuperscriptBox[\(v\),
TagBox[
RowBox[{"(",
RowBox[{"0", ",", "1"}], ")"}],
Derivative],
MultilineFunction->None]\)[x, y] +
\!\(\*SuperscriptBox[\(u\),
TagBox[
RowBox[{"(",
RowBox[{"1", ",", "0"}], ")"}],
Derivative],
MultilineFunction->None]\)[x, y]};
Subscript[\[CapitalGamma],
D] = {DirichletCondition[{u[x, y] == -1, v[x, y] == 0}, x == 0.],
DirichletCondition[{u[x, y] == 1., v[x, y] == 0}, 0 < x < 2.0],
DirichletCondition[w[x, y] == 0.1, x == 2.0]};
{xVel, yVel, pressure} =
NDSolveValue[{stokesFlowOperator == {0, 0, 0},
Subscript[\[CapitalGamma], D]}, {u, v,
w}, {x, y} \[Element] \[CapitalOmega],
Method -> {"FiniteElement",
"InterpolationOrder" -> {u -> 2, v -> 2, w -> 1}}];
rmf = RegionMember[\[CapitalOmega]];
Show[BoundaryDiscretizeRegion[\[CapitalOmega]],
DensityPlot[{xVel[x, y], yVel[x, y]}, {x, 0, 2.0}, {y, 0, 0.48208},
RegionFunction -> Function[{x, y}, rmf[{x, y}]],
AspectRatio -> Automatic, PlotLegends -> Automatic,
ColorFunction -> ColorData["BlueGreenYellow"], PlotPoints -> 20],
ImageSize -> 1000]cmutlu2018-06-05T05:50:17ZFix the following "If else" loop with NIntegrate?
http://community.wolfram.com/groups/-/m/t/1354686
Hi. I made a code for "if else" loop in Mathematica. but it's not giving me the output. will anyone help me in that? the import file used in the code is given in the attachment.
Co = 7.325 10^-11;
Vfb = 0.6;
testing =
Import["D:\\Ph.D\\mathematica\\trapz test.xls", {"Data"}][[1,
Range[1, 121], {1, 2}]];
V = Import["D:\\Ph.D\\mathematica\\trapz test.xls", {"Data"}][[1,
Range[1, 121], 1]];
tit = {#[[1]], 1 - #[[2]]/Co} & /@ testing;
daba = Interpolation[tit];
If[Vfb > V,
{NIntegrate[daba[x], {x, #, Vfb}] & /@ V}
, {NIntegrate[daba[x], {x, Vfb, #}] & /@ V}]
output is this:
If[{0.6} > {-5., -4.9, -4.8, -4.7, -4.6, -4.5, -4.4, -4.3, -4.2, \
-4.1, -4., -3.9, -3.8, -3.7, -3.6, -3.5, -3.4, -3.3, -3.2, -3.1, -3., \
-2.9, -2.8, -2.7, -2.6, -2.5, -2.4, -2.3, -2.2, -2.1, -2., -1.9, \
-1.8, -1.7, -1.6, -1.5, -1.4, -1.3, -1.2, -1.1, -1., -0.9, -0.8, \
-0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0., 0.1, 0.2, 0.3, 0.4, 0.5,
0.6, 0.7, 0.8, 0.9, 1., 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8,
1.9, 2., 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3., 3.1, 3.2,
3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4., 4.1, 4.2, 4.3, 4.4, 4.5,
4.6, 4.7, 4.8, 4.9, 5., 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8,
5.9, 6., 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9,
7.}, {(NIntegrate[daba[x], {x, #1, Vfb}] &) /@
V}, {(NIntegrate[daba[x], {x, Vfb, #1}] &) /@ V}]
Thanksrabia khosa2018-06-12T15:59:35ZRLink install problems
http://community.wolfram.com/groups/-/m/t/1353040
Dear all,
when I try to install R the following error occurs:
In[1]:= Needs["RLink`"]
In[2]:= InstallR[]
During evaluation of In[2]:= InstallR::fail: Failed to install R. The following error was encountered: Unable to load dynamic libraries
Out[2]= $Failed
In[3]:= $Version
Out[3]= "11.2.0 for Linux x86 (64-bit) (September 11, 2017)"Luis Mendes2018-06-07T20:50:09ZMake square parenthesis to grow around an arbitrary expression (in output)?
http://community.wolfram.com/groups/-/m/t/1350218
This is a subroutine that I use to put round parentheses around an arbitrary expression (in output).
dExP [expr_]: = TraditionalForm @ Style ["" [expr]];
Parentheses grow according to the size of the expression.
Is there something similar for square brackets?Ernesto Espinosa2018-06-02T00:34:38ZConvert .wav to .mp3?
http://community.wolfram.com/groups/-/m/t/1354906
Hi,
I have a set of audio snippets in .wav format. I've imported these into Mathmatica without any issues, and edited them according to taste. I then tried to export the snippets (we pretend that I have an audio object called 'audiosnippet') using
Export[audiosnippetfile, audiosnippet, "MP3"]
and also
Export["audiosnippetfile.mp3", audiosnippet]
but all I get is white noise. Is there any functionallity in Mathmatica to convert between different audio formats?
Thanks!Fredrik Erling2018-06-12T13:34:40ZMathematica Single Shot Detector Implementation (Object Detection)
http://community.wolfram.com/groups/-/m/t/1273291
Hi Folks,
I have added an implementation of the Single Shot Detector Object detection system to my CognitoZoo project.
![enter image description here][1]
Please see the following link for details (it's a GitHub project):
[CognitoZoo Wiki link][2]
It can recognise the 20 Pascal object categories. It's really quite fun.
I've also got an implementation of Yolo as well in that project. (The Tiny Yolo v2 version)
From playing with both of them, in my experience the SSD VGG 300 detector seems to have better recognition performance than the tiny Yolo version.There are other versions of Yolo which I hope to implement later.
I hope this is of interest.
Thanks,
Julian Francis.
[1]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ssd.jpg&userId=778270
[2]: https://github.com/jfrancis71/CognitoZoo/wiki/SSDVGG300Julian Francis2018-01-28T10:12:30ZDraw the spanning tree of a hypercube with NumberOfSpanningTrees?
http://community.wolfram.com/groups/-/m/t/1345669
Hey there,
The documentation page of this function is quite limited. I followed the instruction but following code does not output useful information:
Needs["Combinatorica`"]
NumberOfSpanningTrees[HypercubeGraph[3]]
I want to draw the spanning true of a hypercube, do you know any internal functions other than this one?
Thankssmile smile2018-05-26T08:40:46ZSemanticImport fails for every file in Mathematica 11.0
http://community.wolfram.com/groups/-/m/t/904715
This is a follow up on this [post][1].
Using SemanticImport on any file, even those mentioned in the Documentation examples e.g. :
SemanticImport["ExampleData/RetailSales.tsv"]
Gives an error:
**SemanticImport::unexpinvaliderr: Unexpected invalid input was detected. Processing will not continue**
I came across an issue with the SemanticImport as my previous attempt to import a large csv file caused a crash of the Mathematica Kernel and took Windows 10 Pro 64-bit with it as it consumed all remaining 4GB RAM.
The work-around mentioned in the aforementioned post still works i.e. make sure you change the path to the temp directory i.e.
Block[{$TemporaryDirectory = "C:\\temp"}, SemanticImport["ExampleData/RetailSales.tsv"]]
Is this a known bug?
Cheers,
Dave
[1]: http://community.wolfram.com/groups/-/m/t/819494?_19_redirect=http://community.wolfram.com/dashboard?p_p_id=3&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&_3_groupId=0&_3_keywords=semanticimport&_3_struts_action=%252Fsearch%252Fsearch&_3_redirect=%252Fweb%252Fcommunity%252F%253Fsource%253DnavDave Middleton2016-08-13T23:48:12ZFrom Intersecting Cylinders to Ambiguous Rings
http://community.wolfram.com/groups/-/m/t/1353471
Intrigued by the [Ambiguous Cylinder Illusion][1], of prof. Kokichi Sugihara, I started looking for explanations with the help of Wolfram Language.
[![enter image description here][2]][1]
The "ambiguous cylinder" can, for purposes of the viewing illusion, be reduced to its upper rim. We call the rim an "ambiguous ring". This ring can be seen as a circle or a square, depending on the viewpoint. Almost perpendicular, viewpoints can be achieved with the help of a mirror.
![enter image description here][3]
Looking parallel to the axis of the circular cylinder or of the square cylinder (prism) will show a circle or a square respectively.
A possible mathematical expression for this "ambiguous curve" can be obtained by investigating the intersection of a circular with a square cylinder. My Wolfram demonstrations [Intersection of Circular and Polygonal Cylinders][4] [1] and [Ambiguous Rings 1: Polygon Based][5] illustrate the different intersection curves obtained by changing the geometry of the cylinders.
For these intersection curves to form a ring, a tight fit between the square cylinder inside the circular one is required. The circumradius of a perfectly fitted square inside a circle of radius 1 is:
fittedradius4[t_] :=
Module[{n}, n = 2 Floor[4 (.5 t + \[Pi]/8)/\[Pi]] - 1;
Cos[t - (n + 1) \[Pi]/4]]
As can be seen in this simple Manipulate:
Manipulate[
ParametricPlot[
1/Sqrt[2] Sec[
1/2 ArcTan[Cot[2 (\[Theta] - \[Theta]0)]]] {Cos[\[Theta]],
Sin[\[Theta]]}, {\[Theta], 0, 2 \[Pi]},
PlotStyle -> Directive[AbsoluteThickness[4], Orange],
PlotRange -> 1.25, ImageSize -> Small, TicksStyle -> 6,
Prolog -> {{Thick, Dotted, Circle[]}, Cyan, AbsoluteThickness[4],
Line[{{-5, fittedradius4[\[Theta]0]}, {5,
fittedradius4[\[Theta]0]}}],
Line[{{-5, -fittedradius4[\[Theta]0]}, {5, \
-fittedradius4[\[Theta]0]}}], AbsolutePointSize[5], Black,
Point[{0, 0}]}],
{{\[Theta]0, 0.5, "axial rotation\nsquare cylinder"}, 0, 10 \[Pi],
ImageSize -> Tiny}, TrackedSymbols :> Manipulate]
![Fitted square][6]
Based on [1], this is the function for a polygonal ringset:
polyRingsetCF =
Compile[{{\[Theta], _Real}, {r, _Real}, {\[Theta]0, _Real}, {d, \
_Real}, {n, _Integer}, {\[Alpha], _Real}},
Module[{t},
t = Sec[2 ArcTan[Cot[1/2 n (\[Theta] - \[Theta]0)]]/
n]; {(*part1*){Cos[\[Pi]/n] Cos[\[Theta]] t,
Cos[\[Pi]/n] t Sin[\[Theta]],
Sec[\[Alpha]] Sqrt[-d^2 + r^2 +
2 d Cos[\[Pi]/n] t Sin[\[Theta]] -
Cos[\[Pi]/n]^2 t^2 Sin[\[Theta]]^2] -
Cos[\[Pi]/n] Cos[\[Theta]] t Tan[\[Alpha]]},
{(*part 2*)Cos[\[Pi]/n] Cos[\[Theta]] t,
Cos[\[Pi]/
n] t Sin[\[Theta]], -Sec[\[Alpha]] Sqrt[-d^2 + r^2 +
2 d Cos[\[Pi]/n] t Sin[\[Theta]] -
Cos[\[Pi]/n]^2 t^2 Sin[\[Theta]]^2] -
Cos[\[Pi]/n] Cos[\[Theta]] t Tan[\[Alpha]]}}]];
ParametricPlot3D[
polyRingsetCF[t, 1., 0.5, 0., 4, 0.], {t, -\[Pi], \[Pi]},
PlotStyle -> {{Red, Tube[.035]}}, PlotPoints -> 500,
PerformanceGoal -> "Quality", SphericalRegion -> True,
PlotRange -> 1.1, Background -> Lighter[Gray, 0.5], ImageSize -> 300,
PlotTheme -> "Marketing"]
![Complete rindset4][7]
If we now use fittedRadius[\[Theta]0] as the circumradius for the square cylinder, we can create closed ringsets as a function the axial rotation \[Theta]0 of the suare cylinder. This is a GIF scrolling through all possible fitted square cylinders inside a circular cylinder of radius 1 :
![Closed Rindsets4][8]
These intersection curves are composite curves (ringsets) consisting each of two separate curves (rings). We can select one of these two rings by introducing the cutoff angles (t1 and t2) in the parametric plot [2].
polyRingCF =
Compile[{{\[Theta], _Real}, {\[Theta]0, _Real}, {r, _Real}, \
{\[Alpha], _Real}, {n, _Integer}, {d, _Real}, {t1, _Real}, {t2, \
_Real}},(*t1 and t2 are the values of \[Theta] for switching between \
parts*)
Module[{t},(*selection of parts of a composite curve*)
t = Sec[2 ArcTan[Cot[1/2 n (\[Theta] - \[Theta]0)]]/n];
{Cos[\[Pi]/n] Cos[\[Theta]] t,
Cos[\[Pi]/n] Sin[\[Theta]] t,(*select part1 or part 2*)
Piecewise[{{1, \[Theta] <= t1 \[Pi] + 2 \[Theta]0 || \[Theta] >
t2 \[Pi] + 2 \[Theta]0}}, -1]*(Sec[\[Alpha]] Sqrt[-d^2 +
r^2 + 2 d Cos[\[Pi]/n] t Sin[\[Theta]] -
Cos[\[Pi]/n]^2 t^2 Sin[\[Theta]]^2]) -
Cos[\[Pi]/n] Cos[\[Theta]] t Tan[\[Alpha]]}]]
printring4 =
ParametricPlot3D[
polyRingCF[\[Theta], 0., fittedradius4[0.], 0., 4,
0., -.5, .5], {\[Theta], -\[Pi], \[Pi]}, SphericalRegion -> True,
PlotStyle -> {Green, Tube[.05]}, Boxed -> False, Axes -> False,
PlotRange -> 1.05, PlotPoints -> 100, ImageSize -> Small,
PlotTheme -> "ThickSurface"]
![Ring41][9]
This is a GIF showing the different views of this ring: among them a circle, a square, a "lemniscate", etc...
![enter image description here][10]
To test this "ambiguous ring" in a mirror setup, we use Printout3D to send the file to Sculpteo for 3D-printing:
Printout3D[printring4, "Sculpteo", RegionSize -> Quantity[5, "cm"]]
![Sculpteo ring41][11]
And when reflected in an experimental mirror setup:
![Reflected image][12]
The physical ring looks like a circle while the reflected ring looks like a square.
For those who like to print this ring themselves, [This][13] is the link to the Sculpteo file.
[1]: http://illusionoftheyear.com/2016/06/ambiguous-cylinder-illusion/
[2]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2018-06-11at11.52.29AM.png&userId=20103
[3]: http://community.wolfram.com//c/portal/getImageAttachment?filename=mirror-eyeview.png&userId=68637
[4]: http://demonstrations.wolfram.com/IntersectionOfCircularAndPolygonalCylinders/
[5]: http://demonstrations.wolfram.com/preview.html?draft/35335/000250/AmbiguousRings1PolygonBased
[6]: http://community.wolfram.com//c/portal/getImageAttachment?filename=rotatingpoly4.png&userId=68637
[7]: http://community.wolfram.com//c/portal/getImageAttachment?filename=8124curveplot.png&userId=68637
[8]: http://community.wolfram.com//c/portal/getImageAttachment?filename=allClosedPolyRingsets4.gif&userId=68637
[9]: http://community.wolfram.com//c/portal/getImageAttachment?filename=1284communityring41.png&userId=68637
[10]: http://community.wolfram.com//c/portal/getImageAttachment?filename=9891ezgif.com-gif-maker.gif&userId=68637
[11]: http://community.wolfram.com//c/portal/getImageAttachment?filename=sculpteoring41.png&userId=68637
[12]: http://community.wolfram.com//c/portal/getImageAttachment?filename=IMG_5862.jpg&userId=68637
[13]: https://www.sculpteo.com/en/print/model-c2c6f7e7stl/7QTBvwnD?uuid=DSIBRp6xjqbATLH201iFSbErik Mahieu2018-06-08T14:44:16ZGet the Piechart Labeling style found in a documentation example, MMA 11.3?
http://community.wolfram.com/groups/-/m/t/1354152
Hi there,
Regarding to Version 11.3 ["ref/PieChart" page][1] -> Applications (15)-> the third example.
Before evaluation:
![before][2]
After evaluation: (tiny pie chart as label )
![after][3]
Question: How to revert to the style in the first picture?
[1]: http://reference.wolfram.com/language/ref/PieChart.html
[2]: http://community.wolfram.com//c/portal/getImageAttachment?filename=2268Sketch.png&userId=23928
[3]: http://community.wolfram.com//c/portal/getImageAttachment?filename=Sketch2.png&userId=23928Shenghui Yang2018-06-11T10:31:08ZRecognize number string patterns?
http://community.wolfram.com/groups/-/m/t/1345054
Hey everyone,
I've been wondering if there is a good way to find patterns in Mathematica. I'm aware of the existence of the possibility to use string patterns and related functions to work with patterns, but those don't seem to be the best choice for finding patterns in number strings.
I would love to find the 'underlying' pattern in a number string without knowing a priori what the pattern is myself.
Let me make an example:
Given the following string of numbers: 01100110011020110, I would like to use a implemented function to get, that the 'underlying' pattern is 0110, because it always repeats itself and the recurrence is only affected by the occuring 2.
Does anyone of you of a function, would allow something like this or could be used for this?
Best,
RobertRobert Marks2018-05-25T14:45:12ZBuild a convolutional neural network that works on 3D data?
http://community.wolfram.com/groups/-/m/t/1353958
There are a many examples of 2D Convolutional Neural Networks, but i was trying to build one that works on 3D data. Most common Layers (e.g. ConvolutionLayer) work on any dimension, however the DeconvolutionLayer only works in 2D.
Does anyone know a solution/workaround for this?
EDIT
One option i found was to use a ResizeLayer which has no trainable parameters. However this also does not work in 3D. So down-scaling is possible in 3D but up-scaling I cannot find a method for.
EDIT2
Using a combination of ResizeLayer and Convolution layer in 2D i was able to get similar results as using a DeconvolutionLayer in a UNET. With this in mind and the use of TranposeLayers, FlattenLayers, ResizeLayers and ReshapeLayers I was able to generate the needed behaviour in 3D. Although not the most elegant solution it seem to do its job.msHaBa ali2018-06-10T10:53:24ZEvaluate PDF of multivariate Weilbull distribution with 3,4,5 dimensions?
http://community.wolfram.com/groups/-/m/t/1353913
I wan to evaluate PDF of multivariate Weilbull distribution with 3,4,5 dimention . Anyone can help me ?The RainMan2018-06-09T15:38:00ZEmbed wolfram function in python and get returned values in python?
http://community.wolfram.com/groups/-/m/t/1353211
I want to embed a function in wolfram in python so that I can pass in parameters to wolfram function, which would do the manipulation and return the values back to python
let's say a simple function: `gamma = Function [{x},
y = x*x ; y = y*4]`Sagar Mankari2018-06-07T21:39:55Z