# Clifford Attractors

## Clifford Attractors

This kind of reminded me of Nevyn's, LTAM's and Jared's 3-D work. Just saw the interesting plotting effects with this:

http://paulbourke.net/fractals/clifford/

https://fronkonstin.com/2017/11/07/drawing-10-million-points-with-ggplot-clifford-attractors/

------------R Code ----------------
library(Rcpp)
library(ggplot2)
library(dplyr)

opt = theme(legend.position = "none",
panel.background = element_rect(fill="white"),
axis.ticks = element_blank(),
panel.grid = element_blank(),
axis.title = element_blank(),
axis.text = element_blank())

cppFunction('DataFrame createTrajectory(int n, double x0, double y0,
double a, double b, double c, double d) {
// create the columns
NumericVector x(n);
NumericVector y(n);
x[0]=x0;
y[0]=y0;
for(int i = 1; i < n; ++i) {
x[i] = sin(a*y[i-1])+c*cos(a*x[i-1]);
y[i] = sin(b*x[i-1])+d*cos(b*y[i-1]);
}
// return a new data frame
return DataFrame::create(_["x"]= x, _["y"]= y);
}
')

a=-1.24458046630025
b=-1.25191834103316
c=-1.81590817030519
d=-1.90866735205054

df=createTrajectory(10000000, 0, 0, a, b, c, d)

png("Clifford.png", units="px", width=1600, height=1600, res=300)
ggplot(df, aes(x, y)) + geom_point(color="black", shape=46, alpha=.01) + opt
dev.off()

Cr6

Posts : 1149
Join date : 2014-08-09

## Re: Clifford Attractors

Very interesting, and I really like the "sketch" effect. I'm going to try to use such an effect in my next animation, as a motion-trail or path indicator, instead of the ghosting and stuff I've been using which adds to unnecessary clutter. Thanks for sharing, Cr6.

Jared Magneson

Posts : 490
Join date : 2016-10-11

## Re: Clifford Attractors

Hey! No-one told me you could embed C++ code into R! You guys have been holding out on me.

It took me a few reads to even realise that I was reading it as C code. I was thinking about how to port my OpenCL code, which is a variant of C, into R to generate the paths. It should be pretty easy, I thought, and then I looked at that function call cppFunction and realised what that means.

Nevyn

Posts : 1540
Join date : 2014-09-11

## Re: Clifford Attractors

.
I agree, very pretty.

I like paths too, and would love to be able to include the option in Boids so that I could better observe near-collision slingshot like accelerations which are almost as common as direct collisions.

I tried running the Clifford attractor code, no joy.

> library("ggplot2", lib.loc="~/R/win-library/3.3")
Warning message:
package ‘ggplot2’ was built under R version 3.3.3

I’m running R version 3.3.2 (2016-10-31) -- "Sincere Pumpkin Patch".
Tried updating to the latest release (Thursday 2017-09-28, Short Summer)

Warning in install.packages :
unable to move temporary installation ‘C:\Users\Robert\Documents\R\win-library\3.3\file12a07a2e4271\ggplot2’ to ‘C:\Users\Robert\Documents\R\win-library\3.3\ggplot2’

I couldn't find the specified file. Tried reloading ggplot2 with the same Warning and
Error: could not find function "ggplot".

I've used ggplot in my R code here at the site before.
R version 3.4.3 (Kite-Eating Tree) prerelease versions will appear starting Monday 2017-11-20. Final release is scheduled for Thursday 2017-11-30.

I’ll try updating R again in December.
.

LongtimeAirman

Posts : 1196
Join date : 2014-08-10

## Re: Clifford Attractors

R has libraries that can allow for running other languages/scripts (rJava, rPython) and make useful function calls. This really expands R's ability to re-use existing code. I was shocked too Nevyn when I first saw calls to other languages and thought "Nice!" should have commented on that back in the day.

Airman I think you might need to right-click on the latest R installer .exe and ensure you "Run as Admin" for the install. Looks like possibly Windows choked on copying the temp folder to the actual R install location for ggplot2. BTW, I always try to run the Rgui.exe or RStudio as an Admin when updating R packages or installing new packages in Windows.

CRAN version:
https://cran.r-project.org/bin/windows/base/R-3.4.2-win.exe

MRAN version (Microsoft's version):

BTW, this article has a code block to create a gif in R from the Image Magick library. It can be used to read and parse image text as well from image files into plain text:
https://cran.r-project.org/web/packages/magick/vignettes/intro.html
install.packages("magick")

https://fronkonstin.com/2014/11/11/3d-harmonographs-in-motion/

library(rgl)
library(scatterplot3d)
#Extending the harmonograph into 3d
#Antonio's functions creating the oscillations
xt = function(t) exp(-d1*t)*sin(t*f1+p1)+exp(-d2*t)*sin(t*f2+p2)
yt = function(t) exp(-d3*t)*sin(t*f3+p3)+exp(-d4*t)*sin(t*f4+p4)
#Plus one more
zt = function(t) exp(-d5*t)*sin(t*f5+p5)+exp(-d6*t)*sin(t*f6+p6)
#Sequence to plot over
t=seq(1, 100, by=.001)
#generate some random inputs
f1=jitter(sample(c(2,3),1))
f2=jitter(sample(c(2,3),1))
f3=jitter(sample(c(2,3),1))
f4=jitter(sample(c(2,3),1))
f5=jitter(sample(c(2,3),1))
f6=jitter(sample(c(2,3),1))
d1=runif(1,0,1e-02)
d2=runif(1,0,1e-02)
d3=runif(1,0,1e-02)
d4=runif(1,0,1e-02)
d5=runif(1,0,1e-02)
d6=runif(1,0,1e-02)
p1=runif(1,0,pi)
p2=runif(1,0,pi)
p3=runif(1,0,pi)
p4=runif(1,0,pi)
p5=runif(1,0,pi)
p6=runif(1,0,pi)
#and turn them into oscillations
x = xt(t)
y = yt(t)
z = zt(t)
#create values for colours normalised and related to x,y,z coordinates
cr = abs(z)/max(abs(z))
cg = abs(x)/max(abs(x))
cb = abs(y)/max(abs(y))
dat=data.frame(t, x, y, z, cr, cg ,cb)
#plot the black and white version
with(dat, scatterplot3d(x,y,z, pch=16,cex.symbols=0.25, axis=FALSE ))
with(dat, scatterplot3d(x,y,z, pch=16, color=rgb(cr,cg,cb),cex.symbols=0.25, axis=FALSE ))
#Set the stage for 3d plots
# clear scene:
clear3d("all")
# white background
bg3d(color="white")
#lights...camera...
light3d()
#action
# draw shperes in an rgl window
#create animated gif (call to ImageMagic is automatic)
movie3d( spin3d(axis=c(0,0,1),rpm=5),fps=12, duration=12 )
#2d plots to give plan and elevation shots
plot(x,y,col=rgb(cr,cg,cb),cex=.05)
plot(y,z,col=rgb(cr,cg,cb),cex=.05)
plot(x,z,col=rgb(cr,cg,cb),cex=.05)

Cr6

Posts : 1149
Join date : 2014-08-09

## Re: Clifford Attractors

Hey Cr6, are you proficient in using matrices in R? I have some code I think would work well for this type of situation but it is heavy on the matrices. Pretty hard to avoid in 3D work. I can re-work it to generate the location of a BPhoton with any number of spin levels (within reason). Then iterate over that to generate a series of locations over time.

If you can take a series of 3D points and generate that into a 2D image then we can generate something like the image above but it will be the spin path of a particle. If you could render those points as a line then it would generate the same paths that SpinSim can but even just the points would be interesting. It would show a density graph where more dense areas are where the BPhoton spends a lot of its time.

Maybe I should add a point representation to SpinSim? I didn't think it would be useful but I'm starting to see it might be.

Nevyn

Posts : 1540
Join date : 2014-09-11

## Re: Clifford Attractors

.
Thanks for the info Cr6. I should have said I enjoyed Fronkonstin’s site Experiments in R. He refers to his 3D-Harmonographs In Motion in the comments section to the Clifford Attractor. When I tried it, a separate window opened in which the harmonograph was slowly rotating around the z-axis, building an R 3D “movie file” – a very crisp image -before the missing Magic package error terminated it. The R plot window had generated about five images with far less "quality". And now I see you mentioned it too! Fronkonstin seems to be pushing various new packages.

I updated to R version 3.4.2 (2017-09-28) -- "Short Summer". ggplot2 was gone. I tried reloading it and saw many warnings, including 404 errors from a CRAN mirror in the UK (I’ve always selected Berkeley).

I tried again and saw the message - package ‘ggplot2’ successfully unpacked and MD5 sums checked. I also installed Microsoft R Open 3.3. RStudio seems friendlier. What do use RGui for? Can one update Microsoft R with R updates?  In the last week I downloaded firefox developer, thinking I might be able to use it’s JS console. I’m on a roll.

And the Clifford Attractor? Still, no joy. There are errors with each library and the ggplot function is not found. I’ll keep at it.
.

LongtimeAirman

Posts : 1196
Join date : 2014-08-10

## Re: Clifford Attractors

Okay, you might check installing cpp and ggplot2 as well. I use Rgui.exe with SQL Server 2017 Machine Learning Server 9.2 to update R packages. Dependencies can get frustrating at times when certain scripts just won't work with the version/libraries installed.

you might try installing ggplot2 with this command for the new installed R version. Usually R libraries have to be manually copied from the old R version folder to the new R libraries version folder and then a big "update packages" run on the latest R Version to get the latest package versions. New installs of an R version require a reinstallation or "copy over" from the old version.

You can also just manually download a package and install it locally from the local zip file:
https://mran.microsoft.com/snapshot/2017-09-01/bin/windows/contrib/3.4/ggplot2_2.2.1.zip

install.packages("ggplot2")

Here's the R only version of Clifford attractors:

https://gist.github.com/DavisVaughan/549334145e3f38bf31c205295f59e788

a=-1.24458046630025
b=-1.25191834103316
c=-1.81590817030519
d=-1.90866735205054

n <- 10000000
x <- vector("numeric", n)
y <- vector("numeric", n)
x[1] <- 0
y[1] <- 0

t1 <- proc.time()
for(i in 2:n) {
x[i] <- sin(a * y[i-1] + c * cos(a * x[i-1]))
y[i] <- sin(b * x[i-1] + d * cos(b * y[i-1]))
}
df <- data.frame(x = x, y = y)

Cr6

Posts : 1149
Join date : 2014-08-09

## Re: Clifford Attractors

I spent some time adding a point based marker system to SpinSim and it works well (not updated on site yet). The only problem is that it takes so long to build the path. So I started a new app just for this. I implemented the matrix math in Javascript/ThreeJS and put it all into a framework I built last year for ThreeJS apps. Unfortunately, I had to update to the latest version of ThreeJS and it has broken some things in that framework. I am still trying to figure out where it is going wrong (it keeps rendering into the wrong location on the page but the code seems right).

This app is designed to give the user options to setup a particle with spin levels and a few other settings (which I will add more to over time) and some model based settings such as how many iterations to use, change in time between frames, etc. Then the user presses a Generate button and the code will create a series of points that represent the position of the BPhoton over time. Those points are then rendered into a 3D scene which the user can rotate around and zoom in and out. So instead of watching the spin path build over time, you get it all in one hit (which should be much faster).

When it is working, I should be able to use different Material objects to render it differently. The default will be points, but we can also take those points and render them as a line just by using a line based Material object.

I do fear that the results will be a bit misleading. The shapes that we see in these images do not always reflect the paths that the BPhoton takes. It is really just a probability density, not a reflection of the motions themselves. It tells you where you are most likely to find the BPhoton, but not what it is doing at that point. Sometimes you can look at the density and think that the BPhoton will be moving a certain way, but it actually doesn't. A bit dangerous but still useful as long as you remember what you are looking at.

Nevyn

Posts : 1540
Join date : 2014-09-11

## Re: Clifford Attractors

Nevyn wrote:Hey Cr6, are you proficient in using matrices in R? I have some code I think would work well for this type of situation but it is heavy on the matrices. Pretty hard to avoid in 3D work. I can re-work it to generate the location of a BPhoton with any number of spin levels (within reason). Then iterate over that to generate a series of locations over time.

If you can take a series of 3D points and generate that into a 2D image then we can generate something like the image above but it will be the spin path of a particle. If you could render those points as a line then it would generate the same paths that SpinSim can but even just the points would be interesting. It would show a density graph where more dense areas are where the BPhoton spends a lot of its time.

Maybe I should add a point representation to SpinSim? I didn't think it would be useful but I'm starting to see it might be.
That's a great idea Nevyn with point representations. With the B-Photon...enough of these things are flowing in a volume to create stable organized photonic "things" that can at least be weighed?

I'm a bit further along than a few years back with Matrix math in R but still fairly novice for what you are looking at.
I'm not much further along than this tutorial tbh:
https://stats.idre.ucla.edu/r/library/r-library-matrices-and-matrix-computations-in-r/

Cr6

Posts : 1149
Join date : 2014-08-09

## Re: Clifford Attractors

.
Cr6, There’s a lot of math to matrix operations, they are n-dimensional. Learning them can take many more years. I tend to oversimplify and think of matrices as collections of vectors, as in the matrix of ten million (x,y,z) locations of the Clifford Attractor. Any operation that can apply to a position vector should apply to the location matrix itself.

You may have noticed me going on about particles with velocity projections into normal or orthogonal, perpendicular or parallel components. In that perspective, the attractor image above is just a perpendicular projection, a 2 d view of the three d attractor. I think Nevyn is asking for a projection matrix, easy to find in math texts and other programming languages, ( https://www.calpoly.edu/~dhartig/Pages/344/MMCh7-10,Epi/MapleManualCh7pg38to41.pdf,
https://www.scratchapixel.com/lessons/3d-basic-rendering/perspective-and-orthographic-projection-matrix/orthographic-projection-matrix), in R, not so much.

As you well know, R was developed for handling and displaying data, i.e. statistics. A big development has been in GIS – Geographic Information Systems, where maps of data are created. ggplot2 continues to expand R into functional (f(x)) data, math and physics. We see animations are now possible. Porting additional programming languages into R is another big advance. When you first suggested using R to develop a Mathis library I admit I was very skeptical, it’s nice to see time is proving you right.

Still no joy on the Clifford Attractor, the output is “null device”. I had to update RStudio from 1.0.136 to 1.1.383. No problem loading and running with packages. Everything else seems to work properly. There may be a lib location problem. You've helped plenty, please allow me to beg before helping me further.
.

LongtimeAirman

Posts : 1196
Join date : 2014-08-10

## Re: Clifford Attractors

I've already done the math, I just need it ported to R or at least re-worked to fit as C code in R. It uses 4x4 matrices with no special operations, just setting values and multiplying them together. I even have that code in C, so I think there is already enough code to do the job, it just needs to be put into R. I was also hoping that you would have some idea of how to convert 3D points into a 2D image for rendering. I can find the math to do it, but there are usually existing tools for such things. I would expect there to be some library for R to handle that side of it.

So, in essence, I just need the surrounding code in R to support my math in C.

Nevyn

Posts : 1540
Join date : 2014-09-11

## Re: Clifford Attractors

.
How does one search for C within R?

https://cran.r-project.org/doc/manuals/r-release/fullrefman.pdf

/////////////////////////////////////////////

trans3d      3D to 2D Transformation for Perspective Plots

Description
Projection of 3-dimensional to 2-dimensional points using a 4x4 viewing transformation matrix. Mainly for adding to perspective plots such as persp.

Usage
trans3d(x, y, z, pmat)

Arguments
x, y, z  numeric vectors of equal length, specifying points in 3D space.
pmat a4×4viewingtransformationmatrix,suitableforprojectingthe3Dcoordinates (x,y,z) into the 2D plane using homogeneous 4D coordinates (x,y,z,t); such matrices are returned by persp().

Value a list with two components
x,y the projected 2d coordinates of the 3d input (x,y,z).

persp

Examples
## See help(persp) {after attaching the 'graphics' package}
## ----------

//////////////////////////////////////////

persp      Perspective Plots

Description
This function draws perspective plots of a surface over the x–y plane. persp is a generic function.

Usage
persp(x, ...)
## Default S3 method:
persp(x = seq(0, 1, length.out = nrow(z)),
y = seq(0, 1, length.out = ncol(z)),
z, xlim = range(x), ylim = range(y),
zlim = range(z, na.rm = TRUE),
xlab = NULL, ylab
...

//////////////////////////////////////

You may be talking about importing/exporting data, which is a large and complicated subject.
.

LongtimeAirman

Posts : 1196
Join date : 2014-08-10

## Re: Clifford Attractors

trans3d sounds useful, I assume it returns an array of the 2D points since it doesn't take anything in that could be given the new data. Yep, just noticed the next line saying what the return value is.

persp is also useful, although it requires a bit more math to figure out those parameters. Not difficult and I have done it before in OpenGL. No, hang on, persp is taking in a sequence for x, y and I assume z. That looks like it is the data to be rendered but I initially thought they were the position of the camera and the *lim parameters setup the viewing frustrum.

Maybe we don't need persp, since trans3d gives us the 2D points which can then be rendered straight into an image using ggplot. The viewing frustrum is setup in the projection matrix given to trans3d.

Nevyn

Posts : 1540
Join date : 2014-09-11

## Re: Clifford Attractors

Nevyn wrote:I've already done the math, I just need it ported to R or at least re-worked to fit as C code in R. It uses 4x4 matrices with no special operations, just setting values and multiplying them together. I even have that code in C, so I think there is already enough code to do the job, it just needs to be put into R. I was also hoping that you would have some idea of how to convert 3D points into a 2D image for rendering. I can find the math to do it, but there are usually existing tools for such things. I would expect there to be some library for R to handle that side of it.

So, in essence, I just need the surrounding code in R to support my math in C.

This site has a few examples of cpp and c integration that might be of use:
http://dirk.eddelbuettel.com/code/rcpp/html/examples.html
http://dirk.eddelbuettel.com/code/rcpp.html
https://www.r-bloggers.com/three-ways-to-call-cc-from-r/

Trans3d looks pretty good.
It is also possible to pass parameters and a large datasets to a big data database function calc with R as well.

Cr6

Posts : 1149
Join date : 2014-08-09

## Re: Clifford Attractors

Heard a recent lecture that mentioned "Clifford attractors" (involved datamining). This is apparently a big "money" service if qubit computing is offered. Pure "scam" IMHO.

Qubits were mentioned with the Block Sphere:

https://en.wikipedia.org/wiki/Gottesman%E2%80%93Knill_theorem

Gottesman–Knill theorem

In quantum computing, the Gottesman–Knill theorem is a theoretical result by Daniel Gottesman and Emanuel Knill that states that stabilizer circuits, circuits that only consist of gates from the normalizer of the qubit Pauli group, also called Clifford group, can be perfectly simulated in polynomial time on a probabilistic classical computer. The Clifford group can be generated solely by using CNOT, Hadamard, and phase gates [1] , therefore stabilizer circuits can be constructed using only these gates.

Since the reason for the speed up of quantum computers is not yet fully understood, all quantum algorithms with a speed up rely on entanglement which can be achieved with a CNOT and a Hadamard gate to produce entangled states, the theorem proves that this kind of entanglement alone does not give any computing advantage.

There exists a more efficient simulation of stabilizer circuits than the construction of the original publication[1] with an implementation[2].

The Gottesman–Knill theorem was published in a single author paper by Gottesman in which he credits Knill with the result through private communication.[3]
https://en.wikipedia.org/wiki/Gottesman%E2%80%93Knill_theorem

(Also... we need to get on offering a "Mathis" computing service-surface... to gullible Physics depts. ??? )

https://docs.microsoft.com/en-us/quantum/quantum-concepts-4-qubit?view=qsharp-preview
Shor's Algorithm for Quantum Factorization
http://tph.tuwien.ac.at/~oemer/doc/quprog/node18.html

Improved Simulation of Stabilizer Circuits

Scott Aaronson, Daniel Gottesman
(Submitted on 25 Jun 2004 (v1), last revised 18 Jun 2008 (this version, v5))

The Gottesman-Knill theorem says that a stabilizer circuit -- that is, a quantum circuit consisting solely of CNOT, Hadamard, and phase gates -- can be simulated efficiently on a classical computer. This paper improves that theorem in several directions. First, by removing the need for Gaussian elimination, we make the simulation algorithm much faster at the cost of a factor-2 increase in the number of bits needed to represent a state. We have implemented the improved algorithm in a freely-available program called CHP (CNOT-Hadamard-Phase), which can handle thousands of qubits easily. Second, we show that the problem of simulating stabilizer circuits is complete for the classical complexity class ParityL, which means that stabilizer circuits are probably not even universal for classical computation. Third, we give efficient algorithms for computing the inner product between two stabilizer states, putting any n-qubit stabilizer circuit into a "canonical form" that requires at most O(n^2/log n) gates, and other useful tasks. Fourth, we extend our simulation algorithm to circuits acting on mixed states, circuits containing a limited number of non-stabilizer gates, and circuits acting on general tensor-product initial states but containing only a limited number of measurements.

https://arxiv.org/abs/quant-ph/0406196

Cr6

Posts : 1149
Join date : 2014-08-09

## Re: Clifford Attractors

Cr6

Posts : 1149
Join date : 2014-08-09