Welcome to TiddlyWiki created by Jeremy Ruston, Copyright © 2007 UnaMesa Association
#[[Cuda University: online courses for GPU computing ||http://www.nvidia.com/object/cuda_education.html]]
#GPUs can handle sophisticated algorithms, but painful
#CPU can handle Fortran algorithms well
!Collisionless Dynamics
$\Delta \vec{v}=\frac{2Gm}{bv}$
$dn=\frac{2\pi b db}{\pi r^2}N$
$t_{cross} = \frac{R}{V}$
$(\Delta \vec{v})^2=\int dn(\frac{2Gm}{bv})^2=8N(\frac{Gm}{Rv})^2 ln \frac{b_{max}}{b_{min}}$
$\Rightarrow t_{relax}=\frac{N}{8\ln\Lambda} t_{cross}$
!!Collisionless vs. Collisional
Galaxy: $N=10^11$
$t_{cross} \approx 10^{-2} H^{-1}$
Cluster, e.g. collisional.
!!Collisionless systems
Governed by collisionless Boltzmann equation.
$f(\vec x,\vec v,t)$, $\vec w=(\vec x, \vec v)$
$\frac{\partial f}{\partial t} = \frac{\partial}{\partial \vec w}(f \dot{\vec{w}})=0$
$\Rightarrow \frac{\partial f}{\partial t} + \vec{x}\frac{\partial f}{\partial \vec{x}}-\frac{\partial \Phi}{\partial \vec{x}}\frac{\partial f}{\partial \vec{v}}=0$
$\nabla=-\frac{\partial \Phi}{\partial \vec{x}}$
!!Density
$\rho = m \int d^3v f$
$\dot{\vec{v}}=-\frac{\partial \Phi}{\partial \vec{x}}$
$\Rightarrow \vec{\nabla}^2 \Phi= 4\pi G m \int f d^3 v$
!!Jean's equations
$\frac {\partial}{\partial t} \langle v_i \rangle+\langle v_i \rangle \frac {\partial\langle v_i \rangle}{\partial x_i} = -\frac {\partial \Phi}{\partial x_i}-\frac{1}{\rho}\frac {\partial}{\partial x_j}(\rho\sigma_{ij}^2)$
!!Tensor Virial Theorem
$\frac{1}{2} \frac{d^2 I_{jk}}{dt} = 2 K_{jk} + W_{jk}\Rightarrow \frac{dI}{dt}=0$
*moment of inertia tensor: $I_{jk}=\int d^3 x \rho x_j x_k$
*kinetic energy tensor: $K_{jk}=\frac{1}{2}\int d^3 x \rho \langle v_j v_k \rangle$
*potential energy tensor: $W_{jk}=-\int d^3 x \rho x_k \frac{\partial } {}$ #TODO: fill in
!!On to N-body codes
$N<<N_*$
$t_{relax}(N)>>t_{simul}$
!!!Plummer Softening
$\Phi(r)=-G \frac{m}{r} \rightarrow \Phi(r) = -G \frac{m}{\sqrt{r^2+\epsilon^2}}$
Not ideal:
*at all distances potential changed
*we want to modify the field only at small length scales
!!!Spline softening kernel
*looks more or less like Gaussian, except has finite support
$\rho(r)=mW(\frac{r}{h})$
$W(u) = \frac{8}{\pi}\begin{cases}1-6u^2+6u^3 &u<\frac{1}{2}\\2{(1-u)}^3 &\frac{1}{2} <u \leq 1 \\ 0 & u>1 \end{cases}$
!!!Volker's suggested softening in context of CDM
$M_{200}=200\rho_{cr}+\frac{4\pi}{3}R_{200}^3$
$\rho_{cr}= \frac{3H^2}{8\pi G}$
$v_{200}^2 = \frac{G M_{200}}{R_{200}}$
$M_{200} = \frac{v_{200}^3}{10 GH}$
$R_{200} = \frac{v_{200}}{10 GH}$
$10H=\frac{1 \frac{km}{s}}{\frac{kpc}{h}}$
$E_{km}=\frac{1}{2} v_{200}^3 = \frac{1}{2}(10GHM_{200})^{2/3}$
$\rho d^3=m$
!!!!Finally the softening expressed in units of mean particle spacing
$\epsilon \geq (\frac{3}{800\pi N^2})^{1/3}d$
e.g. $N=2\rightarrow \frac{1}{15}d$. But this limit is usually ignored and people are a bit more aggressive.
e.g. $N=5 \rightarrow \frac{1}{30}d$
So in practice people usually us something in between $\frac{1}{40}$ (most aggressive) and $\frac{1}{20}$. You need to actually do a numerical experiment to see what works.
!Equations of Motion in Cosmology
*Physical coordinates $\vec r = a(t) \vec x$
*Comoving coordinates $\vec x$
*Expansion factor $a=\frac{1}{1+z}$
$\dot r = H(a) \vec r + \vec v$
$H(a)=\frac{\dot a}{a}=H\sqrt{\Omega_0 a^{-3}+(1-\Omega_0-\rho_a)a^{-2}+\Omega_{\Lambda}}$
$\ddot r = G \sum \frac {m_j(\vec{r_i}-\vec{r_j})}{|r_i-r_j|^2} + \Omega_{\lambda}H_0^2 \vec r$
from the Friedman equation: $\frac{\ddot a}{a}=-\frac{4piG}{3}\rho+\frac{\Lambda}{3}; \Lambda=3H_0^2\Omega_{\lambda}$
$\Rightarrow \ddot{\vec{x}} + 2\frac{\ddot a}{a}\dot x = - frac{a}{a^3}\sum \frac {m_j(\vec{x_i}-\vec{x_j})}{|x_i-x_j|^2}+\frac{1}{2}\frac{\Omega_0 H_0^2}{a^2}\vec x$
$\Rightarrow \ddot{\vec{x}} + 2\frac{\ddot a}{a}\dot x = - \frac{a}{a^2}\int\frac {\delta \rho(\vec{x}')(\vec{x}-\vec{x}')}{|x-x'|^3}d^3x'$
$\phi(x)=-G\int\frac {\delta \rho(\vec{x}')d^3x'}{|x-x'|^3}$
!!Writing as a Hamiltonian system
We want the solution of the above equation for $\phi$ in a periodic grid.
$\nabla^2\phi=4\pi G(\sum(\delta(\vec x- \vec n L)-\frac{1}{L^3}$
Then the total potential in our box is:
$\phi(\vec x)=\sum m_i \phi(\vec x - \vec x_i)$
Can then introduce:
*conjugate momentum: $\vec{p_i}=a^2 m \dot{\vec{x_i}}$
*Hamiltonian: $H= \sum \frac{p_i^2}{2m_i a^2}+ \frac{1}{2}\sum\frac{m_i m_j \phi(x_i-x_j)}{a}=T+U$
*$\dot{p_i}= -\frac{\partial H}{\partial{x_i}}$
*$\dot{x_i} = -frac{\partial H}{\partial{p_i}}$
Note there is an explicit time dependence in the Hamiltonian.
$\frac{dH}{dt}=\frac{\partial H}{\partial t}=-2\frac{\dot a}{a}T-\frac{\dot a}{a}U$
This implies the cosmic energy equation $\Rightarrow \frac{dE}{dt} = -H(a)(2T+U)$
In practice not that easy to use. Next lecture: initial conditions, etc.
*''merger hypothesis'': tidal features around galaxies occur in collisions which ultimately produce spheriodals
*more important than particle number is physical insight and intuition
!initial conditions
#grid or glass
##glass: start a grid make particles repel. end up with no preferred direction as compared with grid
#initial displacements and velocities
##get from the Zeldovich approximation
#fluctuations in k-space
##assign random amplitudes and phases for individual modes
!Calculating gravitational forces
#direct summation
#[[Particle Mesh method (PM)]]
#[[Tree algorithms]]
!Time integrations
#leapfrog
#leapfrog + adaptive time step
#force-split can be used to construct a symplectic integrator where lang and short range forces are treated independently
!Parallelization: domain decomposition
#we will do ~200 billion particles soon-but how can we cope with the data?
#construction a of a flexible domain decomposition with cache benefits
##order the particles along a space filling curve
##the space filling Hilbert curve is a fractal that fills a square
##Peano-Hilbert curve is the equivalent in 3D
!Parallelization
#[[Ahmdel's law|http://en.wikipedia.org/wiki/Amdahl%27s_law]] used to bound expected improvement from parallelization
#Volker thinks write OpenMPI code, then OpenMP for portions of code
!SPH
#Basic hydrodynamics review
!SPH: Different methods to discretize a fluid
#Eulerian
##discretize space
##representation on a mesh (volue elements)
##high accuracy (shock capturing), low numerical viscosity
#Lagrangian
##discretize mass
##representation by fluid elements (particles)
##resolutions adjusts automatically to the flow
!Density estimation
By means of adaptive kernel estimation. We build continuous fluid quantities from discrete tracer particles. Good kernel shapes need to fulfill
*normalized to unity
*compact support
*high order of interpolation
*spherical symmetery (ffor angular momentum conservation
Cubic spline is mainly used.
!Velocity divergence estimation
Kernel interpolants
!Basic equations for SPH
Each particle carries either energy or entropy per unit mass as independent variable
#density estimate
#Euler equation
#first law of thermodynamics
!Artificial viscosity
An artificial viscosity needs to be introduced to capture shocks. The [[sod shock tube|http://en.wikipedia.org/wiki/Sod_shock_tube]] is a standard test for handling, also see [[shock tube|http://en.wikipedia.org/wiki/Shock_tube]].
!Advantages of SPH
*mass, momentum, total energy (even in presence of self-gravity), angular momentum, entropy are conserved.
*geometrically flexible
*can incorporate vacuum boundary conditions
*no high mach number problem
!SPH equation formulation
Many different formulations
*''entropy formalism''
**deriving temperature from the specific entropy for an adiabatic flow.
**none of the adiabatic schemes conserves energy and entropy simultaneously.
*''Lagrangian''
**fully conservative formulations of SPH
!Neighbor search
Very efficient range searching within the tree.
!Using simulations
Bullet cluster, can constrain dark matter profile, alternate '5th force' models.
!Non standard physics with SPH
*Thermal conduction may partially offset radiative cooling in central cluster regions
*Magnetic fields are the natural enemy of thermal conduction
*SPH discretization of conduction
*SPH with physical viscous stresses
!Incorporate radiative transfer in SPH
Interested in e.g. reionization. Many different possible schemes
#tracing rays, {{{SPHRAY}}} code (publicly available)
#individual rays are integrated in a Monte Carlo fashion through th eSPH density fieled. Optical depth along a ray is calculated form the column density
#following the radiation field in cones {{{TRAPHIC}}} code.
##some radiation is injected into emission cones
##in transfer steps, radiation is received from cones and propogated into emission cones
##complicated
#Moment equations (Petkova &Springel 2009)
##take moments of the radiative transfer equation and achieve closure with an estimated Eddington tensor
##Optically thin variable Eddington Tensor approximation, can be calculated efficiently with a tree algorithm alongside gravitational force
##this OTVT Scheme is used in {{{gadget3}}}
!Magnetic fields in SPH
*possible to treat MHD in SPH, but divB errors remain problematic so far
*much less accurate than say the treatment in {{{athena}}}
!!SPH MHD formulations
#direct discretization of the MHD equations in terms of $B$
#use of the Euler potentials
!Fluid instabilities and SPH
#Disruption of a cloud by Kelvin-Helmholtz Instabilities
##cloud moving through ambient gas shows different long term behavior in SPH and Eulerian mesh codes
##in SPH fluid instabilities at contact discontinuities with large density jumps tend to be suppressed by spurious numerical surface tension
!Mixing in SPH
*unless there is some way to generate entropy outside shocks (this is possible in Eulerian codes), mixing of different phases is energetically forbidden.
!!ways of dealing with mixing in SPH
*artificial heat mixing term
!Better SPH?
*Optimized OSPH, using different ways to estimate the density.
**needs peaked kernel to suppress clumping instability which
!Differences between SPH and Eulerian schemes
| ''Eulerian'' | ''Lagrangian'' |
|sharp shocks|shocks broaded|
|mixing at cell level|mixing suppressed at particle level|
|don't need artificial viscosity|requires artifical viscosity|
|truncation error not Galilean invariant|Galilean invariant|
|self gravity of gas done on mesh, but dark matter particles|self-gravity of gas treated same as DM|
|no conservation of total energy when self-gravity conserved|conserve total energy|
![[AREPO|http://www.mpa-garching.mpg.de/~volker/arepo/]]: New code
Motivated by lack of Galilean invariance in truncation error in SPH. When mesh is fixed, results may change if a bulk velocity is imposed. Ended up not being as important as Volker thought.
!!How AREPO works
*Mesh itself is key, a [[Voronoi mesh|http://en.wikipedia.org/wiki/Voronoi_diagrams]] with [[Delaunay triangulation|http://en.wikipedia.org/wiki/Delaunay_triangulation]] is used.
*The fluxes are calculated with an exact Riemann solver in the frame of the moving cell boundary.
*Velocities of the mesh generating points uniquely determine the motion of all Voronoi faces
!!Summary
*quasi-Lagrangian hydrodynamical code
*allows Galilean invariant solutions
*no artificial viscosity, very low numerical diffusivity
*automatic Lagrangian adaptivity of the mesh
*mesh geometry is flexible
*parallelized for distributed memory systems in 2D and in 3D, gravity adopted from Gadget 3
*moving and curved boundary conditions easily implemented
*can be costlyly in terms of time, also introduces additional algorithmic complexity.
!why use numerics
#field equations complicated
#perturbative techniques only work in weak-field, slow motion, need numerics
#gravitational wave astronomy
##we need template waveforms (predictions of relativity) to convolve with signal
!review of GR
*$ds^2=g_{\alpha\beta} dx^\alpha dx^\beta$,
*$g_{\alpha\beta}=(-1,1,1,1)$ (Lorentzian signature)
*$G_{\alpha\beta} = \frac{8\pi G}{c^4} T_{\alpha\beta}$
Can as usual, relate metric to $G_{\alpha\beta}$, giving us 10 second order, quasi-linear (non-linearities in lower order terms) PDEs depending on the four spacetime coordinates.
!Solving the field equations
Need to decompose
#3+1 (space+time)
##coupled system of 4 elliptic (constraint), 6 hyperbolic (evolution (equations), plus for gauge equations
#null, or characteristic decomposition
##choose one or two of the coordinates are chose to be null, the rest spacelike
##main problem is that caustics for along null directions, no way to deal with
!Expected solutions
If a computational method for a matter field works in a special relativistic setting, no additional complications should arise incorporating it into a GR code.
!Summary
#non-linear
#varying length scales: need AMR
#Runge-Kutta or [[pseudo-spectral|http://en.wikipedia.org/wiki/Pseudo-spectral_method]] methods are used
!Basics of finite difference solution of PDEs
#Denote a general differential system $\mathcal{L}u=f$ (where $\mathcal{L}$ is a differential operator acting on a set of unknown variables $u$ and $f$ are a set of prespecified source functions)
#Represent this as $\mathcal{L}^h u^h=f^h$
#Can define the residual $\mathcal{R}^h=\mathcal{L}^h u^-f^h$
#FD scheme is stable if $\left| u^h \right| < e^{ct}$ with c constant independent of h
#FD scheme is consistent iff it converges.
#In general we will not know what the error is, we assume solution admits a Richardson expansion:
##$u^h=u+e_1h^p+e_2h^{2p}+\dots$ ($e_1,e_2$ are error function sof space and time but independent of mesh spacing, p is the order of the scheme)
##for simple equations one can prove that this expansion exists, for Einstein equations it does if the FD approximations are consistent and solutions are smooth.
##allows for convergence testing and error estimation. performed by comparing solutions obtained a different resolutions.
!Black Holes
#Recall the Schwarzschild metric.
##use the metric in [[ingoing Eddignton-Finkelstein coordinates|http://en.wikipedia.org/wiki/Eddington%E2%80%93Finkelstein_coordinates]], written in terms of ADM variables
#The covariant wave eqaution for a massless scalar field $\phi$ on a gneral background metric with metric $g$ is
**$\nabla^\alpha\nabla_\alpha\phi=\frac{1}{-g} \partial_\alpha(\sqrt{-g}g^{\alpha\beta})\partial_\alpha \phi=0$
#complication: the event horizon. characteristics of the wave equation e.g. the light cone tip over as you cross
!Solutions
Unwanted high-frequency solution components, at best causes unphysical reflections, at worst unstable. Use KO dissipation.
!!Tools
#RNPL: a tool designed to aid in the construction of programs to solve hyperbolic PDEs.
##uses Newton-Gauss-Seidel iteration
###linearize equations (Newton part)
###obtain approximation to the correction, performing one step of a [[Gauss-Seidel iterative||http://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method]] solution
#look at http://physics.princeton.edu/~fpretori/group_resources/index.html, don't have to do all problems but pick and choose
!ADM decomposition
*separate 4D spacetime into 3D space and 1D time
*essential for posing the FE as an initial boundary value (Cauchy problem)
*also need the extrinsic curvature tensor; how space slice is embedded in higher dimensional space
!!Einstein equations in 3+1 form
*$n^\mu-n^\mu$ projection:
**$^{(3)}R+K^2-K_{ij}K^{ij}=16\pi\rho$
*$n^\mu h^{\mu\nu}$ projection:
**$D_bK^{ab}-D^aK=8\pi j^a$, where $D_b = \perp \nabla_b$ is a spatial covariant derivative operator
!Gravity in spherical symmetry
*GR doesn't allow any monopole radiation, no gravitational waves. Dynamics thus driven by matter.
!!Constraint equations
#Hamiltonian
#momentum
#maximal slicing condition
!!Evolution equations
#K=0 gives only metric evolution equation
#scalar filed evolution equation
!!Solutions
Two choices for how to evolve the equations
*''fully constrained'': solve all three elliptics at each time step
*''partially constrained'': solve the epplitics for the lapse and shift, but evolve the conformal factor with the hyperbolic equation
We will only get the same consistent solution to the FE in a partially constrained evolution if
*initial conditions for $\psi$ are supplied by solving the Hamiltonian constraint
*consistent boundary conditions are employed
!!Boundary conditions, beginning from smooth initial data (no black holes)
*outer at $r=R$
**metric asymptotically flat
**place approximate outgoing radiation conditions on the scalar field
*regularity at $r=0$
**all regular fields will have either an even or odd power series expansion about $r=0$
!Generalized Harmonic Decomposition
!!Harmonic coordinates
*$\nabla^\alpha \nabla_\alpha x^\mu = \frac{1}{\sqrt{-g}} \partial_\alpha (\sqrt{-g} g^{\alpha \mu})=H^\mu$
*note that any metric in any coordinate system can be viewed as a generalized harmonic metric
*Do to the Einstein equations what the Lorenz gauge does to Maxwell's equations.
!Example: Binary Black hole merger
*solved Einstein's equations in generalized harmonic form with constraint damping and a set of gauge equations
*simulation of merger of two equal mass initially non-spinning black hole took two months on UT Austin cluster
*what does the merger wave represent?
**fractional oscillatory "distortion" in space induced by the wave trasverse to th edirection of propagation has a maximum amplitude $\frac{\Delta L}{L} \approx 3 \times 10^{-3}$
!!Compactification
*Choose a coordinate system to bring spatial infinity to a finite coordinate location on the computational domain
*possible problem would be getting poor resolution approaching the outer boundary
**solved with dissipation; at this stage the waves then get dissipated away
!!Comment about solution
*in GR code the end product of evolutions is the metric, we need to extract descriptions e.b. black holes, gravitational waves, geodesics, energies, etc. need to be extracted from the metric
*how do we then search for e.g. a black hole
**we search for an ''apparent'' horizon-a marginally outer trapped 2-sphere
!Conclusions
Future of numerical relativity
*much to uncover-intimately tied to the gravitational wave astronomy endeavor
*LIGO has reached initial design sensitivity, advanced LIGO is funded
*wait to see gravitational waves
What role with NR play here?
*the "in principle" vacuum problem (binary black holes) may be "solved"-at least in the regime of a modest number of orbits and non-extreme mass ratios
*though near-extremal mergers and orbital eccentricity may still hold surprises
*most interesting: include matter. What happens with strong-field GR/matter interactions
*GW source modeling will eneter a very exciting era: LIGO detector is biased with predictions of what it is expected to see. new interplay between theory and experiment.
!Orbits
*Spacecraft: 1-100
*Galaxies/Cosmological simulations: 100-1000
*stars around black hole at center: $10^6$
*particles in particle accelerator: $10^9$
!Diffeqs Solvers
!!Analytically
$\frac{d\vec y}{dt}=f(t,\vec y)$
$ddot x=\omega^2 x$, $\vec y=(x,v)$, $v=\dot x$
$\frac{d\vec y}{dt}=\left( \begin{array}{cc} 0&1\\-\omega^2 &0 \end{array} \right)\vec y$
!!!Orbit around a point mass
$\ddot{\vec r}=\vec F-\frac{GM}{r^2} \hat r$
!Hamiltonian
$H(\vec q, \vec p)$
$\frac{d\vec q}{dt}=\frac{\partial\vec H}{\partial \vec{p}}$
$\frac{d\vec q}{dt}=\frac{\partial\vec H}{\partial \vec{q}}$
$\vec y =(\vec q, \vec p)$
$\frac{d\vec y}{dt}=(\vec v,\vec F(\vec r)$
!Order of a method
$\vec y(t)$=true solution
$\vec y_0=\vec y(0)$,
$\vec y_1-\vec y(n)\propto An^{n+1}$
n=order
!Method
$\frac{d\vec y}{dt}=f(t,\vec y)$
$t_{n+1}=t_n+h$
$\vec y_{n+1}=\vec y_n+g(\vec y_n,h, t_n)$
explicit
implicit: $w(\vec y_{n+1},\vec y_n,h,t_n)=0$
multistep: $\vec y_{n+q}=\vec y_n+g(\vec y_n, \vec y_{n-1}, \dots, h, t_n)$
!Methods
!!First Order
*Euler
**simplest
*Modified Euler
**when you advance velocity, instead of using force at old position, you use the force at the new position
!!Second Order
*Leapfrog [[see for a review|http://phycomp.technion.ac.il/~david/thesis/node34.html]]
!!Fourth Order
*Runga-Kutta
!!Comparison
Compare by picking such that each method has same number of force evaluations
!Louville's theorem
Phase space volume is conserved by the flow.
$\vec y = ( \vec q, vec p)$
$\vec y(t, \vec y_0)$
$\vec y(0, \vec y_0)=\vec y_0$
Louville: $ \left| \frac{\vec y}{\vec y_0} \right| = 1$
#Algorithms which Satisfy
##Modified Euler
##leapfrog
#Algorithms which Don't satisfy
#Euler
#Runga-Kutta
!Geometric properties
!!Energy conserving algorithms
#Algorithms that don't satisfy
##Euler
##Modified Euler
##Runga Kutta
##Leapfrog
!!Time reversible algorithms
Check by integrating forward $n$ steps, reverse velocity, integrate $n$ steps. End back where you started $\Rightarrow$ time reversible.
#Algorithms which satisfy
##Leap frog
#Algorithms which don't satisfy
##Euler
##Modified Euler
##Runga Kutta
!!Symplectic algorithms
Check: if you can generate the formula for advancing by one timestep by the Hamiltonian
*for a one-d system symplectic = volume conserving
#Algorithms which satisfy
##Modified Euler
##Leapfrog
#Algorithms which don't satisfy
##Euler
##Runga-Kutta
!!!Proof of sympleticity
$H(\vec q, \vec p)=\frac{1}{2} p^2 + \Phi(q)$
$\dot q=\frac{\partial\vec H}{\partial \vec{p}}$
$\dot p=-\frac{\partial\vec H}{\partial \vec{q}}$
$H_A=\frac{1}{2} p^2$
$H_B=\Phi(q)$
*under $H_A$
$\dot p=0$
$\dot q = p$
over time h
drift step: $q'=q+hp$, $p'= p$
kick step: $\vec{y}'=A(y)$
A is the drift operator
*under $H_B=\Phi(q)$
$q'=\frac{d H_B}{dp}=0$
under time step h
#TODO: missing the next few lines, couldn't see
$\dot q=q$
$p=$ kick step
$\vec{y}'=B_h(\vec y)$
B is the kick operator
*kick-drift modified Euler: $\vec{y}'=A_h B_h \vec y$
*drift-kick modified Euler: $\vec{y}'=B_h A_h \vec y$
*leapfrog: $\vec{y}'=A_{\frac{h}{2}} B_h A_{\frac{h}{2}} \vec y$
!!!We can generalize kick-operators and drift-operators
$\vec{y}'=A_{\alpha h}B_{\beta h}A_{\gamma h}B_{\gamma h}A_{\gamma h}B_{\beta h}A_{\alpha h} \vec y$
$2 \alpha + 2 \gamma =1$
$2 \beta +\delta =1$
Forest-Ruth: 4th order sympletic, time-reversible
$\beta=2*\alpha-\frac{1}{2-2^{1/3}}$
Can follow pattern to generate leapfrog of higher and higher orders
!Geometric integrators: Applications
*planetary systems
**mixed-variable symplectic integrator
***Workhorse for long orbit integrations
***geometric/symplectic and time-reversible
***errors are small than leapfrog
***long term errors reduced by techniques such as warmup
****star with small timesteps and adiabatically change them
***does integration of planets on orbits that are not too far from cercular and don't come too close
***doesn't do close encounters, highly eccentric orbits very well, chaotic
***popular software packages
****Mercury
****SWIFT
!Exceptions to sympleticity
If the timestep is not fixed you begin to have serious problems.
One step integration:
$\vec y_{n+1}=\vec y_n+g(\vec y_n,h, t_n)$
Sympletic if $\left| \frac{\partial(\vec{y_{n+1}})}{\partial(\vec{y_n})} \right|=1$
$h(\vec y_n)$
Usually sympleticity disappears with variable timestep, but we have hope to preserve time reversibility.
!!Leapfrog with variable timestep
possibilities
#allow a variable timestep that depends on phasespace position $h=\tau(r,v)$
#allow a variable timestep that depends on phasespace position $h=\tau(q,p)$
#time-symmetric with a variable timestep that depends on $y, h=\tau(y)$
!What we left out in these lectures
*individual timesteps
*regularization
*non-geometric methods for N-body integration
*roundoff error
*homework
!Introduction to physics and numerics.
[[see lecture slides for more details]]
!!Why fluid dynamics
*galaxy, stars, and planet formation
$\Rightarrow$ represent as fluid, need to solve MHD equations
!!Equations of MHD
*derive from conservation laws
**mass conservation
**momentum conservation
**energy conservation
**flux conservation
*equation of state, use the ideal gas law $P=nkT$
!Summary of wave modes in hydrodynamics
#sound waves
#entropy waves
#Alfen waves
!Shocks
!!Why are there so many physical problems with supersonic velocity
#free fall speed set by gravity
#sound speed set by thermodynamics
#often a disconnect
!!MHD shocks
#slow shock
#fast shock
#switch on shock
#switch of shock
!!Shocks in multidimensions
*weird stuff can happen, as different shocks can interact
!Linear instabilities
#gravitational
#thermal
#Rayleigh-Taylor (RT)
#Rischtmyer-Meshkov (RM)
#Kelvin-Helmholtz (KH)
#Magneto-rotational (MRI)
We want our numerical methods to capture these correctly.
!Numerical methods
How do we solve the equations of MHD on a computer?
!!discretization
#space
#time
#represent dependent variables as either
##point-wise values
##volume-averages
!!errors
#round-off error
##Can be rigorously proved that the relative error of a rounded value is bounded by a small, machine dependent value-the machine precision
#truncation error
##difference between true and approximate (numerical solution).
##Would exist even on a perfect machine with no round off error
!!Convergence, consistency and stability
#consistency: truncation error must decrease as res increased
#convergence: numerical solution should approach analytic as res increases
#stability
!!First-order methods
#Lax-Friedrichs
#Upwind
!!Higher-order methods
#Lax-Wendroff
!!Summary
#Need to understand some MHD to understand numerical methods and applications (also good for code tests)
##Linear waves
##Shocks
##Instabilities
#Discretization is key to grid-based methods
##finate difference vs. finite element vs. finnite volume
#non-linear terms and discontinuities pose special challenges
!Tour
E.g. ZEUS-2D
#setup problem
#Poisson Solver
#Source step
#Transport step
!!1D method
#transport step
##higher order [[advection|http://en.wikipedia.org/wiki/Advection]] step
#finite differencing plus artificial viscosity
##Artificial viscosity is not necessary to make algorithm stable. It is necessary to thermalize kinetic energy in shocks (create entropy)
!!Extensions to multidimensions
#constrained transport
##conservative scheme for the magnetic flux
!Implementation
#most grid codes apply boundary conditions by specifying solution in extra rows of cells ghost cells at boundary of grid
!!Sanity tests for codes
#Sod test
##not enough
#Many other tests
!Example codes
!!Zeus
#Operator split algorithm combining upwided and finite difference methods
#Implementations
##2D
##3D
##MP
#Advantages
##robust
##very fast
##easily to extend with additional physics
##cartesian, cylindrical and spherical grids
#Disadvantages
##finite-differencing for pressure source terms gives poor dispersion relation for compressive waves
##does not use conservative form
##no AMR
!!Athena
##Fully upwind [[Godunov scheme|http://en.wikipedia.org/wiki/Godunov%27s_scheme]]
!!Other algorithms for MHD
#high order finite-difference with hyperviscosity
##PENCIL
#operator split with artificial viscosity
##ZEUS
#Nirvana-1
#Godunov
##Athena
##RAMSES
##PLUTO
##VAC
##BATS-R-US
##FLASH-3
#Central Schemes
##Nirvana-2
!Godunov methods
#discretization
##cell centered mass, momentum, energy
##face centered filed
##face-centered fluxes
##edge centered EMFs
!Godunov method
Due to conservation, don't actually need to solve Riemann problem exactly. Just need to compute state at location of interface to compute fluxes.
!Riemann solvers
[[Riemann problems|http://en.wikipedia.org/wiki/Riemann_problem]] "consist of a conservation law together with a piecewise constant data having a single discontinuity." Require [[Reimann solvers|http://en.wikipedia.org/wiki/Riemann_solver]]. Easy for pure hydro of ideal gases. In MHD complex because there are many wave families, degeneracies. So MHD Godunov schemes use approximate Riemann solvers.
!!First order Godunov method
#Roe's method
##keeps all 7 characteristics, but treats each as a simple wave
#Harten-Lax-van Leer-Einfeld (HLLE)
##keeps only largest and smallest characteristics, averages intermediate states in-beetween
#HLLC/D method
##adds entropy and Alven waves back into HLLE
!!Higher-order reconstruction
#use piecewise linear (MUSCLE) or picewise-parabolic (PPM) reconstruction within cells
!div(B)
Needs to be zero, have to build in something to keep zero. Options
#do noting
#evolve using a vector potential $A$ where $B= \nabla \times A$
#Remove solenoindal part of $B$ using flux cleaning. That is set $B \rightarrow B - \nabla \phi$
#use Powell's "8-wave solver"
#[[constrained transport|http://www.iop.org/EJ/abstract/0004-637X/677/1/520]]
!Instabilities
*Carbuncle instability, small perturbations ini upstream flow produce large perturbations ni postshock gas
!Boundary conditions
Apply by specifying solution in "ghost zones". Several default choices for BCs provided in athena, but user can define their own. Unsplit integrator with PPM requires 4 rows of ghost zone.
!Implementation: Athena
!!Goals
*Modularity
*Ease-of-use
*Portability
*Performance
!!Overview
*Use {{{configure}}} to add change physics
*Parallelization done using MPI via domain decomposition
!Tests
#linear wave convergence
#nonlinear circularly polarized
#shock tubes in multidimensions
#hydrodynamical implosion
#RM instability in circular blast waves
!Mesh refinement
Static mesh refinement: uses divergence free prolongation and restriction operators of Toth and Roe. There's an AMR extensions of Athena.
!Summary
*MHD Godunov methods are mature, excellent choice for study shocks and instabilities
*not good for every application
*Grid codes are Galilean invariant for resolved solutions that are not strongly affected by truncation error
!Adding more physics to numerical MHD
Adding new physics to van Leer unsplit integrator is straightforward, adding new physics to CTU integrator more complicated.
!!Optically-thin cooling
*Easy to add cooling, but makes MHD much more complex. Don't add physics just because you can.
!!Viscosity and thermal conduction
!!Anisotropic conduction and viscosity
*magnetized and weakly collisional plasma, thermal conduction and viscous transport mainly along field lines. Change dynamics qualitatively.
!!Resistivity
*induction equation has an extra damping term
*overriding concern is keeping div(B)=0
*can be extended to ambipolar diffusion and Hall regimes
!!Gravity
*tricky to add to grid codes
*adds term to momentum and term to energy equations
*for fixed graviational potential (e.g. central star)
**momentum not conserved
**total energy is conserved
*self gravity
**conserves total momentum exactly
*must also solve Poisson's equation for the potential
!!Special relativity
*so substantial a change, basically writing a new solver. can use similar techniques
##reconstruction step
##compute fluxes with Riemann solver
##van Leer unsplit integrator
*definition of conserved variables and their fluxes is more complicated, so significant changes in each step above
*good test suits
!Foundations of Radiation Hydrodynamics
!!Why Radiation MHD is hard
*choice of fram
*closer of moment equations
*problem changes in different regines
*non-LTE effects
*wide range of timescales
!!What is Radiation MHD
Means different things to different people. Can include energy or momentum exchange terms or both.
!!Grid vs. particle based method versus particles for radiation transfer
*Grid
**more accurate, less noise
**difficult to extend
*Particles
**flexible, easy to extend
**noisy especially in optically think regions
*We will only discuss grid approach
!!Approach
#operator split
#staggering mesh
!!Moving radiation MHD to Godunov scheme: Hybrid Godunov
#backward Eulere HLLE
#modified Godunov predictor
#modified radiation Riemann solver
#modified Godunov corrector
!Summary
!!Covered
#Basic MHD
#Operator split methods like ZEUS
#Godunov methods like PPM--ATHENA one example of PPM code
#extension with more physics
#radiation hydrodynamics a whole new regime for codes
!!Left out
#other schemes
#other codes
#''Applications''
!Plasma physics on computers
!!plasma
*ionized gas
*stars, sun, ISM etc.
*simulation needed to study collective kinetic effects
*characteristic time and length scales
##plasma freqency
##[[Debye length|http://en.wikipedia.org/wiki/Debye_length]]
##skin depth
###length over which and electromagnetic wave would penetrate into a conductor
##Larmor
!!collisions
*denser, the less you have to worry about collisions, as long as it is not too dense.
*if $L>>\lambda_d, N_D \propto \lambda_D^3 >> 1$
!!Description
*collisionless plasma can be described by [[Vlasov-Maxwell|http://en.wikipedia.org/wiki/Vlasov_equation]] system of eqations for the distribution function $f(x,v,t)$
*direct solution is 6D $\Rightarrow$ very expensive
*Particle method
**along particle trajectory, distribution function is conserved
**instead solve along characteristics (particles), Delta functions cause collisions so smooth them
![[PIC Method|http://en.wikipedia.org/wiki/Particle-in-cell]]
#Load particle distribution
#solve particle EQM
#Monte-Carlo collisions
#extrapolate to grid
#solve Maxwell's eq.
#particle interpolation
#model surface emission
#''goto'' 1
!Electrostatic codes
#time integration
##straightforward, use leapfrog
#charge assignment and force interpolation
##assignment by cloud-in-cell (CIC) in 1D
!Summary for restrictions of simulation parameters
#$dt<\frac{1}{\sqrt{\frac{1}{dx_1^2}+\frac{1}{dx_x^2}}}$, $c=1$, $\omega_{pc}=1$
#$\omega_{max}dt<0.25$
#$v_max$ restricted, see [[Spitkovsky lecture1 pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/]]
!Electromagnetic codes
!integrate the field equations
#Newton-Lorenz EOM
#integrate with implicit explicit Boris Scheme
!!errors
#numerical dispersion is anisotropic, best on grid diagonal
#phase errors for short wavelengths
#numerical Cherenkov radiation
!Codes
All are tuned for different problems, direct code comparison is not usually done.
!!Public codes
[[Berkeley plasma simulation group|http://ptsg.eecs.berkeley.edu/]]
#XES1
#XPDP1/2
#XPDC1/2
#XPDS1/2
#XOOPIC/OOPIC-PRO(public version)
#XIBC
#XGRAFIX
!!Not so public codes
#XOOPIC
#VORPAL
#TRISTAN
#OSIRIS
#LSP
#VLPL
#reconnection research code
#every national lab has PIC codes
Many applications, ranging from planet formation to granular dynmaics.
!PKDGRAV/Gasoline
Gasoline is pkdgrav with SPH enabled.
!Collisional systems
#no singularities
#minimum gravitational timestep bounded
#close-packed equal size spheres have a maximum of 12 touching neighbors
#for less-packed situations, only concern is more dinstant fast-moving particle
!!Search for collisions
Kick, drift, kick second order leapfrog scheme. Drift is linear in the velocities, so can use this to search for collisions. Complications are that our "restitution model" of billiard ball collisions is only an approximation, collisions are treated as instantaneous and single point contact which leads to inelastic collapse and missed collisions due to round-off error.
!Representations
Spheres to ideas, so use pseudoparticles to represent aggregate center of mass including intertia tensor, rotation state and orientation
!Equations
Euler's equations of rigid body rotation.
!Gravitational aggregates
Loose assemblages of coherent pieces held together mostly by gravity. There is some level of cohesion, we see this from data, bodies which are spinning so fast they would otherwise break apart.
Roadrunner supercomputer is the fastest in the world. Expected speedup[[Amdahl's law|http://en.wikipedia.org/wiki/Amdahl%27s_law]], but in fact obeys "Amdah's street justice", i.e. unaccelerated portion of code becomes absolutely more costly, to make room for accelerated portions.
!Science
*[[Inertial confinement fusion|http://en.wikipedia.org/wiki/Inertial_confinement_fusion]]
*Laser ion acceleration
!Advice on gyrokinetic PIC
*use single precision aggressively
*minimizes passes through particles per step
*use voxel-plus-offset particle positions
*do "cold" particle advance wtih 4-way vertical [[SIMD|http://en.wikipedia.org/wiki/SIMD]]
*use regular mesh with cut cells (voxels) to accommodate irregular curved boundaries.
*Hilbert space-filling curve voxel indexing
*elliptic equations bad idea in HPC
**Poisson equation is a bad idea
**information must propagate from each node to all other nodes every field advance
!Conclusions
*Petascale supercomputers can change science, tapping this potential requires rethinking codes and analysis
*Supercomputers getting faster but not the speed of light. Data flow optimization future proofs codes.
Thank you to staff, participants. Summary of participants, goals of program. One quote from each lecture. Some pictures from the program.
|''Type:''|file|
|''URL:''|http://TiddlyWiki.bidix.info/|
|''Workspace:''|(default)|
This tiddler was automatically created to record the details of this server
|''Type:''|file|
|''URL:''|http://bob.mcelrath.org/tiddlyjsmath.html|
|''Workspace:''|(default)|
This tiddler was automatically created to record the details of this server
#First CUDA exercise:
##Install CUDA. Compile and run a program in the SDK (I think fluidsGL is the best one).
## Write a short, nontrivial code in C, and get it to run on the GPU. Serial execution is fine if you are new to this platform.
#Second CUDA exercise:
##Download the GPU version of Gadget2.
##Compile it successfully.
##Do one of Volker's homework problems on your GPU.
##Use this example of CUDA coding to study the details of CUDA programming that you are curious about.
#Third CUDA exercise:
##Download Flagon from Sourceforge.
##Read the documentation and see if you can write, compile and run a program in F9x that sums the numbers in an array (on the GPU) and writes the result to standard out.
Creating bulleted lists is simple.
* Just add an asterisk
* at the beginning of a line.
** If you want to create sub-bullets
** start the line with two asterisks
*** And if you want yet another level
*** use three asterisks
* You can also do [[Numbered Lists]]
{{{
Creating bulleted lists is simple.
* Just add an asterisk
* at the beginning of a line.
** If you want to create sub-bullets
** start the line with two asterisks
*** And if you want yet another level
*** use three asterisks
* You can also do [[Numbered Lists]]
}}}
Notes condensed from Alina Kiessling's
!Dependencies of Gadget-2.0.3
For the Gadget install, used a {{{--prefix=path_to_gadget_dependencies/dependency}}} e.g. {{{ --prefix=/Users/corbett/pitp/pitp_dependencies/fftw-2.1.5}}} instead of installing in {{{/usr/local}}} to minimize version conflict, as Gadget uses several earlier code versions. This is done in the configure script
#OpenMPI-1.3.2
##Mac may have another version of MPI installed; make sure to point to new version instead
#fftw-2.1.5
##need to build both single and double precision
###do this with {{{--enable-type-prefix}}} tag, and {{{configure; make clean; make}}} three times with the following flags to configure
####{{{--enable-mpi --enable-type-prefix}}}
####{{{--enable-mpi --enable-type-prefix --enable-real}}}
####{{{ --enable-mpi --enable-type-prefix --enable-float}}}
###this flag will not work with new versions of fftw ,Gadget requires 2.1.5 anyway
#gsl-1.9
##should be no problems
#hdf5-1.6.9
##not the more recent version 1.8, Gadget uses the same version as enzo
##add the {{{--enable-fortran --enable-cxx }}} flags to the configure script
!Install
Need Gadget-2.0.3
Will need to make versions, of the executable. {{{cd}}} into {{{Gadget-2.0.3/Gadget2}}}
#Edit the Makefile (below is a diff of the new {{{<}}} vs. the old {{{>}}} Makefiles)
{{{
84,85c83,84
< #OPTIMIZE = -O2 -Wall -g # sets optimization and warning flags
< #MPICHLIB = -lmpich
---
> OPTIMIZE = -O2 -Wall -g # sets optimization and warning flags
> MPICHLIB = -lmpich
90c89
< SYSTYPE="Mac"
---
> SYSTYPE="MPA"
101,111d99
< ifeq ($(SYSTYPE),"Mac")
< CC = /Users/corbett/pitp/pitp_dependencies/openmpi-1.3.2/bin/mpicc
< OPTIMIZE = -03 -Wall -g
< GSL_INCL = -I/Users/corbett/pitp/pitp_dependencies/gsl-1.9/include
< GSL_LIBS = -L/Users/corbett/pitp/pitp_dependencies/gsl-1.9/lib
< FFTW_INCL = -I/Users/corbett/pitp/pitp_dependencies/fftw-2.1.5/include
< FFTW_LIBS= -L/Users/corbett/pitp/pitp_dependencies/fftw-2.1.5/lib
< MPICHLIB = -L/Users/corbett/pitp/pitp_dependencies/openmpi-1.3.2/lib
< HDF5INCL = -I/Users/corbett/pitp/pitp_dependencies/hdf5-1.6.9/include
< HDF5LIB = -L/Users/corbett/pitp/pitp_dependencies/hdf5-1.6.9/lib -lhdf5 -lz
< endif
}}}
#Edit again, to create {{{glass}}} executable
{{{
%diff Makefile Makefile.nonglass
72c72
< OPT += -DMAKEGLASS=262144
---
> #OPT += -DMAKEGLASS=262144
223c223
< EXEC = Gadget2_glass
---
> EXEC = Gadget2
}}}
#download the newest version from http://www.netpurgatory.com/zeusmp.html
#made the following modifications to the make file
{{{
#I added these -corbett #NOTE there are no defaults
SYSTYPE="Mac"
ifeq ($(SYSTYPE),"Mac")
MPICHLIB = -L/Users/corbett/pitp/pitp_dependencies/openmpi-1.3.2/lib
MPICHINCL = -I/Users/corbett/pitp/pitp_dependencies/openmpi-1.3.2/include
HDF4INCL = -I/Users/corbett/pitp/pitp_dependencies/HDF4.2r4/include
HDF4LIB = -L/Users/corbett/pitp/pitp_dependencies/HDF4.2r4/lib -lz
endif
#
ZMP_EXE = ../exe/
ZMP_FC = gfortran
ZMP_OPTS3 = -c -O2 -I/usr/include -I/sw/include $(MPICHINCL)
ZMP_OPTS0 = -c -O0 -I/usr/include -I/sw/include $(MPICHINCL)
ZMP_CC = gcc
ZMP_LDR = ${ZMP_FC} -O2 -I/sw/include
ZMP_LIB = -L/sw/lib -L/sw/lib -ldl $(HDF4LIB) -ldf -ljpeg -lz $(MPICHLIB) -lpthread
#-llamf77mpi -llam removed but these are needed #TODO find these
}}}
[[Mathematical Symbols]]
[[Formatting]]
/***
|Name|ExportTiddlersPlugin|
|Source|http://www.TiddlyTools.com/#ExportTiddlersPlugin|
|Documentation|http://www.TiddlyTools.com/#ExportTiddlersPluginInfo|
|Version|2.9.2|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides||
|Description|interactively select/export tiddlers to a separate file|
!!!!!Documentation
>see [[ExportTiddlersPluginInfo]]
!!!!!Inline control panel (live):
><<exportTiddlers inline>>
!!!!!Revisions
<<<
2009.07.06 [2.9.3] moved HTML to section for size reduction
2009.07.03 [2.9.2] TW252 fixup: don't call convertUTF8ToUnicode() for local loadFile() I/O
2009.04.30 [2.9.1] custom fields in CSV output
|please see [[ExportTiddlersPluginInfo]] for additional revision details|
2005.10.09 [0.0.0] development started
<<<
!!!!!Code
***/
//{{{
// version
version.extensions.ExportTiddlersPlugin= {major: 2, minor: 9, revision: 2, date: new Date(2009,7,3)};
// default shadow definition
config.shadowTiddlers.ExportTiddlers='<<exportTiddlers inline>>';
// add 'export' backstage task (following built-in import task)
if (config.tasks) { // TW2.2 or above
config.tasks.exportTask = {
text:'export',
tooltip:'Export selected tiddlers to another file',
content:'<<exportTiddlers inline>>'
}
config.backstageTasks.splice(config.backstageTasks.indexOf('importTask')+1,0,'exportTask');
}
config.macros.exportTiddlers = {
$: function(id) { return document.getElementById(id); }, // abbreviation
label: 'export tiddlers',
prompt: 'Copy selected tiddlers to an export document',
okmsg: '%0 tiddlers written to %1',
failmsg: 'An error occurred while creating %1',
mergeprompt: '%0\nalready contains tiddlers.\n'
+'\nPress OK to merge new/revised tiddlers into existing file.'
+'\nor, press Cancel to completely replace the file contents',
mergestatus: 'Merged %0 new/revised tiddlers with %1 previously saved tiddlers',
statusmsg: '%0 tiddler%1 - %2 selected for export',
newdefault: 'export.html',
datetimefmt: '0MM/0DD/YYYY 0hh:0mm:0ss', // for 'filter date/time' edit fields
type_TW: "tw", type_PS: "ps", type_TX: "tx", type_CS: "cs", type_NF: "nf", // file type tokens
type_map: { // maps type param to token values
tiddlywiki:"tw", tw:"tw", wiki: "tw",
purestore: "ps", ps:"ps", store:"ps",
plaintext: "tx", tx:"tx", text: "tx",
comma: "cs", cs:"cs", csv: "cs",
newsfeed: "nf", nf:"nf", xml: "nf", rss:"nf"
},
handler: function(place,macroName,params) {
if (params[0]!='inline')
{ createTiddlyButton(place,this.label,this.prompt,this.togglePanel); return; }
var panel=this.createPanel(place);
panel.style.position='static';
panel.style.display='block';
},
createPanel: function(place) {
var panel=this.$('exportPanel');
if (panel) { panel.parentNode.removeChild(panel); }
setStylesheet(store.getTiddlerText('ExportTiddlersPlugin##css',''),'exportTiddlers');
panel=createTiddlyElement(place,'span','exportPanel',null,null)
panel.innerHTML=store.getTiddlerText('ExportTiddlersPlugin##html','');
this.initFilter();
this.refreshList(0);
var fn=this.$('exportFilename');
if (window.location.protocol=='file:' && !fn.value.length) {
// get new target path/filename
var newPath=getLocalPath(window.location.href);
var slashpos=newPath.lastIndexOf('/'); if (slashpos==-1) slashpos=newPath.lastIndexOf('\\');
if (slashpos!=-1) newPath=newPath.substr(0,slashpos+1); // trim filename
fn.value=newPath+this.newdefault;
}
return panel;
},
togglePanel: function(e) { var e=e||window.event;
var cme=config.macros.exportTiddlers; // abbrev
var parent=resolveTarget(e).parentNode;
var panel=cme.$('exportPanel');
if (panel==undefined || panel.parentNode!=parent)
panel=cme.createPanel(parent);
var isOpen=panel.style.display=='block';
if(config.options.chkAnimate)
anim.startAnimating(new Slider(panel,!isOpen,e.shiftKey || e.altKey,'none'));
else
panel.style.display=isOpen?'none':'block' ;
if (panel.style.display!='none') {
cme.refreshList(0);
cme.$('exportFilename').focus();
cme.$('exportFilename').select();
}
e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); return(false);
},
process: function(which) { // process panel control interactions
var theList=this.$('exportList'); if (!theList) return;
var count = 0;
var total = store.getTiddlers('title').length;
switch (which.id) {
case 'exportFilter':
count=this.filterExportList();
var panel=this.$('exportFilterPanel');
if (count==-1) { panel.style.display='block'; break; }
this.$('exportStart').disabled=(count==0);
this.$('exportDelete').disabled=(count==0);
this.displayStatus(count,total);
if (count==0) { alert('No tiddlers were selected'); panel.style.display='block'; }
break;
case 'exportStart':
this.go();
break;
case 'exportDelete':
this.deleteTiddlers();
break;
case 'exportHideFilter':
case 'exportToggleFilter':
var panel=this.$('exportFilterPanel')
panel.style.display=(panel.style.display=='block')?'none':'block';
break;
case 'exportSelectChanges':
var lastmod=new Date(document.lastModified);
for (var t = 0; t < theList.options.length; t++) {
if (theList.options[t].value=='') continue;
var tiddler=store.getTiddler(theList.options[t].value); if (!tiddler) continue;
theList.options[t].selected=(tiddler.modified>lastmod);
count += (tiddler.modified>lastmod)?1:0;
}
this.$('exportStart').disabled=(count==0);
this.$('exportDelete').disabled=(count==0);
this.displayStatus(count,total);
if (count==0) alert('There are no unsaved changes');
break;
case 'exportSelectAll':
for (var t = 0; t < theList.options.length; t++) {
if (theList.options[t].value=='') continue;
theList.options[t].selected=true;
count += 1;
}
this.$('exportStart').disabled=(count==0);
this.$('exportDelete').disabled=(count==0);
this.displayStatus(count,count);
break;
case 'exportSelectOpened':
for (var t=0; t<theList.options.length; t++) theList.options[t].selected=false;
var tiddlerDisplay=this.$('tiddlerDisplay');
for (var t=0; t<tiddlerDisplay.childNodes.length;t++) {
var tiddler=tiddlerDisplay.childNodes[t].id.substr(7);
for (var i=0; i<theList.options.length; i++) {
if (theList.options[i].value!=tiddler) continue;
theList.options[i].selected=true; count++; break;
}
}
this.$('exportStart').disabled=(count==0);
this.$('exportDelete').disabled=(count==0);
this.displayStatus(count,total);
if (count==0) alert('There are no tiddlers currently opened');
break;
case 'exportSelectRelated':
// recursively build list of related tiddlers
function getRelatedTiddlers(tid,tids) {
var t=store.getTiddler(tid); if (!t || tids.contains(tid)) return tids;
tids.push(t.title);
if (!t.linksUpdated) t.changed();
for (var i=0; i<t.links.length; i++)
if (t.links[i]!=tid) tids=getRelatedTiddlers(t.links[i],tids);
return tids;
}
// for all currently selected tiddlers, gather up the related tiddlers (including self) and select them as well
var tids=[];
for (var i=0; i<theList.options.length; i++)
if (theList.options[i].selected) tids=getRelatedTiddlers(theList.options[i].value,tids);
// select related tiddlers (includes original selected tiddlers)
for (var i=0; i<theList.options.length; i++)
theList.options[i].selected=tids.contains(theList.options[i].value);
this.displayStatus(tids.length,total);
break;
case 'exportListSmaller': // decrease current listbox size
var min=5;
theList.size-=(theList.size>min)?1:0;
break;
case 'exportListLarger': // increase current listbox size
var max=(theList.options.length>25)?theList.options.length:25;
theList.size+=(theList.size<max)?1:0;
break;
case 'exportClose':
this.$('exportPanel').style.display='none';
break;
}
},
displayStatus: function(count,total) {
var txt=this.statusmsg.format([total,total!=1?'s':'',!count?'none':count==total?'all':count]);
clearMessage(); displayMessage(txt);
return txt;
},
refreshList: function(selectedIndex) {
var theList = this.$('exportList'); if (!theList) return;
// get the sort order
var sort;
if (!selectedIndex) selectedIndex=0;
if (selectedIndex==0) sort='modified';
if (selectedIndex==1) sort='title';
if (selectedIndex==2) sort='modified';
if (selectedIndex==3) sort='modifier';
if (selectedIndex==4) sort='tags';
// unselect headings and count number of tiddlers actually selected
var count=0;
for (var t=5; t < theList.options.length; t++) {
if (!theList.options[t].selected) continue;
if (theList.options[t].value!='')
count++;
else { // if heading is selected, deselect it, and then select and count all in section
theList.options[t].selected=false;
for ( t++; t<theList.options.length && theList.options[t].value!=''; t++) {
theList.options[t].selected=true;
count++;
}
}
}
// disable 'export' and 'delete' buttons if no tiddlers selected
this.$('exportStart').disabled=(count==0);
this.$('exportDelete').disabled=(count==0);
// show selection count
var tiddlers = store.getTiddlers('title');
if (theList.options.length) this.displayStatus(count,tiddlers.length);
// if a [command] item, reload list... otherwise, no further refresh needed
if (selectedIndex>4) return;
// clear current list contents
while (theList.length > 0) { theList.options[0] = null; }
// add heading and control items to list
var i=0;
var indent=String.fromCharCode(160)+String.fromCharCode(160);
theList.options[i++]=
new Option(tiddlers.length+' tiddlers in document', '',false,false);
theList.options[i++]=
new Option(((sort=='title' )?'>':indent)+' [by title]', '',false,false);
theList.options[i++]=
new Option(((sort=='modified')?'>':indent)+' [by date]', '',false,false);
theList.options[i++]=
new Option(((sort=='modifier')?'>':indent)+' [by author]', '',false,false);
theList.options[i++]=
new Option(((sort=='tags' )?'>':indent)+' [by tags]', '',false,false);
// output the tiddler list
switch(sort) {
case 'title':
for(var t = 0; t < tiddlers.length; t++)
theList.options[i++] = new Option(tiddlers[t].title,tiddlers[t].title,false,false);
break;
case 'modifier':
case 'modified':
var tiddlers = store.getTiddlers(sort);
// sort descending for newest date first
tiddlers.sort(function (a,b) {if(a[sort] == b[sort]) return(0); else return (a[sort] > b[sort]) ? -1 : +1; });
var lastSection = '';
for(var t = 0; t < tiddlers.length; t++) {
var tiddler = tiddlers[t];
var theSection = '';
if (sort=='modified') theSection=tiddler.modified.toLocaleDateString();
if (sort=='modifier') theSection=tiddler.modifier;
if (theSection != lastSection) {
theList.options[i++] = new Option(theSection,'',false,false);
lastSection = theSection;
}
theList.options[i++] = new Option(indent+indent+tiddler.title,tiddler.title,false,false);
}
break;
case 'tags':
var theTitles = {}; // all tiddler titles, hash indexed by tag value
var theTags = new Array();
for(var t=0; t<tiddlers.length; t++) {
var title=tiddlers[t].title;
var tags=tiddlers[t].tags;
if (!tags || !tags.length) {
if (theTitles['untagged']==undefined) { theTags.push('untagged'); theTitles['untagged']=new Array(); }
theTitles['untagged'].push(title);
}
else for(var s=0; s<tags.length; s++) {
if (theTitles[tags[s]]==undefined) { theTags.push(tags[s]); theTitles[tags[s]]=new Array(); }
theTitles[tags[s]].push(title);
}
}
theTags.sort();
for(var tagindex=0; tagindex<theTags.length; tagindex++) {
var theTag=theTags[tagindex];
theList.options[i++]=new Option(theTag,'',false,false);
for(var t=0; t<theTitles[theTag].length; t++)
theList.options[i++]=new Option(indent+indent+theTitles[theTag][t],theTitles[theTag][t],false,false);
}
break;
}
theList.selectedIndex=selectedIndex; // select current control item
this.$('exportStart').disabled=true;
this.$('exportDelete').disabled=true;
this.displayStatus(0,tiddlers.length);
},
askForFilename: function(here) {
var msg=here.title; // use tooltip as dialog box message
var path=getLocalPath(document.location.href);
var slashpos=path.lastIndexOf('/'); if (slashpos==-1) slashpos=path.lastIndexOf('\\');
if (slashpos!=-1) path = path.substr(0,slashpos+1); // remove filename from path, leave the trailing slash
var filetype=this.$('exportFormat').value.toLowerCase();
var defext='html';
if (filetype==this.type_TX) defext='txt';
if (filetype==this.type_CS) defext='csv';
if (filetype==this.type_NF) defext='xml';
var file=this.newdefault.replace(/html$/,defext);
var result='';
if(window.Components) { // moz
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var nsIFilePicker = window.Components.interfaces.nsIFilePicker;
var picker = Components.classes['@mozilla.org/filepicker;1'].createInstance(nsIFilePicker);
picker.init(window, msg, nsIFilePicker.modeSave);
var thispath = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
thispath.initWithPath(path);
picker.displayDirectory=thispath;
picker.defaultExtension=defext;
picker.defaultString=file;
picker.appendFilters(nsIFilePicker.filterAll|nsIFilePicker.filterText|nsIFilePicker.filterHTML);
if (picker.show()!=nsIFilePicker.returnCancel) var result=picker.file.persistentDescriptor;
}
catch(e) { alert('error during local file access: '+e.toString()) }
}
else { // IE
try { // XPSP2 IE only
var s = new ActiveXObject('UserAccounts.CommonDialog');
s.Filter='All files|*.*|Text files|*.txt|HTML files|*.htm;*.html|XML files|*.xml|';
s.FilterIndex=defext=='txt'?2:'html'?3:'xml'?4:1;
s.InitialDir=path;
s.FileName=file;
if (s.showOpen()) var result=s.FileName;
}
catch(e) { // fallback
var result=prompt(msg,path+file);
}
}
return result;
},
initFilter: function() {
this.$('exportFilterStart').checked=false; this.$('exportStartDate').value='';
this.$('exportFilterEnd').checked=false; this.$('exportEndDate').value='';
this.$('exportFilterTags').checked=false; this.$('exportTags').value='';
this.$('exportFilterText').checked=false; this.$('exportText').value='';
this.showFilterFields();
},
showFilterFields: function(which) {
var show=this.$('exportFilterStart').checked;
this.$('exportFilterStartBy').style.display=show?'block':'none';
this.$('exportStartDate').style.display=show?'block':'none';
var val=this.$('exportFilterStartBy').value;
this.$('exportStartDate').value
=this.getFilterDate(val,'exportStartDate').formatString(this.datetimefmt);
if (which && (which.id=='exportFilterStartBy') && (val=='other'))
this.$('exportStartDate').focus();
var show=this.$('exportFilterEnd').checked;
this.$('exportFilterEndBy').style.display=show?'block':'none';
this.$('exportEndDate').style.display=show?'block':'none';
var val=this.$('exportFilterEndBy').value;
this.$('exportEndDate').value
=this.getFilterDate(val,'exportEndDate').formatString(this.datetimefmt);
if (which && (which.id=='exportFilterEndBy') && (val=='other'))
this.$('exportEndDate').focus();
var show=this.$('exportFilterTags').checked;
this.$('exportTags').style.display=show?'block':'none';
var show=this.$('exportFilterText').checked;
this.$('exportText').style.display=show?'block':'none';
},
getFilterDate: function(val,id) {
var result=0;
switch (val) {
case 'file':
result=new Date(document.lastModified);
break;
case 'other':
result=new Date(this.$(id).value);
break;
default: // today=0, yesterday=1, one week=7, two weeks=14, a month=31
var now=new Date(); var tz=now.getTimezoneOffset()*60000; now-=tz;
var oneday=86400000;
if (id=='exportStartDate')
result=new Date((Math.floor(now/oneday)-val)*oneday+tz);
else
result=new Date((Math.floor(now/oneday)-val+1)*oneday+tz-1);
break;
}
return result;
},
filterExportList: function() {
var theList = this.$('exportList'); if (!theList) return -1;
var filterStart=this.$('exportFilterStart').checked;
var val=this.$('exportFilterStartBy').value;
var startDate=config.macros.exportTiddlers.getFilterDate(val,'exportStartDate');
var filterEnd=this.$('exportFilterEnd').checked;
var val=this.$('exportFilterEndBy').value;
var endDate=config.macros.exportTiddlers.getFilterDate(val,'exportEndDate');
var filterTags=this.$('exportFilterTags').checked;
var tags=this.$('exportTags').value;
var filterText=this.$('exportFilterText').checked;
var text=this.$('exportText').value;
if (!(filterStart||filterEnd||filterTags||filterText)) {
alert('Please set the selection filter');
this.$('exportFilterPanel').style.display='block';
return -1;
}
if (filterStart&&filterEnd&&(startDate>endDate)) {
var msg='starting date/time:\n'
msg+=startDate.toLocaleString()+'\n';
msg+='is later than ending date/time:\n'
msg+=endDate.toLocaleString()
alert(msg);
return -1;
}
// if filter by tags, get list of matching tiddlers
// use getMatchingTiddlers() (if MatchTagsPlugin is installed) for full boolean expressions
// otherwise use getTaggedTiddlers() for simple tag matching
if (filterTags) {
var fn=store.getMatchingTiddlers||store.getTaggedTiddlers;
var t=fn.apply(store,[tags]);
var tagged=[];
for (var i=0; i<t.length; i++) tagged.push(t[i].title);
}
// scan list and select tiddlers that match all applicable criteria
var total=0;
var count=0;
for (var i=0; i<theList.options.length; i++) {
// get item, skip non-tiddler list items (section headings)
var opt=theList.options[i]; if (opt.value=='') continue;
// get tiddler, skip missing tiddlers (this should NOT happen)
var tiddler=store.getTiddler(opt.value); if (!tiddler) continue;
var sel=true;
if ( (filterStart && tiddler.modified<startDate)
|| (filterEnd && tiddler.modified>endDate)
|| (filterTags && !tagged.contains(tiddler.title))
|| (filterText && (tiddler.text.indexOf(text)==-1) && (tiddler.title.indexOf(text)==-1)))
sel=false;
opt.selected=sel;
count+=sel?1:0;
total++;
}
return count;
},
deleteTiddlers: function() {
var list=this.$('exportList'); if (!list) return;
var tids=[];
for (i=0;i<list.length;i++)
if (list.options[i].selected && list.options[i].value.length)
tids.push(list.options[i].value);
if (!confirm('Are you sure you want to delete these tiddlers:\n\n'+tids.join(', '))) return;
store.suspendNotifications();
for (t=0;t<tids.length;t++) {
var tid=store.getTiddler(tids[t]); if (!tid) continue;
var msg="'"+tid.title+"' is tagged with 'systemConfig'.\n\n";
msg+='Removing this tiddler may cause unexpected results. Are you sure?'
if (tid.tags.contains('systemConfig') && !confirm(msg)) continue;
store.removeTiddler(tid.title);
story.closeTiddler(tid.title);
}
store.resumeNotifications();
alert(tids.length+' tiddlers deleted');
this.refreshList(0); // reload listbox
store.notifyAll(); // update page display
},
go: function() {
if (window.location.protocol!='file:') // make sure we are local
{ displayMessage(config.messages.notFileUrlError); return; }
// get selected tidders, target filename, target type, and notes
var list=this.$('exportList'); if (!list) return;
var tids=[]; for (var i=0; i<list.options.length; i++) {
var opt=list.options[i]; if (!opt.selected||!opt.value.length) continue;
var tid=store.getTiddler(opt.value); if (!tid) continue;
tids.push(tid);
}
if (!tids.length) return; // no tiddlers selected
var target=this.$('exportFilename').value.trim();
if (!target.length) {
displayMessage('A local target path/filename is required',target);
return;
}
var filetype=this.$('exportFormat').value.toLowerCase();
var notes=this.$('exportNotes').value.replace(/\n/g,'<br>');
var total={val:0};
var out=this.assembleFile(target,filetype,tids,notes,total);
var link='file:///'+target.replace(/\\/g,'/');
var samefile=link==decodeURIComponent(window.location.href);
var p=getLocalPath(document.location.href);
if (samefile) {
if (config.options.chkSaveBackups) { var t=loadOriginal(p);if(t)saveBackup(p,t); }
if (config.options.chkGenerateAnRssFeed && saveRss instanceof Function) saveRss(p);
}
var ok=saveFile(target,out);
displayMessage((ok?this.okmsg:this.failmsg).format([total.val,target]),link);
},
plainTextHeader:
'Source:\n\t%0\n'
+'Title:\n\t%1\n'
+'Subtitle:\n\t%2\n'
+'Created:\n\t%3 by %4\n'
+'Application:\n\tTiddlyWiki %5 / %6 %7\n\n',
plainTextTiddler:
'- - - - - - - - - - - - - - -\n'
+'| title: %0\n'
+'| created: %1\n'
+'| modified: %2\n'
+'| edited by: %3\n'
+'| tags: %4\n'
+'- - - - - - - - - - - - - - -\n'
+'%5\n',
plainTextFooter:
'',
newsFeedHeader:
'<'+'?xml version="1.0"?'+'>\n'
+'<rss version="2.0">\n'
+'<channel>\n'
+'<title>%1</title>\n'
+'<link>%0</link>\n'
+'<description>%2</description>\n'
+'<language>en-us</language>\n'
+'<copyright>Copyright '+(new Date().getFullYear())+' %4</copyright>\n'
+'<pubDate>%3</pubDate>\n'
+'<lastBuildDate>%3</lastBuildDate>\n'
+'<docs>http://blogs.law.harvard.edu/tech/rss</docs>\n'
+'<generator>TiddlyWiki %5 / %6 %7</generator>\n',
newsFeedTiddler:
'\n%0\n',
newsFeedFooter:
'</channel></rss>',
pureStoreHeader:
'<html><body>'
+'<style type="text/css">'
+' #storeArea {display:block;margin:1em;}'
+' #storeArea div {padding:0.5em;margin:1em;border:2px solid black;height:10em;overflow:auto;}'
+' #pureStoreHeading {width:100%;text-align:left;background-color:#eeeeee;padding:1em;}'
+'</style>'
+'<div id="pureStoreHeading">'
+' TiddlyWiki "PureStore" export file<br>'
+' Source'+': <b>%0</b><br>'
+' Title: <b>%1</b><br>'
+' Subtitle: <b>%2</b><br>'
+' Created: <b>%3</b> by <b>%4</b><br>'
+' TiddlyWiki %5 / %6 %7<br>'
+' Notes:<hr><pre>%8</pre>'
+'</div>'
+'<div id="storeArea">',
pureStoreTiddler:
'%0\n%1',
pureStoreFooter:
'</div><!--POST-BODY-START-->\n<!--POST-BODY-END--></body></html>',
assembleFile: function(target,filetype,tids,notes,total) {
var revised='';
var now = new Date().toLocaleString();
var src=convertUnicodeToUTF8(document.location.href);
var title = convertUnicodeToUTF8(wikifyPlain('SiteTitle').htmlEncode());
var subtitle = convertUnicodeToUTF8(wikifyPlain('SiteSubtitle').htmlEncode());
var user = convertUnicodeToUTF8(config.options.txtUserName.htmlEncode());
var twver = version.major+'.'+version.minor+'.'+version.revision;
var v=version.extensions.ExportTiddlersPlugin; var pver = v.major+'.'+v.minor+'.'+v.revision;
var headerargs=[src,title,subtitle,now,user,twver,'ExportTiddlersPlugin',pver,notes];
switch (filetype) {
case this.type_TX: // plain text
var header=this.plainTextHeader.format(headerargs);
var footer=this.plainTextFooter;
break;
case this.type_CS: // comma-separated
var fields={};
for (var i=0; i<tids.length; i++) for (var f in tids[i].fields) fields[f]=f;
var names=['title','created','modified','modifier','tags','text'];
for (var f in fields) names.push(f);
var header=names.join(',')+'\n';
var footer='';
break;
case this.type_NF: // news feed (XML)
headerargs[0]=store.getTiddlerText('SiteUrl','');
var header=this.newsFeedHeader.format(headerargs);
var footer=this.newsFeedFooter;
break;
case this.type_PS: // PureStore (no code)
var header=this.pureStoreHeader.format(headerargs);
var footer=this.pureStoreFooter;
break;
case this.type_TW: // full TiddlyWiki
default:
var currPath=getLocalPath(window.location.href);
var original=loadFile(currPath);
if (!original) { displayMessage(config.messages.cantSaveError); return; }
var posDiv = locateStoreArea(original);
if (!posDiv) { displayMessage(config.messages.invalidFileError.format([currPath])); return; }
var header = original.substr(0,posDiv[0]+startSaveArea.length)+'\n';
var footer = '\n'+original.substr(posDiv[1]);
break;
}
var out=this.getData(target,filetype,tids,fields);
var revised = header+convertUnicodeToUTF8(out.join('\n'))+footer;
// if full TW, insert page title and language attr, and reset all MARKUP blocks...
if (filetype==this.type_TW) {
var newSiteTitle=convertUnicodeToUTF8(getPageTitle()).htmlEncode();
revised=revised.replaceChunk('<title'+'>','</title'+'>',' ' + newSiteTitle + ' ');
revised=updateLanguageAttribute(revised);
var titles=[]; for (var i=0; i<tids.length; i++) titles.push(tids[i].title);
revised=updateMarkupBlock(revised,'PRE-HEAD',
titles.contains('MarkupPreHead')? 'MarkupPreHead' :null);
revised=updateMarkupBlock(revised,'POST-HEAD',
titles.contains('MarkupPostHead')?'MarkupPostHead':null);
revised=updateMarkupBlock(revised,'PRE-BODY',
titles.contains('MarkupPreBody')? 'MarkupPreBody' :null);
revised=updateMarkupBlock(revised,'POST-SCRIPT',
titles.contains('MarkupPostBody')?'MarkupPostBody':null);
}
total.val=out.length;
return revised;
},
getData: function(target,filetype,tids,fields) {
// output selected tiddlers and gather list of titles (for use with merge)
var out=[]; var titles=[];
var url=store.getTiddlerText('SiteUrl','');
for (var i=0; i<tids.length; i++) {
out.push(this.formatItem(store,filetype,tids[i],url,fields));
titles.push(tids[i].title);
}
// if TW or PureStore format, ask to merge with existing tiddlers (if any)
if (filetype==this.type_TW || filetype==this.type_PS) {
var txt=loadFile(target);
if (txt && txt.length) {
var remoteStore=new TiddlyWiki();
if (version.major+version.minor*.1+version.revision*.01<2.52) txt=convertUTF8ToUnicode(txt);
if (remoteStore.importTiddlyWiki(txt) && confirm(this.mergeprompt.format([target]))) {
var existing=remoteStore.getTiddlers('title');
for (var i=0; i<existing.length; i++)
if (!titles.contains(existing[i].title))
out.push(this.formatItem(remoteStore,filetype,existing[i],url));
displayMessage(this.mergestatus.format([tids.length,out.length-tids.length]));
}
}
}
return out;
},
formatItem: function(s,f,t,u,fields) {
if (f==this.type_TW)
var r=s.getSaver().externalizeTiddler(s,t);
if (f==this.type_PS)
var r=this.pureStoreTiddler.format([t.title,s.getSaver().externalizeTiddler(s,t)]);
if (f==this.type_NF)
var r=this.newsFeedTiddler.format([t.saveToRss(u)]);
if (f==this.type_TX)
var r=this.plainTextTiddler.format([t.title, t.created.toLocaleString(), t.modified.toLocaleString(),
t.modifier, String.encodeTiddlyLinkList(t.tags), t.text]);
if (f==this.type_CS) {
function toCSV(t) { return '"'+t.replace(/"/g,'""')+'"'; } // always encode CSV
var out=[ toCSV(t.title), toCSV(t.created.toLocaleString()), toCSV(t.modified.toLocaleString()),
toCSV(t.modifier), toCSV(String.encodeTiddlyLinkList(t.tags)), toCSV(t.text) ];
for (var f in fields) out.push(toCSV(t.fields[f]||''));
var r=out.join(',');
}
return r||"";
}
}
//}}}
/***
!!!Control panel CSS
//{{{
!css
#exportPanel {
display: none; position:absolute; z-index:12; width:35em; right:105%; top:6em;
background-color: #eee; color:#000; font-size: 8pt; line-height:110%;
border:1px solid black; border-bottom-width: 3px; border-right-width: 3px;
padding: 0.5em; margin:0em; -moz-border-radius:1em;-webkit-border-radius:1em;
}
#exportPanel a, #exportPanel td a { color:#009; display:inline; margin:0px; padding:1px; }
#exportPanel table {
width:100%; border:0px; padding:0px; margin:0px;
font-size:8pt; line-height:110%; background:transparent;
}
#exportPanel tr { border:0px;padding:0px;margin:0px; background:transparent; }
#exportPanel td { color:#000; border:0px;padding:0px;margin:0px; background:transparent; }
#exportPanel select { width:98%;margin:0px;font-size:8pt;line-height:110%;}
#exportPanel input { width:98%;padding:0px;margin:0px;font-size:8pt;line-height:110%; }
#exportPanel textarea { width:98%;padding:0px;margin:0px;overflow:auto;font-size:8pt; }
#exportPanel .box {
border:1px solid black; padding:3px; margin-bottom:5px;
background:#f8f8f8; -moz-border-radius:5px;-webkit-border-radius:5px; }
#exportPanel .topline { border-top:2px solid black; padding-top:3px; margin-bottom:5px; }
#exportPanel .rad { width:auto;border:0 }
#exportPanel .chk { width:auto;border:0 }
#exportPanel .btn { width:auto; }
#exportPanel .btn1 { width:98%; }
#exportPanel .btn2 { width:48%; }
#exportPanel .btn3 { width:32%; }
#exportPanel .btn4 { width:24%; }
#exportPanel .btn5 { width:19%; }
!end
//}}}
!!!Control panel HTML
//{{{
!html
<!-- target path/file -->
<div>
export to path/filename:<br>
<input type="text" id="exportFilename" size=40 style="width:93%"><input
type="button" id="exportBrowse" value="..." title="select or enter a local folder/file..." style="width:5%"
onclick="var fn=config.macros.exportTiddlers.askForFilename(this); if (fn.length) this.previousSibling.value=fn; ">
</div>
<!-- output format -->
<div>
output file format:
<select id="exportFormat" size=1>
<option value="TW">TiddlyWiki HTML document (includes core code)</option>
<option value="PS">TiddlyWiki "PureStore" HTML file (tiddler data only)</option>
<option value="TX">TiddlyWiki plain text TXT file (tiddler source listing)</option>
<option value="CS">Comma-Separated Value (CSV) data file</option>
<option value="NF">RSS NewsFeed XML file</option>
</select>
</div>
<!-- notes -->
<div>
notes:<br>
<textarea id="exportNotes" rows=3 cols=40 style="height:4em;margin-bottom:5px;" onfocus="this.select()"></textarea>
</div>
<!-- list of tiddlers -->
<table><tr align="left"><td>
select:
<a href="JavaScript:;" id="exportSelectAll"
onclick="config.macros.exportTiddlers.process(this)" title="select all tiddlers">
all </a>
<a href="JavaScript:;" id="exportSelectChanges"
onclick="config.macros.exportTiddlers.process(this)" title="select tiddlers changed since last save">
changes </a>
<a href="JavaScript:;" id="exportSelectOpened"
onclick="config.macros.exportTiddlers.process(this)" title="select tiddlers currently being displayed">
opened </a>
<a href="JavaScript:;" id="exportSelectRelated"
onclick="config.macros.exportTiddlers.process(this)" title="select tiddlers related to the currently selected tiddlers">
related </a>
<a href="JavaScript:;" id="exportToggleFilter"
onclick="config.macros.exportTiddlers.process(this)" title="show/hide selection filter">
filter </a>
</td><td align="right">
<a href="JavaScript:;" id="exportListSmaller"
onclick="config.macros.exportTiddlers.process(this)" title="reduce list size">
– </a>
<a href="JavaScript:;" id="exportListLarger"
onclick="config.macros.exportTiddlers.process(this)" title="increase list size">
+ </a>
</td></tr></table>
<select id="exportList" multiple size="10" style="margin-bottom:5px;"
onchange="config.macros.exportTiddlers.refreshList(this.selectedIndex)">
</select><br>
<!-- selection filter -->
<div id="exportFilterPanel" style="display:none">
<table><tr align="left"><td>
selection filter
</td><td align="right">
<a href="JavaScript:;" id="exportHideFilter"
onclick="config.macros.exportTiddlers.process(this)" title="hide selection filter">hide</a>
</td></tr></table>
<div class="box">
<input type="checkbox" class="chk" id="exportFilterStart" value="1"
onclick="config.macros.exportTiddlers.showFilterFields(this)"> starting date/time<br>
<table cellpadding="0" cellspacing="0"><tr valign="center"><td width="50%">
<select size=1 id="exportFilterStartBy"
onchange="config.macros.exportTiddlers.showFilterFields(this);">
<option value="0">today</option>
<option value="1">yesterday</option>
<option value="7">a week ago</option>
<option value="30">a month ago</option>
<option value="file">file date</option>
<option value="other">other (mm/dd/yyyy hh:mm)</option>
</select>
</td><td width="50%">
<input type="text" id="exportStartDate" onfocus="this.select()"
onchange="config.macros.exportTiddlers.$('exportFilterStartBy').value='other';">
</td></tr></table>
<input type="checkbox" class="chk" id="exportFilterEnd" value="1"
onclick="config.macros.exportTiddlers.showFilterFields(this)"> ending date/time<br>
<table cellpadding="0" cellspacing="0"><tr valign="center"><td width="50%">
<select size=1 id="exportFilterEndBy"
onchange="config.macros.exportTiddlers.showFilterFields(this);">
<option value="0">today</option>
<option value="1">yesterday</option>
<option value="7">a week ago</option>
<option value="30">a month ago</option>
<option value="file">file date</option>
<option value="other">other (mm/dd/yyyy hh:mm)</option>
</select>
</td><td width="50%">
<input type="text" id="exportEndDate" onfocus="this.select()"
onchange="config.macros.exportTiddlers.$('exportFilterEndBy').value='other';">
</td></tr></table>
<input type="checkbox" class="chk" id=exportFilterTags value="1"
onclick="config.macros.exportTiddlers.showFilterFields(this)"> match tags<br>
<input type="text" id="exportTags" onfocus="this.select()">
<input type="checkbox" class="chk" id=exportFilterText value="1"
onclick="config.macros.exportTiddlers.showFilterFields(this)"> match titles/tiddler text<br>
<input type="text" id="exportText" onfocus="this.select()">
</div> <!--box-->
</div> <!--panel-->
<!-- action buttons -->
<div style="text-align:center">
<input type=button class="btn4" onclick="config.macros.exportTiddlers.process(this)"
id="exportFilter" value="apply filter">
<input type=button class="btn4" onclick="config.macros.exportTiddlers.process(this)"
id="exportStart" value="export tiddlers">
<input type=button class="btn4" onclick="config.macros.exportTiddlers.process(this)"
id="exportDelete" value="delete tiddlers">
<input type=button class="btn4" onclick="config.macros.exportTiddlers.process(this)"
id="exportClose" value="close">
</div><!--center-->
!end
//}}}
***/
!Basics
--strike through--
//italic//
''bold''
__underline__
@@highlighted@@
@@color(yellow):yellow colored text@@
----
{{{
--strike through--
//italic//
''bold''
__underline__
@@highlighted@@
@@color(yellow):yellow colored text@@
----
}}}
!Lists, quotes, tables
#[[Numbered Lists]]
#[[Bullet Points]]
#[[Block quotes]]
#[[Tables]]
#[[Images]]
#[[GPUs supporting CUDA|http://www.nvidia.com/object/cuda_education.html]]
#[[OpenMP/OpenMPI|http://ci-tutor.ncsa.uiuc.edu/login.php]] (requires registration)
#[[Data visualization|http://ci-tutor.ncsa.uiuc.edu/login.php]] (requires registration)
Package with commands such as {{{animate}}} and {{{convert}}}. Useful for making movies of a series of {{{.gif}}} images, viewing and converting images quickly in xwindows. [[Go here to install|http://www.imagemagick.org/script/binary-releases.php#macosx]]. [[Examples here|http://www.imagemagick.org/Usage/]]
#go to http://www.nvidia.com/object/cuda_get.html, select your OS and download toolkit and SDK
#add
{{{
export PATH=/usr/local/cuda/bin:$PATH
export DYLD_LIBRARY_PATH=/usr/local/cuda/lib:$DYLD_LIBRARY_PATH
}}}
to {{{.bash_profile}}}
#SDK is located in {{{/Developer/CUDA}}}
##cd there, {{{make}}}
##may need to
#CUDA compiler is {{{nvcc}}}
Modify the Makefile (adjust the absolute paths to your install)
{{{
SYSTYPE="Mac"
ifeq ($(SYSTYPE),"Mac")
FFTW_INCL = -I/Users/corbett/pitp/pitp_dependencies/fftw-2.1.5/include
FFTW_LIBS= -L/Users/corbett/pitp/pitp_dependencies/fftw-2.1.5/lib
MPICHLIB =-L/Users/corbett/pitp/pitp_dependencies/openmpi-1.3.2/lib
endif
}}}
If you have problems, that certain fftw files do not exist make sure you followed the multiple install procedure in [[Compiling Gadget2 for OSX]] for fftw. (e.g. compiling for both float and double precision, with the {{{--enable-mpi prefix}}}
!2-6
*Installed athena, compiled with suggested flags to configure, ran
*Installed VAPOR as suggested by CK as well as conversion files for {{{.bin}}} athena output
**had to edit conversion file {{{.sh}}} script
!Plotting/Analysis
Using the python sage library, I made some plots, animating various properties suggested to plot. A [[link to my sage notebook|./pitp_homeworks/code/Athena_plots.sws]] used to generate these.
!!Movies/Images
!!!Exercise 2
Convergence rate
[img[./pitp_homeworks/visualization/pictures/stone_problem2_LinWave-errors.0.convergence_rate.png]]
!!!Exercise 3 (All plots are against position, animations evolving forward in time)
*Wave steepening: density
[img[./pitp_homeworks/visualization/movies/stone_ex3_density_wavesteepening.gif]]
*Wave steepening: pressure
[img[./pitp_homeworks/visualization/movies/stone_ex3_pressure_wavesteepening.gif]]
!!!Exercise 4 (All plots are against position, animations evolving forward in time)
*Shock tube
**B1c-3c
[img[./pitp_homeworks/visualization/movies/stone_ex4_shocktubeBrio-Wu.0040.tab.B1c.gif]]
[img[./pitp_homeworks/visualization/movies/stone_ex4_shocktubeBrio-Wu.0040.tab.B2c.gif]]
[img[./pitp_homeworks/visualization/movies/stone_ex4_shocktubeBrio-Wu.0040.tab.B3c.gif]]
**B1i-3i
[img[./pitp_homeworks/visualization/movies/stone_ex4_shocktubeBrio-Wu.0040.tab.B2i.gif]]
[img[./pitp_homeworks/visualization/movies/stone_ex4_shocktubeBrio-Wu.0040.tab.B1i.gif]]
[img[./pitp_homeworks/visualization/movies/stone_ex4_shocktubeBrio-Wu.0040.tab.B3i.gif]]
**Density
[img[./pitp_homeworks/visualization/movies/stone_ex4_shocktubeBrio-Wu.0040.tab.density.gif]]
**Pressure
[img[./pitp_homeworks/visualization/movies/stone_ex4_shocktubeBrio-Wu.0040.tab.pressure.gif]]
**Velocity
[img[./pitp_homeworks/visualization/movies/stone_ex4_shocktubeBrio-Wu.0040.tab.velocity.gif]]
#Don't be too clever
#Don't be too dumb
#Keep it simple
#Know your language
#Don't mix logical and arithmetic operators
##in C, e.g. bit operations have lower precedence in order of operations
#Avoid macros in C and C++
##used to be important for efficiency; no longer-esp. function macros
#Don't sacrifice clarity for efficiency
##modern compilers are smarter than you are
#Avoid the bad features of a language
#Know the pitfalls
#Use the idioms of your language
#Test programs at their boundaries
#Program defensively
##check parameters
###"What could possibly go wrong"
##don't trust input
##watch for overflows
#If... If... If...: Bad Bad Bad
##Everytime you make a decision, do something
##If, else if, else if, ..., else
#Put regularity in control flow, irregularity in data
#Modularize
#Make sure code and comments agree
#Don't just echo the code with comments
#Make every comment count
#Don't document bad code rewrite it
#Avoid magic numbers
#Use names that mean something
''Say what you mean, simply and directly. Write as clearly as you can.''
/***
|''Name:''|LoadRemoteFileThroughProxy (previous LoadRemoteFileHijack)|
|''Description:''|When the TiddlyWiki file is located on the web (view over http) the content of [[SiteProxy]] tiddler is added in front of the file url. If [[SiteProxy]] does not exist "/proxy/" is added. |
|''Version:''|1.1.0|
|''Date:''|mar 17, 2007|
|''Source:''|http://tiddlywiki.bidix.info/#LoadRemoteFileHijack|
|''Author:''|BidiX (BidiX (at) bidix (dot) info)|
|''License:''|[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D ]]|
|''~CoreVersion:''|2.2.0|
***/
//{{{
version.extensions.LoadRemoteFileThroughProxy = {
major: 1, minor: 1, revision: 0,
date: new Date("mar 17, 2007"),
source: "http://tiddlywiki.bidix.info/#LoadRemoteFileThroughProxy"};
if (!window.bidix) window.bidix = {}; // bidix namespace
if (!bidix.core) bidix.core = {};
bidix.core.loadRemoteFile = loadRemoteFile;
loadRemoteFile = function(url,callback,params)
{
if ((document.location.toString().substr(0,4) == "http") && (url.substr(0,4) == "http")){
url = store.getTiddlerText("SiteProxy", "/proxy/") + url;
}
return bidix.core.loadRemoteFile(url,callback,params);
}
//}}}
These require you to install the [[jsMath plugin|http://bob.mcelrath.org/tiddlyjsmath-2.0.3.html]]
|!Symbol|![[LaTeX]]|!Use|
| $\mathbb{R} \;\; \mathbb{C} \;\; n \;\; \ud{a}$ | {{{ \mathbb{R} \mathbb{C} n \ud{a} }}} |[[real numbers|http://en.wikipedia.org/wiki/Real_numbers]], complex numbers, dimension, [[Grassmann number]] |
| $M \; \; T_p M \; \; T_p^* M$ | {{{M T_p M T_p^* M }}} |[[manifold]], [[tangent space to M at point p|coordinate basis vectors]], [[cotangent space to M at point p|coordinate basis 1-forms]] |
| $x^i \; \; \ve{\pa_i} \; \; \ve{v} \; \; \vv{l}$ | {{{x^i \ve{\pa_i} \ve{v} \vv{l} }}} |[[coordinates|manifold]] and [[coordinate basis vectors]] with coordinate [[indices]], [[tangent vector]], [[loop|vector-form algebra]] |
| $t \; \; \ta$ | {{{ t \ta }}} |parameter time, [[proper time]] |
| $\f{dx^i} \;\; \f{a} \;\; \ff{b} \;\; \fff{c} \;\; \nf{f}$ | {{{\f{dx^i} \f{a} \ff{b} \fff{c} \nf{f} }}} |[[coordinate basis 1-forms]], [[1-form]], [[2-form|differential form]], 3-form, [[differential form]] of high or unspecified form grade |
| $\pa_i \;\; \f{\pa} \;\; \f{d}$ | {{{\pa_i \f{\pa} \f{d} }}} |[[partial derivative]], partial derivative, [[exterior derivative]] |
| $\ph \; \; \ph^* \; \; \ph_*$ | {{{\ph \ph^* \ph_* }}} |[[diffeomorphism]], [[pullback]], pushforward |
| ${\cal L}_{\ve{v}} \;\; \lb\ve{v},\ve{u}\rb_L \;\; \ve{\De}$ | {{{{\cal L}_{\ve{v}} \lb\ve{v},\ve{u}\rb_L \ve{\De} }}} |[[Lie derivative]], [[Lie bracket|Lie derivative]] of two [[vector fields|tangent bundle]], [[distribution]] |
| $\nf{\ve{A}} \;\; {\cal L}_{\nf{\ve{K}}} \;\; \lb\nf{\ve{K}},\nf{\ve{L}}\rb_L \;\; \f{\ve{P}}$ | {{{ \f{\ve{A}} {\cal L}_{ \nf{\ve{K}} } \lb\nf{\ve{K}},\nf{\ve{L}}\rb_L \f{\ve{P}} }}} |[[vector valued form]], [[FuN derivative]], FuN bracket, [[vector projection]] |
| $\f{\ve{\cal A}} \;\; \ff{\ve{\cal F}} \;\; \f{\cal D}$ | {{{ \f{\ve{\cal A}} \ff{\ve{\cal F}} \f{\cal D} }}} |[[Ehresmann connection]], [[FuN curvature]], [[Ehresmann covariant derivative]] |
| $\de_i^j \;\; \et_{\al \be} \; \; \ep_{\al \dots \be} \; \; \otimes$ | {{{ \de_i^j \et_{\al \be} \ep_{\al \dots \be} \otimes }}} |[[Kronecker delta|http://en.wikipedia.org/wiki/Kronecker_delta]], [[Minkowski metric]], [[permutation symbol]], [[Kronecker product]] |
| $G \;\; g^- \;\; T_A \;\; \lb{T_A,T_B}\rb$ | {{{G g^- T_A \lb{T_A,T_B}\rb }}} |[[Lie group]], [[inverse]] of a group element, [[Lie algebra]] generators, [[commutator]] bracket |
| $\f{\na} \;\; \f{A} \;\; \ff{F}$ | {{{\f{\na} \f{A} \ff{F} }}} |[[covariant derivative]], [[connection]], [[curvature]] |
| $\f{\cal I} \;\; \f{\ve{\cal I}} \;\; \ve{\xi^L_A} \;\; \ve{\xi^R_A}$ | {{{\f{\cal I} \f{\ve{\cal I}} \ve{\xi^L_A} \ve{\xi^R_A} }}} |[[Maurer-Cartan form]], Ehresmann-Maurer-Cartan form, [[left and right action vector fields|Lie group geometry]] |
| $Cl \; \; Cl^*$ | {{{Cl Cl^* }}} |[[Clifford algebra]], [[Clifford group]] |
| $\ga_\al \; \; \ga_{\al \dots \be} \; \; \ga$ | {{{\ga_\al \ga_{\al \dots \be} \ga }}} |[[Clifford basis vectors]], [[Clifford basis elements]], Clifford [[pseudoscalar]] |
| $\hat{A} \; \; \tilde{A} \; \; \bar{A} \; \; A^\dagger \; \; \overline{A}$ | {{{\hat{ \tilde{ \bar{ \overline{A}^\dagger } } } }}} |[[Clifford involution, reverse, conjugate, Hermitian conjugate, Dirac conjugate|Clifford conjugate]] |
| $\cdot \; \; \times$ | {{{\cdot \times }}} |symmetric and antisymmetric [[Clifford algebra]] product |
| $\lb{A,\dots,B}\rb_A \;\; a_{\lb{\al\dots\be}\rb}$ | {{{ \lb{A,\dots,B}\rb_A a_{\lb{\al\dots\be}\rb} }}} |[[antisymmetric bracket]], [[index bracket]] |
| $\li{A}\ri_q \; \; \li{A}\ri$ | {{{ \li{A}\ri_q \li{A}\ri }}} |[[Clifford grade]] $q$ part, [[scalar part|Clifford grade]] |
| $\f{A} \; \; \ff{b} \; \; \ve{e}$ | {{{ \f{A} \ff{b} \ve{e} }}} |[[Lieform]]s or [[Clifform]]s |
| $\lp{e_i}\rp^\al \;\; \lp{e_\al}\rp^i \;\; g_{ij} \;\; \lp\ve{u},\ve{v}\rp$ | {{{ \lp{e_i}\rp^\al \lp{e_\al}\rp^i g_{ij} \lp\ve{u},\ve{v}\rp }}} |co[[frame]] matrix, frame matrix, [[metric]], scalar product |
| $\f{e^\al} \;\; \ve{e_\al}$ | {{{ \f{e^\al} \ve{e_\al} }}} |co[[frame]] 1-forms, orthonormal basis vectors |
| $\f{e} \;\; \ve{e}$ | {{{ \f{e} \lp{e_i}\rp^\al \ve{e} \lp{e_\al}\rp^i g_{ij} }}} |co[[frame]], frame |
| $\nf{e} \;\; \ll{e}\rl$ | {{{ \nf{e} \ll{e}\rl }}} |[[volume form]], frame [[determinant]] |
| $\nf{*f} \;\; \ff{\vv{\ep}}$ | {{{ \nf{*f} \ff{ \vv{\ep} } }}} |[[Hodge dual]], Hodge dual projector |
| $\f{e^s} \;\; \lp{e^s_i}\rp^\al \;\; s$ | {{{ \f{e^s} \;\; \lp{e^s_i}\rp^\al \;\; s }}} |[[special frame]], special coframe matrix, conformal scalar |
| $TM \;\; T^*M$ | {{{ TM T^*M }}} |[[tangent bundle]], [[cotangent bundle]] |
| $\Ga^k{}_{ij} \;\; \f{\Ga}^k{}_j \;\; \ff{R}^k{}_j$ | {{{ \Ga^k{}_{ij} \f{\Ga}^k{}_j \ff{R}^k{}_j }}} |[[Christoffel symbols]], [[tangent bundle connection]], [[Riemann curvature]] |
| $\f{R}{}_j \;\; R$ | {{{ \f{R}{}_j R }}} |[[Ricci curvature]], [[curvature scalar]] |
| $L^\be{}_\al \;\; \f{w}^\be{}_\al \;\; \ff{F}^\be{}_\al$ | {{{ L^\be{}_\al \f{w}^\be{}_\al \ff{F}^\be{}_\al }}} |[[Lorentz rotation]], [[tangent bundle spin connection|tangent bundle connection]], [[Riemann curvature]] |
| $ClM \;\; Cl^1M$ | {{{ ClM Cl^1M }}} |[[Clifford bundle]], [[Clifford vector bundle]] |
| $\f{A} \;\; \f{\om} \;\; \ff{R}$ | {{{ \f{A} \f{\om} \ff{R} }}} |[[Clifford connection]], [[spin connection]], [[Clifford-Riemann curvature]] |
| $\f{R} \;\; R$ | {{{ \f{R} R }}} |[[Clifford-Ricci curvature]], [[Clifford curvature scalar]] |
| $\ff{T} \;\; \f{\ka}$ | {{{ \ff{T} \f{\ka} }}} |[[torsion]], contorsion |
| $\ud{C} \;\; \nf{\od{B}} \;\; \udf{A} \;\; \udff{F}$ | {{{ \ud{C} \nf{\od{B}} \udf{A} \udff{F} }}} |[[BRST|BRST technique]] ghost, anti-ghost, extended connection, extended curvature |
(Copied from Garret Lisi's TiddlyWiki...)
!Installing yt and enzo
*[[enzo binary|https://www.sns.ias.edu/twiki/pub/Main/EnzoWork/enzo_darwin.zip]] for osx is available
*yt can be installed using [[this script|https://www.sns.ias.edu/twiki/pub/Main/EnzoWork/parameter_files.zip]]
**actually, that is a world of pain. better to install by hand.
!Running enzo
!!Exercise 1: Seldov Blast
*get example [[parameter files|https://www.sns.ias.edu/twiki/pub/Main/EnzoWork/parameter_files.zip]], make a run directory, copy relevant input files to directory
{{{
mkdir ex1; cd ex1; cp ../parameter_files/SedovBlastAMR.enzo .
mpirun -np 2 ../enzo.exe SedovBlastAMR.enzo
}}}
**then plot with {{{yt plot -f Density -a 2 --show-grids DD0004/sb_L2x2_0004}}}
*Plot:
[img[./pitp_homeworks/visualization/movies/norman_ex1_seldovblast.gif]]
!!Exercise 2: Collapse Test
*run the sphere collapse, in a similar manner to above. note that the file {{{parameter_files/cool_rates.in}}} is also required in the directory of the run
**then plot with {{{yt plot -f Density -a 2 --show-grids DD0004/moving7_0004}}}
*Plot:
[img[./pitp_homeworks/visualization/movies/norman_ex2_collapsetest.gif]]
!!Exercise 3: Sphere Collision
*modify CollapseTest.enzo to create two colliding spheres. There's already an example of this in SphereCollision.enzo, but we can further modify it {{{diff SphereCollision.enzo CollapseTest.enzo}}}
**then plot with
{{{
yt plot --colormap=bds_highcontrast -z 1e-26 1e-24 -g Density -f Density -p --show-grids DD0016/moving7_0016
}}}
*made a bash script to plot all, can be modified to plot all in a given directory
{{{
#!/bin/bash
for file in $(ls -d DD*); do
newfile=`echo $file | sed 's/DD\(.*\)/\1/g'`
nice yt plot --colormap=bds_highcontrast -z 1e-26 1e-24 -g Density -f Density -p --show-grids $file/moving7_$newfile
done
}}}
*Plot:
[img[./pitp_homeworks/visualization/movies/norman_ex3_spherecollision_z.gif]]
!!Exercise 4: Unigrid
As Exercise 3 is taking so much time to run on my laptop, I decided to run on apollo, which is accomplished by {{{source /home/pitp097/enzo.sh}}}, making available {{{enzo.exe}}} and {{{inits.exe}}}. I ran initial conditions, and created a qsub script {{{norman_ex1.qsub}}}:
{{{
#!/bin/bash
#$ -pe orte 16
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
cd $HOME/norman_ex1/Ex4Unigrid
/usr/local/openmpi/bin/mpirun /home/pitp097/packages/bin/enzo.exe UnigridCosmologySimulation.enzo
wait
}}}
and then ran with the command {{{qsub norman_ex1.qsub}}}. Currently running, ran halo finder on fifth snapshot with the command {{{nice yt hop RD0005/RedshiftOutput0005}}}, got {{{.hop}}} ascii out, but found no halos TODO: run with a later snapshot/debug if necessary
*Plot:
[img[./pitp_homeworks/visualization/movies/norman_ex4_unigrid.gif]]
!!Excercise 5: Nested Grid
Generated initial conditions with
{{{
$nice inits.exe -d -s AMRCosmologySimulation_L1.inits AMRCosmologySimulation_L0.inits
$nice inits.exe -d AMRCosmologySimulation_L1.inits
}}}
Created a qsub script similar to the one above for {{{AMRCosmologySimulation_L2.enzo}}} and submitted. It has finished, but plotting was less successful than the other exercises
!Making movies
After plotting with {{{yt}}} I took [[Alina]]'s suggestion and made movies of the {{{.png}}} files with [[ImageMagick]]. } For a lot of files it takes awhile to run, then opens up an animation window at which point you can right click and save.
{{{
animate -delay 10 -loop 0 DD*.png
}}}
*check out [[MayaVi]], [[MLab]]
@@color(yellow):Note: for the inline latex to render correctly, you must install jsMath: detailed instructions [[here|http://bob.mcelrath.org/tiddlyjsmath-2.0.3.html]].@@
!Homeworks
[[Jim Stone homework 1]] [[assignment link|http://carma.astro.umd.edu/nemo/pitp/papers/exercises/stone_homework.pdf]]
[[Spitkovsky homework 1]] [[assignment link|https://www.sns.ias.edu/twiki/bin/view/Main/PICwork]]
[[Richardson Homework 1]] [[assignment link|http://www.astro.umd.edu/~dcr/Courses/PiTP/index.html#homework]]
[[Norman Homework]] [[assignment link|https://www.sns.ias.edu/twiki/bin/view/Main/EnzoWork]]
[[Pretorius homework]] [[assignment link|http://physics.princeton.edu/~fpretori/group_resources/PiTP_2009/index.html]]
[[Tremaine's homework 1]] [[assignment link|http://www.sns.ias.edu/~tremaine/assign.pdf]]
[[Bill Dorland's homework]] [[assignment link|https://www.sns.ias.edu/twiki/bin/view/Main/CudaWork]]
[[Volker Springel's homework 1]] [[assignment link|http://www.mpa-garching.mpg.de/~volker/PiTP_exercises/]]
[[Volker Springel's homework 2-4]] [[assignment link|http://www.mpa-garching.mpg.de/~volker/PiTP_exercises/]]
!Lectures
!!Norman
[["Computation astrophysics versus the big questions: an assessment" Michael Norman]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/Computational_Astrophysics_versus_the_Big_Questions.pdf]]
[["Self consistent cosmological radiation hydrodynamics" Michael Norman]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/norman_Cosmo.pdf]]
!!Dorland
[["Clustered many-core computing with CPUs + GPUs" William Dorland (1 of 2 tutorials)]]
[["Clustered many-core computing with CPUs + GPUs" William Dorland (2 of 2 tutorials)]]
!!Springel
[["Collisionless dynamics and smoothed particle hydrodynamics" Volker Springel (1 of 5)]] [[jpg|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/springel_lecture1.jpg]]
[["Collisionless dynamics and smoothed particle hydrodynamics" Volker Springel (2 of 5)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/springel_lecture2.pdf]]
[["Collisionless dynamics and smoothed particle hydrodynamics" Volker Springel (3 of 5)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/springel_lecture3.pdf]]
[["Collisionless dynamics and smoothed particle hydrodynamics" Volker Springel (4 of 5)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/springel_lecture4.pdf]]
[["Collisionless dynamics and smoothed particle hydrodynamics" Volker Springel (5 of 5)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/springel_lecture5.pdf]]
!!Pretorius
[["Computational methods for numerical relativity" Frans Pretorius (1 of 4)]] [[pdf|http://physics.princeton.edu/~fpretori/PiTP_NR_Lecture_1.pdf]]
[["Computational methods for numerical relativity" Frans Pretorius (2 of 4)]] [[pdf|http://physics.princeton.edu/~fpretori/group_resources/PiTP_2009/PiTP_NR_Lecture_2.pdf]]
[["Computational methods for numerical relativity" Frans Pretorius (3 of 4)]] [[pdf|http://physics.princeton.edu/~fpretori/group_resources/PiTP_2009/PiTP_NR_Lecture_3.pdf]]
[["Computational methods for numerical relativity" Frans Pretorius (4 of 4)]] [[pdf|http://physics.princeton.edu/~fpretori/group_resources/PiTP_2009/PiTP_NR_Lecture_3.pdf]]
!!Tremaine
[["Geometric methods for orbit integration" Scott Tremaine]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/tremaine_geometric.pdf]]
!!Stone
[["Grid-based methods for hydrodynamics, magnetohydrodynamics, and radiation hydrodynamics" Jim Stone (1 of 4)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/stone_Lecture1.pdf]]
[["Grid-based methods for hydrodynamics, magnetohydrodynamics, and radiation hydrodynamics" Jim Stone (2 of 4)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/stone_Lecture2.pdf]]
[["Grid-based methods for hydrodynamics, magnetohydrodynamics, and radiation hydrodynamics" Jim Stone (3 of 4)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/stone_Lecture3.pdf]]
[["Grid-based methods for hydrodynamics, magnetohydrodynamics, and radiation hydrodynamics" Jim Stone (4 of 4)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/stone_Lecture4.pdf]]
[["Program Summary" Jim Stone]]
!!Spitkovsky
[["Kinetic simulations of astrophysical plasmas" Anatoly Spitkovsky (1 of 2)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/spitkovsky_PICtutorialPiTP.pdf]]
[["Kinetic simulations of astrophysical plasmas" Anatoly Spitkovsky (2 of 2)]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/spitkovsky_PICtutorialPiTP.pdf]]
!!Richardson
[["N rigid-body dynamics" Derek Richardson]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/Richardson.pdf]]
!!Kernighan
[[Lecture "Elements of programming style" Brian Kernighan]]
!!Bowers
[["Petascale kinetic plasma simulation with VPIC and Roadrunner" Kevin Bowers]]
!!Panels
[[Panel Discussion: "Legacy codes in astrophysics"]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/panel_on_code_writing.pdf]]
[[Open Discussion: "Visualization and scripting tools"]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/script_vis_richardson.pdf]] [[pdf|http://carma.astro.umd.edu/nemo/pitp/papers/lectures/script_vis_teuben.pdf]]
!Other
!!Installation
[[Compiling Gadget2 for OSX]]
[[Compiling Zeus for OSX]]
[[Installing N-GenIC for mac]]
!!Further method details
[[Particle Mesh method (PM)]]
[[Tree algorithms]]
!TODO
!!Homework
#look through [[Springel homework 2]], [[Springel homework 3]], [[Springel homework 4]]
!!Plotting/analysis
#why does [[Norman homework]] 4 and 5 seem off
#plot Mercury output for [[Tremaine's homework 1]] (currently in orbital elements in {{{.aei}}} files)
##I have sage file set up to do plotting, but want to check how to convert elements (e.g. what is node, why two different types of M?)
#figure out why {{{xvs}}} plots don't look the same as examples for [[Pretorius homework]]
##modify an RNPL file
#plot athena output for [[Jim Stone homework 1]]
##done, but for problems 5 and 6, {{{animate}}} and {{{convert}}} have a bus error, if {{{ppm}}} files output by athena are input.
!!Understanding
#attempt analytic work on Tremaine and Spitkovsky
#go through plots, review physical meaning
*Ray tracing
*All done with scripts
<div id='header' class='header' macro='gradient vert #555555 #3b3b3b '>
<div class='siteTitle' refresh='content' tiddler='SiteTitle'></div>
<span id='topMenu' refresh='content' tiddler='MainMenu'></span>
</div>
<div id='sidebar'>
<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>
<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
!Four steps
#density assignment
#compute potential
##FFT forward of the density filed
##multiply with the Green's function
##FFT backwards to obtain potential
#determine force filed
##finite differencing of the potential
##interpolate the mesh forces to the particle locations
##needs to bet the same method as the density assignment
#assign foreces to particles
!Advantages and disadvantages
*Pros
**speed and simplicity
*Cons
**Spatial force resolution limited to mesh size
***cannot make the mesh fine enough and resolve internal structure of halos as well as large cosmological scaes
**force errors somewhat anisotropic on the scale of the cell size
!Particle-Particle PM scheme $P^3 M$
*supplement the PM forces with a direct summation short-range force at the scale of the mesh cells. The particles in cells are linked together by a linking list.
*in $AP^3M$ mesh-refinements are placed on clustered regions
**can avoid clustering slow-down but has higher complexity and ambiguities
*offers much higher dynamic range but becomes slow when clustering sets in
!Other methods of determining the potential
*iterative Poisson solvers
*in ''multigrid methods'' a hierarchy of meshes is used to speed up convergence resulting in a fast method that allows for locally varying resolution
*on adaptive meshes, sometimes a combination of Fourier tehcniques and real-space solvers is used.
/***
|''Name:''|PasswordOptionPlugin|
|''Description:''|Extends TiddlyWiki options with non encrypted password option.|
|''Version:''|1.0.2|
|''Date:''|Apr 19, 2007|
|''Source:''|http://tiddlywiki.bidix.info/#PasswordOptionPlugin|
|''Author:''|BidiX (BidiX (at) bidix (dot) info)|
|''License:''|[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D ]]|
|''~CoreVersion:''|2.2.0 (Beta 5)|
***/
//{{{
version.extensions.PasswordOptionPlugin = {
major: 1, minor: 0, revision: 2,
date: new Date("Apr 19, 2007"),
source: 'http://tiddlywiki.bidix.info/#PasswordOptionPlugin',
author: 'BidiX (BidiX (at) bidix (dot) info',
license: '[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D]]',
coreVersion: '2.2.0 (Beta 5)'
};
config.macros.option.passwordCheckboxLabel = "Save this password on this computer";
config.macros.option.passwordInputType = "password"; // password | text
setStylesheet(".pasOptionInput {width: 11em;}\n","passwordInputTypeStyle");
merge(config.macros.option.types, {
'pas': {
elementType: "input",
valueField: "value",
eventName: "onkeyup",
className: "pasOptionInput",
typeValue: config.macros.option.passwordInputType,
create: function(place,type,opt,className,desc) {
// password field
config.macros.option.genericCreate(place,'pas',opt,className,desc);
// checkbox linked with this password "save this password on this computer"
config.macros.option.genericCreate(place,'chk','chk'+opt,className,desc);
// text savePasswordCheckboxLabel
place.appendChild(document.createTextNode(config.macros.option.passwordCheckboxLabel));
},
onChange: config.macros.option.genericOnChange
}
});
merge(config.optionHandlers['chk'], {
get: function(name) {
// is there an option linked with this chk ?
var opt = name.substr(3);
if (config.options[opt])
saveOptionCookie(opt);
return config.options[name] ? "true" : "false";
}
});
merge(config.optionHandlers, {
'pas': {
get: function(name) {
if (config.options["chk"+name]) {
return encodeCookie(config.options[name].toString());
} else {
return "";
}
},
set: function(name,value) {config.options[name] = decodeCookie(value);}
}
});
// need to reload options to load passwordOptions
loadOptionsCookie();
/*
if (!config.options['pasPassword'])
config.options['pasPassword'] = '';
merge(config.optionsDesc,{
pasPassword: "Test password"
});
*/
//}}}
[[web specs|http://physics.princeton.edu/~fpretori/group_resources/PiTP_2009/index.html]]
*RNPL is already installed on apollo. Simply add the following lines to {{{.bash_profile}}} and the Makefiles will be ready to use
{{{
#RNPL
export RNPL_RNPL=rnpl
export RNPL_F77=gfortran
export RNPL_F77LOAD=gfortran
export RNPL_FLIBS=-lrnpl
}}}
*xvs is needed to visualize images. xvs uses a client/server model. make sure {{{export XVSHOST=`hostname`}}} is added to {{{.bash_profile}}}
!Example
Am able to make, and run.
{{{
cd w1dcnm
./w1dcnm id0
./w1dcnm id1
./w1dcnm id2
./w1dcnm id3
./w1dcnm id4
}}}
After launching {{{xvs}}} I can send output {{{sdf}}} files for viewing. There is however, a small problem in that the graphs are not actually displayed.
!Project 1
I am able to generate c or fortran code using rnpl:
*c: {{{rnpl -lc problem_rnpl}}}
*fortran {{{rnpl -lf90 problem_rnpl}}}
!Project 2
Code provided up until problem 5 [[download|http://physics.princeton.edu/~fpretori/group_resources/PiTP_2009/emkg_5.tar.gz]]
!Setup and sample run
to bet able to run pkdgrav, ssh into the apollo cluster then
{{{
source /home/teuben/astromake/astromake_start.sh
astroload pkdgrav
}}}
to get the parameter files needed (which can later be tweaked)
{{{
wget http://www.astro.umd.edu/~dcr/Courses/PiTP/rpg.par http://www.astro.umd.edu/~dcr/Courses/PiTP/ss.par http://www.astro.umd.edu/~dcr/Courses/PiTP/ssdraw.par http://www.astro.umd.edu/~dcr/Courses/PiTP/world.ss
}}}
to do a sample run of two asteroids that collide at 10 m/s
{{{
pkdgrav +overwrite ss.par
mkmov
}}}
You will now have a file called movie.mpg. You can open it in your favorite media player, or even your webbrowser.
!Tweaking: creating a new rubble pile
#I created a new directory, and created a new rubble pile, editing {{{rpg.par}}}
{{{
$ diff rpg.par ../default/rpg.par
12,13c12,13
< Number of particles 1000 # this is only a hint
< Color 12 # see below
---
> Number of particles 250 # this is only a hint
> Color 3 # see below
16c16
< Particle max speed 25 # in units of escape speed (ICs only)
---
> Particle max speed 0.1 # in units of escape speed (ICs only)
18c18
< Initial spin period .1 # in h, around z-axis (0=no spin)
---
> Initial spin period 0 # in h, around z-axis (0=no spin)
}}}
then running
{{{
rpg
}}}
to generate the new rubble pile, {{{rpg.ss}}}.
Finally I then combined it with the world.ss rubble piles via the rpx command (giving my new rpg.ss and the old world.ss piles as arguments), creating the file {{{newworld.ss}}}, and edited {{{ss.par}}} to point to {{{newworld.ss}}} instead of {{{world.ss}}} as an input and ran pkdgrav as above
{{{
pkdgrav +overwrite ss.par
mkmov
}}}
!Tweaking: creating random initial conditions
!Analysis
Ran {{{rpa}}} on my output files.
{{{
rpa ss.?????
}}}
Obtained {{{.sm}}} file for the plotting package of the same file {{{wget http://www.astro.umd.edu/~dcr/Courses/PiTP/rpa.sm}}}. Then gave as an input to sm with
{{{
sm inp_new rpa.sm
}}}
!Movies
*[[standard|./pitp_homeworks/visualization/movies/richardson_movie.mpg]]
*[[added my own asteroid, at a higher velocity/different color|./pitp_homeworks/visualization/movies/richardson_new_movie.mpg]]
!Plots
[img[./pitp_homeworks/visualization/pictures/richardson_rpasmout_tweak1.png]]
[img[./pitp_homeworks/visualization/pictures/richardson_rpasmsout_tweak1.2.png]]
[img[./pitp_homeworks/visualization/pictures/richardson_rpasmsout_tweak1.3.png]]
[img[./pitp_homeworks/visualization/pictures/richardson_rpasmsout_tweak1.4.png]]
[img[./pitp_homeworks/visualization/pictures/richardson_rpasmsout_tweak1.5.png]]
[img[./pitp_homeworks/visualization/pictures/richardson_rpasmsout_tweak1.6.png]]
[img[./pitp_homeworks/visualization/pictures/richardson_rpasmsout_tweak1.7.png]]
[img[./pitp_homeworks/visualization/pictures/richardson_rpasmsout_tweak1.8.png]]
[[link|https://www.sns.ias.edu/twiki/bin/view/Main/PICwork]]
#Ran, output some movies.
##varied number of particles per cell {{{numElectronsPerCell}}}
###fewer $\Rightarrow$ plasma oscillation is much faster, happens sooner
###greater $\Rightarrow$ plasma oscillation is much slower, happens later
##varied spatial resolution {{{ds}}}
###less $\Rightarrow$ oscillation much slower, happens later
###greater $\Rightarrow$ oscillation faster, happens sooner
##varied timestep
###less $\Rightarrow$ oscillation much slower, happens later
###greater $\Rightarrow$ oscillation much faster, more erratic
##varied initial conditions
###added B field by adding {{{B1init=1}}} to control section of input file. this was different than what was suggested in the problem spect (add a B03 parameter in this section), but it actually changes things.
#Ran, output some movies
##varied initial temperature changing
{{{
v1thermal = 10*rmsElectronSpeedMKS
v2thermal = 10*rmsElectronSpeedMKS
v3thermal = 10*rmsElectronSpeedMKS
}}}
##also tried 100, 1000, 10000 (last was superluminal, gave error). seemed to proceed quicker, but not by much.
!!Movies
*Plasma Oscillations
**Energy
[img[./pitp_homeworks/visualization/movies/spitkovsky_plasmaoscex_TE-beige_KE-green_Efield-yellow_Bfield-Orange.gif]]
**Phase Space
[img[./pitp_homeworks/visualization/movies/spitkovsky_plasmaoscex_ux_vs_x,_all_species.gif]]
*Two stream
**energy
[img[./pitp_homeworks/visualization/movies/sptikovsky_twostreamhw_TE-beige_KE-green_Efield-yellow_Bfield-Orange.gif]]
**Phase space
[img[./pitp_homeworks/visualization/movies/spitkovsky_twostreamhw_x-y_phase_space_for_electrons.gif]]
/*{{{*/
/*Monochrome Theme for TiddlyWiki*/
/*Design and CSS by Saq Imtiaz*/
/*Version 1.0*/
/*}}}*/
/*{{{*/
body {background:#3B3B3B; color:#C3C3C3; font:12px Verdana, Helvetica, sans-serif;
}
#header {padding: 0em 0em 0em 0em; background:transparent; font-family: arial,helvetica; font-size:12px;
}
.siteTitle {
padding-top:5px;
float:left;
font-family: 'Trebuchet MS' sans-serif;
font-weight: bold;
font-size: 32px;
color: #ccc; margin-right:2em;margin-left:0.5em;
}
#topMenu br {display:none;}
#topMenu a, #topMenu .tiddlyLink, #topMenu .button {margin:0em; color:#666; padding:15px 15px 10px 15px;padding-top:1.6em;border:none; border-right: 1px solid #666;float:left;}
#topMenu {border-left: 1px solid #666; float:left;margin:0;}
#topMenu a:hover {color:#ccc; background:#3b3b3b;}
#displayArea {margin-left:1.35em; margin-right:17.65em; margin-top:0.5em; padding-top:1em; padding-bottom:10px;}
.tiddler {background:#454545; margin-bottom:20px; padding:1em 2em 1em 2em;}
a, a:hover{
color:#fff;
text-decoration: none; background:transparent;
}
.viewer a, .viewer a:hover{border-bottom:1px dotted #fff; font-weight:normal;}
.viewer .button, .editorFooter .button{
color: #fff;
border: 1px solid #fff;
}
.viewer .button:hover,
.editorFooter .button:hover, .viewer .button:active, .viewer .highlight,.editorFooter .button:active, .editorFooter .highlight{
color: #fff;
background: #3B3B3B;
border-color: #3B3B3B;
}
.title {color:#ccc; font-family:'Lucida Grande', Verdana, Sans-Serif; font-size:1.5em;
}
.subtitle, .subtitle a { color: #777; font-size: 0.95em;margin:0.2em;}
.shadow .title{color:#777;}
.toolbar {font-size:90%;}
.selected .toolbar a {color:#666;border:0;}
.selected .toolbar a:hover {color:#999; background:transparent;border:0;}
.toolbar .button:hover, .toolbar .highlight, .toolbar .marked, .toolbar a.button:active{color:#666;border:0; background:transparent;border:0;}
.tagging, .tagged {
border: 1px solid #555;
background-color: #444;
}
.selected .tagging, .selected .tagged {
background-color: #3B3B3B;
border: 1px solid #666;
}
.tagging .listTitle, .tagged .listTitle {
color: #666;
}
.selected .tagging .listTitle, .selected .tagged .listTitle {
color: #aaa;
}
.tagging .button, .tagged .button {
color: #838383;
}
.selected .tagging .button, .selected .tagged .button {
color:#c3c3c3;
}
.highlight, .marked {background:transparent; color:#111; border:none; text-decoration:underline;}
.tagging .button:hover, .tagged .button:hover, .tagging .button:active, .tagged .button:active {
border: none; background:transparent; text-decoration:underline; color:#333;
}
#sidebarOptions {margin-top:1em;}
#sidebar {margin-right:1.35em;}
#sidebarTabs .tabContents {
font-family: arial,helvetica;}
#sidebarOptions a, #sidebarOptions a:hover{border:none;color:#666;}
#sidebarOptions a:hover, #sidebarOptions a:active {background:#454545; color:#ccc;}
#sidebarTabs .tabContents {background:#454545;border:0px solid #666; border-right:1px solid #454545;}
#sidebarOptions input {background:#ccc; border:1px solid #666;}
#sidebarTabs .tabContents .tiddlyLink, #sidebarTabs .tabContents .button{color:#666;font-weight:normal;}
#sidebarTabs .tabContents .tiddlyLink:hover, #sidebarTabs .tabContents .button:hover {color:#ccc; background:transparent;}
.listTitle {color:#777;}
#sidebarTabs .tabSelected,#sidebarTabs .tabSelected:hover{background:#454545;border:none;color:#ccc; border:1px solid #454545;}
#sidebarTabs .tabUnselected{background:#3B3B3B; border:1px solid #454545; color:#666;}
#sidebarTabs .txtMoreTab .tabSelected,
#sidebarTabs .txtMoreTab .tab:hover,
#sidebarTabs .txtMoreTab .tabContents{
color: #ccc;
background: #3B3B3B; border:1px solid #3B3B3B;
}
#sidebarTabs .txtMoreTab .tabUnselected {
color: #777; border:1px solid #3B3B3B;
background: #454545;
}
#sidebarTabs .tabContents .button:hover, #sidebarTabs .tabContents .highlight, #sidebarTabs .tabContents .marked, #sidebarTabs .tabContents a.button:active{color:#ccc; background:transparent;}
#sidebarOptions .sliderPanel {
background: #454545; font-size: .9em;
}
#sidebarOptions .sliderPanel input {border:1px solid #666; background:#ccc;}
#sidebarOptions .sliderPanel .txtOptionInput {border:1px solid #666;width:9em;}
#sidebarOptions .sliderPanel a {font-weight:normal; color:#666;background-color: #454545; border-bottom:1px dotted #333;}
#sidebarOptions .sliderPanel a:hover {
color:#ccc;
background-color: #454545;
border:none;
border-bottom:1px dotted #111;
}
.popup {
background: #3B3B3B;
border: 1px solid #454545;
}
.popup li.disabled {
color: #000;
}
.popup li a, .popup li a:visited {
color: #777;
border: none;
}
.popup li a:hover {
background: #3b3b3b;
color: #c3c3c3;
border: none;
}
.popup hr {
color: #777;
background: #777;
border-bottom: 1px;
}
.listBreak div{
border-bottom: 1px solid #777;
}
#messageArea {
border: 4px dotted #ccc;
background: #454545;
color: #777;
font-size:90%;
}
#messageArea .button{
color: #3B3B3B;
background:#ccc;
border: 1px solid #ccc;
}
#messageArea .button:hover {
color: #ccc;
background: #3B3B3B;
border-color: #3B3B3B;
}
.viewer blockquote {
border-left: 5px solid #3B3B3B; background:#3B3B3B
}
.viewer table, .viewer td {
border: 1px solid #2E2E2E;
}
.viewer th, thead td {
background: #3B3B3B;
border: 1px solid #3B3B3B;
color: #ccc;
}
.viewer pre {
border: 1px solid #3b3b3b;
background: #5F5F5F;
}
.viewer code {
color: #c3c3c3; background:#5f5f5f;
}
.viewer hr {
border-top: dashed 1px #222; margin:0 1em;
}
.editor input {
border: 1px solid #ccc; margin-top:5px;
}
.editor textarea {
border: 1px solid #ccc;
}
h1,h2,h3,h4,h5 { color: #9c9c9c; background: transparent; padding-bottom:2px; font-family: Arial, Helvetica, sans-serif; }
h1 {font-size:18px;}
h2 {font-size:16px;}
h3 {font-size: 14px;}
!Hierarchical tree algorithms generally
*approximate the force on a point with a multipole expansion
*group distant particles together and use their multipole expansion
*$\Rightarrow$ only $log(N)$ force terms per particle
*for a single force evaluation only $log(N)$ multipoles need to be computed depending on the opening angle
*no instrinsic restrictions for its dynamic range
*force accuracy can be conveniently adjusted to the desired level
*speed depends only weakly on clustering state
*arbitrary geometries
!Fast multipole method (FFM)
*Generalizes tree algirhtm, expanding the field symmetrically for each pair of interacting cells
*Advantages
**faster
**momentum conserved
*Disadvantages
**doesn't work well with individual timesteps
**difficult to parallelize for distributed memory machines
!TreePM
*split potential for a single particle in Fourier space into a long range and a short range part and compute them separately with PM and TREE algorithms, respectively
#$\phi_k^{long}=\phi_k exp(-k^2 r_s^2)$
##solve with PM-method
#$\phi_k^{short}$
##solve with TREE method
!Software installation
#Installing Mercury
##downloaded from: http://www.arm.ac.uk/%7Ejec/home.html
##needed g77, downloaded binary from HPC http://hpc.sourceforge.net/
###for now using binary, later can do full install
##Next compiled the following by hand (no Makefile)
###g77 -o mercury6 mercury6_2.for
###g77 -o element6 element6.for
###g77 -o close6 close6.for
!Answers to questions
#A particle orbiting in a spherically symmetric potential conserves its angular momentum per unit mass $L=r \times v$ and therefore remains on a surface of constant angular momentum in phase space. Modified Euler and leapfrog are symplectic, thus they conserve this geometric property. Runge-Kutta does not.
##I have sage file set up to do plotting
#Orbit integration code written, see sage {{{.sws}}} file.
#Modified {{{big.in}}}, {{{small.in}}}, {{{param.in}}}, ran
#The algorithm is not guaranteed to be symplectic generally with a variable timestep.
!Full solution guis
[[paraview]]
[[visit]]
!Older but functional, scripts+guis
[[Tipsy]]
[[Tipgrid]]
[[Healpix]]
[[Salsa]]
!Python driven
[[yt]]
[[glnemo2]]
[[mayavi]]
!Command line
[[ImageMagick]]
[[mlab]]
[[pgplot]]
[[gnuplot]]
[[s2plot]]
!3D/Game style
[[POV-Ray]]
[[blender]]
[[Second Life]]
[[opengl]]
!Installation/setup
!!N-Genic
See [[Installing N-GenIC for mac]]
Edited parameter file for N-GenIC. Questions
#came with unperturbed glass grid but not Cartesian grid {{{.dat}}} file. where to get Cartesian grid?: check out {{{make_dummy_glass.pro }}} this is how the glass {{{.dat}}} file was generated
#For now, using {{{dummy_glass.dat}}} just for testing
##worked, printed: initial scale factor = 0.015625
!!Gadget param file
#how to pick gravitational softening length
!Analysis
!!Visualization
*Glnemo reads natively
*Paraview may read hdf5 format files
*Wrote conversion script from gadget2 bin format to ascii
!!Halo finding
#Analyzing via FoF
##first converting the snapshots.
###edited Gadget-2.0.4/Analysis/read_snapshot.c example to point to my snapshots.
###compiled with {{{gcc -lm read_snapshot.c -o read_snapshot}}}
<<<
Glnemo2 is an interactive visualization 3D program , using OpenGL and trolltech
QT 4.X API. It displays in 3D, particles positions of the different components of an
nbody snapshot.
You can zoom in/out, rotate, scale, translate, select different particles
and plot them in different blending colors, color particles according to their density,
play with the density threshold, trace orbits, play different time steps, take automatic
screenshots to make movies, select particles using the mouse, fly over your simulation
using camera path. All this features are accessible from a very intuitive graphic user interface.
Currently, glnemo2 reads NEMO files (http://carma.astro.umd.edu/nemo),
Gadget 1 and 2 -little and big endian- files (http://www.mpa-garching.mpg.de/gadget/),
FTM files (Clayton Heller's sph/nbody code),
phiGRAPE file (http://wiki.cs.rit.edu/bin/view/GRAPEcluster/phiGRAPE) and a list of files
stored in a file.
<<<
enhanced interactive [[python]], doesn't always come with python installation. Allows you to execute unix commands interchangeably with [[python]]
"the gateway drug to [[mayavi]]"
[[link|http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html]]
#plotting program
#"super easy"
/***
|''Name:''|tagCloud plugin|
|''Version:''|1.0.2 (2007-08-21)|
|''Source:''|http://checkettsweb.com/styles/themes.htm|
|''Author:''|Clint Checketts|
|''Contributors:''|Jonny Leroy, Eric Shulman, Piotr Likus|
|''Licence:''|[[?/BSD open source license|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 1.0.4+; Firefox 1.5; ~InternetExplorer 6.0|
!Parameters
* reqOrTags - tags that are required to be assigned to tiddlers that are source for tag cloud (''any'')
* reqAndTags - tags that are required to be assigned to tiddlers that are source for tag cloud (''all'' are required)
* exTags - tags that are excluded
* (unnamed param) - tags that are excluded (mask with '*' is allowed, e.g. '*Project')
* reqTids - list of names for tiddlers that are source for tag cloud (''any'')
* italics - if equal to "yes" tags will be italic if no tiddler is found with a title equal to tag name
!Usage
{{{<<tagCloud>>}}}
<<tagCloud>>
or (require Plugin or PluginDoc tags, exclude PluginExamples tags and any PluginEx* tags):
{{{<<tagCloud reqOrTags:'Plugin,PluginDoc' exTags:'PluginExamples' PluginEx*>>
}}}
<<tagCloud reqOrTags:'Plugin,PluginDoc' exTags:'PluginExamples' PluginEx*>>
{{{<<tagCloud reqTids:'*Plugin' italics:"yes">>
}}}
<<tagCloud reqTids:'*Plugin' italics:"yes">>
!Source Code
***/
//{{{
version.extensions.tagCloud = {major: 1, minor: 0 , revision: 1, date: new Date(2005,8,16)};
//Created by Clint Checketts, contributions by Jonny Leroy and Eric Shulman
//Modified by PiotrL, 2007/07/29 - filter for excluded tags
config.macros.tagCloud = {
noTags: "No tag cloud created because there are no tags.",
tooltip: "%1 tiddlers tagged with '%0'"
};
config.macros.tagCloud.handler = function(place,macroName,params,wikifier,paramString,tiddler) {
var tagCloudWrapper = createTiddlyElement(place,"div",null,"tagCloud",null);
var parameters = paramString.parseParams("name",null,true);
// excluded
var exTags = parameters[0]["exTags"]?parameters[0]["exTags"][0].split(","):[];
// required
var reqOrTags = parameters[0]["reqOrTags"]?parameters[0]["reqOrTags"][0].split(","):[];
var reqAndTags = parameters[0]["reqAndTags"]?parameters[0]["reqAndTags"][0].split(","):[];
var reqTids = parameters[0]["reqTids"]?parameters[0]["reqTids"][0].split(","):[];
var useItalics = parameters[0]["italics"]?parameters[0]["italics"] == "yes":false;
//testFunc('italics: '+parameters[0]["italics"]);
var tags = store.getTags();
var foundCnt = 0;
for (t=0; t<tags.length; t++) {
for (p=0;p<params.length; p++)
{
if (matchesMask(tags[t][0], params[p]))
tags[t][0] = "";
}
for (p=0;p<exTags.length; p++)
{
if (matchesMask(tags[t][0], exTags[p]))
tags[t][0] = "";
}
foundCnt = 0;
for (p=0;p<reqOrTags.length; p++)
{
if (tagAssignedWith(tags[t][0], reqOrTags[p]))
foundCnt++;
}
if (!foundCnt && reqOrTags.length)
tags[t][0] = "";
foundCnt = 0;
for (p=0;p<reqAndTags.length; p++)
{
if (tagAssignedWith(tags[t][0], reqAndTags[p]))
foundCnt++;
}
if (foundCnt != reqAndTags)
tags[t][0] = "";
foundCnt = 0;
for (p=0;p<reqTids.length; p++)
{
if (tagAssignedToMask(tags[t][0], reqTids[p]))
foundCnt++;
}
if (!foundCnt && reqTids.length)
tags[t][0] = "";
}
if(tags.length == 0)
createTiddlyElement(tagCloudWrapper,"span",null,null,this.noTags);
//Findout the maximum number of tags
var mostTags = 0;
for (t=0; t<tags.length; t++) if (tags[t][0].length > 0){
if (tags[t][1] > mostTags) mostTags = tags[t][1];
}
//divide the mostTags into 4 segments for the 4 different tagCloud sizes
var tagSegment = mostTags / 4;
for (t=0; t<tags.length; t++) if (tags[t][0].length > 0){
var tagCloudElement = createTiddlyElement(tagCloudWrapper,"span",null,null,null);
tagCloudWrapper.appendChild(document.createTextNode(" "));
var tagClassName = "tagCloud"+(Math.round(tags[t][1]/tagSegment)+1);
if (useItalics && !store.tiddlerExists(tags[t][0]))
tagClassName += "It";
var theTag = createTiddlyButton(tagCloudElement,tags[t][0],this.tooltip.format(tags[t]),onClickTag,"tagCloudtag "+tagClassName);
theTag.setAttribute("tag",tags[t][0]);
}
function testFunc(txt) {
alert(txt);
}
function matchesMask(txt, mask) {
var idx, prefix, suffix, res;
res = false;
if (mask.indexOf('*') >= 0)
{
sToken = mask;
idx = sToken.indexOf('*');
if (idx > 0)
prefix = sToken.substring(0, idx - 1);
else
prefix = '';
suffix = sToken.substring(idx+1, sToken.length);
if ((txt.indexOf(prefix) == 0) || (prefix == ''))
if ((txt.indexOf(suffix) == txt.length - suffix.length) || (suffix == ''))
res = true;
}
else if (txt == mask)
res = true;
return(res);
}
function tagAssignedWith(tag1, tag2) {
//var tiddlerNames = store.reverseLookup("tags",tag1,false,"title");
var res;
var collected = [];
var foundTids = 0;
store.forEachTiddler( function ( title,tiddler ) {
if (tiddler.isTagged(tag1) && tiddler.isTagged(tag2)) {
collected.push(title );
foundTids++;
}
}
);
if (foundTids>0)
res = true;
else
res = false;
return res;
}
function tagAssignedToMask(tag, tidMask) {
var res;
var collected = [];
var foundTids = 0;
store.forEachTiddler( function ( title,tiddler ) {
if (tiddler.isTagged(tag) && matchesMask(title, tidMask)) {
collected.push(title);
foundTids++;
}
}
);
if (foundTids>0)
res = true;
else
res = false;
return res;
}
};
setStylesheet(
".tagCloud span{height: 1.8em;margin: 3px;}"+
".tagCloud1{font-size: 1.2em;}"+
".tagCloud2{font-size: 1.4em;}"+
".tagCloud3{font-size: 1.6em;}"+
".tagCloud4{font-size: 1.8em;}"+
".tagCloud5{font-size: 1.8em;font-weight: bold;}"+
".tagCloudIt span{height: 1.8em;margin: 3px;font-style: italic;}"+
".tagCloud1It{font-size: 1.2em;font-style: italic;}"+
".tagCloud2It{font-size: 1.4em;font-style: italic;}"+
".tagCloud3It{font-size: 1.6em;font-style: italic;}"+
".tagCloud4It{font-size: 1.8em;font-style: italic;}"+
".tagCloud5It{font-size: 1.8em;font-weight: bold;font-style: italic;}"+
"",
"tagCloudsStyles");
//}}}
[[download link|https://wci.llnl.gov/codes/visit/about.html]]
<<<
VisIt is a free interactive parallel visualization and graphical analysis tool for viewing scientific data on Unix and PC platforms. Users can quickly generate visualizations from their data, animate them through time, manipulate them, and save the resulting images for presentations.
<<<
Useful for amr data, particularly [[enzo]] output. Written in python. Source code available. Code paper [[here|yt.enzotools.org/files/scipy08_paper_mturk.pdf]]