---
title: "Spacekime Analytics (Time Complexity and Inferential Uncertainty)"
subtitle: "Chapter 6: Circular Kime-Phase and Electron Orbit Densities (Circular Distributions)"
author: "SOCR Team "
date: "`r format(Sys.time(),'%m/%d/%Y')`"
output: 
  html_document:
    theme: spacelab
    highlight: tango
    includes:
      before_body: TCIU_header.html
    toc: true
    number_sections: true
    toc_depth: 2
    toc_float:
      collapsed: false
      smooth_scroll: true
    code_folding: hide
---

```{r error=F, message=F, warning=F}
#install.packages("circular")
library("circular")
library("animation")
library(ggplot2)
library(tidyr)
library(plotly)
```

Here we show some of the parallels between circular kime-phase densities and electron orbit densities depicted as circular distributions.

# Circular Electron Orbit Densities 

In many physics systems and chemistry applications, it's important to model the spatial distribution of elementary particles, such as electrons. For instance, in photoelectron spectroscopy experiments, we may measure the intensities of electrons to track their angular dependencies, which may be described as electric dipole approximations. These estimates may subsequently be used to study the electron emissions resulting from their interaction with photons. Suppose we measure the electron emission intensity, $I(\theta)$, which can be expressed as a differential of the partial cross section:

$$I(\theta)\equiv \frac{d\sigma}{d \Omega}=
\frac{\sigma}{4\pi}\left ( 1+ \frac{\beta}{2}(3\cos^2(\theta)-1) \right ).$$

This ordinary differential equation describes the angular distribution of the emitted electrons from
a gas-phase sample in a random orientation, excited by $100\%$ linearly polarized light, see [this reference](https://www.researchgate.net/publication/356920774_Dynamique_electronique_dans_les_molecules_organiques_par_la_spectroscopie_Core-Hole_Clock).

In this equation, $-\pi\leq \theta<\pi$ is the angle between the electric field vector and the vector that describes the *direction* (phase) of the electron ejected after the collision of the particle (electron) with a photon, $\sigma$ is the angle integrated cross-section of a given particle state, and $-1\le \beta\le 2$ is the [photoelectron asymmetry parameter](https://journals.aps.org/rmp/pdf/10.1103/RevModPhys.54.389), which is independent of $\theta$, but can depend on the excitation energy or the particle's (electrons’) kinetic energy.

The graph below shows the probabilistic photoelectron differential cross-section showing
the photoionization of an atomic $1s$ orbital. An electron in this orbital has angular momentum $l=0$. Upon the electron-photon collision, the angular momentum of the electron increases to $l = 1$, according to the dipole selection rules ($\Delta l = \pm 1$). The ejected electron leaves the system as a *p-wave*, corresponding to the case of $\beta = 2$. In this case, the intensity in the polarization vector plane is maximized and close to zero in the plane perpendicular to the polarization vector. Similar arguments hold for the orbital distributions of electrons with different characters and their relations to the corresponding $\beta$ parameters.

Note the connections between all four angular distributions (corresponding to $\beta\in \{-1, 0, 1, 2 \}$) in four symmetrical points, where the angular distributions are independent of the
$\beta$−values. For instance, the first point corresponding to $\theta=54.7^o$ (see black line in the first quadrant, or $0.954695$ radians) is called the *magic angle* of the polarization vector of electromagnetic radiation. This *magic* is due to the intensity distribution being independent of the wave-character of the emitted electron. Assuming a perfect, $100\%$, linear polarization, for an electron energy detector mounted at the *magic angle*, the angular distribution vanishes and the differential partial cross-section in
the above equation is proportional to the integral partial cross-section. When the particle analyzing detector is focused at a different angle, the correction factors (dependencies) need to be accounted for due to angular distribution effects.

The significance of the $\beta$ parameter can be explicated in terms of an isolated carbon ($C$) atom. At all energies, an idealized and isolated $C\ 1s$ photoelectron exhibits angular distribution corresponding to $\beta = 2$ (green density). The polar angle (phase) represents the angle between the polarization vector (horizontal axis) and the emitted electron. The (green) plot shows that the electrons are preferentially emitted along the polarization vector. At one extreme, when $\beta = 0$, the angular distribution is completely isotropic (circular, as it's independent of $\theta$). In the other extreme, when $\beta = -1$, the maximum of the distribution is mostly vertical, i.e., perpendicular to the horizontal polarization vector. This interpretation is valid only under the dipole approximation assumption when the wavelength of light is much larger than the dimension of the atoms (the wave is not varying inside the atom). For instance, experiments frequently use small radiation wavelength around $2\ nm$, whereas the entire atom may be $10$ times smaller at about $0.2\ nm$, which justifies the dipole approximation assumption. 

This electron distribution map suggests that experiments are expect to observe more electrons when performing a measurement at $0^o$ angle and much fewer electrons when measuring at $90^o$. However, in practice, the difference in the observed electron densities compered to model predictions between the $0^o$ and $90^o$ angles is smaller than expected. This difference is a function of the photon energy. See [this publication demonstrating how the observed intensities can be used to estimate the $\beta$ parameter](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.106.193009#fulltext) for the *chlorine* substituted carbon and for the *methyl* carbon in a series of chloroethanes. The more chlorine atoms are present in a molecule, the [lower $\beta$ parameter is, and the deviation $2-\beta$ is larger at the lowest ionization energies](https://journals.aps.org/rmp/pdf/10.1103/RevModPhys.54.389).

Note that the angular distributions of these particles (electrons) are very structured.
They tend to be symmetric and do not come out independently all over the place. Rather, the distributions emerge in just a few directions, as narrow sprays or jets. About $90\%$ of the time these distributions represent just two polar opposite jets, about $10\%$ of the time there are three jets, $1\%$ four jets, and so on progressively less likely.

```{r electron_densities, warning=F, error=F, message=F}
# Display the electron densities for
theta <- seq(-pi, pi, length.out=200)

# beta = is the asymmetry parameter, independent of θ, can depend on the excitation
# energy or the electrons’ kinetic energy
# σ is the angle integrated cross-section of a given state
f <- function (theta, beta = -1, sigma=1) {
    return ( (sigma/(4*pi))*(1 + (beta/2) * (3*cos(theta) * cos(theta) - 1)) )
}

df <- data.frame(cbind(theta=theta,
                       beta_1 = f(theta=theta, beta=-1, sigma=1),
                       beta0 = f(theta=theta, beta=0, sigma=1),
                       beta1 = f(theta=theta, beta=1, sigma=1),
                       beta2 = f(theta=theta, beta=2, sigma=1)))

df_long <- gather(df, beta, value, c(beta_1,beta0, beta1,beta2), factor_key=TRUE)

plot1 <- ggplot(df_long, aes(x = theta, y = value, colour = beta)) +
    geom_line() +
    geom_vline(xintercept=0.954695) +   # 54.7^o = 0.954695 radians
    labs(title = "", x = "", y = "")+
    # theme_bw() +
    ggtitle("Electron angular density") +
    coord_polar(start = pi/2, direction = -1) +
    scale_color_manual(labels = c("beta=-1", "beta=0", "beta=1", "beta=2"),
                       values = c("red", "gray", "blue", "green")) +
    theme(axis.text.y = element_blank(), plot.title = element_text(hjust=0.5),
          axis.ticks.y = element_blank(), legend.position="bottom") +
    guides(color=guide_legend("Beta\nValues"))
# ggplotly(plot1)
plot1
```

# Kime-Phases Circular Distributions 

```{r kime_phases, eval=F, echo=T, warning=F, error=F, message=F}
saveHTML(
  {
  oopt = ani.options(interval = 0.2)
  set.seed(1234)
  x <- rvonmises(n=1000, mu=circular(pi/5), kappa=3)
  y <- rvonmises(n=1000, mu=circular(-pi/3), kappa=5)
  z <- rvonmises(n=1000, mu=circular(0), kappa=10)
  r <- runif(n=1000, min=0, max=2)
  vectorX = as.vector(x)
  vectorY = as.vector(y)
  vectorZ = as.vector(z)
  plotX = c(vectorX[1])
  plotY = c(vectorY[1])
  plotZ = c(vectorZ[1])
  for (i in 2:1000){
    plotX = c(plotX,vectorX[i])
    plotY = c(plotY,vectorY[i])
    plotZ = c(plotZ,vectorZ[i])
    
    # Try to "stack=T the points ....
    #r1 = sqrt((resx$x)^2+(resx$y)^2)/2; 
    #resx$x = r1*cos(resx$data)
    #resx$x = r1*cos(resx$data)
    
    tempX = circular(plotX)
    tempY = circular(plotY)
    tempZ = circular(plotZ)
    resx <- density(tempX, bw=25, xaxt='n', yaxt='n')
    resy <- density(tempY, bw=25, xaxt='n', yaxt='n')
    resz <- density(tempZ, bw=25, xaxt='n', yaxt='n')
    res <- plot(resx, points.plot=TRUE, xlim=c(-1.1,1.5), ylim=c(-1.5, 1.5), 
                main="Trivariate random sampling of\n kime-magnitudes (times) and kime-directions (phases)", 
                offset=0.9, shrink=1.0, ticks=T, lwd=3, axes=F, stack=TRUE, bins=150)
    lines(resy, points.plot=TRUE, col=2, points.col=2, plot.info=res, offset=1.0, shrink=1.45, lwd=3, stack=T)
    lines(resz, points.plot=TRUE, col=3, points.col=3, plot.info=res, offset=1.1, shrink=1.2, lwd=3, stack=T)
    segments(0, 0, r[i]*cos(vectorX[i]), r[i]*sin(vectorX[i]), lwd=2, col= 'black')
    segments(0, 0, r[i]*cos(vectorY[i]), r[i]*sin(vectorY[i]), lwd=2, col= 'red')
    segments(0, 0, r[i]*cos(vectorZ[i]), r[i]*sin(vectorZ[i]), lwd=2, col= 'green')
    ani.pause()
  }
  
  
  # To save animation as MP4 video
  saveVideo({ 
    oopt = ani.options(interval = 0.2)
    set.seed(1234)
    x <- rvonmises(n=1000, mu=circular(pi/5), kappa=3)
    y <- rvonmises(n=1000, mu=circular(-pi/3), kappa=5)
    z <- rvonmises(n=1000, mu=circular(0), kappa=10)
    r <- runif(n=1000, min=0, max=2)
    vectorX = as.vector(x)
    vectorY = as.vector(y)
    vectorZ = as.vector(z)
    plotX = c(vectorX[1])
    plotY = c(vectorY[1])
    plotZ = c(vectorZ[1])
    for (i in 2:1000){
      plotX = c(plotX,vectorX[i])
      plotY = c(plotY,vectorY[i])
      plotZ = c(plotZ,vectorZ[i])
      
      # Try to "stack=T the points ....
      #r1 = sqrt((resx$x)^2+(resx$y)^2)/2; 
      #resx$x = r1*cos(resx$data)
      #resx$x = r1*cos(resx$data)
      
      tempX = circular(plotX)
      tempY = circular(plotY)
      tempZ = circular(plotZ)
      resx <- density(tempX, bw=25, xaxt='n', yaxt='n')
      resy <- density(tempY, bw=25, xaxt='n', yaxt='n')
      resz <- density(tempZ, bw=25, xaxt='n', yaxt='n')
      res <- plot(resx, points.plot=TRUE, xlim=c(-1.1,1.5), ylim=c(-1.5, 1.5), 
                  main="Trivariate random sampling of\n kime-magnitudes (times) and kime-directions (phases)", 
                  offset=0.9, shrink=1.0, ticks=T, lwd=3, axes=F, stack=TRUE, bins=150)
      lines(resy, points.plot=TRUE, col=2, points.col=2, plot.info=res, offset=1.0, shrink=1.45, lwd=3, stack=T)
      lines(resz, points.plot=TRUE, col=3, points.col=3, plot.info=res, offset=1.1, shrink=1.2, lwd=3, stack=T)
      segments(0, 0, r[i]*cos(vectorX[i]), r[i]*sin(vectorX[i]), lwd=2, col= 'black')
      segments(0, 0, r[i]*cos(vectorY[i]), r[i]*sin(vectorY[i]), lwd=2, col= 'red')
      segments(0, 0, r[i]*cos(vectorZ[i]), r[i]*sin(vectorZ[i]), lwd=2, col= 'green')
      ani.pause()
    }
    }, 
    video.name = "C:/Users/Dinov/Desktop/KimeRandomSamplingAnimation.mp4", 
    other.opts = "-pix_fmt yuv420p -b:v 500K",
    ffmpeg = "E:/Ivo.dir/Ivo_Tools/ffmpeg-20200218-ebee808-win64-static/bin/ffmpeg.exe", 
    ani.width = 600, ani.height = 600
  )
  },
  htmlfile  = "Chapter6_Kime_Phases.html"
  
)
```

<video autosize:true controls>
  <source src="KimeRandomSamplingAnimation.mp4" type="video/mp4">
</video>


<!--html_preserve-->
<div>
    	<footer><center>
			<a href="https://www.socr.umich.edu/">SOCR Resource</a>
				Visitor number <img class="statcounter" src="https://c.statcounter.com/5714596/0/038e9ac4/0/" alt="Web Analytics" align="middle" border="0">
				<script type="text/javascript">
					var d = new Date();
					document.write(" | " + d.getFullYear() + " | ");
				</script> 
				<a href="https://socr.umich.edu/img/SOCR_Email.png"><img alt="SOCR Email"
	 			title="SOCR Email" src="https://socr.umich.edu/img/SOCR_Email.png"
	 			style="border: 0px solid ;"></a>
	 		 </center>
	 	</footer>

	<!-- Start of StatCounter Code -->
		<script type="text/javascript">
			var sc_project=5714596; 
			var sc_invisible=1; 
			var sc_partition=71; 
			var sc_click_stat=1; 
			var sc_security="038e9ac4"; 
		</script>
		
		<script type="text/javascript" src="https://www.statcounter.com/counter/counter.js"></script>
	<!-- End of StatCounter Code -->
	
	<!-- GoogleAnalytics -->
		<script src="https://www.google-analytics.com/urchin.js" type="text/javascript"> </script>
		<script type="text/javascript"> _uacct = "UA-676559-1"; urchinTracker(); </script>
	<!-- End of GoogleAnalytics Code -->
</div>
<!--/html_preserve-->

