diff --git a/html/angular diameter distance.html b/html/angular diameter distance.html index 9a9a5b1..79a27bd 100644 --- a/html/angular diameter distance.html +++ b/html/angular diameter distance.html @@ -1347,7 +1347,7 @@ .ansiblack{color:#000} .ansired{color:#8b0000} .ansigreen{color:#006400} -.ansiyellow{color:#c4a000} +.ansiyellow{color:#a52a2a} .ansiblue{color:#00008b} .ansipurple{color:#9400d3} .ansicyan{color:#4682b4} @@ -1680,7 +1680,13 @@
The information presented here is placed in the public domain, and was written by Doug Burke. The notebook used to create this page is available, and questions can be asked using the GitHub issues page or via Twitter: https://twitter.com/doug_burke.
+The information presented here is placed in the public domain, and was written by +Doug Burke. The +notebook +used to create this page is available, and questions can be +asked using the +GitHub issues page +or via Twitter: https://twitter.com/doug_burke.
... or at least, a little bit of each.
-Although I mention a few bits and pieces below, I'm going to leave it to Ned Wright's Cosmology Tutorial to explain things properly. Ned's javascript Cosmology Calculator should also be preferred to any of the code presented here, as I am ignoring some things (e.g. the contribution of neutrinos).
-This is not intended to be a Haskell tutorial, rather it is meant as an example showing that it is possible to use Haskell for Astronomy. Haskell is rather different to the computer languages commonly used in Astronomy, so I try and provide Python equivalents as I go along. One thing I am not going to do is try and convince you that Haskell is the one true language for Astronomy, since it isn't. I also don't think that many of the selling points of functional programming, or using a static typing system with type inference, can easily be shown in an IHaskell notebook.
-If you are interested in learning more about Haskell, then I suggest you look at one of the several guides to Haskell out there on the internet, such as Chris Allen's Learn Haskell, How to Learn Haskell, and Stephen Diehl's "What I wish I knew when learning Haskell". The newly-renovated Haskell home page is also a useful resource.
+Although I mention a few bits and pieces below, I'm going to leave it to +Ned Wright's Cosmology Tutorial +to explain things properly. Ned's +javascript Cosmology Calculator +should also be preferred to any of the code presented here, as I am ignoring +some things (e.g. the contribution of neutrinos).
+This is not intended to be a Haskell tutorial, rather it is meant as +an example showing that it is possible to use Haskell for Astronomy. +Haskell is rather different to the computer languages commonly used in Astronomy, +so I try and provide Python equivalents as I go along. +One thing I am not going to do is try and convince you that Haskell +is the one true language for Astronomy, since it isn't. +I also don't think that many of the selling points of functional programming, +or using a static typing system with type inference, can easily be +shown in an IHaskell notebook.
+If you are interested in learning more about Haskell, +then I suggest you look at one of the several guides to Haskell out there on the internet, such as +Chris Allen's Learn Haskell, +How to Learn Haskell, +and +Stephen Diehl's "What I wish I knew when learning Haskell". +The newly-renovated Haskell home page is also a useful resource.
import Data.Time
@@ -1738,7 +1765,7 @@ Last time the notebook was run
-2015-02-15 22:58:07.009619 UTC
+2015-02-23 20:04:21.617488 UTC
I was recently re-reading the paper "Experience Report: Type-checking Polymorphic Units for Astrophysics Research in Haskell" by Takayuki Muranushi and Richard A. Eisenberg (Haskell Symposium 2014, Gothenburg, Sweden) and wanted to try out the units package. I have some (private) code that calculates cosmological quantities (distance, time, volume) that uses a different approach for handling units in Haskell (via the dimensional package), and thougt I'd try converting the code to use units. Then I thought, I should put it online for all to see - an a moment of perhaps ill-advised grandeur - and so here we are. Unfortunately, during the development of this notebook, I found that I can't actually build the units module (since I am using the default ghc version provided by Ubuntu 14.10, which is version 7.6.3), so I ended up using a variant of the dimensional package.
I had best point out that the following is not going to present a robust, well-thought out, API for a Cosmology library!
+I was recently re-reading the paper
+"Experience Report: Type-checking Polymorphic Units for Astrophysics Research in Haskell"
+by Takayuki Muranushi and Richard A. Eisenberg (Haskell Symposium 2014, Gothenburg, Sweden)
+and wanted to try out the
+units package. I have some (private) code that calculates
+cosmological quantities (distance, time, volume) that uses a different approach for handling
+units in Haskell (via the
+dimensional
+package), and thougt I'd try converting the code to use units. Then I thought, I should
+put it online for all to see - an a moment of perhaps ill-advised grandeur - and so here we are.
+Unfortunately, during the development of this notebook, I found that I can't actually build
+the units module (since I am using the default ghc version provided by Ubuntu 14.10, which
+is version 7.6.3), so I ended up using a variant of the dimensional package.
I had best point out that the following is not going to present a robust, well-thought +out, API for a Cosmology library!
This is an IHaskell notebook, which uses the notebook features of IPython to support an interactive Haskell environment. Now, Haskell compilers tend to provide an interactive environment - commonly known as a repl - but the advantage of IHaskell is the HTML support and easy display of non-textual items (so, similar to why people like IPython notebooks when there's the ipython command-line environment).
Since this is an interactive environment, there are several differences to how code would be written and run in compiled code, but we can ignore these for now.
+This is an
+IHaskell
+notebook, which uses the notebook features of
+IPython to support an interactive Haskell environment.
+Now, Haskell compilers tend to provide an interactive environment - commonly known as a
+repl - but the
+advantage of IHaskell is the HTML support and easy display of non-textual items (so,
+similar to why people like IPython notebooks when there's the ipython command-line
+environment).
Since this is an interactive environment, there are several differences to how code would +be written and run in compiled code, but we can ignore these for now.
This section can be skipped if you are not interested in trying the code out.
-For this analysis, I am using the default set of packages on my Ubuntu 14.10 machine: ghc version 7.6.3, the Haskell compiler, and cabal-install (at version 1.20.0), which is used for package management (e.g. is is something like pip). Later versions should (hopefully) work, but earlier versions may not (the cabal sandbox command needs a cabal-install version of at least 1.18 and I don't know how well ghc version 7.4 or earlier are going to work).
With these installed, and having moved to a new directory, I set up a "sandbox" environment in which to install the Haskell packages (to avoid conflicting packages and to make it easy to remove or update changes for just this project), and enter
+For this analysis, I am using the default set of packages on my Ubuntu 14.10 machine: ghc version 7.6.3, the
+Haskell compiler, and cabal-install
+(at version 1.20.0), which is used for package management (e.g. is is something like pip).
+Later versions should (hopefully) work, but earlier versions may not (the cabal sandbox command needs a cabal-install version of at least 1.18 and I don't know how well ghc version 7.4 or earlier are going to work).
With these installed, and having moved to a new directory, I set up a "sandbox" environment in which to +install the Haskell packages (to avoid conflicting packages and to make it easy to remove or update changes for just this project), and enter
% cabal update
% cabal sandbox init
% cabal install integration chart-diagrams ihaskell ihaskell-blaze --dry-run
@@ -1823,8 +1876,8 @@ How do you install and setup the
Downloading OneTuple-0.2.1...
...
... and wait quite a while
-...
-This will create (if it doesn't already) the directory ~/.cabal/ as well as .cabal-sandbox/ in the current directory.
This will create (if it doesn't already) the directory ~/.cabal/ as well as .cabal-sandbox/ in the current directory.
At this point you should be able to say
% cabal repl
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
@@ -1833,8 +1886,8 @@ How do you install and setup the
Loading package base ... linking ... done.
Prelude> import Numeric.Integration.TanhSinh
Prelude Numeric.Integration.TanhSinh> :quit
-Leaving GHCi.
-which checks that things are set up correctly.
+Leaving GHCi. +which checks that things are set up correctly.
We now need to run IHaskell, which will then set up its own version of IPython (unless it can find one it is able to use), and store it in ~/.ihaskell/.
% mkdir notebooks
% cabal exec IHaskell -- notebook --serve=notebooks/
@@ -1850,8 +1903,13 @@ How do you install and setup the
... normal ipython notebook output
...
2015-02-09 19:28:24.287 [NotebookApp] The IPython Notebook is running at: http://localhost:8778/
-2015-02-09 19:28:24.287 [NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
-At this point you should be able to go the URL where the server is running and start a notebook to follow along. If you just want to try a few things out, then the Try Haskell! and FP Complete sites provide on-line environments for trying out Haskell.
+2015-02-09 19:28:24.287 [NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). +At this point you should be able to go the URL where the server is running and start a notebook to follow along. If you just +want to try a few things out, then the +Try Haskell! +and +FP Complete +sites provide on-line environments for trying out Haskell.
For reference, the versions of the major packages used in this notebook are (dimensional-tf is added in later):
cabal exec ghc-pkg -- list | egrep -i 'ihaskell|integration|dimensional|chart'
Chart-1.3.3
@@ -1859,7 +1917,8 @@ How do you install and setup the
dimensional-tf-0.3.0.1
ihaskell-0.4.3.0
ihaskell-blaze-0.1.0.0
- integration-0.2.0.1
+ integration-0.2.0.1
+
Here I just load in a few modules that will be used later, for displaying a graph. In Haskell, the form import a loads all the symbols defined for export from the module a; that is, it is like Python's from a import *. There are ways to import just one or more symbols, or to load in a module using a qualified name, both of which are used later.
Here I just load in a few modules that will be used later, for displaying
+a graph. In Haskell, the form import a loads all the symbols defined for
+export from the module a; that is, it is like Python's from a import *.
+There are ways to import just one or more symbols, or
+to load in a module using a qualified name, both of which are used later.
import IHaskell.Display
+:option no-pager
+import IHaskell.Display
import Graphics.Rendering.Chart.Backend.Diagrams
import Graphics.Rendering.Chart.Easy
@@ -1903,13 +1969,24 @@ Setting things up
-Normally we would just install the ihaskell-charts package and not have to bother with this, but version 0.1.0.0 of this package does not build with version 1.3 of Chart. There is a fix for this on the GitHub version of ihaskell-charts but it's also possible to write it directly by converting the output of Chart into a form that the ihaskell-blaze package knows how to display.
+Normally we would just install the
+ihaskell-charts
+package and not have to bother with this, but version 0.1.0.0 of
+this package does not build with version 1.3 of
+Chart. There is a fix
+for this on the GitHub version of ihaskell-charts but it's also
+possible to write it directly by converting the output of Chart
+into a form that the
+ihaskell-blaze
+package knows how to display.
-- For the purposes of this notebook you do not need to understand this
@@ -1944,20 +2021,34 @@ What is the distance between t
I want to calculate the angular-diameter distance to a source, so that I can find out what the projected separation between two points is when all I know is a redshift and an angle. The parameters we are interested in are the redshift of the source, \(z\), the matter-density (\(\Omega_m\)), the vacuum-density (\(\Omega_\lambda\)), and Hubble's constant (\(H_0\)).
-The angular-diameter distance, \(d_A\), is
-\[d_A (z; \Omega_m, \Omega_\lambda) = \frac{c}{H_0} \frac{d_c(z; \Omega_m, \Omega_\lambda)}{1+z}\]
-where \(d_c\) is the comoving distance to the source. For simplicity, I am going to assume that we are only interested in flat cosmologies; that is, where \(\Omega_m + \Omega_\lambda = 1\) (i.e. \(\Omega_k = 0\)), which leaves me to calculate:
-\[d_A (z; \Omega_m) = \frac{c}{H_0} \frac{\int_0^z f(z; \Omega_m) dz}{1+z}\]
+I want to calculate the +angular-diameter distance +to a source, so that I can find out what the projected separation between +two points is when all I know is a redshift and an angle. The parameters we +are interested in are the redshift of the source, $z$, the +matter-density ($\Omega_m$), the vacuum-density ($\Omega_\lambda$), +and Hubble's constant ($H_0$).
+The angular-diameter distance, $d_A$, is
+$$d_A (z; \Omega_m, \Omega_\lambda) = \frac{c}{H_0} \frac{d_c(z; \Omega_m, \Omega_\lambda)}{1+z}$$
+where $d_c$ is the +comoving distance +to the source. For simplicity, +I am going to assume that we are only interested in flat cosmologies; that +is, where $\Omega_m + \Omega_\lambda = 1$ (i.e. $\Omega_k = 0$), which +leaves me to calculate:
+$$d_A (z; \Omega_m) = \frac{c}{H_0} \frac{\int_0^z f(z; \Omega_m) dz}{1+z}$$
where
-\[f (z; \Omega_m) = 1 / \sqrt{ (1+z)^2 (1 + \Omega_m z) - (2+z) (1-\Omega_m) z }\]
-So, I start by defining the \(f\) function, which has arguments of \(\Omega_m\) (om) and redshift (z):
$$f (z; \Omega_m) = 1 / \sqrt{ (1+z)^2 (1 + \Omega_m z) - (2+z) (1-\Omega_m) z }$$
+So, I start by defining the $f$ function, which has arguments of $\Omega_m$ (om)
+and redshift (z):
-- Calculate f(z; omega_m). The first argument is the matter density
@@ -1980,25 +2071,49 @@ What is the distance between t
There are several things to note here:
-The first two lines are comments.
-The third line gives the signature of the function: the label before :: is the name of the function and the types of the arguments are separated by the arrows (->), with the last type being the value calculated by the function. So, f takes two Double values and returns a Double.
-This signature line is not required, since the Haskell compiler can determine the types. However the types it infers a more general than the ones I gave (it has worked out that both Float or Double could be used). I chose to force Double since the integration routine I use below works on Double types and it simplifies some of the discussion below, such as when asking for the type of the g function.
-The function arguments on line four are separated by spaces rather than brackets and commas.
-The definition of the function (lines four to siz) uses the let xxx in yyy form, which defines a set of local symbols (in this case ol and t) which are then used to calculate a value.
-Function application does not use brackets, so the denominator of the fraction is just sqrt t. However, precedence rules means that brackets may be needed to clarify what is an argument. For instance, if I had not used the temporary symbol t then I would have had to write 1 / sqrt ((1 + z)^2 * (1 + om*z) - (2 + z) * ol * z).
+The first two lines are comments.
+
+The third line gives the signature of the function: the label before :: is the name of the
+function and the types of the arguments are separated by the arrows (->), with the last
+type being the value calculated by the function. So, f takes two Double values and
+returns a Double.
+This signature line is not required, since the Haskell compiler can determine the types.
+However the types it infers a more general than the ones I gave (it has worked out that
+both Float or Double could be used). I chose to force Double since the integration
+routine I use below works on Double types and it simplifies some of the discussion
+below, such as when asking for the type of the g function.
+
+The function arguments on line four are separated by spaces rather than brackets and commas.
+
+The definition of the function (lines four to siz) uses the let xxx in yyy form, which defines a set of
+local symbols (in this case ol and t) which are then used to calculate a value.
+
+Function application does not use brackets, so the denominator of the fraction is
+just sqrt t. However, precedence rules means that brackets may be needed to clarify
+what is an argument. For instance, if I had not used the temporary symbol t then I would
+have had to write 1 / sqrt ((1 + z)^2 * (1 + om*z) - (2 + z) * ol * z).
+
The above is similar to the Python code:
def f(om,z):
ol = 1 - om
t = (1 + z)**2 * (1 + om*z) - (2 + z) * ol * z
- return 1 / math.sqrt(t)
-I now want to check how \(f\) varies with redshift for a given \(\Omega_m\) value (in this case I want to use a value of 0.3, since that is close to the currently-preferred cosmological model). I can do this by taking advantage of partial application to easily create a function that calls f with the first argument fixed to 0.3:
+ return 1 / math.sqrt(t)
+I now want to check how $f$ varies with redshift for a given $\Omega_m$ value (in this case
+I want to use a value of 0.3, since that is close to the
+currently-preferred cosmological
+model). I can do this by
+taking advantage of
+partial application to easily create a function
+that calls f with the first argument fixed to 0.3:
g = f 0.3
@@ -2017,17 +2132,23 @@ What is the distance between t
The Python version would be something like
def g(z):
return f(0.3, z)
-
-or
-g = lambda z: f(0.3, z)
-Since I am often going to be interested in how things vary with redshift, I am going to make this parameter the last one, so that it makes it easy to partially apply the functions I write (as in the case of making g a specialized version of f).
-The :type command - which is part of the interactive Haskell environment rather than Haskell itself - reports the type of a symbol: in this case it shows us that g is a function that takes a Double and returns a Double (so it has one less "Double ->" term than f).
+or
+g = lambda z: f(0.3, z)
+Since I am often going to be interested in how things vary with redshift, I am going to
+make this parameter the last one, so that it makes it easy to partially apply
+the functions I write (as in the case of making g a specialized version of f).
The :type command - which is part of the interactive Haskell environment rather than
+Haskell itself - reports the type of a symbol: in this case it shows us that g is
+a function that takes a Double and returns a Double (so it has one less "Double ->"
+term than f).
:type g
@@ -2067,14 +2188,21 @@ What is the distance between t
I am going to gloss over the fact that Haskell functions only ever accept a single argument, using curried functions to implement what appear to be multi-argument functions. It is an important point to understand if you are going to be writing Haskell, but I don't want to derail the discussion too much.
-Getting back to the code, I can evaluate g for \(z=0\) and then \(z=1.2\) (taking advantage of the automatic-display capabilities of the IHaskell notebook; in an actual Haskell program we would have to say something like print (g 0) to display the value):
I am going to gloss over the fact that Haskell functions only ever accept a single argument, using +curried functions to implement what appear to be multi-argument functions. +It is an important point to understand if you are going to be writing Haskell, +but I don't want to derail the discussion too much.
+Getting back to the code, I can evaluate g for $z=0$ and then $z=1.2$
+(taking advantage of the automatic-display capabilities of the
+IHaskell notebook; in an actual Haskell program we would have to say something like print (g 0) to display the value):
g 0
@@ -2105,7 +2233,9 @@ What is the distance between t
g 1.2
@@ -2139,14 +2269,21 @@ What is the distance between t
I want to evaluate this function for a number of different redshifts, so I want to automate this process, which leads to lists and the map function.
In Haskell, lists of objects are represented by comma-separated values enclosed by [] brackets - e.g. [1.2, 3.4, 9.8] - and have a type of [a], where a is the type of the list element. The map function takes a function which accepts one argument, as well as a list of arguments, and returns a list of values created by applying the function to each argument. That is, it has a type of:
I want to evaluate this function for a number of different redshifts, so I want to
+automate this process, which leads to lists and the map function.
In Haskell, lists of objects are represented by comma-separated values enclosed by
+[] brackets - e.g. [1.2, 3.4, 9.8] - and have a type of [a], where a is the
+type of the list element. The map function takes a function which accepts one
+argument, as well as a list of arguments, and returns a list of values created
+by applying the function to each argument. That is, it has a type of:
:type map
@@ -2178,13 +2315,18 @@ What is the distance between t
For this discussion we can ignore the forall a b part of the type.
-To be general, the function supplied to map can have different types for its input and output lists, (so a and b above) but here we will use g which means that the input and output lists have a type of [Double]:
+To be general, the function supplied to map can have different types for its input and output lists,
+(so a and b above)
+but here we will use g which means that the input and output lists have a type
+of [Double]:
:type map g
@@ -2221,7 +2363,9 @@ What is the distance between t
map g [0, 0.4, 3.2]
@@ -2255,13 +2399,19 @@ What is the distance between t
I want to look at g evaluated for a range of redshits between 0 and 10, so let's create the list of redshifts (a common scheme when naming variables in Haskell is to add a s for a list of values, hence the use of zs here) and evaluate g on each element:
I want to look at g evaluated for a range of redshits
+between 0 and 10, so let's create the list of redshifts
+(a common scheme when naming
+variables in Haskell is to add a s for a list of values, hence the
+use of zs here) and evaluate g on each element:
zs = [0::Double, 0.1 .. 10]
@@ -2278,25 +2428,34 @@ What is the distance between t
The form [a, a+dx .. b] is similar to NumPy's numpy.arange(a, b+dx, dx), so this is similar to the Python/NumPy code
The form [a, a+dx .. b] is similar to NumPy's numpy.arange(a, b+dx, dx), so this is similar to the Python/NumPy code
zs = numpy.arange(0, 10.1, 0.1)
# You could use Python's map
gs = map(g, zs)
# or a list compreshension
-gs = [g(z) for z in zs]
-Note that I am ignoring the difference between Python lists and NumPy arrays here.
+gs = [g(z) for z in zs] +Note that I am ignoring the difference between Python lists and NumPy arrays here.
I did not need to add ::Double to 0 when creating zs, but did so just to keep the types "concrete". If I had said
zs = [0, 0.1 .. 10]
-then gs would still be a list of Double values, but the type of zs would be
forall t. (Enum t, Fractional t) => [t]
-and I don't really want to try and explain Haskell type classes (the names to the left of the =>) here.
We can finally take advantage of the display code I wrote at the start of the notebook, and use the routines from the Graphics.Rendering.Chart.Easy module of the Chart package to display gs versus zs:
zs = [0, 0.1 .. 10]
+then gs would still be a list of Double values, but the type of zs would be
forall t. (Enum t, Fractional t) => [t]
+and I don't really want to try and explain
+Haskell type classes
+(the names to the left of the =>) here.
We can finally take advantage of the display code I wrote at the start of the notebook, and
+use the routines from the
+Graphics.Rendering.Chart.Easy module
+of the
+Chart package
+to display gs versus zs:
toRenderable (do
@@ -3111,8 +3270,17 @@ What is the distance between t
This command doesn't look like anything I've shown so far, and I don't really want to explain it too much, but the toRenderable function takes a list of actions, which describes the plot, and converts it a value with a Renderable type, defined in the Chart package, which is itself then converted into SVG and automatically displayed by the notebook, due to the code I wrote way back at the start.
The list of actions is created using do notation, which is a way of representing a chain of actions - in this case things like "set the X-axis label to 'Redshift'" and "plot up this list of (x,y) points" - in Haskell. This is very terse and it's best if you just let your eyes skip over the code and focus on the plot instead.
This command doesn't look like anything I've shown so far, and I don't really want to explain it too much, but the
+toRenderable function takes a list of actions, which describes the plot, and converts it a value with a
+Renderable type, defined in the
+Chart package,
+which is itself then converted into SVG and automatically
+displayed by the notebook, due to the code I wrote way back at the start.
The list of actions is created using
+do notation,
+which is a way of representing a chain of actions - in this case things
+like "set the X-axis label to 'Redshift'" and "plot up this list of (x,y) points" - in Haskell. This is very terse
+and it's best if you just let your eyes skip over the code and focus on the plot instead.
To calculate the angular-diameter distance I need to integrate f. The "Why functional programming matters" (link to PDF) article by John Hughes provides a nice implementation that highlights some of the ways that lazy evaluation can be used to simplify code. However, it's easier to use a pre-canned solution, and in this case I have chosen to use the integration package:
To calculate the angular-diameter distance I need to integrate f. The
+"Why functional programming matters" (link to PDF)
+article by John Hughes provides a nice implementation that highlights
+some of the ways that
+lazy evaluation can be used to
+simplify code. However, it's easier to use a pre-canned solution,
+and in this case I have chosen to use the
+integration package:
absolute 1.0e-6 (simpson g 0 2)
@@ -3190,7 +3374,9 @@ Integrating \(f\)
-In [16]:
+
+In [16]:
+
absolute 1.0e-6 (trap g 0 2)
@@ -3224,13 +3410,16 @@ Integrating \(f\)
-The result of absolute is a Haskell record, but all we need worry about now is that the value of the integrated function can be retrieved from it by using result, as shown below:
+The result of absolute is a Haskell record, but all we need worry about now is that the
+value of the integrated function can be retrieved from it by using result, as shown below:
-In [17]:
+
+In [17]:
+
-In [18]:
+
+In [18]:
+
:type simpson
@@ -3329,13 +3521,16 @@ Integrating \(f\)
-We can look at these return values, using the take 3 function that returns the first three elements of a list, to see that the result has converged quickly:
+We can look at these return values, using the take 3 function that returns the first three elements of a list,
+to see that the result has converged quickly:
-In [19]:
+
+In [19]:
+
take 3 (trap g 0 2)
@@ -3366,7 +3561,9 @@ Integrating \(f\)
-In [20]:
+
+In [20]:
+
take 3 (simpson g 0 2)
@@ -3400,13 +3597,16 @@ Integrating \(f\)
-Getting back to the task at hand, I can define daH as a function that accepts \(\Omega_m\) and \(z\) and returns the angular-diameter distance, in units of the Hubble length, by saying:
+Getting back to the task at hand, I can define daH as a function that accepts $\Omega_m$ and $z$
+and returns the angular-diameter distance, in units of the Hubble length, by saying:
-In [21]:
+
+In [21]:
+
daH om z = let fs = result (absolute 1.0e-6 (trap (f om) 0 z))
@@ -3428,14 +3628,17 @@ Integrating \(f\)
-In [22]:
+
+In [22]:
+
-In [23]:
+
+In [23]:
+
-- This uses the list of redshifts defined earlier.
@@ -3506,7 +3714,8 @@ Integrating \(f\)Integrating \(f\)
-In [24]:
+
+In [24]:
+
toRenderable (do
@@ -4466,13 +4677,17 @@ Converting to a physical distance
-To get a value with physical units, we multiply daH by c/\(H_0\), which, if the speed of light is in km/s and \(H_0\) in km/s/Mpc, will give a value in Megaparsecs:
+To get a value with physical units, we multiply daH by c/$H_0$, which,
+if the speed of light is in km/s and $H_0$ in km/s/Mpc, will give a value
+in Megaparsecs:
-In [25]:
+
+In [25]:
+
-- Calculate the angular-diameter distance for a flat Cosmology
@@ -4510,7 +4725,9 @@ Converting to a physical distance
-In [26]:
+
+In [26]:
+
map (da 0.3 70) [0, 0.5, 1.0, 1.2, 2.0]
@@ -4544,13 +4761,19 @@ Converting to a physical distance
-As a sanity check, I used Ned Wright's CosmoCalc calculator and recorded the distances for several redshifts. These are stored in the nedWrightDA list, and then I calculate the ratio of the distance I calculate to those from CosmoCalc (the rel list). As can be seen, the values are all close to 1.0.
+As a sanity check, I used Ned Wright's
+CosmoCalc calculator and recorded
+the distances for several redshifts. These are stored in the nedWrightDA list,
+and then I calculate the ratio of the distance I calculate to those from CosmoCalc
+(the rel list). As can be seen, the values are all close to 1.0.
-In [27]:
+
+In [27]:
+
nedWrightDA = [1259.0, 1651.8, 1710.5, 1726.3]
@@ -4602,17 +4825,20 @@ Converting to a physical distance
-The Python equivalent for calculating rel would be something like (where I have decided to use shorter variable names than above):
+The Python equivalent for calculating rel would be something like (where I have
+decided to use shorter variable names than above):
da = [da(0.3,70,z) for z in [0.5, 1, 1.2, 2]]
nw = [1259.0, 1651.8, 1710.5, 1726.3]
-rel = np.asarray(da) / np.asarray(nw)
-I can now repeat the previous plot, this time with physical units:
+rel = np.asarray(da) / np.asarray(nw)
+I can now repeat the previous plot, this time with physical units:
-In [28]:
+
+In [28]:
+
calcDA om = zip zs (map (da om 70) zs)
@@ -5493,13 +5719,19 @@ Calculating the separatio
-To get the linear distance between two points at the same redshift, separated by an angle of theta, we can use the small-angle approximation: convert the angle to radians and then multiply it by the angular-diameter distance. Astronomers use all kinds of funny units for angles; in this case I am assuming the input angle has units of arcminutes. As there are 60 arcminutes to a degree, the conversion to radians is just \(\pi / (180*60)\).
+To get the linear distance between two points at the same redshift, separated by an angle of theta,
+we can use the small-angle approximation: convert the angle to radians and then multiply it by the
+angular-diameter distance. Astronomers use all kinds of funny units for angles; in this case I
+am assuming the input angle has units of arcminutes. As there are 60 arcminutes to a degree, the
+conversion to radians is just $\pi / (180*60)$.
-In [29]:
+
+In [29]:
+
-- Given Omega_m, H_0 in km/s/Mpc, z, and an angle in arcminutes,
@@ -5523,13 +5755,18 @@ Calculating the separatio
-For a redshift of 2, with a closed cosmology and \(\Omega_m = 0.3\), the CosmoCalc calculator calculate a scale of 8.370 kiloparsecs per arcsec. How close do I get (given that one arcsec is 1/60 of an arcminute and I intentionally made adist return values in kpc):
+For a redshift of 2, with a closed cosmology and $\Omega_m = 0.3$, the
+CosmoCalc calculator calculate a scale of 8.370 kiloparsecs per arcsec. How close
+do I get (given that one arcsec is 1/60 of an arcminute and I intentionally made
+adist return values in kpc):
-In [30]:
+
+In [30]:
+
adist 0.3 70 2 (1/60)
@@ -5566,20 +5803,21 @@ Calculating the separatio
So, not bad agreement. As a reminder, the code I had to write to get this (stripping out all the non-essential bits, including niceties like type signatures and comments, from above) was:
f om z = let ol = 1 - om
in 1 / sqrt( (1+z)^2 * (1 + om*z) - (2+z) * ol * z )
-
+
daH om z = let fs = result (absolute 1.0e-6 (trap (f om) 0 z))
in fs / (1+z)
-
+
da om h0 z = daH om z * c / h0
where
c = 299792.458
-
+
adist om h0 z angle = 1000 * d * a
where
a = pi * angle / (180 * 60)
d = da om h0 z
-
-If I wanted to make this code usable I would spend some time thinking about whether it is worth defining types especially for the matter density, Hubble's constant, or redshift values, to clarify routines like adist which take four Double values and it is easy to mix them up - e.g. swapping om and h0 - leading to incorrect results. However, that's a discussion for another day.
+
If I wanted to make this code usable I would spend some time thinking about whether it is worth defining types
+especially for the matter density, Hubble's constant, or redshift values, to clarify routines like adist which take four Double values and it is easy to mix them up - e.g. swapping om and h0 - leading to incorrect results. However,
+that's a discussion for another day.
@@ -5598,21 +5836,46 @@ Adding units and quantities
-The above calculation is fine, but I'd like to explicitly include the units in the calculation, so that you know the answer is in Mpc (or some other unit). There are several Haskell packages that support this; I have previously used the dimensional package and there is also unittyped and quantities, but today I want to try the units package. As I have not tried out the support for quantities and units in astropy I do not provide Python equivalents for the rest of this notebook.
-Unfortunately, using ghc version 7.6.3 means that only the first version (1.0.0) of units can be used, which is a problem, since it doesn't build! So I decided to try out the dimensional-tf package, since it a different approach to the dimensional package, which I have used. The difference between the two is not really relevant here; we can just look at is as being one way to model quantities and units in a physical calculation in Haskell. I hope to have time to repeat this with a more-recent version of ghc so that I can try out units.
+The above calculation is fine, but I'd like to explicitly include the units in the calculation, so that
+you know the answer is in Mpc (or some other unit). There are several Haskell packages that
+support this; I have previously used the
+dimensional
+package and there is also
+unittyped
+and
+quantities, but today
+I want to try the units package.
+As I have not tried out the
+support for quantities and units in astropy
+I do not provide Python equivalents for the rest of this notebook.
+Unfortunately, using ghc version 7.6.3 means that only the first version (1.0.0) of units can
+be used, which is a problem, since it doesn't build! So I decided to try out the
+dimensional-tf
+package, since it a different approach to the dimensional package, which I have
+used. The difference between the two is not really relevant here; we can just look at
+is as being one way to model quantities and units in a physical calculation in Haskell.
+I hope to have time to repeat this with a more-recent version of ghc so that I can
+try out units.
To install the necessary package we need to use cabal again:
cabal install dimensional-tf --dry-run
... check that no problems are reported
cabal install dimensional-tf
... this should be relatively quick as there's not that many
-... dependencies that need to be built
-The following statement is similar to Python's import foo.bar.baz as bob statement; symbols defined by the module must be preceeded by the quaifier P. The reason for doing this is that this module provides versions of common mathematical operations - such as multiplication - which would conflict with the default versions. It will make it clear what version I am using, but is visually distracting, as you will soon see!
+... dependencies that need to be built
+The following statement is similar to Python's import foo.bar.baz as bob
+statement; symbols defined by the module must be preceeded by the quaifier
+P. The reason for doing this is that this module provides versions of
+common mathematical operations - such as multiplication - which would
+conflict with the default versions. It will make it clear what version
+I am using, but is visually distracting, as you will soon see!
-In [31]:
+
+In [31]:
+
import qualified Numeric.Units.Dimensional.TF.Prelude as P
@@ -5634,7 +5897,9 @@ Adding units and quantities
-In [32]:
+
+In [32]:
+
c = 299792458.0 P.*~ (P.meter P./ P.second)
@@ -5656,7 +5921,9 @@ Adding units and quantities
-In [33]:
+
+In [33]:
+
@@ -5689,13 +5954,16 @@ Adding units and quantities
-This can be fixed by giving an explicit type, as shown below (it's not actually necessary to do so, but I do so because I can):
+This can be fixed by giving an explicit type, as shown below (it's not actually necessary
+to do so, but I do so because I can):
-In [34]:
+
+In [34]:
+
c :: P.Velocity Double
@@ -5709,7 +5977,9 @@ Adding units and quantities
-In [35]:
+
+In [35]:
+
:type c
@@ -5740,15 +6010,42 @@ Adding units and quantities
-The type is now more readable, but in reality this is just a synonym for the original type (except that the Fractional constraint has been replaced by the use of an explicit type Double, which is a member of the Fractional type class). Although not relevant here - as I'm treating the module as something of a black box - the dimensions of the value are encoded here using Peano numbers, where Z indicates 0, S a is one more than a (so S Z is 1 and S (S (S Z)) is 3), and N a is used to negate a. The Dim statement from the original type of c can therefore be read as Dim 1 0 -1 0 0 0 0, so this suggests that the first element refers to length and the third refers to time. I believe the reason for using Peano numbers here is because they are inductively defined (the base case is 0 and the inductive step is add one), which means that the type checker can match up things as needed. One thing to note, if you've read this far into the paragraph, is that this information is only relevant when the code is compiled. This means that you only "pay" for the checking when you build the code (which can, unfortunately, take some time for particularly complex cases) rather than when you run it.
-More information on the API of the dimensional-tf package can be found in the source code to this module, as it uses a literate programming style which means that the comments do not get displayed in the standard module documentation. The main thing to note just now is that there are types for quantities - such as the speed of light in meters per second - and for units - such as second. These types are labelled Quantity or Unit and contain the relevant dimension information (the Dim type seen above) and the type of the numerical value (e.g. Double). Synonyms are used to make these more readable, such as Velocity meaning Quantity DVelocity and DVelocity being Dim (S Z) Z (N (S Z)) Z Z Z Z, which can sometimes be a bit confusing when you are trying to work out how everything fits together.
+The type is now more readable, but in reality this is just a synonym for the original type (except that the
+Fractional constraint has been replaced by the use of an explicit type Double, which is a member of the
+Fractional type class).
+Although not relevant here - as I'm treating the module as something of a black box - the
+dimensions of the value are encoded here using
+Peano numbers, where Z indicates 0, S a is one more than a (so
+S Z is 1 and S (S (S Z)) is 3),
+and N a is used to negate a. The Dim statement from the original type of c can therefore
+be read as Dim 1 0 -1 0 0 0 0, so this suggests that the first element refers to length and the third refers
+to time. I believe the reason for using Peano numbers here is because they are inductively defined (the base
+case is 0 and the inductive step is add one), which means that the type checker can match up things as needed.
+One thing to note, if you've read this far into the paragraph, is that this information is only relevant when
+the code is compiled. This means that you only "pay" for the checking when you build
+the code (which can, unfortunately, take some time for particularly complex cases) rather than when you run it.
+More information on the API of the dimensional-tf package
+can be found in the
+source code
+to this module, as it uses a literate programming style which means that the comments do not
+get displayed in the standard
+module documentation.
+The main thing to note just now is that there are types for quantities - such as the speed of light
+in meters per second - and for units - such as second. These types are labelled
+Quantity or Unit and contain the relevant dimension information (the Dim type seen above)
+and the type of the numerical value (e.g. Double). Synonyms are used to make these
+more readable, such as Velocity meaning Quantity DVelocity and
+DVelocity being Dim (S Z) Z (N (S Z)) Z Z Z Z, which can sometimes be a bit confusing
+when you are trying to work out how everything fits together.
The symbol c now retains both the quantity and the units, as displaying it shows:
-In [36]:
+
+In [36]:
+
c
@@ -5782,13 +6079,16 @@ Adding units and quantities
-The quantity stored in c can be extracted, converting to a given unit, using the /~ operator, as shown below (note that this is one point where the use of the P prefix is visually distracting):
+The quantity stored in c can be extracted, converting to a given unit, using the /~ operator,
+as shown below (note that this is one point where the use of the P prefix is visually distracting):
-In [37]:
+
+In [37]:
+
c P./~ (P.kilo P.meter P./ P.second)
@@ -5822,13 +6122,17 @@ Adding units and quantities
-Using it in a calculation is also somewhat unsatisfting, since you need to use the mathematical operators from the module - leading to visual clutter if you use the approach I have taken here - and the need to use constants such as P._2 to represent the value 2:
+Using it in a calculation is also somewhat unsatisfting, since you need to use the mathematical
+operators from the module - leading to visual clutter if you use the approach I have taken
+here - and the need to use constants such as P._2 to represent the value 2:
-In [38]:
+
+In [38]:
+
c P./ P._2
@@ -5862,13 +6166,16 @@ Adding units and quantities
-Alternatively, I can "convert" a value into a dimensionless number by using the form value *~ one (which is needed when there is no pre-defined constant):
+Alternatively, I can "convert" a value into a dimensionless number by using the form value *~ one (which is needed
+when there is no pre-defined constant):
-In [39]:
+
+In [39]:
+
c P./ (2 P.*~ P.one)
@@ -5902,13 +6209,16 @@ Adding units and quantities
-Here I define a symbol that represents one arcminute. The use of 1::Double is just to make sure that this is a Double value, rather than a more general one, in a similar manner to how c was defined.
+Here I define a symbol that represents one arcminute. The use of 1::Double is just to make sure that this is a Double
+value, rather than a more general one, in a similar manner to how c was defined.
-In [40]:
+
+In [40]:
+
arcmin = (1::Double) P.*~ P.minuteOfArc
@@ -5921,7 +6231,9 @@ Adding units and quantities
-In [41]:
+
+In [41]:
+
:type arcmin
@@ -5952,13 +6264,18 @@ Adding units and quantities
-One of the reasons for using a system which also encodes units is to make it an error for combining incompatible values; in this case trying to add together the speed of light and an angle is an error. Admittedly, a rather confusing one if you're not used to the Haskell type system.
+One of the reasons for using a system which also encodes units is to make it
+an error for combining incompatible values; in this case trying to add
+together the speed of light and an angle is an error. Admittedly, a
+rather confusing one if you're not used to the Haskell type system.
-In [42]:
+
+In [42]:
+
@@ -5989,13 +6306,15 @@ Adding units and quantities
-I guess that the "native" value for angles is radians, so let's check this:
+I guess that the "native" value for angles is radians, so let's check this:
-In [43]:
+
+In [43]:
+
arcmin
@@ -6035,7 +6354,9 @@ Adding units and quantities
-In [44]:
+
+In [44]:
+
pi / (60 * 180)
@@ -6069,13 +6390,16 @@ Adding units and quantities
-I can also check that the numerical values are equal directly, by using /~ radian to extract then numeric value from arcmin:
+I can also check that the numerical values are equal directly, by
+using /~ radian to extract then numeric value from arcmin:
-In [45]:
+
+In [45]:
+
arcmin P./~ P.radian == (pi / (60*180))
@@ -6109,13 +6433,16 @@ Adding units and quantities
-If I had not "converted" arcmin from a quantity to a standard value, using /~ radian, then I would have come across another rather frightening error message:
+If I had not "converted" arcmin from a quantity to a standard value, using /~ radian, then
+I would have come across another rather frightening error message:
-In [46]:
+
+In [46]:
+
@@ -6146,13 +6473,16 @@ Adding units and quantities
-I want to be able to handle lengths which contain parsecs, so I need to create a unit for this, using the prefix function:
+I want to be able to handle lengths which contain parsecs, so I need to create a unit
+for this, using the prefix function:
-In [47]:
+
+In [47]:
+
parsec :: P.Unit P.DLength Double
@@ -6175,7 +6505,9 @@ Adding units and quantities
-In [48]:
+
+In [48]:
+
3.2 P.*~ P.mega parsec
@@ -6215,7 +6547,9 @@ Adding units and quantities
-In [49]:
+
+In [49]:
+
-In [50]:
+
+In [50]:
+
-In [51]:
+
+In [51]:
+
70 P.*~ hubbleConstant
@@ -6307,7 +6651,9 @@ Adding units and quantities
-In [52]:
+
+In [52]:
+
:type 70 P.*~ hubbleConstant
@@ -6338,13 +6684,18 @@ Adding units and quantities
-Since I will want to use this type a few times below, I define an alias for it, using the type command. After this, I can use HConstant to simplify signatures of functions that take a Hubble constant as a parameter; I also add in a Length alias, since this will also come in useful.
+Since I will want to use this type a few times below, I define an alias for it, using the type
+command. After this, I can use HConstant to simplify signatures of functions that take
+a Hubble constant as a parameter; I also add in a Length alias, since this will also
+come in useful.
-In [53]:
+
+In [53]:
+
type HConstant = P.Quantity P.DFrequency Double
@@ -6361,23 +6712,24 @@ Adding units and quantities
-With these definitions I should now be able to replicate the angular-diameter calculation, but this time tracking the types as well. As a reminder, I want:
+With these definitions I should now be able to replicate the angular-diameter
+calculation, but this time tracking the types as well. As a reminder, I want:
f om z = let ol = 1 - om
in 1 / sqrt( (1+z)^2 * (1 + om*z) - (2+z) * ol * z )
-
+
daH om z = let fs = result (absolute 1.0e-6 (trap (f om) 0 z))
in fs / (1+z)
-
+
da om h0 z = daH om z * c / h0
where
c = 299792.458
-
+
adist om h0 z angle = 1000 * d * a
where
a = pi * angle / (180 * 60)
d = da om h0 z
-
-Since f and daH are dimensionless, I'll just re-use them and concentrate on da and adist.
+Since f and daH are dimensionless, I'll just re-use them and concentrate on
+da and adist.
@@ -6387,18 +6739,31 @@ Adding units and quantities
There are four main points in the conversion of da:
-
-I added a signature to ensure that the Hubble constant has the required units. This trades off generic behavior (accepting any quantity) against some measure of type safety (in the sense that I want to make sure the second argument has the units of Hubble's constant). The results below would not change if I did not give the signature.
-I have not had to convert c from m/s to km/s (or, equivalently, explictly convert the Hubble constant to account for the use of both km and Mpc).
-The value returned by daH is converted to a dimensionless quantity by "multiplying" it by one.
-The result does not look too different from the original form.
+
+I added a signature to ensure that the Hubble constant has the required
+units. This trades off generic behavior (accepting any quantity)
+against some measure of type safety (in the sense that I want to make
+sure the second argument has the units of Hubble's constant). The
+results below would not change if I did not give the signature.
+
+I have not had to convert c from m/s to km/s (or, equivalently,
+explictly convert the Hubble constant to account for the use of both
+km and Mpc).
+
+The value returned by daH is converted to a dimensionless quantity
+by "multiplying" it by one.
+
+The result does not look too different from the original form.
+
-In [54]:
+
+In [54]:
+
da2 :: Double -> HConstant -> Double -> Length
@@ -6421,7 +6786,9 @@ Adding units and quantities
-In [55]:
+
+In [55]:
+
adist2 om h0 z angle = da2 om h0 z P.* angle
@@ -6437,13 +6804,18 @@ Adding units and quantities
-Since I did not give a type signature, the inferred version does not require that the angle be dimensionless (shown by the fact that d', which represents the dimensions of the value, is listed as forall rather than being an explicit value):
+Since I did not give a type signature, the inferred version does not
+require that the angle be dimensionless (shown by the fact that d',
+which represents the dimensions of the value,
+is listed as forall rather than being an explicit value):
-In [56]:
+
+In [56]:
+
@@ -6485,7 +6852,9 @@ Adding units and quantities
-In [57]:
+
+In [57]:
+
adist3 :: Double -> HConstant -> Double -> P.Quantity P.DPlaneAngle Double -> Length
@@ -6502,13 +6871,17 @@ Adding units and quantities
-The difference in type signatures can be seen if I give a non-angle value for the last argument: the adist2 form returns a value whereas the adist3 version raises an error:
+The difference in type signatures can be seen if I give a non-angle value for the
+last argument: the adist2 form returns a value whereas the adist3
+version raises an error:
-In [58]:
+
+In [58]:
+
adist2 0.3 (70 P.*~ hubbleConstant) 2 (1 P.*~ P.meter)
@@ -6539,7 +6912,9 @@ Adding units and quantities
-In [59]:
+
+In [59]:
+
adist3 0.3 (70 P.*~ hubbleConstant) 2 (1 P.*~ P.meter)
@@ -6556,7 +6931,7 @@ Adding units and quantities
@@ -6571,13 +6946,16 @@ Adding units and quantities
With this, I can repeat the earlier calculation, which gave
-adist 0.3 70 2 (1/60) = 8.370893333112804
+adist 0.3 70 2 (1/60) = 8.370893333112804
+
-In [60]:
+
+In [60]:
+
adist3 0.3 (70 P.*~ hubbleConstant) 2 (1 P.*~ P.secondOfArc)
@@ -6617,7 +6995,9 @@ Adding units and quantities
-In [61]:
+
+In [61]:
+
adist3 0.3 (70 P.*~ hubbleConstant) 2 (1 P.*~ P.secondOfArc) P./~ P.kilo parsec
@@ -6651,13 +7031,16 @@ Adding units and quantities
-It is easy to change units, such as to use an angle in arcminutes and to convert the answer to Mpc:
+It is easy to change units, such as to use an angle in arcminutes and to convert
+the answer to Mpc: