Below is an animated gif of the end result of this post or you can see the real page here.
I have spent the last year learning some of the maths I should have learned about 27 years ago. One of the things that I have found interesting while learning maths is the relationship between the unit circle and a sine wave graph of
y = sin(x).
A sine wave is a mathmatical curve that describes a smooth repetitive oscillation and the unit circle is a circle of radius 1 centred at the origin
(0, 0). The unit circle can be used to find special trigonometric ratios as well as aid in graphing. There is also a real number line wrapped around the circle that serves as the input value when evaluating trig functions.
A sine wave is a periodic function or a function that repeats itself at regular intervals. The most important examples of periodic functions are the trigonometric functions that repeat themselves over intervals of 2π. One journey around the unit circle is 360 degrees or 2π in radians. A sine wave shows the excursion around the circle happening in time. A sine wave is ultimately a circle expressed in time. I have used d3.js to illlustrate how the journey around the circle corresponds to the sine wave movement over time.
There are a number of concepts that I wanted to capture in the animation:
Illustrate where the input value of the unit circle corresponds to the
(x, y)coordinate on the horizontal axis of the sine wave.
Demonstrate how the right angle is formed by the angle of the radius moving counter-clockwise around the unit circle.
Show the number scale of the unit circle in radians as ratios in proper mathmatical notation in the browser in both the unit circle and the x axis of the sine graph. MathJax appears to be the only show in town that fits this requiremnt.
This process of creating graphs from the unit circle is often called unwrapping the unit circle.
Unit Circle Setup
The first step is to create the basic shapes that will illustrate the unit circle and use cartesian coordinates to position them. D3.js has an excelent scale abstraction that allows you to deal in a finer grained scale than pixels. I can now think of the dimensions of the svg document as a 20 x 20 grid which makes positioning things easier to reason about.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
On lines 6 and 10 of the above code, horizontal
x and vertical
y scales are created and bound to two variables. These d3
scale functions take the input domain of 0 to 20 and map it to an output range of either the viewport width for the horizontal
x axis or the viewport height for the vertical
y axis. It is much easier to think of cartesian coordinates with ranging from 0 to 20 rathen than the very fine grained pixel scale.
With the scales in place, it is much easier to start positioning the elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
An svg group element or a
g element is created on line 5. All elements will be added to this group or container. Transformations applied to an svg group or
g element are applied to all elements in the group which makes it extremely useful.
The 3 lines that will make up the right angle triangle are created and bound to the
hypotenuse variables using the d3.js svg line shape. The initial values of the triangle line’s
y2 coordinates are irrelevant at this stage, they will be set on each tick of the animation. It is just important to get them onto the document during the initialisation phase.
The larger unit circle is created and appended onto the group on line 10 of the above snippet and another smaller circle is added on line 38 which will be positioned counter-clockwise around the large circle by setting its
cy coordinates on each tick of the animation. This will give the impression that the small circle is rotating around the larger circle.
Below is how things look so far:
The next stage is to add the number line in radians of the unit circle:
In order to divide the circle into 8 lines and position the labels, I can kill two birds with one stone by creating an array of objects which have label and angle properties that I can iterate over and create the lines and labels:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Lines 2 to 11 define the array of objects to iterate over. Each object contains a
val property that can be thought of as an angle to move counter-clockwise around the unit circle for each element in the array. There is also a label property which is the text of the angle in radians. The cryptic syntax of the label is written in LaTex, which allows you to define mathmatical notation that can be displayed in the browser. Mathjax will later parse these labels into authentic looking math symbols in the browser. More on my difficulties with MathJax at the end of the post.
On lines 12 and 13 the
y coordinates are determined for each angle value in the array. By finding the
cos(x) * radius and
sin(x) * radius of each angle in the iteration of objects, I can ascertain the (
y) coordinate of the point on the circumference of where to position the radian label and of where do draw the dividing line that will show the number scale on my unit circle.
Lines 15 to 16 add offset values for each
y coordinate to ensure the labels all appear outside of the circle and not flush on the circumference.
Line 18 adds a new svg group element and the textual label is added to this newly created group.
Line 24 simply adds a line from the centre of the circle to the
y coordinates on the circumference.
Before MathJax does the parsing, the circle looks like this:
A similar approach is used to create the sine graph axis but instead of iterating over an array, a pair of d3.js axis are created and in the x-axis instance, latex symbols are employed for the tickValues or labels of this axis.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
The basic setup is now complete:
Animating the unit circle
My first step is to create a hash of values that I am going to pass into the animation function that will set the new position of the elements on each tick of the animation. After that, the animation is kicked off with a call to
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Arguably the most important value in the above is the
time property on line 15 this will provide the
x value or the horizontal value of the sine graph. This will be incremented on each tick of the animation.
drawGraph function is below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
Every time the
drawGraph function is called, the
time property of the
state variable is incremented by roughly 1 degree on line 4 to simulate time moving along the x axis. I do the same on line 5 for the circle that travels along the
x axis. I have a separate counter as I need to reset it to zero each time the
xIncrement variable exceeds 2π.
Line 7 calls the
drawSine function that draws the sine wave on each tick of the animation. More on this later.
Lines 9 to 17 position the small circle traveling alon the horizontal
x axis and resetting the counter each time it exceeds 2π.
The rest of the code in this function takes care of finding and positoning the shapes on the unit circle to simulate the small circle rotating counter-clockwise on the unit circle and constructing the right angle triangle.
Lines 19 and 20 find the next
y coordinates of the next point on the circumference of where to position the small circle and bind them to the variables
dx. I use
radius * -Math.sin(state.time) because we want to simultate rotating back counter-clockwise. Once we have this coordintate it is easy to position the three lines that make up the right angled triangle on lines 26 to 38.
Line 49 calls requestAnimationFrame which tells the browser that you wish to perform an animation and requests the browser call a specific function,
drawGraph in this instance, before the next browser repaint.
I am also using a lesser known overload of bind on line 37 that allows you to create a new partially applied function with some or all of the arguments already bound each time it is called. I have blogged about this previously here. In this case, the
state hash will be bound every time the function is called because I am passing it into
bind as an extra argument after
Animating the Sine wave
Now to the meat and potato of the piece, namely animating a smooth sine wave. The sine wave is mathmatically a very simple curve and a very simple graph. It is a simple
y plot with the x-axis representing time and the y-axis representing angular displacement around the unit circle.
Below is the
drawSineWave function that is called on each tick of the animation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
The fist step on line 2 is to remove the previously plotted curve before recreating it on each tick of the animation.
Lines 4 to 8 creates the points that will be used to plot the sine graph against.
One Line 4 the an array of integers is initialized using the d3
range function is used, this will create an array of 54 elements ranging from 0 to 53:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13...etc...53]
The upper bound of the array which is 53 is chosen to fill the available width in the viewport
I will come back to why the calculation on line 5 is needed but on line 6 I do a further
map of the array that was initialised on line 4 to create an
y coordinate for each element in the array that can be used to plot the sine wave. The
x coordinate is simply the element of the array and y is calculated by getting the negative
x because we are simulating the sine wave moving counter-clockwise. For each tick of the animation we simply subtract the
state.time variable that we have used previously from
x. If you look at the animation, you can see how the small circle in the middle of the unit circle moves up and down at exactly the same rate. Maths in action!
Below is how the sine wave looks without the rather crtypic looking
.map(x => x * 10 / 84) transformation applied to the original array:
If we just use integers to plot the points we get the rough sine wave but if we use floats, we get a much smoother flowing sine wave. I multiply each value by 10 to space it out across the width and then divide by 84 to ensure I get a float back. 84 was arrived at by trial and error to ensure the wave spans across the graph.
Once I have my coordinates to plot the curve, the following code takes care of creating the curve on each animation tick:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Lines 7 to 10 define a d3 line function that will be used by the svg path element on lines 12 to 15. The d3
line function can be thought of as a path generator for a line or in this case a curve as the interpolation mode is set to montone interpolation in order to create a smooth curve for the sine wave. The
line function will take the data array (
sineData) and convert it into the rather cryptic svg path mini language instructions that the svg path element on lines 12 to 15 will use to construct the curve. We define accessor functions on lines 9 and 10 that will be called for every
y coordinate of the
sineData array on line 1. A monotone interpolation will then be performed by the path function for each point. Every
y is mapped to the correct scale on lines 3 and 4.
Lines 12 to 15 attach the path element and sets its data via the
datum attribute. The
d attribute sets the path data or the mini language of path commands that the line function on line 7 will generate. The
y accessors of the
line function are invoked exactly once for each element in the array.
All that remains is to tell MathJax to parse the latex into math symbols. I cannot believe how hard I found this. Below is how the code ended up after a lot of coffee, profanity and self doubt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
First of all MathJax did not seem to play nicely with react, I have to use a
wait function to suspend execution until the MathJax is available. On lines 12 to 18 can best be desribed as extreme hackery. I have tagged any element on the svg document that contains latex with the
tick css class. I add a hook to mathjax that is called whenever it has done its first parse, I then remove the svg element that was added by MathJax and readd it again. This causes MathJax to reparse it and the symbols are rendered correctly. I don’t know if it was the fact that this is a react site that made this so difficult but it really did not play well with this site.
wait function is below for completeness:
1 2 3 4 5 6 7
I found this hugely enjoyable and I am more than satisfied with the result. This probably means I should get out more.
If you disagree with any of the above or can suggest better ways then please leave a comment below.