L-System tree won't branch correctly - c++

I have tried to implement the L-System in c++ with SFML, but for some reason it doesn't work as expected.
I tried replicating this program:
https://www.youtube.com/watch?v=E1B4UoSQMFw?t=1256
And everything works fine except the branching. At the timestamp(20:56) you can see the tree branching off into two branches, and these two branches branch off individually.
However, this shouldn't be possible due to the rules(the turtle can save position/rotation to make a new branch, but it can only save one position at a time so branching off inside a branch multiple times isn't possible)
In my program instead of branching off in two branches that are branching off individually only one of the branches(right one) branches of further, as should be expected.
But why then does his code produce a completely different result, that shouldn't be possible with this ruleset?

You implemented an L system with the following alphabet:
Alphabet: F+-[]
And the following rule:
Rule 1: F → FF+[+F-F-F]-[-F+F+F]
The meanings of the alphabet characters are very turtle-graphic-like and are as follows:
F Move forward 1 unit and draw a line as you go.
+ Turn Clockwise
- Turn Counter-Clockwise
[ Push the current state onto the stack.
] Pop state from the stack and make it the current state.
This requires that you know what a stack is.
You can see, because there is an F inside the square brackets in the rule, how in the second generation there will be nested square brackets.
(Sorry for the long line below, but it's a long rule and breaking the line would be confusing. Just scroll right. Observe how I have highlighted the outer group of matching nested brackets.)
FF+[+F-F-F]-[-F+F+F]FF+[+F-F-F]-[-F+F+F]+[+FF+[+F-F-F]-[-F+F+F]-FF+[+F-F-F]-[-F+F+F]-FF+[+F-F-F]-[-F+F+F]]-[-FF+[+F-F-F]-[-F+F+F]+FF+[+F-F-F]-[-F+F+F]+FF+[+F-F-F]-[-F+F+F]]
[...............................................................] [...............................................................]
When applying the turtle-graphics interpretation, when we encounter a second [ before encountering a ], we will now have multiple states saved on the stack. An arbitrary number of states may be saved. The stack is "first in, last out", much like stacking plates, you can only access the plate at the top of the stack. Each time you push state with [ it's like adding a plate to the stack of plates. When you see a ] you remove the top plate from the stack. To remove a plate from the top of the stack in this way is to pop it. Each plate, in this scenario, represents the state of the turtle as it was when it was pushed. Popping a state restores the turtle's position and orientation back to that saved position.

Related

Can we send output from 1 branch to another in parallel type step function execution?

I need the output from that 2nd branch to be included as input to 1st branch's next step. Like multiple inheritance just check the diagram to get clear picture.
You want indeed an inner parallel block to reconciliate the two branches.
Sorry for the bad quality of my drawing.
And in this specific context, it could also mean that the step should be outside of the parallel block, if you want to have one single parallel block.

Skip gram in word2vec - what is the number of outputs

The following images are often represented to describe the word2vec model with skip-gram:
However, after reading this discussion on stackoverflow, it seems that word2vec actually take 1 word and input and 1 word as output. The output word is randomly samples from the window. (And this is performed X number of times to generate X input/output pairs.)
It seems to me then that the above image is not correctly describing the network. My question is: is the 1 input/1 output standard (the Tensorflow word2vec tutorial takes this approach and calls it skip-gram) or do some networks actually take the structure of the above image?
It's not a great diagram.
In CBOW, those converging arrows are an averaging that happens all-at-once, to create one single 'training example' (desired prediction) that is (average(context1, context2, ..., contextN) -> target-word). (In practice averaging is more common than the 'SUM' shown in the diagram.)
In Skip-Gram, those diverging arrows are multiple training examples (desired predictions) made one-after-the-other.
And in both diagrams, while they look a bit like neural-net node-architectures, the actual hidden-layer and internal-connection weights are just implied inside the middle-column-to-right-column arrows.
Skip-gram is always 1 "input" context word used to predict 1 nearby (within the effective 'window') "output" target word.
Implementations tend to iterate through the whole effective window, so every (context -> target) pair gets used as a training-example. And in practice, it doesn't matter if you consider the central word the target-word and each word around it to be context-words, or the central word the context-word and each word around it to be target-words – both methods result in the exact same set of (word -> word) pairs being trained, just in a slightly different iteration order. (I believe the original Word2Vec paper described it one way, but then Google's released code did it the other way for reasons of slightly-better cache efficiency.)
In fact the effective window, for each central word considered, is chosen to be some random number from 1 to the configured maximum window value. This turns out to be a cheap way of essentially weighting nearer-words more: the immediate neighbors are always part of training-pairs, further words only sometimes. That is, pairs are not randomly sampled from the whole window - it's just a random window size. (There's another down-sampling where the most-frequent words will be randomly dropped so as not to overtrain them at the expense of less-frequent words, but that's a totally separate process not reflected in the above.)
In CBOW, instead of up-to 2*window input-output pairs of the (context-word -> target-word) form, there's a single input-output pair of (context-words-average -> target-word). (In CBOW, a loop creates the average value for a single N:1 training-example for one central word, and then splits the backpropagated error across all contributing words. In skip-gram, a loop creates multiple alternate 1:1 training-examples for one central word.)

Use the function "mod" in the instructions "if" and "select case"

I wrote a little code in Fortran. But the code doesn't behave as I thought, and I can figure out where is the problem.
I will not put the code here because it has 1200 lines but here its philosophy:
I create a 3D grid represented by a four dimensional table (I stock a vector of 2 elements on each point of the grid, corresponding at the nature of the site and who is occupying the site). This grid represents what we call a crystal (where atoms can be found periodically)
When this grid is constructed, the code scans each point of this grid and it looks to the neighboring sites to count the different type of atoms or the vacancies.
For this last point, I use a triple imbricated loop which permit to explore the different sites and I check the different neighboring site using either the if or the select case instructions. As I want my grid to be periodic, I have the function mod in the argument of the if or the select case.
The problem is sometimes, It found a different element in a neighboring site that the actual element in this specific neighboring site. As an example:
In the two ouput files where all the coordinates are written with the
element type I have grid(0,0,1)=-1 (which correspond to a empty site).
But while the code is looking to the neighboring sites of grdi(0,0,1) It tells that there is actually an element indexed 2 in grid(0,0,1).
I look carefully to the block in the triple implemented loop, but it seems fine.
I would like to know if anyone has already meet this kind of problem, or know if there is some problems using mod in a if or select case argument ?
If some of you want to look closer, I can send you the code, with some explanations.
Arrays are usually dimensioned as:
REAL(KIND=8),DIMENSION(0:N) ::A
or
REAL(KIND=8),DIMENSION(N) :: A
In the later example, they are assumed to start at 1.
You could also go (-N:N) or (10:191)
If you use the compiler switch '-check bounds' or ;-check all' you will see if you are going outside the array/etc. This is not an uncommon thing to get hosed up, but the compiler will abort quickly when the dimension is outside.
Once it works then removed the -check bounds and/or -check all.
Thanks for your consideration francescalus and haraldkl.
It was not related to the dimension of arrays Holmz, but thank you to try to help
It seems I finally succeed to fix it. I will post an over answer If I fully understand why it was not working properly.
Apparently, it was related to the combination of a different argument order in a call procedure and the subroutine header + a declaration in the subroutine with intent(inout).
It was like the intent(inout) was masking the problem. But It a bit strange for me.
Some explanations about the code :
As I said, the code create a 3D grid where each intersection of the 3D grid correspond to a crystallographic site. I attribute a value at each site -1 for an empty site, 1 for a crystal atom (0 if there is a vacancy instead of a crystal atom), 2,3,4,5 for different impurities. Actually, the empty sites and the sites which received crystal atoms are not of the same type, that's why an empty site and a vacancy are distinguished. The impurities can only occupied the empty site and are forbidden to occupied a crystal site.
The aim of the code is to explore the configurational space of the system, in other words all the possible distribution we can obtained with the different elements. To do so I start from a initial configuration and I choose randomly to site (respecting the rules of occupation) and I virtually switch them. I calculate the energy of the old an new configurations, if the new has a lower energy I keep it, if not, i keep the old one. The calculus of the energy is based on the knowledge of the environment of each vacancies and impurities, so we need to know their neighbors. And I repeat the all procedure again and again to converge to the most stable (so the most probable) configuration.
The next step is to include the temperature effect, and to add the second type of empty sites.
Have a nice day,
M.

How to normalize sequence of numbers?

I am working user behavior project. Based on user interaction I have got some data. There is nice sequence which smoothly increases and decreases over the time. But there are little discrepancies, which are very bad. Please refer to graph below:
You can also find data here:
2.0789 2.09604 2.11472 2.13414 2.15609 2.17776 2.2021 2.22722 2.25019 2.27304 2.29724 2.31991 2.34285 2.36569 2.38682 2.40634 2.42068 2.43947 2.45099 2.46564 2.48385 2.49747 2.49031 2.51458 2.5149 2.52632 2.54689 2.56077 2.57821 2.57877 2.59104 2.57625 2.55987 2.5694 2.56244 2.56599 2.54696 2.52479 2.50345 2.48306 2.50934 2.4512 2.43586 2.40664 2.38721 2.3816 2.36415 2.33408 2.31225 2.28801 2.26583 2.24054 2.2135 2.19678 2.16366 2.13945 2.11102 2.08389 2.05533 2.02899 2.00373 1.9752 1.94862 1.91982 1.89125 1.86307 1.83539 1.80641 1.77946 1.75333 1.72765 1.70417 1.68106 1.65971 1.64032 1.62386 1.6034 1.5829 1.56022 1.54167 1.53141 1.52329 1.51128 1.52125 1.51127 1.50753 1.51494 1.51777 1.55563 1.56948 1.57866 1.60095 1.61939 1.64399 1.67643 1.70784 1.74259 1.7815 1.81939 1.84942 1.87731
1.89895 1.91676 1.92987
I would want to smooth out this sequence. The technique should be able to eliminate numbers with characteristic of X and Y, i.e. error in mono-increasing or mono-decreasing.
If not eliminate, technique should be able to shift them so that series is not affected by errors.
What I have tried and failed:
I tried to test difference between values. In some special cases it works, but for sequence as presented in this the distance between numbers is not such that I can cut out errors
I tried applying a counter, which is some X, then only change is accepted otherwise point is mapped to previous point only. Here I have great trouble deciding on value of X, because this is based on user-interaction, I am not really controller of it. If user interaction is such that its plot would be a zigzag pattern, I am ending up with 'no user movement data detected at all' situation.
Please share the techniques that you are aware of.
PS: Data made available in this example is a particular case. There is no typical pattern in which numbers are going to occure, but we expect some range to be continuous with all the examples. Solution I am seeking is generic.
I do not know how much effort you want to involve in this problem but if you want theoretical guaranties,
topological persistence seems well adapted to your problem imho.
Basically with that method, you can filtrate local maximum/minimum by fixing a scale
and there are theoritical proofs that says that if you sampling is
close from your function, then you extracts correct number of maximums with persistence.
You can see these slides (mainly pages 7-9 to get the idea) to get an idea of the method.
Basically, if you take your points as a landscape and imagine a watershed starting from maximum height and decreasing, you have some picks.
Every pick has a time where it is born which is the time where it becomes emerged and a time where it dies which is when it merges with an higher pick. Now a persistence diagram pictures a point for every pick where its x/y coordinates are its time of birth/death (by assumption the first pick does not die and is not shown).
If a pick is a global maximal, then it will be further from the diagonal in the persistence diagram than a local maximum pick. To remove local maximums you have to remove picks close to the diagonal. There are fours local maximums in your example as you can see with the persistence diagram of your data (thanks for providing the data btw) and two global ones (the first pick is not pictured in a persistence diagram):
If you noise your data like that :
You will still get a very decent persistence diagram that will allow you to filter local maximum as you want :
Please ask if you want more details or references.
Since you can not decide on a cut off frequency, and not even on the filter you want to use, I would implement several, and let the user set the parameters.
The first thing that I thought of is running average, and you can see that there are so many things to set, to get different outputs.

C++, determine the part that have the highest zero crosses

I’m not specialist in signal processing. I’m doing simple processing on 1D signal using c++. I want really to know how I can determine the part that have the highest zero cross rate (highest frequency!). Is there a simple way or method to tell the beginning and the end of this part.
This image illustrate the form of my signal, and this image is what I need to do (two indexes of beginning and end)
Edited:
Actually I have no prior idea about the width of the beginning and the end, it's so variable.
I could calculate the number of zero crossing, but I have no idea how to define it's range
double calculateZC(vector<double> signals){
int ZC_counter=0;
int size=signals.size();
for (int i=0; i<size-1; i++){
if((signals[i]>=0 && signals[i+1]<0) || (signals[i]<0 && signals[i+1]>=0)){
ZC_counter++;
}
}
return ZC_counter;
}
Here is a fairly simple strategy which might give you some point to start. The outline of the algorithm is as follows
Input: Vector of your data points {y0,y1,...}
Parameters:
Window size sigma.
A threshold 0<p<1 defining when to start looking for a region.
Output: The start- and endpoint {t0,t1} of the region with the most zero-crossings
I won't give any C++ code, but the method should be easy to implement. As example let us use the following function
What we desire is the region between about 480 and 600 where the zero density higher than in the front. First step in the algorithm is to calculate the positions of zeros. You can do this by what you already have but instead of counting, you store the values for i where you met a zero.
This will give you a list of zero positions
From this list (you can do this directly in the above for-loop!) you create a list having the same size as your input data which looks like {0,0,0,...,1,0,..,1,0,..}. Every zero-crossing position in your input data is marked with a 1.
The next step is to smooth this list with a smoothing filter of size sigma. Here, you can use what you like; in the simplest case a moving average or a Gaussian filter. The higher you choose sigma the bigger becomes your look around window which measures how many zero-crossings are around a certain point. Let me give the output of this filter together with the original zero positions. Note that I used a Gaussian filter of size 10 here
In a next step, you go through the filtered data find the maximum value. In this case it is about 0.15. Now you choose your second parameter which is some percentage of this maximum. Lets say p=0.6.
The final step is to go through the filtered data and when the value is greater than p you start to remember a new region. As soon as the value drops below p, you end this region and remember start and endpoint. Once you are finished walking through the data, you are left with a list of regions, each defined by a start and an endpoint. Now you choose the region with the biggest extend and you are done.
(Optionally, you could add the filter size to each end of the final region)
For the above example, I get 11 regions as follows
{{164,173},{196,205},{220,230},{241,252},{259,271},{278,290},
{297,309},{318,327},{341,350},{458,468},{476,590}}
where the one with the biggest extend is the last one {476,590}. The final result looks (with 1/2 filter region padding)
Conclusion
Please don't be discouraged by the length of my answer. I tried to explain everything in detail. The implementation is really just some loops:
one loop to create the zero-crossings list {0,0,..,1,0,...}
one nested loop for the moving average filter (or you use some library Gaussian filter). Here you can at the same time extract the maximum value
one loop to extract all regions
one loop to extract the largest region if you haven't already extracted it in the above step