| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562 | 
							- <!doctype html>
 
- <html lang="en">
 
- <head>
 
- <meta charset="utf-8">
 
- <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
 
- <meta name="generator" content="pdoc 0.5.2" />
 
- <title>simulation API documentation</title>
 
- <meta name="description" content="Definition of the Simulation class and the Galaxy constructor." />
 
- <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
 
- <link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
 
- <link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
 
- <style>.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{font-weight:bold}#index h4 + ul{margin-bottom:.6em}#index .two-column{column-count:2}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.name small{font-weight:normal}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase;cursor:pointer}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}.admonition{padding:.1em .5em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
 
- <style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
 
- <style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
 
- </head>
 
- <body>
 
- <main>
 
- <article id="content">
 
- <header>
 
- <h1 class="title"><code>simulation</code> module</h1>
 
- </header>
 
- <section id="section-intro">
 
- <p>Definition of the Simulation class and the Galaxy constructor.</p>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">"""Definition of the Simulation class and the Galaxy constructor."""
 
- import os
 
- import pickle
 
- import numpy as np
 
- import matplotlib.pyplot as plt
 
- from utils import random_unit_vectors, cascade_round
 
- from distributions import PLUMMER, HERNQUIST, UNIFORM, EXP, NFW
 
- import acceleration
 
- ##############################################################################
 
- ##############################################################################
 
- class Simulation:
 
-     """"Main class for the gravitational simulation.
 
-     Attributes:
 
-         r_vec (array): position of the particles in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         rprev_vec (array): position of the particles in the previous timestep.
 
-             Shape: (number of particles, 3)
 
-         v_vec (array): velocity in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         a_vec (array): acceleration in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         mass (array): mass of each particle in the simulation.
 
-             Shape: (number of particles,)
 
-         type (array): non-unique identifier for each particle.
 
-             Shape: (number of particles,)
 
-         tracks (array): list of positions through the simulation for central
 
-             masses. Shape: (tracked particles, n+1, 3).
 
-         CONFIG (array): configuration used to create the simulation.
 
-             It will be saved along the state of the simulation.
 
-         dt (float): timestep of the simulation
 
-         n (int): current timestep. Initialized as n=0.
 
-         soft (float): softening length used by the simulation.
 
-         verbose (boolean): When True progress statements will be printed.
 
-     """
 
-     def __init__(self, dt, soft, verbose, CONFIG, method, **kwargs):
 
-         """Constructor for the Simulation class.
 
-         Arguments:
 
-             dt (float): timestep of the simulation
 
-             n (int): current timestep. Initialized as n=0.
 
-             soft (float): softening length used by the simulation.
 
-             verbose (bool): When True progress statements will be printed.
 
-             CONFIG (dict): configuration file used to create the simulation.
 
-             method (string): Optional. Algorithm to use when computing the 
 
-                 gravitational forces. One of 'bruteForce', 'bruteForce_numba',
 
-                 'bruteForce_numbaopt', 'bruteForce_CPP', 'barnesHut_CPP'.
 
-         """
 
-         self.n = 0
 
-         self.t = 0
 
-         self.dt = dt
 
-         self.soft = soft
 
-         self.verbose = verbose
 
-         self.CONFIG = CONFIG
 
-         # Initialize empty arrays for all necessary properties
 
-         self.r_vec = np.empty((0, 3))
 
-         self.v_vec = np.empty((0, 3))
 
-         self.a_vec = np.empty((0, 3))
 
-         self.mass = np.empty((0,))
 
-         self.type = np.empty((0, 2))
 
-         algorithms = {
 
-             'bruteForce': acceleration.bruteForce,
 
-             'bruteForceNumba': acceleration.bruteForceNumba,
 
-             'bruteForceNumbaOptimized': acceleration.bruteForceNumbaOptimized,
 
-             'bruteForceCPP': acceleration.bruteForceCPP,
 
-             'barnesHutCPP': acceleration.barnesHutCPP
 
-         }
 
-         try:
 
-             self.acceleration = algorithms[method]
 
-         except: raise Exception("Method '{}' unknown".format(method))
 
-     def add(self, body):
 
-         """Add a body to the simulation. It must expose the public attributes
 
-            body.r_vec, body.v_vec, body.a_vec, body.type, body.mass.
 
-         Arguments:
 
-             body: Object to be added to the simulation (e.g. a Galaxy object)
 
-         """
 
-         # Extend all relevant attributes by concatenating the body
 
-         for name in ['r_vec', 'v_vec', 'a_vec', 'type', 'mass']:
 
-             simattr, bodyattr = getattr(self, name), getattr(body, name)
 
-             setattr(self, name, np.concatenate([simattr, bodyattr], axis=0))
 
-         # Order based on mass
 
-         order = np.argsort(-self.mass)
 
-         for name in ['r_vec', 'v_vec', 'a_vec', 'type', 'mass']: 
 
-             setattr(self, name, getattr(self, name)[order])
 
-         # Update the list of objects to keep track of
 
-         self.tracks = np.empty((np.sum(self.type[:,0]=='center'), 0, 3))
 
-     def step(self):
 
-         """Perform a single step of the simulation.
 
-            Makes use of a 4th order Verlet integrator.
 
-         """
 
-         # Calculate the acceleration
 
-         self.a_vec = self.acceleration(self.r_vec, self.mass, soft=self.soft)
 
-         # Update the state using the Verlet algorithm
 
-         # (A custom algorithm is written mainly for learning purposes)
 
-         self.r_vec, self.rprev_vec = (2*self.r_vec - self.rprev_vec
 
-             + self.a_vec * self.dt**2, self.r_vec)
 
-         self.n += 1
 
-         # Update tracks
 
-         self.tracks = np.concatenate([self.tracks,
 
-             self.r_vec[self.type[:,0]=='center'][:,np.newaxis]], axis=1)
 
-     def run(self, tmax, saveEvery, outputFolder, **kwargs):
 
-         """Run the galactic simulation.
 
-         Attributes:
 
-             tmax (float): Time to which the simulation will run to.
 
-                 This is measured here since the start of the simulation,
 
-                 not since pericenter.
 
-             saveEvery (int): The state is saved every saveEvery steps.
 
-             outputFolder (string): It will be saved to /data/outputFolder/
 
-         """
 
-         # When the simulation starts, intialize self.rprev_vec
 
-         self.rprev_vec = self.r_vec - self.v_vec * self.dt
 
-         if self.verbose: print('Simulation starting. Bon voyage!')
 
-         while(self.t < tmax):
 
-             self.step()
 
-             if(self.n % saveEvery == 0):
 
-                 self.save('data/{}'.format(outputFolder))
 
-         print('Simulation complete.')
 
-     def save(self, outputFolder):
 
-         """Save the state of the simulation to the outputFolder.
 
-            Two files are saved:
 
-                 sim{self.n}.pickle: serializing the state.
 
-                 sim{self.n}.png: a simplified 2D plot of x, y.
 
-         """
 
-         # Create the output folder if it doesn't exist
 
-         if not os.path.exists(outputFolder): os.makedirs(outputFolder)
 
-         # Compute some useful quantities
 
-         # v_vec is not required by the integrator, but useful
 
-         self.v_vec = (self.r_vec - self.rprev_vec)/self.dt
 
-         self.t = self.n * self.dt # prevents numerical rounding errors
 
-         # Serialize state
 
-         file = open(outputFolder+'/data{}.pickle'.format(self.n), "wb")
 
-         pickle.dump({'r_vec': self.r_vec, 'v_vec': self.v_vec,
 
-                      'type': self.type, 'mass': self.mass,
 
-                      'CONFIG': self.CONFIG, 't': self.t,
 
-                      'tracks': self.tracks}, file)
 
-         # Save simplified plot of the current state.
 
-         # Its main use is to detect ill-behaved situations early on.
 
-         fig = plt.figure()
 
-         plt.xlim(-5, 5); plt.ylim(-5, 5); plt.axis('equal')
 
-         # Dark halo is plotted in red, disk in blue, bulge in green
 
-         PLTCON = [('dark', 'r', 0.3), ('disk', 'b', 1.0), ('bulge', 'g', 0.5)]
 
-         for type_, c, a in PLTCON: 
 
-             plt.scatter(self.r_vec[self.type[:,0]==type_][:,0],
 
-                 self.r_vec[self.type[:,0]==type_][:,1], s=0.1, c=c, alpha=a)
 
-         # Central mass as a magenta star 
 
-         plt.scatter(self.r_vec[self.type[:,0]=='center'][:,0],
 
-             self.r_vec[self.type[:,0]=='center'][:,1], s=100, marker="*", c='m')
 
-         # Save to png file
 
-         fig.savefig(outputFolder+'/sim{}.png'.format(self.n), dpi=150)
 
-         plt.close(fig)
 
-     def project(self, theta, phi, view=0):
 
-         """Projects the 3D simulation onto a plane as viewed from the
 
-            direction described by the (theta, phi, view). Angles in radians.
 
-            (This is used by the simulated annealing algorithm)
 
-         
 
-         Parameters:
 
-             theta (float): polar angle.
 
-             phi (float): azimuthal angle.
 
-             view (float): rotation along line of sight.
 
-         """
 
-         M1 = np.array([[np.cos(phi), np.sin(phi), 0],
 
-                        [-np.sin(phi), np.cos(phi), 0],
 
-                        [0, 0, 1]])
 
-         M2 = np.array([[1, 0, 0],
 
-                        [0, np.cos(theta), np.sin(theta)],
 
-                        [0, -np.sin(theta), np.cos(theta)]])
 
-         M3 = np.array([[np.cos(view), np.sin(view), 0],
 
-                        [-np.sin(view), np.cos(view), 0],
 
-                        [0, 0, 1]])
 
-         M = np.matmul(M1, np.matmul(M2, M3)) # combine rotations
 
-         r = np.tensordot(self.r_vec, M, axes=[1, 0])
 
-         return r[:,0:2]
 
-     def setOrbit(self, galaxy1, galaxy2, e, rmin, R0):
 
-         """Sets the two galaxies galaxy1, galaxy2 in an orbit.
 
-         Parameters:
 
-             galaxy1 (Galaxy): 1st galaxy (main)
 
-             galaxy2 (Galaxy): 2nd galaxy (companion)
 
-             e: eccentricity of the orbit
 
-             rmin: distance of closest approach
 
-             R0: initial separation
 
-         """
 
-         m1, m2 = np.sum(galaxy1.mass), np.sum(galaxy2.mass)
 
-         # Relevant formulae:
 
-         # $r_0 = r (1 + e) \cos(\phi)$, where $r_0$ ($\neq R_0$) is the semi-latus rectum
 
-         # $r_0 = r_\textup{min} (1 + e)$
 
-         # $v^2 = G M (2/r - 1/a)$, where a is the semimajor axis
 
-         # Solve the reduced two-body problem with reduced mass $\mu$ (mu)
 
-         M = m1 + m2
 
-         r0 = rmin * (1 + e)
 
-         try:
 
-             phi = np.arccos((r0/R0 - 1) / e) # inverting the orbit equation
 
-             phi = -np.abs(phi) # Choose negative (incoming) angle
 
-             ainv = (1 - e) / rmin # ainv = $1/a$, as a may be infinite
 
-             v = np.sqrt(M * (2/R0 - ainv))
 
-             # Finally, calculate the angle of motion. angle = tan(dy/dx)
 
-             # $dy/dx = ((dr/d\phi) sin(\phi) + r \cos(\phi))/((dr/d\phi) cos(\phi) - r \sin(\phi))$
 
-             dy = R0/r0 * e * np.sin(phi)**2 + np.cos(phi)
 
-             dx = R0/r0 * e * np.sin(phi) * np.cos(phi) - np.sin(phi)
 
-             vangle = np.arctan2(dy, dx)
 
-         except: raise Exception('''The orbital parameters cannot be satisfied.
 
-             For elliptical orbits check that R0 is posible (<rmax).''')
 
-         # We now need the actual motion of each body
 
-         R_vec = np.array([[R0*np.cos(phi), R0*np.sin(phi), 0.]])
 
-         V_vec = np.array([[v*np.cos(vangle), v*np.sin(vangle), 0.]])
 
-         galaxy1.r_vec += m2/M * R_vec
 
-         galaxy1.v_vec += m2/M * V_vec
 
-         galaxy2.r_vec += -m1/M * R_vec
 
-         galaxy2.v_vec += -m1/M * V_vec
 
-         # Explicitely add the galaxies to the simulation
 
-         self.add(galaxy1)
 
-         self.add(galaxy2)
 
-         if self.verbose: print('Galaxies set in orbit.')
 
- ##############################################################################
 
- ##############################################################################
 
- class Galaxy():
 
-     """"Helper class for creating galaxies.
 
-     Attributes:
 
-         r_vec (array): position of the particles in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         v_vec (array): velocity in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         a_vec (array): acceleration in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         mass (array): mass of each particle in the simulation.
 
-             Shape: (number of particles,)
 
-         type (array): non-unique identifier for each particle.
 
-             Shape: (number of particles,)    """
 
-     def __init__(self, orientation, centralMass, bulge, disk, halo, sim):
 
-         """Constructor for the Galaxy class.
 
-            Parameters:
 
-                 orientation (tupple): (inclination i, argument of pericenter w)
 
-                 centralMass (float): mass at the center of the galaxy
 
-                 bulge (dict): passed to the addBulge method.
 
-                 disk (dict): passed to the addDisk method.
 
-                 halo (dict): passed to the addHalo method.
 
-                 sim (Simulation): simulation object
 
-         """
 
-         if sim.verbose: print('Initializing galaxy')
 
-         # Build the central mass
 
-         self.r_vec = np.zeros((1, 3))
 
-         self.v_vec = np.zeros((1, 3))
 
-         self.a_vec = np.zeros((1, 3))
 
-         self.mass = np.array([centralMass])
 
-         self.type = np.array([['center', 0]])
 
-         # Build the other components
 
-         self.addBulge(**bulge)
 
-         if sim.verbose: print('Bulge created.')
 
-         self.addDisk(**disk)
 
-         if sim.verbose: print('Disk created.')
 
-         self.addHalo(**halo)
 
-         if sim.verbose: print('Halo created.')
 
-         # Correct particles velocities to generate circular orbits
 
-         # $a_\textup{centripetal} = v^2/r$
 
-         a_vec = sim.acceleration(self.r_vec, self.mass, soft=sim.soft)
 
-         a = np.linalg.norm(a_vec, axis=-1, keepdims=True)
 
-         r = np.linalg.norm(self.r_vec, axis=-1, keepdims=True)
 
-         v = np.linalg.norm(self.v_vec[1:], axis=-1, keepdims=True)
 
-         direction_unit = self.v_vec[1:]/v
 
-         # Set orbital velocities (except for central mass)
 
-         self.v_vec[1:] = np.sqrt(a[1:] * r[1:]) * direction_unit
 
-         self.a_vec = np.zeros_like(self.r_vec)
 
-         # Rotate the galaxy into its correct orientation
 
-         self.rotate(*(np.array(orientation)/360 * 2*np.pi))
 
-         if sim.verbose: print('Galaxy set in rotation and oriented.')
 
-     def addBulge(self, model, totalMass, particles, l):
 
-         """Adds a bulge to the galaxy.
 
-             Parameters:
 
-                 model (string): parametrization of the bulge.
 
-                     'plummer' and 'hernquist' are supported.
 
-                 totalMass (float): total mass of the bulge
 
-                 particles (int): number of particles in the bulge
 
-                 l (float): characteristic length scale of the model.
 
-         """
 
-         if particles == 0: return None
 
-         # Divide the mass equally among all particles
 
-         mass = np.ones(particles) * totalMass/particles
 
-         self.mass = np.concatenate([self.mass, mass], axis=0)
 
-         # Create particles according to the radial distribution from model
 
-         if model == 'plummer':
 
-             r = PLUMMER.ppf(np.random.rand(particles), scale=l)
 
-         elif model == 'hernquist':
 
-             r = HERNQUIST.ppf(np.random.rand(particles), scale=l)
 
-         else: raise Exception("""Bulge distribution not allowed.
 
-                     'plummer' and 'hernquist' are the supported values""")
 
-         r_vec = r[:,np.newaxis] * random_unit_vectors(size=particles)
 
-         self.r_vec = np.concatenate([self.r_vec, r_vec], axis=0)
 
-         # Set them orbitting along random directions normal to r_vec
 
-         v_vec = np.cross(r_vec, random_unit_vectors(size=particles))
 
-         self.v_vec = np.concatenate([self.v_vec, v_vec], axis=0)
 
-         # Label the particles
 
-         type_ = [['bulge', 0]]*particles
 
-         self.type = np.concatenate([self.type, type_], axis=0)
 
-     def addDisk(self, model, totalMass, particles, l):
 
-         """Adds a disk to the galaxy.
 
-             Parameters:
 
-                 model (string): parametrization of the disk.
 
-                     'rings', 'uniform' and 'exp' are supported.
 
-                 totalMass (float): total mass of the bulge
 
-                 particles (int): number of particles in the bulge
 
-                 l: fot 'exp' and 'uniform' characteristic length of the
 
-                     model. For 'rings' tupple of the form (inner radius,
 
-                     outer radius, number of rings)
 
-         """
 
-         if particles == 0: return None
 
-         # Create particles according to the radial distribution from model
 
-         if model == 'uniform':
 
-             r = UNIFORM.ppf(np.random.rand(particles), scale=l)
 
-             type_ = [['disk', 0]]*particles
 
-             r_vec = r[:,np.newaxis] * random_unit_vectors(particles, '2D')
 
-             self.type = np.concatenate([self.type, type_], axis=0)
 
-         elif model == 'rings':
 
-             # l = [inner radius, outter radius, number of rings]
 
-             distances = np.linspace(*l)
 
-             # Aim for roughly constant areal density
 
-             # Cascade rounding preserves the total number of particles
 
-             perRing = cascade_round(particles * distances / np.sum(distances))
 
-             particles = int(np.sum(perRing)) # prevents numerical errors
 
-             r_vec = np.empty((0, 3))
 
-             for d, n, i in zip(distances, perRing, range(l[2])):
 
-                 type_ = [['disk', i+1]]*int(n)
 
-                 self.type = np.concatenate([self.type, type_], axis=0)
 
-                 phi = np.linspace(0, 2 * np.pi, n, endpoint=False)
 
-                 ringr = d * np.array([[np.cos(i), np.sin(i), 0] for i in phi])
 
-                 r_vec = np.concatenate([r_vec, ringr], axis=0)
 
-         elif model == 'exp':
 
-             r = EXP.ppf(np.random.rand(particles), scale=l)
 
-             r_vec = r[:,np.newaxis] * random_unit_vectors(particles, '2D')
 
-             type_ = [['disk', 0]]*particles
 
-             self.type = np.concatenate([self.type, type_], axis=0)
 
-         else:
 
-             raise Exception("""Disk distribution not allowed.
 
-                     'uniform', 'rings' and 'exp' are the supported values""")
 
-         self.r_vec = np.concatenate([self.r_vec, r_vec], axis=0)
 
-         # Divide the mass equally among all particles
 
-         mass = np.ones(particles) * totalMass/particles
 
-         self.mass = np.concatenate([self.mass, mass], axis=0)
 
-         # Set them orbitting along the spin plane
 
-         v_vec = np.cross(r_vec, [0, 0, 1])
 
-         self.v_vec = np.concatenate([self.v_vec, v_vec], axis=0)
 
-     def addHalo(self, model, totalMass, particles, rs):
 
-         """Adds a halo to the galaxy.
 
-             Parameters:
 
-                 model (string): parametrization of the halo.
 
-                     Only 'NFW' is supported.
 
-                 totalMass (float): total mass of the halo
 
-                 particles (int): number of particles in the halo
 
-                 rs (float): characteristic length scale of the NFW profile.
 
-         """
 
-         if particles == 0: return None
 
-         # Divide the mass equally among all particles
 
-         mass = np.ones(particles)*totalMass/particles
 
-         self.mass = np.concatenate([self.mass, mass], axis=0)
 
-         # Create particles according to the radial distribution from model
 
-         if model == 'NFW':
 
-             r = NFW.ppf(np.random.rand(particles), scale=rs)
 
-         else: raise Exception("""Bulge distribution not allowed.
 
-                     'plummer' and 'hernquist' are the supported values""")
 
-         r_vec = r[:,np.newaxis] * random_unit_vectors(size=particles)
 
-         self.r_vec = np.concatenate([self.r_vec, r_vec], axis=0)
 
-         # Orbit along random directions normal to the radial vector
 
-         v_vec = np.cross(r_vec, random_unit_vectors(size=particles))
 
-         self.v_vec = np.concatenate([self.v_vec, v_vec], axis=0)
 
-         # Label the particles
 
-         type_ = [['dark'], 0]*particles
 
-         self.type = np.concatenate([self.type, type_], axis=0)
 
-     def rotate(self, theta, phi):
 
-         """Rotates the galaxy so that its spin is along the (theta, phi)
 
-            direction.
 
-         Parameters:
 
-             theta (float): polar angle.
 
-             phi (float): azimuthal angle.
 
-         """
 
-         M1 = np.array([[1, 0, 0],
 
-                        [0, np.cos(theta), np.sin(theta)],
 
-                        [0, -np.sin(theta), np.cos(theta)]])
 
-         M2 = np.array([[np.cos(phi), np.sin(phi), 0],
 
-                        [-np.sin(phi), np.cos(phi), 0],
 
-                        [0, 0, 1]])
 
-         M = np.matmul(M1, M2) # combine rotations
 
-         self.r_vec = np.tensordot(self.r_vec, M, axes=[1, 0])
 
-         self.v_vec = np.tensordot(self.v_vec, M, axes=[1, 0])</code></pre>
 
- </details>
 
- </section>
 
- <section>
 
- </section>
 
- <section>
 
- </section>
 
- <section>
 
- </section>
 
- <section>
 
- <h2 class="section-title" id="header-classes">Classes</h2>
 
- <dl>
 
- <dt id="simulation.Galaxy"><code class="flex name class">
 
- <span>class <span class="ident">Galaxy</span></span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>"Helper class for creating galaxies.</p>
 
- <h2 id="attributes">Attributes</h2>
 
- <dl>
 
- <dt><strong><code>r_vec</code></strong> : <code>array</code></dt>
 
- <dd>position of the particles in the current timestep.
 
- Shape: (number of particles, 3)</dd>
 
- <dt><strong><code>v_vec</code></strong> : <code>array</code></dt>
 
- <dd>velocity in the current timestep.
 
- Shape: (number of particles, 3)</dd>
 
- <dt><strong><code>a_vec</code></strong> : <code>array</code></dt>
 
- <dd>acceleration in the current timestep.
 
- Shape: (number of particles, 3)</dd>
 
- <dt><strong><code>mass</code></strong> : <code>array</code></dt>
 
- <dd>mass of each particle in the simulation.
 
- Shape: (number of particles,)</dd>
 
- <dt><strong><code>type</code></strong> : <code>array</code></dt>
 
- <dd>non-unique identifier for each particle.
 
- Shape: (number of particles,)</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">class Galaxy():
 
-     """"Helper class for creating galaxies.
 
-     Attributes:
 
-         r_vec (array): position of the particles in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         v_vec (array): velocity in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         a_vec (array): acceleration in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         mass (array): mass of each particle in the simulation.
 
-             Shape: (number of particles,)
 
-         type (array): non-unique identifier for each particle.
 
-             Shape: (number of particles,)    """
 
-     def __init__(self, orientation, centralMass, bulge, disk, halo, sim):
 
-         """Constructor for the Galaxy class.
 
-            Parameters:
 
-                 orientation (tupple): (inclination i, argument of pericenter w)
 
-                 centralMass (float): mass at the center of the galaxy
 
-                 bulge (dict): passed to the addBulge method.
 
-                 disk (dict): passed to the addDisk method.
 
-                 halo (dict): passed to the addHalo method.
 
-                 sim (Simulation): simulation object
 
-         """
 
-         if sim.verbose: print('Initializing galaxy')
 
-         # Build the central mass
 
-         self.r_vec = np.zeros((1, 3))
 
-         self.v_vec = np.zeros((1, 3))
 
-         self.a_vec = np.zeros((1, 3))
 
-         self.mass = np.array([centralMass])
 
-         self.type = np.array([['center', 0]])
 
-         # Build the other components
 
-         self.addBulge(**bulge)
 
-         if sim.verbose: print('Bulge created.')
 
-         self.addDisk(**disk)
 
-         if sim.verbose: print('Disk created.')
 
-         self.addHalo(**halo)
 
-         if sim.verbose: print('Halo created.')
 
-         # Correct particles velocities to generate circular orbits
 
-         # $a_\textup{centripetal} = v^2/r$
 
-         a_vec = sim.acceleration(self.r_vec, self.mass, soft=sim.soft)
 
-         a = np.linalg.norm(a_vec, axis=-1, keepdims=True)
 
-         r = np.linalg.norm(self.r_vec, axis=-1, keepdims=True)
 
-         v = np.linalg.norm(self.v_vec[1:], axis=-1, keepdims=True)
 
-         direction_unit = self.v_vec[1:]/v
 
-         # Set orbital velocities (except for central mass)
 
-         self.v_vec[1:] = np.sqrt(a[1:] * r[1:]) * direction_unit
 
-         self.a_vec = np.zeros_like(self.r_vec)
 
-         # Rotate the galaxy into its correct orientation
 
-         self.rotate(*(np.array(orientation)/360 * 2*np.pi))
 
-         if sim.verbose: print('Galaxy set in rotation and oriented.')
 
-     def addBulge(self, model, totalMass, particles, l):
 
-         """Adds a bulge to the galaxy.
 
-             Parameters:
 
-                 model (string): parametrization of the bulge.
 
-                     'plummer' and 'hernquist' are supported.
 
-                 totalMass (float): total mass of the bulge
 
-                 particles (int): number of particles in the bulge
 
-                 l (float): characteristic length scale of the model.
 
-         """
 
-         if particles == 0: return None
 
-         # Divide the mass equally among all particles
 
-         mass = np.ones(particles) * totalMass/particles
 
-         self.mass = np.concatenate([self.mass, mass], axis=0)
 
-         # Create particles according to the radial distribution from model
 
-         if model == 'plummer':
 
-             r = PLUMMER.ppf(np.random.rand(particles), scale=l)
 
-         elif model == 'hernquist':
 
-             r = HERNQUIST.ppf(np.random.rand(particles), scale=l)
 
-         else: raise Exception("""Bulge distribution not allowed.
 
-                     'plummer' and 'hernquist' are the supported values""")
 
-         r_vec = r[:,np.newaxis] * random_unit_vectors(size=particles)
 
-         self.r_vec = np.concatenate([self.r_vec, r_vec], axis=0)
 
-         # Set them orbitting along random directions normal to r_vec
 
-         v_vec = np.cross(r_vec, random_unit_vectors(size=particles))
 
-         self.v_vec = np.concatenate([self.v_vec, v_vec], axis=0)
 
-         # Label the particles
 
-         type_ = [['bulge', 0]]*particles
 
-         self.type = np.concatenate([self.type, type_], axis=0)
 
-     def addDisk(self, model, totalMass, particles, l):
 
-         """Adds a disk to the galaxy.
 
-             Parameters:
 
-                 model (string): parametrization of the disk.
 
-                     'rings', 'uniform' and 'exp' are supported.
 
-                 totalMass (float): total mass of the bulge
 
-                 particles (int): number of particles in the bulge
 
-                 l: fot 'exp' and 'uniform' characteristic length of the
 
-                     model. For 'rings' tupple of the form (inner radius,
 
-                     outer radius, number of rings)
 
-         """
 
-         if particles == 0: return None
 
-         # Create particles according to the radial distribution from model
 
-         if model == 'uniform':
 
-             r = UNIFORM.ppf(np.random.rand(particles), scale=l)
 
-             type_ = [['disk', 0]]*particles
 
-             r_vec = r[:,np.newaxis] * random_unit_vectors(particles, '2D')
 
-             self.type = np.concatenate([self.type, type_], axis=0)
 
-         elif model == 'rings':
 
-             # l = [inner radius, outter radius, number of rings]
 
-             distances = np.linspace(*l)
 
-             # Aim for roughly constant areal density
 
-             # Cascade rounding preserves the total number of particles
 
-             perRing = cascade_round(particles * distances / np.sum(distances))
 
-             particles = int(np.sum(perRing)) # prevents numerical errors
 
-             r_vec = np.empty((0, 3))
 
-             for d, n, i in zip(distances, perRing, range(l[2])):
 
-                 type_ = [['disk', i+1]]*int(n)
 
-                 self.type = np.concatenate([self.type, type_], axis=0)
 
-                 phi = np.linspace(0, 2 * np.pi, n, endpoint=False)
 
-                 ringr = d * np.array([[np.cos(i), np.sin(i), 0] for i in phi])
 
-                 r_vec = np.concatenate([r_vec, ringr], axis=0)
 
-         elif model == 'exp':
 
-             r = EXP.ppf(np.random.rand(particles), scale=l)
 
-             r_vec = r[:,np.newaxis] * random_unit_vectors(particles, '2D')
 
-             type_ = [['disk', 0]]*particles
 
-             self.type = np.concatenate([self.type, type_], axis=0)
 
-         else:
 
-             raise Exception("""Disk distribution not allowed.
 
-                     'uniform', 'rings' and 'exp' are the supported values""")
 
-         self.r_vec = np.concatenate([self.r_vec, r_vec], axis=0)
 
-         # Divide the mass equally among all particles
 
-         mass = np.ones(particles) * totalMass/particles
 
-         self.mass = np.concatenate([self.mass, mass], axis=0)
 
-         # Set them orbitting along the spin plane
 
-         v_vec = np.cross(r_vec, [0, 0, 1])
 
-         self.v_vec = np.concatenate([self.v_vec, v_vec], axis=0)
 
-     def addHalo(self, model, totalMass, particles, rs):
 
-         """Adds a halo to the galaxy.
 
-             Parameters:
 
-                 model (string): parametrization of the halo.
 
-                     Only 'NFW' is supported.
 
-                 totalMass (float): total mass of the halo
 
-                 particles (int): number of particles in the halo
 
-                 rs (float): characteristic length scale of the NFW profile.
 
-         """
 
-         if particles == 0: return None
 
-         # Divide the mass equally among all particles
 
-         mass = np.ones(particles)*totalMass/particles
 
-         self.mass = np.concatenate([self.mass, mass], axis=0)
 
-         # Create particles according to the radial distribution from model
 
-         if model == 'NFW':
 
-             r = NFW.ppf(np.random.rand(particles), scale=rs)
 
-         else: raise Exception("""Bulge distribution not allowed.
 
-                     'plummer' and 'hernquist' are the supported values""")
 
-         r_vec = r[:,np.newaxis] * random_unit_vectors(size=particles)
 
-         self.r_vec = np.concatenate([self.r_vec, r_vec], axis=0)
 
-         # Orbit along random directions normal to the radial vector
 
-         v_vec = np.cross(r_vec, random_unit_vectors(size=particles))
 
-         self.v_vec = np.concatenate([self.v_vec, v_vec], axis=0)
 
-         # Label the particles
 
-         type_ = [['dark'], 0]*particles
 
-         self.type = np.concatenate([self.type, type_], axis=0)
 
-     def rotate(self, theta, phi):
 
-         """Rotates the galaxy so that its spin is along the (theta, phi)
 
-            direction.
 
-         Parameters:
 
-             theta (float): polar angle.
 
-             phi (float): azimuthal angle.
 
-         """
 
-         M1 = np.array([[1, 0, 0],
 
-                        [0, np.cos(theta), np.sin(theta)],
 
-                        [0, -np.sin(theta), np.cos(theta)]])
 
-         M2 = np.array([[np.cos(phi), np.sin(phi), 0],
 
-                        [-np.sin(phi), np.cos(phi), 0],
 
-                        [0, 0, 1]])
 
-         M = np.matmul(M1, M2) # combine rotations
 
-         self.r_vec = np.tensordot(self.r_vec, M, axes=[1, 0])
 
-         self.v_vec = np.tensordot(self.v_vec, M, axes=[1, 0])</code></pre>
 
- </details>
 
- <h3>Methods</h3>
 
- <dl>
 
- <dt id="simulation.Galaxy.__init__"><code class="name flex">
 
- <span>def <span class="ident">__init__</span></span>(<span>self, orientation, centralMass, bulge, disk, halo, sim)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Constructor for the Galaxy class.</p>
 
- <h2 id="parameters">Parameters</h2>
 
- <dl>
 
- <dt><strong><code>orientation</code></strong> : <code>tupple</code></dt>
 
- <dd>(inclination i, argument of pericenter w)</dd>
 
- <dt><strong><code>centralMass</code></strong> : <code>float</code></dt>
 
- <dd>mass at the center of the galaxy</dd>
 
- <dt><strong><code>bulge</code></strong> : <code>dict</code></dt>
 
- <dd>passed to the addBulge method.</dd>
 
- <dt><strong><code>disk</code></strong> : <code>dict</code></dt>
 
- <dd>passed to the addDisk method.</dd>
 
- <dt><strong><code>halo</code></strong> : <code>dict</code></dt>
 
- <dd>passed to the addHalo method.</dd>
 
- <dt><strong><code>sim</code></strong> : <a title="simulation.Simulation" href="#simulation.Simulation"><code>Simulation</code></a></dt>
 
- <dd>simulation object</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def __init__(self, orientation, centralMass, bulge, disk, halo, sim):
 
-     """Constructor for the Galaxy class.
 
-        Parameters:
 
-             orientation (tupple): (inclination i, argument of pericenter w)
 
-             centralMass (float): mass at the center of the galaxy
 
-             bulge (dict): passed to the addBulge method.
 
-             disk (dict): passed to the addDisk method.
 
-             halo (dict): passed to the addHalo method.
 
-             sim (Simulation): simulation object
 
-     """
 
-     if sim.verbose: print('Initializing galaxy')
 
-     # Build the central mass
 
-     self.r_vec = np.zeros((1, 3))
 
-     self.v_vec = np.zeros((1, 3))
 
-     self.a_vec = np.zeros((1, 3))
 
-     self.mass = np.array([centralMass])
 
-     self.type = np.array([['center', 0]])
 
-     # Build the other components
 
-     self.addBulge(**bulge)
 
-     if sim.verbose: print('Bulge created.')
 
-     self.addDisk(**disk)
 
-     if sim.verbose: print('Disk created.')
 
-     self.addHalo(**halo)
 
-     if sim.verbose: print('Halo created.')
 
-     # Correct particles velocities to generate circular orbits
 
-     # $a_\textup{centripetal} = v^2/r$
 
-     a_vec = sim.acceleration(self.r_vec, self.mass, soft=sim.soft)
 
-     a = np.linalg.norm(a_vec, axis=-1, keepdims=True)
 
-     r = np.linalg.norm(self.r_vec, axis=-1, keepdims=True)
 
-     v = np.linalg.norm(self.v_vec[1:], axis=-1, keepdims=True)
 
-     direction_unit = self.v_vec[1:]/v
 
-     # Set orbital velocities (except for central mass)
 
-     self.v_vec[1:] = np.sqrt(a[1:] * r[1:]) * direction_unit
 
-     self.a_vec = np.zeros_like(self.r_vec)
 
-     # Rotate the galaxy into its correct orientation
 
-     self.rotate(*(np.array(orientation)/360 * 2*np.pi))
 
-     if sim.verbose: print('Galaxy set in rotation and oriented.')</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Galaxy.addBulge"><code class="name flex">
 
- <span>def <span class="ident">addBulge</span></span>(<span>self, model, totalMass, particles, l)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Adds a bulge to the galaxy.</p>
 
- <h2 id="parameters">Parameters</h2>
 
- <dl>
 
- <dt><strong><code>model</code></strong> : <code>string</code></dt>
 
- <dd>parametrization of the bulge.
 
- 'plummer' and 'hernquist' are supported.</dd>
 
- <dt><strong><code>totalMass</code></strong> : <code>float</code></dt>
 
- <dd>total mass of the bulge</dd>
 
- <dt><strong><code>particles</code></strong> : <code>int</code></dt>
 
- <dd>number of particles in the bulge</dd>
 
- <dt><strong><code>l</code></strong> : <code>float</code></dt>
 
- <dd>characteristic length scale of the model.</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def addBulge(self, model, totalMass, particles, l):
 
-     """Adds a bulge to the galaxy.
 
-         Parameters:
 
-             model (string): parametrization of the bulge.
 
-                 'plummer' and 'hernquist' are supported.
 
-             totalMass (float): total mass of the bulge
 
-             particles (int): number of particles in the bulge
 
-             l (float): characteristic length scale of the model.
 
-     """
 
-     if particles == 0: return None
 
-     # Divide the mass equally among all particles
 
-     mass = np.ones(particles) * totalMass/particles
 
-     self.mass = np.concatenate([self.mass, mass], axis=0)
 
-     # Create particles according to the radial distribution from model
 
-     if model == 'plummer':
 
-         r = PLUMMER.ppf(np.random.rand(particles), scale=l)
 
-     elif model == 'hernquist':
 
-         r = HERNQUIST.ppf(np.random.rand(particles), scale=l)
 
-     else: raise Exception("""Bulge distribution not allowed.
 
-                 'plummer' and 'hernquist' are the supported values""")
 
-     r_vec = r[:,np.newaxis] * random_unit_vectors(size=particles)
 
-     self.r_vec = np.concatenate([self.r_vec, r_vec], axis=0)
 
-     # Set them orbitting along random directions normal to r_vec
 
-     v_vec = np.cross(r_vec, random_unit_vectors(size=particles))
 
-     self.v_vec = np.concatenate([self.v_vec, v_vec], axis=0)
 
-     # Label the particles
 
-     type_ = [['bulge', 0]]*particles
 
-     self.type = np.concatenate([self.type, type_], axis=0)</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Galaxy.addDisk"><code class="name flex">
 
- <span>def <span class="ident">addDisk</span></span>(<span>self, model, totalMass, particles, l)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Adds a disk to the galaxy.</p>
 
- <h2 id="parameters">Parameters</h2>
 
- <dl>
 
- <dt><strong><code>model</code></strong> : <code>string</code></dt>
 
- <dd>parametrization of the disk.
 
- 'rings', 'uniform' and 'exp' are supported.</dd>
 
- <dt><strong><code>totalMass</code></strong> : <code>float</code></dt>
 
- <dd>total mass of the bulge</dd>
 
- <dt><strong><code>particles</code></strong> : <code>int</code></dt>
 
- <dd>number of particles in the bulge</dd>
 
- <dt><strong><code>l</code></strong></dt>
 
- <dd>fot 'exp' and 'uniform' characteristic length of the
 
- model. For 'rings' tupple of the form (inner radius,
 
- outer radius, number of rings)</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def addDisk(self, model, totalMass, particles, l):
 
-     """Adds a disk to the galaxy.
 
-         Parameters:
 
-             model (string): parametrization of the disk.
 
-                 'rings', 'uniform' and 'exp' are supported.
 
-             totalMass (float): total mass of the bulge
 
-             particles (int): number of particles in the bulge
 
-             l: fot 'exp' and 'uniform' characteristic length of the
 
-                 model. For 'rings' tupple of the form (inner radius,
 
-                 outer radius, number of rings)
 
-     """
 
-     if particles == 0: return None
 
-     # Create particles according to the radial distribution from model
 
-     if model == 'uniform':
 
-         r = UNIFORM.ppf(np.random.rand(particles), scale=l)
 
-         type_ = [['disk', 0]]*particles
 
-         r_vec = r[:,np.newaxis] * random_unit_vectors(particles, '2D')
 
-         self.type = np.concatenate([self.type, type_], axis=0)
 
-     elif model == 'rings':
 
-         # l = [inner radius, outter radius, number of rings]
 
-         distances = np.linspace(*l)
 
-         # Aim for roughly constant areal density
 
-         # Cascade rounding preserves the total number of particles
 
-         perRing = cascade_round(particles * distances / np.sum(distances))
 
-         particles = int(np.sum(perRing)) # prevents numerical errors
 
-         r_vec = np.empty((0, 3))
 
-         for d, n, i in zip(distances, perRing, range(l[2])):
 
-             type_ = [['disk', i+1]]*int(n)
 
-             self.type = np.concatenate([self.type, type_], axis=0)
 
-             phi = np.linspace(0, 2 * np.pi, n, endpoint=False)
 
-             ringr = d * np.array([[np.cos(i), np.sin(i), 0] for i in phi])
 
-             r_vec = np.concatenate([r_vec, ringr], axis=0)
 
-     elif model == 'exp':
 
-         r = EXP.ppf(np.random.rand(particles), scale=l)
 
-         r_vec = r[:,np.newaxis] * random_unit_vectors(particles, '2D')
 
-         type_ = [['disk', 0]]*particles
 
-         self.type = np.concatenate([self.type, type_], axis=0)
 
-     else:
 
-         raise Exception("""Disk distribution not allowed.
 
-                 'uniform', 'rings' and 'exp' are the supported values""")
 
-     self.r_vec = np.concatenate([self.r_vec, r_vec], axis=0)
 
-     # Divide the mass equally among all particles
 
-     mass = np.ones(particles) * totalMass/particles
 
-     self.mass = np.concatenate([self.mass, mass], axis=0)
 
-     # Set them orbitting along the spin plane
 
-     v_vec = np.cross(r_vec, [0, 0, 1])
 
-     self.v_vec = np.concatenate([self.v_vec, v_vec], axis=0)</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Galaxy.addHalo"><code class="name flex">
 
- <span>def <span class="ident">addHalo</span></span>(<span>self, model, totalMass, particles, rs)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Adds a halo to the galaxy.</p>
 
- <h2 id="parameters">Parameters</h2>
 
- <dl>
 
- <dt><strong><code>model</code></strong> : <code>string</code></dt>
 
- <dd>parametrization of the halo.
 
- Only 'NFW' is supported.</dd>
 
- <dt><strong><code>totalMass</code></strong> : <code>float</code></dt>
 
- <dd>total mass of the halo</dd>
 
- <dt><strong><code>particles</code></strong> : <code>int</code></dt>
 
- <dd>number of particles in the halo</dd>
 
- <dt><strong><code>rs</code></strong> : <code>float</code></dt>
 
- <dd>characteristic length scale of the NFW profile.</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def addHalo(self, model, totalMass, particles, rs):
 
-     """Adds a halo to the galaxy.
 
-         Parameters:
 
-             model (string): parametrization of the halo.
 
-                 Only 'NFW' is supported.
 
-             totalMass (float): total mass of the halo
 
-             particles (int): number of particles in the halo
 
-             rs (float): characteristic length scale of the NFW profile.
 
-     """
 
-     if particles == 0: return None
 
-     # Divide the mass equally among all particles
 
-     mass = np.ones(particles)*totalMass/particles
 
-     self.mass = np.concatenate([self.mass, mass], axis=0)
 
-     # Create particles according to the radial distribution from model
 
-     if model == 'NFW':
 
-         r = NFW.ppf(np.random.rand(particles), scale=rs)
 
-     else: raise Exception("""Bulge distribution not allowed.
 
-                 'plummer' and 'hernquist' are the supported values""")
 
-     r_vec = r[:,np.newaxis] * random_unit_vectors(size=particles)
 
-     self.r_vec = np.concatenate([self.r_vec, r_vec], axis=0)
 
-     # Orbit along random directions normal to the radial vector
 
-     v_vec = np.cross(r_vec, random_unit_vectors(size=particles))
 
-     self.v_vec = np.concatenate([self.v_vec, v_vec], axis=0)
 
-     # Label the particles
 
-     type_ = [['dark'], 0]*particles
 
-     self.type = np.concatenate([self.type, type_], axis=0)</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Galaxy.rotate"><code class="name flex">
 
- <span>def <span class="ident">rotate</span></span>(<span>self, theta, phi)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Rotates the galaxy so that its spin is along the (theta, phi)
 
- direction.</p>
 
- <h2 id="parameters">Parameters</h2>
 
- <dl>
 
- <dt><strong><code>theta</code></strong> : <code>float</code></dt>
 
- <dd>polar angle.</dd>
 
- <dt><strong><code>phi</code></strong> : <code>float</code></dt>
 
- <dd>azimuthal angle.</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def rotate(self, theta, phi):
 
-     """Rotates the galaxy so that its spin is along the (theta, phi)
 
-        direction.
 
-     Parameters:
 
-         theta (float): polar angle.
 
-         phi (float): azimuthal angle.
 
-     """
 
-     M1 = np.array([[1, 0, 0],
 
-                    [0, np.cos(theta), np.sin(theta)],
 
-                    [0, -np.sin(theta), np.cos(theta)]])
 
-     M2 = np.array([[np.cos(phi), np.sin(phi), 0],
 
-                    [-np.sin(phi), np.cos(phi), 0],
 
-                    [0, 0, 1]])
 
-     M = np.matmul(M1, M2) # combine rotations
 
-     self.r_vec = np.tensordot(self.r_vec, M, axes=[1, 0])
 
-     self.v_vec = np.tensordot(self.v_vec, M, axes=[1, 0])</code></pre>
 
- </details>
 
- </dd>
 
- </dl>
 
- </dd>
 
- <dt id="simulation.Simulation"><code class="flex name class">
 
- <span>class <span class="ident">Simulation</span></span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>"Main class for the gravitational simulation.</p>
 
- <h2 id="attributes">Attributes</h2>
 
- <dl>
 
- <dt><strong><code>r_vec</code></strong> : <code>array</code></dt>
 
- <dd>position of the particles in the current timestep.
 
- Shape: (number of particles, 3)</dd>
 
- <dt><strong><code>rprev_vec</code></strong> : <code>array</code></dt>
 
- <dd>position of the particles in the previous timestep.
 
- Shape: (number of particles, 3)</dd>
 
- <dt><strong><code>v_vec</code></strong> : <code>array</code></dt>
 
- <dd>velocity in the current timestep.
 
- Shape: (number of particles, 3)</dd>
 
- <dt><strong><code>a_vec</code></strong> : <code>array</code></dt>
 
- <dd>acceleration in the current timestep.
 
- Shape: (number of particles, 3)</dd>
 
- <dt><strong><code>mass</code></strong> : <code>array</code></dt>
 
- <dd>mass of each particle in the simulation.
 
- Shape: (number of particles,)</dd>
 
- <dt><strong><code>type</code></strong> : <code>array</code></dt>
 
- <dd>non-unique identifier for each particle.
 
- Shape: (number of particles,)</dd>
 
- <dt><strong><code>tracks</code></strong> : <code>array</code></dt>
 
- <dd>list of positions through the simulation for central
 
- masses. Shape: (tracked particles, n+1, 3).</dd>
 
- <dt><strong><code>CONFIG</code></strong> : <code>array</code></dt>
 
- <dd>configuration used to create the simulation.
 
- It will be saved along the state of the simulation.</dd>
 
- <dt><strong><code>dt</code></strong> : <code>float</code></dt>
 
- <dd>timestep of the simulation</dd>
 
- <dt><strong><code>n</code></strong> : <code>int</code></dt>
 
- <dd>current timestep. Initialized as n=0.</dd>
 
- <dt><strong><code>soft</code></strong> : <code>float</code></dt>
 
- <dd>softening length used by the simulation.</dd>
 
- <dt><strong><code>verbose</code></strong> : <code>boolean</code></dt>
 
- <dd>When True progress statements will be printed.</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">class Simulation:
 
-     """"Main class for the gravitational simulation.
 
-     Attributes:
 
-         r_vec (array): position of the particles in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         rprev_vec (array): position of the particles in the previous timestep.
 
-             Shape: (number of particles, 3)
 
-         v_vec (array): velocity in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         a_vec (array): acceleration in the current timestep.
 
-             Shape: (number of particles, 3)
 
-         mass (array): mass of each particle in the simulation.
 
-             Shape: (number of particles,)
 
-         type (array): non-unique identifier for each particle.
 
-             Shape: (number of particles,)
 
-         tracks (array): list of positions through the simulation for central
 
-             masses. Shape: (tracked particles, n+1, 3).
 
-         CONFIG (array): configuration used to create the simulation.
 
-             It will be saved along the state of the simulation.
 
-         dt (float): timestep of the simulation
 
-         n (int): current timestep. Initialized as n=0.
 
-         soft (float): softening length used by the simulation.
 
-         verbose (boolean): When True progress statements will be printed.
 
-     """
 
-     def __init__(self, dt, soft, verbose, CONFIG, method, **kwargs):
 
-         """Constructor for the Simulation class.
 
-         Arguments:
 
-             dt (float): timestep of the simulation
 
-             n (int): current timestep. Initialized as n=0.
 
-             soft (float): softening length used by the simulation.
 
-             verbose (bool): When True progress statements will be printed.
 
-             CONFIG (dict): configuration file used to create the simulation.
 
-             method (string): Optional. Algorithm to use when computing the 
 
-                 gravitational forces. One of 'bruteForce', 'bruteForce_numba',
 
-                 'bruteForce_numbaopt', 'bruteForce_CPP', 'barnesHut_CPP'.
 
-         """
 
-         self.n = 0
 
-         self.t = 0
 
-         self.dt = dt
 
-         self.soft = soft
 
-         self.verbose = verbose
 
-         self.CONFIG = CONFIG
 
-         # Initialize empty arrays for all necessary properties
 
-         self.r_vec = np.empty((0, 3))
 
-         self.v_vec = np.empty((0, 3))
 
-         self.a_vec = np.empty((0, 3))
 
-         self.mass = np.empty((0,))
 
-         self.type = np.empty((0, 2))
 
-         algorithms = {
 
-             'bruteForce': acceleration.bruteForce,
 
-             'bruteForceNumba': acceleration.bruteForceNumba,
 
-             'bruteForceNumbaOptimized': acceleration.bruteForceNumbaOptimized,
 
-             'bruteForceCPP': acceleration.bruteForceCPP,
 
-             'barnesHutCPP': acceleration.barnesHutCPP
 
-         }
 
-         try:
 
-             self.acceleration = algorithms[method]
 
-         except: raise Exception("Method '{}' unknown".format(method))
 
-     def add(self, body):
 
-         """Add a body to the simulation. It must expose the public attributes
 
-            body.r_vec, body.v_vec, body.a_vec, body.type, body.mass.
 
-         Arguments:
 
-             body: Object to be added to the simulation (e.g. a Galaxy object)
 
-         """
 
-         # Extend all relevant attributes by concatenating the body
 
-         for name in ['r_vec', 'v_vec', 'a_vec', 'type', 'mass']:
 
-             simattr, bodyattr = getattr(self, name), getattr(body, name)
 
-             setattr(self, name, np.concatenate([simattr, bodyattr], axis=0))
 
-         # Order based on mass
 
-         order = np.argsort(-self.mass)
 
-         for name in ['r_vec', 'v_vec', 'a_vec', 'type', 'mass']: 
 
-             setattr(self, name, getattr(self, name)[order])
 
-         # Update the list of objects to keep track of
 
-         self.tracks = np.empty((np.sum(self.type[:,0]=='center'), 0, 3))
 
-     def step(self):
 
-         """Perform a single step of the simulation.
 
-            Makes use of a 4th order Verlet integrator.
 
-         """
 
-         # Calculate the acceleration
 
-         self.a_vec = self.acceleration(self.r_vec, self.mass, soft=self.soft)
 
-         # Update the state using the Verlet algorithm
 
-         # (A custom algorithm is written mainly for learning purposes)
 
-         self.r_vec, self.rprev_vec = (2*self.r_vec - self.rprev_vec
 
-             + self.a_vec * self.dt**2, self.r_vec)
 
-         self.n += 1
 
-         # Update tracks
 
-         self.tracks = np.concatenate([self.tracks,
 
-             self.r_vec[self.type[:,0]=='center'][:,np.newaxis]], axis=1)
 
-     def run(self, tmax, saveEvery, outputFolder, **kwargs):
 
-         """Run the galactic simulation.
 
-         Attributes:
 
-             tmax (float): Time to which the simulation will run to.
 
-                 This is measured here since the start of the simulation,
 
-                 not since pericenter.
 
-             saveEvery (int): The state is saved every saveEvery steps.
 
-             outputFolder (string): It will be saved to /data/outputFolder/
 
-         """
 
-         # When the simulation starts, intialize self.rprev_vec
 
-         self.rprev_vec = self.r_vec - self.v_vec * self.dt
 
-         if self.verbose: print('Simulation starting. Bon voyage!')
 
-         while(self.t < tmax):
 
-             self.step()
 
-             if(self.n % saveEvery == 0):
 
-                 self.save('data/{}'.format(outputFolder))
 
-         print('Simulation complete.')
 
-     def save(self, outputFolder):
 
-         """Save the state of the simulation to the outputFolder.
 
-            Two files are saved:
 
-                 sim{self.n}.pickle: serializing the state.
 
-                 sim{self.n}.png: a simplified 2D plot of x, y.
 
-         """
 
-         # Create the output folder if it doesn't exist
 
-         if not os.path.exists(outputFolder): os.makedirs(outputFolder)
 
-         # Compute some useful quantities
 
-         # v_vec is not required by the integrator, but useful
 
-         self.v_vec = (self.r_vec - self.rprev_vec)/self.dt
 
-         self.t = self.n * self.dt # prevents numerical rounding errors
 
-         # Serialize state
 
-         file = open(outputFolder+'/data{}.pickle'.format(self.n), "wb")
 
-         pickle.dump({'r_vec': self.r_vec, 'v_vec': self.v_vec,
 
-                      'type': self.type, 'mass': self.mass,
 
-                      'CONFIG': self.CONFIG, 't': self.t,
 
-                      'tracks': self.tracks}, file)
 
-         # Save simplified plot of the current state.
 
-         # Its main use is to detect ill-behaved situations early on.
 
-         fig = plt.figure()
 
-         plt.xlim(-5, 5); plt.ylim(-5, 5); plt.axis('equal')
 
-         # Dark halo is plotted in red, disk in blue, bulge in green
 
-         PLTCON = [('dark', 'r', 0.3), ('disk', 'b', 1.0), ('bulge', 'g', 0.5)]
 
-         for type_, c, a in PLTCON: 
 
-             plt.scatter(self.r_vec[self.type[:,0]==type_][:,0],
 
-                 self.r_vec[self.type[:,0]==type_][:,1], s=0.1, c=c, alpha=a)
 
-         # Central mass as a magenta star 
 
-         plt.scatter(self.r_vec[self.type[:,0]=='center'][:,0],
 
-             self.r_vec[self.type[:,0]=='center'][:,1], s=100, marker="*", c='m')
 
-         # Save to png file
 
-         fig.savefig(outputFolder+'/sim{}.png'.format(self.n), dpi=150)
 
-         plt.close(fig)
 
-     def project(self, theta, phi, view=0):
 
-         """Projects the 3D simulation onto a plane as viewed from the
 
-            direction described by the (theta, phi, view). Angles in radians.
 
-            (This is used by the simulated annealing algorithm)
 
-         
 
-         Parameters:
 
-             theta (float): polar angle.
 
-             phi (float): azimuthal angle.
 
-             view (float): rotation along line of sight.
 
-         """
 
-         M1 = np.array([[np.cos(phi), np.sin(phi), 0],
 
-                        [-np.sin(phi), np.cos(phi), 0],
 
-                        [0, 0, 1]])
 
-         M2 = np.array([[1, 0, 0],
 
-                        [0, np.cos(theta), np.sin(theta)],
 
-                        [0, -np.sin(theta), np.cos(theta)]])
 
-         M3 = np.array([[np.cos(view), np.sin(view), 0],
 
-                        [-np.sin(view), np.cos(view), 0],
 
-                        [0, 0, 1]])
 
-         M = np.matmul(M1, np.matmul(M2, M3)) # combine rotations
 
-         r = np.tensordot(self.r_vec, M, axes=[1, 0])
 
-         return r[:,0:2]
 
-     def setOrbit(self, galaxy1, galaxy2, e, rmin, R0):
 
-         """Sets the two galaxies galaxy1, galaxy2 in an orbit.
 
-         Parameters:
 
-             galaxy1 (Galaxy): 1st galaxy (main)
 
-             galaxy2 (Galaxy): 2nd galaxy (companion)
 
-             e: eccentricity of the orbit
 
-             rmin: distance of closest approach
 
-             R0: initial separation
 
-         """
 
-         m1, m2 = np.sum(galaxy1.mass), np.sum(galaxy2.mass)
 
-         # Relevant formulae:
 
-         # $r_0 = r (1 + e) \cos(\phi)$, where $r_0$ ($\neq R_0$) is the semi-latus rectum
 
-         # $r_0 = r_\textup{min} (1 + e)$
 
-         # $v^2 = G M (2/r - 1/a)$, where a is the semimajor axis
 
-         # Solve the reduced two-body problem with reduced mass $\mu$ (mu)
 
-         M = m1 + m2
 
-         r0 = rmin * (1 + e)
 
-         try:
 
-             phi = np.arccos((r0/R0 - 1) / e) # inverting the orbit equation
 
-             phi = -np.abs(phi) # Choose negative (incoming) angle
 
-             ainv = (1 - e) / rmin # ainv = $1/a$, as a may be infinite
 
-             v = np.sqrt(M * (2/R0 - ainv))
 
-             # Finally, calculate the angle of motion. angle = tan(dy/dx)
 
-             # $dy/dx = ((dr/d\phi) sin(\phi) + r \cos(\phi))/((dr/d\phi) cos(\phi) - r \sin(\phi))$
 
-             dy = R0/r0 * e * np.sin(phi)**2 + np.cos(phi)
 
-             dx = R0/r0 * e * np.sin(phi) * np.cos(phi) - np.sin(phi)
 
-             vangle = np.arctan2(dy, dx)
 
-         except: raise Exception('''The orbital parameters cannot be satisfied.
 
-             For elliptical orbits check that R0 is posible (<rmax).''')
 
-         # We now need the actual motion of each body
 
-         R_vec = np.array([[R0*np.cos(phi), R0*np.sin(phi), 0.]])
 
-         V_vec = np.array([[v*np.cos(vangle), v*np.sin(vangle), 0.]])
 
-         galaxy1.r_vec += m2/M * R_vec
 
-         galaxy1.v_vec += m2/M * V_vec
 
-         galaxy2.r_vec += -m1/M * R_vec
 
-         galaxy2.v_vec += -m1/M * V_vec
 
-         # Explicitely add the galaxies to the simulation
 
-         self.add(galaxy1)
 
-         self.add(galaxy2)
 
-         if self.verbose: print('Galaxies set in orbit.')</code></pre>
 
- </details>
 
- <h3>Methods</h3>
 
- <dl>
 
- <dt id="simulation.Simulation.__init__"><code class="name flex">
 
- <span>def <span class="ident">__init__</span></span>(<span>self, dt, soft, verbose, CONFIG, method, **kwargs)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Constructor for the Simulation class.</p>
 
- <h2 id="arguments">Arguments</h2>
 
- <dl>
 
- <dt><strong><code>dt</code></strong> : <code>float</code></dt>
 
- <dd>timestep of the simulation</dd>
 
- <dt><strong><code>n</code></strong> : <code>int</code></dt>
 
- <dd>current timestep. Initialized as n=0.</dd>
 
- <dt><strong><code>soft</code></strong> : <code>float</code></dt>
 
- <dd>softening length used by the simulation.</dd>
 
- <dt><strong><code>verbose</code></strong> : <code>bool</code></dt>
 
- <dd>When True progress statements will be printed.</dd>
 
- <dt><strong><code>CONFIG</code></strong> : <code>dict</code></dt>
 
- <dd>configuration file used to create the simulation.</dd>
 
- <dt><strong><code>method</code></strong> : <code>string</code></dt>
 
- <dd>Optional. Algorithm to use when computing the
 
- gravitational forces. One of 'bruteForce', 'bruteForce_numba',
 
- 'bruteForce_numbaopt', 'bruteForce_CPP', 'barnesHut_CPP'.</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def __init__(self, dt, soft, verbose, CONFIG, method, **kwargs):
 
-     """Constructor for the Simulation class.
 
-     Arguments:
 
-         dt (float): timestep of the simulation
 
-         n (int): current timestep. Initialized as n=0.
 
-         soft (float): softening length used by the simulation.
 
-         verbose (bool): When True progress statements will be printed.
 
-         CONFIG (dict): configuration file used to create the simulation.
 
-         method (string): Optional. Algorithm to use when computing the 
 
-             gravitational forces. One of 'bruteForce', 'bruteForce_numba',
 
-             'bruteForce_numbaopt', 'bruteForce_CPP', 'barnesHut_CPP'.
 
-     """
 
-     self.n = 0
 
-     self.t = 0
 
-     self.dt = dt
 
-     self.soft = soft
 
-     self.verbose = verbose
 
-     self.CONFIG = CONFIG
 
-     # Initialize empty arrays for all necessary properties
 
-     self.r_vec = np.empty((0, 3))
 
-     self.v_vec = np.empty((0, 3))
 
-     self.a_vec = np.empty((0, 3))
 
-     self.mass = np.empty((0,))
 
-     self.type = np.empty((0, 2))
 
-     algorithms = {
 
-         'bruteForce': acceleration.bruteForce,
 
-         'bruteForceNumba': acceleration.bruteForceNumba,
 
-         'bruteForceNumbaOptimized': acceleration.bruteForceNumbaOptimized,
 
-         'bruteForceCPP': acceleration.bruteForceCPP,
 
-         'barnesHutCPP': acceleration.barnesHutCPP
 
-     }
 
-     try:
 
-         self.acceleration = algorithms[method]
 
-     except: raise Exception("Method '{}' unknown".format(method))</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Simulation.add"><code class="name flex">
 
- <span>def <span class="ident">add</span></span>(<span>self, body)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Add a body to the simulation. It must expose the public attributes
 
- body.r_vec, body.v_vec, body.a_vec, body.type, body.mass.</p>
 
- <h2 id="arguments">Arguments</h2>
 
- <dl>
 
- <dt><strong><code>body</code></strong></dt>
 
- <dd>Object to be added to the simulation (e.g. a Galaxy object)</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def add(self, body):
 
-     """Add a body to the simulation. It must expose the public attributes
 
-        body.r_vec, body.v_vec, body.a_vec, body.type, body.mass.
 
-     Arguments:
 
-         body: Object to be added to the simulation (e.g. a Galaxy object)
 
-     """
 
-     # Extend all relevant attributes by concatenating the body
 
-     for name in ['r_vec', 'v_vec', 'a_vec', 'type', 'mass']:
 
-         simattr, bodyattr = getattr(self, name), getattr(body, name)
 
-         setattr(self, name, np.concatenate([simattr, bodyattr], axis=0))
 
-     # Order based on mass
 
-     order = np.argsort(-self.mass)
 
-     for name in ['r_vec', 'v_vec', 'a_vec', 'type', 'mass']: 
 
-         setattr(self, name, getattr(self, name)[order])
 
-     # Update the list of objects to keep track of
 
-     self.tracks = np.empty((np.sum(self.type[:,0]=='center'), 0, 3))</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Simulation.project"><code class="name flex">
 
- <span>def <span class="ident">project</span></span>(<span>self, theta, phi, view=0)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Projects the 3D simulation onto a plane as viewed from the
 
- direction described by the (theta, phi, view). Angles in radians.
 
- (This is used by the simulated annealing algorithm)</p>
 
- <h2 id="parameters">Parameters</h2>
 
- <dl>
 
- <dt><strong><code>theta</code></strong> : <code>float</code></dt>
 
- <dd>polar angle.</dd>
 
- <dt><strong><code>phi</code></strong> : <code>float</code></dt>
 
- <dd>azimuthal angle.</dd>
 
- <dt><strong><code>view</code></strong> : <code>float</code></dt>
 
- <dd>rotation along line of sight.</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def project(self, theta, phi, view=0):
 
-     """Projects the 3D simulation onto a plane as viewed from the
 
-        direction described by the (theta, phi, view). Angles in radians.
 
-        (This is used by the simulated annealing algorithm)
 
-     
 
-     Parameters:
 
-         theta (float): polar angle.
 
-         phi (float): azimuthal angle.
 
-         view (float): rotation along line of sight.
 
-     """
 
-     M1 = np.array([[np.cos(phi), np.sin(phi), 0],
 
-                    [-np.sin(phi), np.cos(phi), 0],
 
-                    [0, 0, 1]])
 
-     M2 = np.array([[1, 0, 0],
 
-                    [0, np.cos(theta), np.sin(theta)],
 
-                    [0, -np.sin(theta), np.cos(theta)]])
 
-     M3 = np.array([[np.cos(view), np.sin(view), 0],
 
-                    [-np.sin(view), np.cos(view), 0],
 
-                    [0, 0, 1]])
 
-     M = np.matmul(M1, np.matmul(M2, M3)) # combine rotations
 
-     r = np.tensordot(self.r_vec, M, axes=[1, 0])
 
-     return r[:,0:2]</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Simulation.run"><code class="name flex">
 
- <span>def <span class="ident">run</span></span>(<span>self, tmax, saveEvery, outputFolder, **kwargs)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Run the galactic simulation.</p>
 
- <h2 id="attributes">Attributes</h2>
 
- <dl>
 
- <dt><strong><code>tmax</code></strong> : <code>float</code></dt>
 
- <dd>Time to which the simulation will run to.
 
- This is measured here since the start of the simulation,
 
- not since pericenter.</dd>
 
- <dt><strong><code>saveEvery</code></strong> : <code>int</code></dt>
 
- <dd>The state is saved every saveEvery steps.</dd>
 
- <dt><strong><code>outputFolder</code></strong> : <code>string</code></dt>
 
- <dd>It will be saved to /data/outputFolder/</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def run(self, tmax, saveEvery, outputFolder, **kwargs):
 
-     """Run the galactic simulation.
 
-     Attributes:
 
-         tmax (float): Time to which the simulation will run to.
 
-             This is measured here since the start of the simulation,
 
-             not since pericenter.
 
-         saveEvery (int): The state is saved every saveEvery steps.
 
-         outputFolder (string): It will be saved to /data/outputFolder/
 
-     """
 
-     # When the simulation starts, intialize self.rprev_vec
 
-     self.rprev_vec = self.r_vec - self.v_vec * self.dt
 
-     if self.verbose: print('Simulation starting. Bon voyage!')
 
-     while(self.t < tmax):
 
-         self.step()
 
-         if(self.n % saveEvery == 0):
 
-             self.save('data/{}'.format(outputFolder))
 
-     print('Simulation complete.')</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Simulation.save"><code class="name flex">
 
- <span>def <span class="ident">save</span></span>(<span>self, outputFolder)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Save the state of the simulation to the outputFolder.
 
- Two files are saved:
 
- sim{self.n}.pickle: serializing the state.
 
- sim{self.n}.png: a simplified 2D plot of x, y.</p></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def save(self, outputFolder):
 
-     """Save the state of the simulation to the outputFolder.
 
-        Two files are saved:
 
-             sim{self.n}.pickle: serializing the state.
 
-             sim{self.n}.png: a simplified 2D plot of x, y.
 
-     """
 
-     # Create the output folder if it doesn't exist
 
-     if not os.path.exists(outputFolder): os.makedirs(outputFolder)
 
-     # Compute some useful quantities
 
-     # v_vec is not required by the integrator, but useful
 
-     self.v_vec = (self.r_vec - self.rprev_vec)/self.dt
 
-     self.t = self.n * self.dt # prevents numerical rounding errors
 
-     # Serialize state
 
-     file = open(outputFolder+'/data{}.pickle'.format(self.n), "wb")
 
-     pickle.dump({'r_vec': self.r_vec, 'v_vec': self.v_vec,
 
-                  'type': self.type, 'mass': self.mass,
 
-                  'CONFIG': self.CONFIG, 't': self.t,
 
-                  'tracks': self.tracks}, file)
 
-     # Save simplified plot of the current state.
 
-     # Its main use is to detect ill-behaved situations early on.
 
-     fig = plt.figure()
 
-     plt.xlim(-5, 5); plt.ylim(-5, 5); plt.axis('equal')
 
-     # Dark halo is plotted in red, disk in blue, bulge in green
 
-     PLTCON = [('dark', 'r', 0.3), ('disk', 'b', 1.0), ('bulge', 'g', 0.5)]
 
-     for type_, c, a in PLTCON: 
 
-         plt.scatter(self.r_vec[self.type[:,0]==type_][:,0],
 
-             self.r_vec[self.type[:,0]==type_][:,1], s=0.1, c=c, alpha=a)
 
-     # Central mass as a magenta star 
 
-     plt.scatter(self.r_vec[self.type[:,0]=='center'][:,0],
 
-         self.r_vec[self.type[:,0]=='center'][:,1], s=100, marker="*", c='m')
 
-     # Save to png file
 
-     fig.savefig(outputFolder+'/sim{}.png'.format(self.n), dpi=150)
 
-     plt.close(fig)</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Simulation.setOrbit"><code class="name flex">
 
- <span>def <span class="ident">setOrbit</span></span>(<span>self, galaxy1, galaxy2, e, rmin, R0)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Sets the two galaxies galaxy1, galaxy2 in an orbit.</p>
 
- <h2 id="parameters">Parameters</h2>
 
- <dl>
 
- <dt><strong><code>galaxy1</code></strong> : <a title="simulation.Galaxy" href="#simulation.Galaxy"><code>Galaxy</code></a></dt>
 
- <dd>1st galaxy (main)</dd>
 
- <dt><strong><code>galaxy2</code></strong> : <a title="simulation.Galaxy" href="#simulation.Galaxy"><code>Galaxy</code></a></dt>
 
- <dd>2nd galaxy (companion)</dd>
 
- <dt><strong><code>e</code></strong></dt>
 
- <dd>eccentricity of the orbit</dd>
 
- <dt><strong><code>rmin</code></strong></dt>
 
- <dd>distance of closest approach</dd>
 
- <dt><strong><code>R0</code></strong></dt>
 
- <dd>initial separation</dd>
 
- </dl></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def setOrbit(self, galaxy1, galaxy2, e, rmin, R0):
 
-     """Sets the two galaxies galaxy1, galaxy2 in an orbit.
 
-     Parameters:
 
-         galaxy1 (Galaxy): 1st galaxy (main)
 
-         galaxy2 (Galaxy): 2nd galaxy (companion)
 
-         e: eccentricity of the orbit
 
-         rmin: distance of closest approach
 
-         R0: initial separation
 
-     """
 
-     m1, m2 = np.sum(galaxy1.mass), np.sum(galaxy2.mass)
 
-     # Relevant formulae:
 
-     # $r_0 = r (1 + e) \cos(\phi)$, where $r_0$ ($\neq R_0$) is the semi-latus rectum
 
-     # $r_0 = r_\textup{min} (1 + e)$
 
-     # $v^2 = G M (2/r - 1/a)$, where a is the semimajor axis
 
-     # Solve the reduced two-body problem with reduced mass $\mu$ (mu)
 
-     M = m1 + m2
 
-     r0 = rmin * (1 + e)
 
-     try:
 
-         phi = np.arccos((r0/R0 - 1) / e) # inverting the orbit equation
 
-         phi = -np.abs(phi) # Choose negative (incoming) angle
 
-         ainv = (1 - e) / rmin # ainv = $1/a$, as a may be infinite
 
-         v = np.sqrt(M * (2/R0 - ainv))
 
-         # Finally, calculate the angle of motion. angle = tan(dy/dx)
 
-         # $dy/dx = ((dr/d\phi) sin(\phi) + r \cos(\phi))/((dr/d\phi) cos(\phi) - r \sin(\phi))$
 
-         dy = R0/r0 * e * np.sin(phi)**2 + np.cos(phi)
 
-         dx = R0/r0 * e * np.sin(phi) * np.cos(phi) - np.sin(phi)
 
-         vangle = np.arctan2(dy, dx)
 
-     except: raise Exception('''The orbital parameters cannot be satisfied.
 
-         For elliptical orbits check that R0 is posible (<rmax).''')
 
-     # We now need the actual motion of each body
 
-     R_vec = np.array([[R0*np.cos(phi), R0*np.sin(phi), 0.]])
 
-     V_vec = np.array([[v*np.cos(vangle), v*np.sin(vangle), 0.]])
 
-     galaxy1.r_vec += m2/M * R_vec
 
-     galaxy1.v_vec += m2/M * V_vec
 
-     galaxy2.r_vec += -m1/M * R_vec
 
-     galaxy2.v_vec += -m1/M * V_vec
 
-     # Explicitely add the galaxies to the simulation
 
-     self.add(galaxy1)
 
-     self.add(galaxy2)
 
-     if self.verbose: print('Galaxies set in orbit.')</code></pre>
 
- </details>
 
- </dd>
 
- <dt id="simulation.Simulation.step"><code class="name flex">
 
- <span>def <span class="ident">step</span></span>(<span>self)</span>
 
- </code></dt>
 
- <dd>
 
- <section class="desc"><p>Perform a single step of the simulation.
 
- Makes use of a 4th order Verlet integrator.</p></section>
 
- <details class="source">
 
- <summary>Source code</summary>
 
- <pre><code class="python">def step(self):
 
-     """Perform a single step of the simulation.
 
-        Makes use of a 4th order Verlet integrator.
 
-     """
 
-     # Calculate the acceleration
 
-     self.a_vec = self.acceleration(self.r_vec, self.mass, soft=self.soft)
 
-     # Update the state using the Verlet algorithm
 
-     # (A custom algorithm is written mainly for learning purposes)
 
-     self.r_vec, self.rprev_vec = (2*self.r_vec - self.rprev_vec
 
-         + self.a_vec * self.dt**2, self.r_vec)
 
-     self.n += 1
 
-     # Update tracks
 
-     self.tracks = np.concatenate([self.tracks,
 
-         self.r_vec[self.type[:,0]=='center'][:,np.newaxis]], axis=1)</code></pre>
 
- </details>
 
- </dd>
 
- </dl>
 
- </dd>
 
- </dl>
 
- </section>
 
- </article>
 
- <nav id="sidebar">
 
- <h1>Index</h1>
 
- <div class="toc">
 
- <ul></ul>
 
- </div>
 
- <ul id="index">
 
- <li><h3><a href="#header-classes">Classes</a></h3>
 
- <ul>
 
- <li>
 
- <h4><code><a title="simulation.Galaxy" href="#simulation.Galaxy">Galaxy</a></code></h4>
 
- <ul class="">
 
- <li><code><a title="simulation.Galaxy.__init__" href="#simulation.Galaxy.__init__">__init__</a></code></li>
 
- <li><code><a title="simulation.Galaxy.addBulge" href="#simulation.Galaxy.addBulge">addBulge</a></code></li>
 
- <li><code><a title="simulation.Galaxy.addDisk" href="#simulation.Galaxy.addDisk">addDisk</a></code></li>
 
- <li><code><a title="simulation.Galaxy.addHalo" href="#simulation.Galaxy.addHalo">addHalo</a></code></li>
 
- <li><code><a title="simulation.Galaxy.rotate" href="#simulation.Galaxy.rotate">rotate</a></code></li>
 
- </ul>
 
- </li>
 
- <li>
 
- <h4><code><a title="simulation.Simulation" href="#simulation.Simulation">Simulation</a></code></h4>
 
- <ul class="two-column">
 
- <li><code><a title="simulation.Simulation.__init__" href="#simulation.Simulation.__init__">__init__</a></code></li>
 
- <li><code><a title="simulation.Simulation.add" href="#simulation.Simulation.add">add</a></code></li>
 
- <li><code><a title="simulation.Simulation.project" href="#simulation.Simulation.project">project</a></code></li>
 
- <li><code><a title="simulation.Simulation.run" href="#simulation.Simulation.run">run</a></code></li>
 
- <li><code><a title="simulation.Simulation.save" href="#simulation.Simulation.save">save</a></code></li>
 
- <li><code><a title="simulation.Simulation.setOrbit" href="#simulation.Simulation.setOrbit">setOrbit</a></code></li>
 
- <li><code><a title="simulation.Simulation.step" href="#simulation.Simulation.step">step</a></code></li>
 
- </ul>
 
- </li>
 
- </ul>
 
- </li>
 
- </ul>
 
- </nav>
 
- </main>
 
- <footer id="footer">
 
- <p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.5.2</a>.</p>
 
- </footer>
 
- <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
 
- <script>hljs.initHighlightingOnLoad()</script>
 
- </body>
 
- </html>
 
 
  |