<!--{{{-->
<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml'/>
<!--}}}-->
Background: #fff
Foreground: #000
PrimaryPale: #8cf
PrimaryLight: #18f
PrimaryMid: #04b
PrimaryDark: #014
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
/*{{{*/
body {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}

a {color:[[ColorPalette::PrimaryMid]];}
a:hover {background-color:[[ColorPalette::PrimaryMid]]; color:[[ColorPalette::Background]];}
a img {border:0;}

h1,h2,h3,h4,h5,h6 {color:[[ColorPalette::SecondaryDark]]; background:transparent;}
h1 {border-bottom:2px solid [[ColorPalette::TertiaryLight]];}
h2,h3 {border-bottom:1px solid [[ColorPalette::TertiaryLight]];}

.button {color:[[ColorPalette::PrimaryDark]]; border:1px solid [[ColorPalette::Background]];}
.button:hover {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::SecondaryLight]]; border-color:[[ColorPalette::SecondaryMid]];}
.button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::SecondaryDark]];}

.header {background:[[ColorPalette::PrimaryMid]];}
.headerShadow {color:[[ColorPalette::Foreground]];}
.headerShadow a {font-weight:normal; color:[[ColorPalette::Foreground]];}
.headerForeground {color:[[ColorPalette::Background]];}
.headerForeground a {font-weight:normal; color:[[ColorPalette::PrimaryPale]];}

.tabSelected{color:[[ColorPalette::PrimaryDark]];
	background:[[ColorPalette::TertiaryPale]];
	border-left:1px solid [[ColorPalette::TertiaryLight]];
	border-top:1px solid [[ColorPalette::TertiaryLight]];
	border-right:1px solid [[ColorPalette::TertiaryLight]];
}
.tabUnselected {color:[[ColorPalette::Background]]; background:[[ColorPalette::TertiaryMid]];}
.tabContents {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::TertiaryPale]]; border:1px solid [[ColorPalette::TertiaryLight]];}
.tabContents .button {border:0;}

#sidebar {}
#sidebarOptions input {border:1px solid [[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel {background:[[ColorPalette::PrimaryPale]];}
#sidebarOptions .sliderPanel a {border:none;color:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:hover {color:[[ColorPalette::Background]]; background:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:active {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::Background]];}

.wizard {background:[[ColorPalette::PrimaryPale]]; border:1px solid [[ColorPalette::PrimaryMid]];}
.wizard h1 {color:[[ColorPalette::PrimaryDark]]; border:none;}
.wizard h2 {color:[[ColorPalette::Foreground]]; border:none;}
.wizardStep {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];
	border:1px solid [[ColorPalette::PrimaryMid]];}
.wizardStep.wizardStepDone {background:[[ColorPalette::TertiaryLight]];}
.wizardFooter {background:[[ColorPalette::PrimaryPale]];}
.wizardFooter .status {background:[[ColorPalette::PrimaryDark]]; color:[[ColorPalette::Background]];}
.wizard .button {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryLight]]; border: 1px solid;
	border-color:[[ColorPalette::SecondaryPale]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryPale]];}
.wizard .button:hover {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Background]];}
.wizard .button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::Foreground]]; border: 1px solid;
	border-color:[[ColorPalette::PrimaryDark]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryDark]];}

#messageArea {border:1px solid [[ColorPalette::SecondaryMid]]; background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]];}
#messageArea .button {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::SecondaryPale]]; border:none;}

.popupTiddler {background:[[ColorPalette::TertiaryPale]]; border:2px solid [[ColorPalette::TertiaryMid]];}

.popup {background:[[ColorPalette::TertiaryPale]]; color:[[ColorPalette::TertiaryDark]]; border-left:1px solid [[ColorPalette::TertiaryMid]]; border-top:1px solid [[ColorPalette::TertiaryMid]]; border-right:2px solid [[ColorPalette::TertiaryDark]]; border-bottom:2px solid [[ColorPalette::TertiaryDark]];}
.popup hr {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::PrimaryDark]]; border-bottom:1px;}
.popup li.disabled {color:[[ColorPalette::TertiaryMid]];}
.popup li a, .popup li a:visited {color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:active {background:[[ColorPalette::SecondaryPale]]; color:[[ColorPalette::Foreground]]; border: none;}
.popupHighlight {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
.listBreak div {border-bottom:1px solid [[ColorPalette::TertiaryDark]];}

.tiddler .defaultCommand {font-weight:bold;}

.shadow .title {color:[[ColorPalette::TertiaryDark]];}

.title {color:[[ColorPalette::SecondaryDark]];}
.subtitle {color:[[ColorPalette::TertiaryDark]];}

.toolbar {color:[[ColorPalette::PrimaryMid]];}
.toolbar a {color:[[ColorPalette::TertiaryLight]];}
.selected .toolbar a {color:[[ColorPalette::TertiaryMid]];}
.selected .toolbar a:hover {color:[[ColorPalette::Foreground]];}

.tagging, .tagged {border:1px solid [[ColorPalette::TertiaryPale]]; background-color:[[ColorPalette::TertiaryPale]];}
.selected .tagging, .selected .tagged {background-color:[[ColorPalette::TertiaryLight]]; border:1px solid [[ColorPalette::TertiaryMid]];}
.tagging .listTitle, .tagged .listTitle {color:[[ColorPalette::PrimaryDark]];}
.tagging .button, .tagged .button {border:none;}

.footer {color:[[ColorPalette::TertiaryLight]];}
.selected .footer {color:[[ColorPalette::TertiaryMid]];}

.sparkline {background:[[ColorPalette::PrimaryPale]]; border:0;}
.sparktick {background:[[ColorPalette::PrimaryDark]];}

.error, .errorButton {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Error]];}
.warning {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryPale]];}
.lowlight {background:[[ColorPalette::TertiaryLight]];}

.zoomer {background:none; color:[[ColorPalette::TertiaryMid]]; border:3px solid [[ColorPalette::TertiaryMid]];}

.imageLink, #displayArea .imageLink {background:transparent;}

.annotation {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border:2px solid [[ColorPalette::SecondaryMid]];}

.viewer .listTitle {list-style-type:none; margin-left:-2em;}
.viewer .button {border:1px solid [[ColorPalette::SecondaryMid]];}
.viewer blockquote {border-left:3px solid [[ColorPalette::TertiaryDark]];}

.viewer table, table.twtable {border:2px solid [[ColorPalette::TertiaryDark]];}
.viewer th, .viewer thead td, .twtable th, .twtable thead td {background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::Background]];}
.viewer td, .viewer tr, .twtable td, .twtable tr {border:1px solid [[ColorPalette::TertiaryDark]];}

.viewer pre {border:1px solid [[ColorPalette::SecondaryLight]]; background:[[ColorPalette::SecondaryPale]];}
.viewer code {color:[[ColorPalette::SecondaryDark]];}
.viewer hr {border:0; border-top:dashed 1px [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::TertiaryDark]];}

.highlight, .marked {background:[[ColorPalette::SecondaryLight]];}

.editor input {border:1px solid [[ColorPalette::PrimaryMid]];}
.editor textarea {border:1px solid [[ColorPalette::PrimaryMid]]; width:100%;}
.editorFooter {color:[[ColorPalette::TertiaryMid]];}

#backstageArea {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::TertiaryMid]];}
#backstageArea a {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstageArea a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; }
#backstageArea a.backstageSelTab {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
#backstageButton a {background:none; color:[[ColorPalette::Background]]; border:none;}
#backstageButton a:hover {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstagePanel {background:[[ColorPalette::Background]]; border-color: [[ColorPalette::Background]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]];}
.backstagePanelFooter .button {border:none; color:[[ColorPalette::Background]];}
.backstagePanelFooter .button:hover {color:[[ColorPalette::Foreground]];}
#backstageCloak {background:[[ColorPalette::Foreground]]; opacity:0.6; filter:'alpha(opacity:60)';}
/*}}}*/
/*{{{*/
* html .tiddler {height:1%;}

body {font-size:.75em; font-family:arial,helvetica; margin:0; padding:0;}

h1,h2,h3,h4,h5,h6 {font-weight:bold; text-decoration:none;}
h1,h2,h3 {padding-bottom:1px; margin-top:1.2em;margin-bottom:0.3em;}
h4,h5,h6 {margin-top:1em;}
h1 {font-size:1.35em;}
h2 {font-size:1.25em;}
h3 {font-size:1.1em;}
h4 {font-size:1em;}
h5 {font-size:.9em;}

hr {height:1px;}

a {text-decoration:none;}

dt {font-weight:bold;}

ol {list-style-type:decimal;}
ol ol {list-style-type:lower-alpha;}
ol ol ol {list-style-type:lower-roman;}
ol ol ol ol {list-style-type:decimal;}
ol ol ol ol ol {list-style-type:lower-alpha;}
ol ol ol ol ol ol {list-style-type:lower-roman;}
ol ol ol ol ol ol ol {list-style-type:decimal;}

.txtOptionInput {width:11em;}

#contentWrapper .chkOptionInput {border:0;}

.externalLink {text-decoration:underline;}

.indent {margin-left:3em;}
.outdent {margin-left:3em; text-indent:-3em;}
code.escaped {white-space:nowrap;}

.tiddlyLinkExisting {font-weight:bold;}
.tiddlyLinkNonExisting {font-style:italic;}

/* the 'a' is required for IE, otherwise it renders the whole tiddler in bold */
a.tiddlyLinkNonExisting.shadow {font-weight:bold;}

#mainMenu .tiddlyLinkExisting,
	#mainMenu .tiddlyLinkNonExisting,
	#sidebarTabs .tiddlyLinkNonExisting {font-weight:normal; font-style:normal;}
#sidebarTabs .tiddlyLinkExisting {font-weight:bold; font-style:normal;}

.header {position:relative;}
.header a:hover {background:transparent;}
.headerShadow {position:relative; padding:4.5em 0em 1em 1em; left:-1px; top:-1px;}
.headerForeground {position:absolute; padding:4.5em 0em 1em 1em; left:0px; top:0px;}

.siteTitle {font-size:3em;}
.siteSubtitle {font-size:1.2em;}

#mainMenu {position:absolute; left:0; width:10em; text-align:right; line-height:1.6em; padding:1.5em 0.5em 0.5em 0.5em; font-size:1.1em;}

#sidebar {position:absolute; right:3px; width:16em; font-size:.9em;}
#sidebarOptions {padding-top:0.3em;}
#sidebarOptions a {margin:0em 0.2em; padding:0.2em 0.3em; display:block;}
#sidebarOptions input {margin:0.4em 0.5em;}
#sidebarOptions .sliderPanel {margin-left:1em; padding:0.5em; font-size:.85em;}
#sidebarOptions .sliderPanel a {font-weight:bold; display:inline; padding:0;}
#sidebarOptions .sliderPanel input {margin:0 0 .3em 0;}
#sidebarTabs .tabContents {width:15em; overflow:hidden;}

.wizard {padding:0.1em 1em 0em 2em;}
.wizard h1 {font-size:2em; font-weight:bold; background:none; padding:0em 0em 0em 0em; margin:0.4em 0em 0.2em 0em;}
.wizard h2 {font-size:1.2em; font-weight:bold; background:none; padding:0em 0em 0em 0em; margin:0.4em 0em 0.2em 0em;}
.wizardStep {padding:1em 1em 1em 1em;}
.wizard .button {margin:0.5em 0em 0em 0em; font-size:1.2em;}
.wizardFooter {padding:0.8em 0.4em 0.8em 0em;}
.wizardFooter .status {padding:0em 0.4em 0em 0.4em; margin-left:1em;}
.wizard .button {padding:0.1em 0.2em 0.1em 0.2em;}

#messageArea {position:fixed; top:2em; right:0em; margin:0.5em; padding:0.5em; z-index:2000; _position:absolute;}
.messageToolbar {display:block; text-align:right; padding:0.2em 0.2em 0.2em 0.2em;}
#messageArea a {text-decoration:underline;}

.tiddlerPopupButton {padding:0.2em 0.2em 0.2em 0.2em;}
.popupTiddler {position: absolute; z-index:300; padding:1em 1em 1em 1em; margin:0;}

.popup {position:absolute; z-index:300; font-size:.9em; padding:0; list-style:none; margin:0;}
.popup .popupMessage {padding:0.4em;}
.popup hr {display:block; height:1px; width:auto; padding:0; margin:0.2em 0em;}
.popup li.disabled {padding:0.4em;}
.popup li a {display:block; padding:0.4em; font-weight:normal; cursor:pointer;}
.listBreak {font-size:1px; line-height:1px;}
.listBreak div {margin:2px 0;}

.tabset {padding:1em 0em 0em 0.5em;}
.tab {margin:0em 0em 0em 0.25em; padding:2px;}
.tabContents {padding:0.5em;}
.tabContents ul, .tabContents ol {margin:0; padding:0;}
.txtMainTab .tabContents li {list-style:none;}
.tabContents li.listLink { margin-left:.75em;}

#contentWrapper {display:block;}
#splashScreen {display:none;}

#displayArea {margin:1em 17em 0em 14em;}

.toolbar {text-align:right; font-size:.9em;}

.tiddler {padding:1em 1em 0em 1em;}

.missing .viewer,.missing .title {font-style:italic;}

.title {font-size:1.6em; font-weight:bold;}

.missing .subtitle {display:none;}
.subtitle {font-size:1.1em;}

.tiddler .button {padding:0.2em 0.4em;}

.tagging {margin:0.5em 0.5em 0.5em 0; float:left; display:none;}
.isTag .tagging {display:block;}
.tagged {margin:0.5em; float:right;}
.tagging, .tagged {font-size:0.9em; padding:0.25em;}
.tagging ul, .tagged ul {list-style:none; margin:0.25em; padding:0;}
.tagClear {clear:both;}

.footer {font-size:.9em;}
.footer li {display:inline;}

.annotation {padding:0.5em; margin:0.5em;}

* html .viewer pre {width:99%; padding:0 0 1em 0;}
.viewer {line-height:1.4em; padding-top:0.5em;}
.viewer .button {margin:0em 0.25em; padding:0em 0.25em;}
.viewer blockquote {line-height:1.5em; padding-left:0.8em;margin-left:2.5em;}
.viewer ul, .viewer ol {margin-left:0.5em; padding-left:1.5em;}

.viewer table, table.twtable {border-collapse:collapse; margin:0.8em 1.0em;}
.viewer th, .viewer td, .viewer tr,.viewer caption,.twtable th, .twtable td, .twtable tr,.twtable caption {padding:3px;}
table.listView {font-size:0.85em; margin:0.8em 1.0em;}
table.listView th, table.listView td, table.listView tr {padding:0px 3px 0px 3px;}

.viewer pre {padding:0.5em; margin-left:0.5em; font-size:1.2em; line-height:1.4em; overflow:auto;}
.viewer code {font-size:1.2em; line-height:1.4em;}

.editor {font-size:1.1em;}
.editor input, .editor textarea {display:block; width:100%; font:inherit;}
.editorFooter {padding:0.25em 0em; font-size:.9em;}
.editorFooter .button {padding-top:0px; padding-bottom:0px;}

.fieldsetFix {border:0; padding:0; margin:1px 0px 1px 0px;}

.sparkline {line-height:1em;}
.sparktick {outline:0;}

.zoomer {font-size:1.1em; position:absolute; overflow:hidden;}
.zoomer div {padding:1em;}

* html #backstage {width:99%;}
* html #backstageArea {width:99%;}
#backstageArea {display:none; position:relative; overflow: hidden; z-index:150; padding:0.3em 0.5em 0.3em 0.5em;}
#backstageToolbar {position:relative;}
#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em 0.3em 0.5em;}
#backstageButton {display:none; position:absolute; z-index:175; top:0em; right:0em;}
#backstageButton a {padding:0.1em 0.4em 0.1em 0.4em; margin:0.1em 0.1em 0.1em 0.1em;}
#backstage {position:relative; width:100%; z-index:50;}
#backstagePanel {display:none; z-index:100; position:absolute; margin:0em 3em 0em 3em; padding:1em 1em 1em 1em;}
.backstagePanelFooter {padding-top:0.2em; float:right;}
.backstagePanelFooter a {padding:0.2em 0.4em 0.2em 0.4em;}
#backstageCloak {display:none; z-index:20; position:absolute; width:100%; height:100px;}

.whenBackstage {display:none;}
.backstageVisible .whenBackstage {display:block;}
/*}}}*/
/***
StyleSheet for use when a translation requires any css style changes.
This StyleSheet can be used directly by languages such as Chinese, Japanese and Korean which need larger font sizes.
***/
/*{{{*/
body {font-size:0.8em;}
#sidebarOptions {font-size:1.05em;}
#sidebarOptions a {font-style:normal;}
#sidebarOptions .sliderPanel {font-size:0.95em;}
.subtitle {font-size:0.8em;}
.viewer table.listView {font-size:0.95em;}
/*}}}*/
/*{{{*/
@media print {
#mainMenu, #sidebar, #messageArea, .toolbar, #backstageButton, #backstageArea {display: none ! important;}
#displayArea {margin: 1em 1em 0em 1em;}
/* Fixes a feature in Firefox 1.5.0.2 where print preview displays the noscript content */
noscript {display:none;}
}
/*}}}*/
<!--{{{-->
<div class='header' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'>
<div class='headerShadow'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
<div class='headerForeground'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
</div>
<div id='mainMenu' refresh='content' tiddler='MainMenu'></div>
<div id='sidebar'>
<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>
<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='title' macro='view title'></div>
<div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='tagging' macro='tagging'></div>
<div class='tagged' macro='tags'></div>
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
<!--{{{-->
<div class='toolbar' macro='toolbar +saveTiddler -cancelTiddler deleteTiddler'></div>
<div class='title' macro='view title'></div>
<div class='editor' macro='edit title'></div>
<div macro='annotations'></div>
<div class='editor' macro='edit text'></div>
<div class='editor' macro='edit tags'></div><div class='editorFooter'><span macro='message views.editor.tagPrompt'></span><span macro='tagChooser'></span></div>
<!--}}}-->
To get started with this blank TiddlyWiki, you'll need to modify the following tiddlers:
* SiteTitle & SiteSubtitle: The title and subtitle of the site, as shown above (after saving, they will also appear in the browser title bar)
* MainMenu: The menu (usually on the left)
* DefaultTiddlers: Contains the names of the tiddlers that you want to appear when the TiddlyWiki is opened
You'll also need to enter your username for signing your edits: <<option txtUserName>>
These InterfaceOptions for customising TiddlyWiki are saved in your browser

Your username for signing your edits. Write it as a WikiWord (eg JoeBloggs)

<<option txtUserName>>
<<option chkSaveBackups>> SaveBackups
<<option chkAutoSave>> AutoSave
<<option chkRegExpSearch>> RegExpSearch
<<option chkCaseSensitiveSearch>> CaseSensitiveSearch
<<option chkAnimate>> EnableAnimations

----
Also see AdvancedOptions
<<importTiddlers>>
*Stephan's Law:
**Black body distribution, <<tex 'B_{\nu}(T)'>>;
**Spectral radiance, <<tex 'L_{\nu}'>>: The power per unit area, per unit solid angle, per unit frequency;
**Irradiance, <<tex 'I_{\nu}'>>: Radiance over on hemisphere;
**Stephan's law: from integrating irradiance over wavelengths, gives an //energy flux// power per unit area emitted by a black body:
><<tex '\displaystyle{\int_{\Theta = 0}^{\pi}} \displaystyle{\int_{\phi = 0}^{\pi / 2}} \displaystyle{\int_{\lambda = 0}^{\infty}} B_{\lambda} (T) d \lambda = F_{BB} = \sigma T^4'>>
*The maximum of <<tex 'B_{\lambda}(T)'>> follows ''Wien's law'':
><<tex '\lambda_{MAX} = \dfrac{hc}{4.96 k T}'>>

*X-ray diffraction seen as x-rays reflecting off lattice planes:
[img[Bragg Diffraction|images/1211305450.png]]
*Extra path difference travelled by subsequent rays: <<tex '2d \sin \theta'>>
*Constructive interference if <<tex '2d \sin \theta = n \lambda'>>, or more conveniently:
><<tex '\lambda = 2 d_{hkl} \sin \theta'>>
*Here higher orders (<<tex 'n > 1'>>) are accommodated for by using multiples of miller indices <<tex 'hkl'>>.
*e.g. <<tex 'n=2'>> reflection from <<tex '(110)'>> planes is equivalent to <<tex 'n=1'>> reflection from <<tex '(220)'>> planes (the <<tex '(220)'>> planes have half the spacing).
*''Systematic Absence'' (missing orders):
**Due to use of non-primitive unit cell.
**E.g:
***reflection off <<tex '(100)'>> planes of a BCC unit cell will be destructively interfered by planes of the central points mid way between the <<tex '(100)'>> planes.
***reflection off <<tex '(110)'>> planes of a FCC unit cell will be destructively interfered by planes of the face points mid way between the <<tex '(110)'>> planes.

*The composition of dry (molar mass <<tex '\sim 29 \textrm{g mol}^{-1}'>>) is as follows
**78% Nitrogen (<<tex 'N_2'>>);
**21% Oxygen (<<tex 'O_2'>>);
**0.5% Water Vapour (<<tex 'H_2 0'>>);
**< 0.1% Other
*Main diatomic constituents don't absorb strongly in visible or infra red (something about dipole moments);
*Tri atomic molecules absorb IR strongly but water vapour also weakly in the visible;
*At atmospheric pressures and temperatures, ideal gas behaviours are observed (due to lack of phase changes).
*Vorticity is the curl of the velocity vector field:
><<tex '\boldsymbol{\omega}(\textbf{r}, t) = \nabla \times \textbf{u}(\textbf{r}, t)'>>
*Measure of local 'spin' or 'rotation'.
*Binding energy:
><<tex 'Q(Z,N) = [ZM_p + NM_n - M(Z,N)]c^2 '>>
*Energy release:
**<<tex '4 \textrm{H} \rightarrow {}^4\textrm{He}, \epsilon = 0.007'>>
**<<tex '56 \textrm{H} \rightarrow {}^{56}\textrm{He}, \epsilon = 0.0084'>>
**Iron is the most stable configuration, but most of the energy is released from <<tex '4 \textrm{H} \rightarrow {}^4\textrm{He}'>>
*Newtonian gravitational force and potential energy given by:
><<tex 'F = -G \dfrac{M m}{r^2}'>>
>
><<tex 'U = -G \dfrac{M m}{r}'>>
*Notes:
**1. Force within a spherically symmetric cavity due to gravity is zero;
**2. The force due to a spherically symmetric concentration of matter is equivalent to that of a point source at the origin with the total mass.

*Smooth distribution, density <<tex '\rho'>>;
*Choose arbitrary sphere radius <<tex 'r'>> within it, with mass <<tex 'M = \frac{4}{3} \rho \pi r^3'>>. Due to note 1, can ignore everything outside;
><<tex 'V = - \frac{4}{3} \pi G m r^2'>>
>
><<tex 'K = \frac{1}{2} m \dot{r}^2'>>
*<<tex 'E_{\textrm{tot}} = K + V'>> so:
><<tex '\dot{r}^2 - \dfrac{8 \pi G}{3} \rho r^2 = \dfrac{2 E_{\textrm{tot}}}{m}'>>
*Using <<tex 'r = a x, \dot{r} = \dot{a} x'>>:
><<tex '\left( \dfrac{\dot{a}}{a} \right)^2 - \dfrac{8 \pi G}{3} \rho = \dfrac{2 E_{\textrm{tot}}}{mx^2} \dfrac{1}{a^2}'>>
*Defining <<tex '-kc^2 \equiv 2 E_{\textrm{tot}} / (m x^2)'>>:
><<tex 'H = \left( \dfrac{\dot{a}}{a} \right)^2 = \dfrac{8 \pi G}{3} \rho - \dfrac{k c^2}{a^2}'>>
*This is the Friedmann equation, or ~Friedmann-Robertson-Walker equation (FRW).
* ''Fermi Energy'': The energy of the state occupied by the highest energy electron in the metal at absolute zero, due to the Pauli Exclusion Principle.
* ''Fermi Temperature'': The temperature relating to the Fermi energy, <<tex 'T_F = E_F / k_B'>>.
* ''Fermi Surface'': The surface of constant energy in k-space that exists at the Fermi energy. Using <<tex 'E = \frac{\hbar^2 k^2}{2m}'>>, we have<<tex '|k_F| = \sqrt{2 m E_F} / \hbar'>> where <<tex '|k_F|'>> is the radius of the Fermi sphere.
* The Fermi surface takes up the volume of <<tex '1/2'>> of 1 Brillouin zone.
*Most stars are in binary or multiple systems;
*Orbital period can range from 11mins to <<tex '10^6'>> years;
*Binary systems have stars far apart which don't interact much;
*Close binaries (~ less than 10 year period) can transfer mass altering their structures;
*Large range of eccentricities of orbits.
*Homogeneous broadening affects all atoms in a sample equally, and all atoms will interact with a radiation beam of specific frequency with the same strength. Examples listed below.
*Inhomogeneous broadening affects different atoms in a sample by different amounts, e.g. Doppler broadening - as not all atoms have the same velocity (velocity distribution given by ~Maxwell-Boltzmann), not all atoms will be Doppler broadened by the same amount.
*The radiative lifetime of an excited atom decays exponentially, according to:
><<tex 'N_k(t) = N_k(0) e^{-t/\tau_\kappa^{rad}'>>
where 
><<tex '\gamma = \dfrac{1}{\tau_\kappa^{rad}} = \displaystyle\sum_{E_i < E_k} A_{ki}'>>
>
>(the sum of all the Einstein A coefficients for levels below the current level - i.e. spontaneous emission).
*''Lifetime (or Natural) Broadening'':
**As energy is related to time by the uncertainty principle, <<tex '\Delta E \Delta t \simeq \hbar'>>, a range of energies will be produced due to the finite lifetime of the atom.
**Alternatively, as the electron in the atom is modelled as a damped oscillator, and the frequency distribution is the FT of this oscillation, as the oscillation is damped and not purely harmonic, its FT will give a range of frequencies.
**The FWHM of the line distribution, which is given by a Lorentzian distribution, is:
><<tex '\Delta \omega_N = \gamma'>>
*''Pressure Broadening'':
**This model assumes, that collisions with other atoms in the gas causes a radiating electron to stop radiating;
**This effectively further shortens the radiative natural lifetime of the decay, and broadens the frequency spectrum further.
**The characteristic timescale will be the mean time between collisions, <<tex '\tau_c'>> and we get the expression:
><<tex '\Delta \omega_p = \gamma + \dfrac{2}{\tau_c}'>>
*''Thermal or Phonon Broadening'':
**The energy levels of an atom in a crystal lattice depends on the positions of the neighbouring atoms. Thermal fluctuations change this distance, and cause a rich energy level structure that gives a broadened appearence.
*(Aside: Phonon excitation does not result in emission or absorption of a photon, so population inversion can be helped by exciting atoms to higher states through specific frequency optic phonon absorption - this can be useful in building a laser system.)
*The sky is dark:
**Assume all stars have a luminosity L, and brightness <<tex 'B = L / (4 \pi r^2)'>>;
**Number density of stars <<tex 'n = N/V'>>;
**Gives <<tex 'dN = 4 \pi r^2 n dr'>> for number of stars in a shell;
**Brightness <<tex 'dB = BdN'>>:
><<tex 'B_{\textrm{tot}} = \int_0^{\infty} \dfrac{L}{4 \pi r^2} 4 \pi r^2 n dr = \infty'>>
**So there must be a cutoff: galaxies are moving away from us.
*Can calculate distance to a star, and relative speed by various methods e.g doppler shift of spectral lines
*Hubble measured distances to different galaxies and their velocities, obtained ''Hubble's Law'':
><<tex 'v = H_0 r'>>
*<<tex 'H_0 = 67 \textrm{km s}^{-1} \textrm{Mpc}^{-1}}'>> is Hubble's constant.
*Hubbles law can also be written in terms of coordinates:
**Can write //physical coordinates// <<tex '\textbf{r}(t) = a(t)\textbf{x}'>>, where <<tex '\textbf{x}'>> are //conformal// (fixed in time) coordinates.
**Now:
><<tex '\textbf{v} = \dfrac{d \textbf{r}}{dt} = \dfrac{d (a \textbf{x})}{dt} = \dot{a} \textbf{x} = \dfrac{\dot{a}}{a} \textbf{r} \equiv H \textbf{r}'>>
*Classically, the heat capacity is <<tex 'C = 3 N k_B'>>, and this is independent of temperature. However, this is not actually the case.
*Summing over all modes, where 's' is the branch index, i.e the different optic/acoustic branches etc.
><<tex '\langle E \rangle = \displaystyle\sum_{\mathbf{k}, \mathbf{s}} (n_s (k) + \frac{1}{2}) \hbar \omega_s(k)'>> 
*For a simplification, can replace the sum with an integral with the density of states, and <<tex 'n_s(k)'>> is replaced by the Planck distribution:
><<tex '\Rightarrow C = \dfrac{\partial}{\partial T} \displaystyle\int_0^\infty \dfrac{\hbar \omega}{e^{\beta \hbar \omega} - 1} g(\omega) d \omega'>>
*The density of states:
**<<tex 'g(\omega) d \omega'>> = The number of modes in an interval <<tex '\omega \rightarrow \omega + d \omega'>> or similarly, <<tex 'k \rightarrow k + dk'>>.
**<<tex 'g(\omega) d \omega \rightarrow \dfrac{V}{(2 \pi)^3} 4 \pi k^2 dk'>> in 3D.
*For p degenerate brances, <<tex 'g(\omega) d \omega = p g(k) dk'>>


*Can measure ''redshift'' by:
**Doppler shift of spectral lines;
*Can measure distance by:
**Parallax, <<tex 'D = 1 / \alpha'>>;
**Luminosity and brightness comparison: <<tex 'B = L / (4 \pi D^2)'>>, Luminosity from:
***Colour relates to temperature (black body spectra);
***Temperature relates to Luminosity via radius;
***Spectroscopic parallax (up to 10kpc):
****Radius can be inferred from broadness of spectral lines - broader lines, smaller radius.
***Cephid variables (up to 30Mpc):
****Very luminous (<<tex 'L \sim 100 \rightarrow 1000 L_{\odot}'>>), can be seen v far away;
****Luminosity intrinsic to period of brightness oscillations;
****Period of only a few days, easily measurable.
***~Tully-Fisher relation (up to 100Mpc):
****21cm line of Hydrogen doppler shifted by rotating galaxy;
****Rotation of galaxy linked to mass of galaxy;
****More massive galaxy - more stars - more luminous. 
****Therefore line broadening relates to luminosity.
***Supernovae (up to 1000Mpc):
****<<tex '10^9 L_{\odot}'>>;
****Luminosity can be known as above, distance from brightness (inverse square law);
****Type <<tex I_a>> - Luminosity related to time it takes to fade after explosion, formed from white dwarf collapse.
*Electron travelling through a solid, <<tex '\psi = e^{ixk}'>>, is Bragg scattered by the crystal potential, by a wave vector <<tex 'G'>>, where <<tex '|G| = 2 \pi / a'>>. This shifts the wavefunction by 1 BZ in whichever direction.
*The crystal potential is periodic, so can be Fourier transformed. The potential wells can also be quite complicated mathematically, <<tex 'V(x) = \sum _G V_G e^{iGx}'>>, so we look at a single Fourier component, which gives a good approximation: <<tex 'V(x) = V_G (e^{iGx} + e^{-iGx})'>>.
*Next we use the Schrodinger equation,
><<tex 'H \psi = - \dfrac{\hbar^2}{2m} \dfrac{\partial^2 \psi}{\partial x^2} + V(x) \psi = E \psi'>>
*Inserting <<tex '\psi = e^{ikx}'>> reveals it is no longer a solution due to the "cross terms" from <<tex 'V(x)'>>.
*Instead we can solve with <<tex "\psi = A_k e^{ikx} + B_{k'} e^{ik'x}">>, where <<tex "k' = k -G">>, i.e. a superposition of the before and after states:
><<tex "H \psi = \dfrac{\hbar^2 k^2}{2m} A e^{ikx} + \dfrac{\hbar^2 k'^2}{2m} B e^{ik'x} + V_G[A e^{i(k \pm G)} + B e^{i(k' \pm G)}]">>
>
><<tex "H \psi = E ( A e^{ikx} + B e^{ik'x} )">>
*Multiply by <<tex "e^{-ikx}">> and integrate from 0 to L, to obtain <<tex 'EA = \frac{\hbar^2 k^2}{2m} A + V_G B'>>.
*Similarly by <<tex "e^{-ik'x}">> to obtain <<tex 'E B = \frac{\hbar^2 (k - G)^2}{2m} B + V_G A'>>
*Solve at the Brillouin boundary, <<tex "|k| = |k'| = \pi / a">>:
><<tex "\begin{array} {|cc|} \dfrac{\hbar^2 (\frac{\pi}{a})^2}{2m} - E & V_G \\ V_G & \dfrac{\hbar^2 (\frac{\pi}{a})^2}{2m} - E \end{array} = 0">>
>
>Eigenvalues: <<tex "\lambda_{\pm} = \dfrac{\hbar^2 (\frac{\pi}{a})^2}{2m} \pm V_G">>
>
>Eigenstates: <<tex "\psi = e^{i(\pi / a)x} \pm e^{-i(\pi / a) x}">>
*This is a standing wave, <<tex "\cos \theta">> and <<tex "\sin \theta">> solutions, <<tex "\Delta E = 2 |V_G|">> between them.
*<<tex "\cos">> has nodes in potential's peaks, and sits in the dips, therefore energy is lowered. <<tex "\sin">> is the opposite: 'fights' with the potential's peaks and its energy must therefore be raised.
*To cover all Fourier frequencies, we can write <<tex "\psi (x) = e^{ikx} u_K (x)">>, where <<tex "u_K (x)">> is a periodic "Bloch function", which represents the full crystal structure.
*Number of allowed modes in a frequency range <<tex '\omega \rightarrow \omega + d \omega'>>is proportional to the volume of the cube. 
*For a large enough cavity, the number of modes per unit volume becomes independent of the size or shape, and for <<tex 'V \rightarrow \infty'>>, an essentially continuous spectrum of frequencies is produced, given by a ''mode density'':
><<tex 'g(\omega) d \omega = \dfrac{\omega^2}{\pi^2 c^3} d \omega'>>
*Classically, the energy of a radiation mode is given by:
><<tex 'W_{mode} = \displaystyle\int_{vol} \overline{\left( \frac{1}{2} \mathbf{E \cdot D} + \frac{1}{2} \mathbf{B \cdot H} \right)} d \tau'>>
*However, we need a more complete picture accounting for QM. As the modes oscillate harmonically:
><<tex 'W_{mode} = (n + \frac{1}{2}) \hbar \omega, n=1,2,3...'>>
*In this picture the field can be said to be in the nth excited state, or containing n photons. Number of photons per mode is given by:
><<tex '\langle n \rangle = \dfrac{\displaystyle\sum_{n=0}^\infty n e^{- \beta (n + 1/2) \hbar \omega}}{\displaystyle\sum_{n=0}^\infty e^{- \beta (n + 1/2) \hbar \omega}} = \dfrac{1}{e^{\beta \hbar \omega} - 1}'>>
*Energy density per frequency interval <<tex 'd \omega'>> is then given by number of photons per mode, times no of modes per unit vol, times energy of each photon:
><<tex '\begin{array}{rl} \rho (\omega) d \omega &= \langle n_\omega \rangle \times g (\omega) d \omega \times \hbar \omega \\ & \\ &= \dfrac{\hbar \omega^3}{\pi^2 c^3} \dfrac{d \omega}{e^{\beta \hbar \omega} - 1} \end{array}'>>
*The above equation is ''always'' true, so if the energy density is known the number of photons per mode can be found. This is ''Planck's Law''.
*Apply N.II to a 'blob' of fluid that (ideal case) moves along with the flow, dimensions <<tex '\delta x, \delta y, \delta z'>>;
*<<tex '\lambda \ll \delta x, \delta y, \delta z \ll L'>>, the length scale of the flow.
><<tex 'F = m a'>>
>
><<tex '\rho(\delta x, \delta y, \delta z) a = \delta \textbf{F}'>>
*Net pressure in x direction:
[img[Pressure forces|images/1210586546.jpg]]
><<tex '\delta F= (p(x) - p(x + dx))\delta A'>>
>
><<tex '\delta F = -\delta x \dfrac{\partial p}{\partial x} \delta A = \delta V \dfrac{\partial p}{\partial x}'>>
>
>So:
><<tex '\delta \textbf{F} = - (\delta V) \nabla p'>>
*Previously calculated, <<tex '\rho \propto \dfrac{1}{a^4}'>>
*Consider radiation in thermal equilibrium as a black body;
*Energy density:
><<tex '\epsilon(\nu) \textrm{d} \nu = \dfrac{8 \pi \nu^3 \textrm{d} \nu}{c^3} \dfrac{1}{exp(\frac{h \nu}{kT}) - 1}'>>
*Integrating over all energies gives:
><<tex '\rho_{\gamma} = \dfrac{\pi^2}{15} (k T) \left( \dfrac{k T}{\hbar c} \right)^3'>>
*Showing:
><<tex 'T \propto \dfrac{1}{a}'>>
*For this to be the temperature of the universe:
**everything has to interact with photons, (true at high T);
**radiation must dominate over other forms of matter - be careful!
***Energy density of radiation decreases more quickly, but number density does not;
***Far more photons than baryons in the universe (<<tex 'n_B / n_{\gamma} \approx 10^{-10}'>>).
*We write a general rate equation for e.g. the upper laser level as:
><<tex '\dfrac{d N_2}{dt} = R_2 - (N_2 B_{21} - N_1 B_{12}) \displaystyle\int_0^\infty g_H (\omega - \omega_0) \rho (\omega) d \omega + ...'>>
*i.e the total rate is given by integrating the lineshape with the energy density.
*Can rewrite this as (with <<tex '\omega_L'>> as the central frequency of a the incident narrow beam:
><<tex '\begin{array}{rl} \dfrac{d N_2}{dt} &= R_2 - N^* \displaystyle\int_0^\infty \sigma_{21} (\omega - \omega_0) \dfrac{I_T \delta (\omega - \omega_L)}{\hbar \omega} d \omega + ... \\ & \\ &= R_2 - N^* \sigma_{21} (\omega_L - \omega_0) \dfrac{I_T}{\hbar \omega_L} + ...\end{array}'>>
*This can be viewed as the effective number density of inverted atoms, times their cross sectional area, times the beam's photon flux <<tex 'I_T / \hbar \omega'>>.

*Reciprocal Lattice is the Fourier Transform of the lattice.
><<tex '\displaystyle\sum_{\mathbf{l}} \int \delta (\mathbf{r} - \mathbf{l}) e^{i \mathbf{Q} . \mathbf{r}} d^3 \mathbf{r}'>>
>
><<tex '= \displaystyle\sum_{\mathbf{l}} e^{i \mathbf{Q} . \mathbf{l}}'>>
*and for orthogononal axes:
><<tex '= \displaystyle\sum_{n_1} e^{i Q_x a n_1} \cdot \displaystyle\sum_{n_2} e^{i Q_y b n_2} \cdot \displaystyle\sum_{n_3} e^{i Q_z c n_3}'>>
*carrying on:
><<tex '\propto \displaystyle\sum_h \delta(Q_x - h \frac{2 \pi}{a}) \displaystyle\sum_k \delta(Q_y - k \frac{2 \pi}{b}) \displaystyle\sum_l \delta(Q_z - l \frac{2 \pi}{c})'>>
>
><<tex '\propto \displaystyle\sum_{\mathbf{G}_{hkl}}} \delta(\mathbf{Q} - \mathbf{G}_{hkl})'>>
*Here, <<tex '\{\mathbf{G}_{hkl}\}'>> is the set of reciprocal lattice vectors:
><<tex '\mathbf{G}_{hkl} = h \mathbf{a}^* + k \mathbf{b}^* + l \mathbf{c}^*'>>
*General case:
><<tex '\mathbf{a}^* = \dfrac{2 \pi \mathbf{b} \times \mathbf{c}}{\mathbf{a} \cdot ( \mathbf{b} \times \mathbf{c} )}'>>
*Simpler orthogonal case:
><<tex '\mathbf{a}^* = \dfrac{2 \pi}{a} \mathbf{\hat{a}}'>>
*Notes:
**Reciprocal lattice is FT of crystal lattice;
**Lattice of points in ''Q'' space, basis vectors ''a''*, ''b''*, ''c''*, and dimensions of inverse length;
**<<tex '\mathbf{G}_{hkl}'>> is the normal to the plane <<tex '(hkl)'>>;
***(Can show this by taking two lines in the plane, e.g <<tex '(\frac{\mathbf{a}}{h} - \frac{\mathbf{b}}{k})'>> and <<tex '(\frac{\mathbf{a}}{h} - \frac{\mathbf{c}}{l})'>>, and crossing them to get a normal etc.
**Spacing between <<tex '(hkl)'>> planes is:
><<tex 'd_{hkl} = \dfrac{2 \pi}{| \mathbf{G}_{hkl} |}'>>
*//Poiseuille Flow//
[img[Rectilinear Flow|images/1210603405.jpg]]
>''N.S.:'' 
>
><<tex '\dfrac{D \textbf{u}}{Dt} \equiv \dfrac{\partial \textbf{u}}{\partial t} + ( \textbf{u} \cdot \nabla) \textbf{u} = - \dfrac{1}{\rho} \nabla p + \dfrac{\mu}{\rho} \nabla^2 \textbf{u}'>>
>
>(Neglecting gravity)
*Setup:
**<<tex '\textrm{u} = (u, 0, 0)'>>;
**<<tex '\nabla \cdot \textbf{u} = 0'>> (Incompressibility) - gives <<tex '\partial u / \partial x = 0'>>
**<<tex '\partial u / \partial t = 0'>> (Steady flow);
**<<tex '\partial u / \partial y = 0'>> (y-independent flow);
**so: 
><<tex 'u = u(z)'>>
*Plug into ''NS'':
><<tex '\dfrac{\partial u}{\partial t} + u\dfrac{\partial u}{\partial x} + v\dfrac{\partial u}{\partial y} + w\dfrac{\partial u}{\partial z} = - \dfrac{1}{\rho} \dfrac{\partial p}{\partial x} + \dfrac{\mu}{\rho} \nabla^2 u'>>
>
><<tex '\dfrac{\partial v}{\partial t} + u\dfrac{\partial v}{\partial x} + v\dfrac{\partial v}{\partial y} + w\dfrac{\partial v}{\partial z} = - \dfrac{1}{\rho} \dfrac{\partial p}{\partial x} + \dfrac{\mu}{\rho} \nabla^2 v'>>
>
>etc.
*As <<tex '\textrm{u} = (u, 0, 0) \Rightarrow v, w =0'>> and the y, z components of pressure are zero:
><<tex '\dfrac{\partial p}{\partial y} = \dfrac{\partial p}{\partial z} = 0'>>
*Look at x-component, all that's left is:
><<tex ' \dfrac{\partial p}{\partial x} = \mu \nabla^2 u = \mu \dfrac{d^2 u}{dz^2}'>>
>
>//The viscous force balances the pressure gradient.//

*Boundary Conditions:
**No slip: <<tex 'u = 0'>> at the walls, <<tex 'z = \pm h'>>
*Solve the differential equation gives:
><<tex 'u = \dfrac{G}{2 \mu} (h^2 - z^2)'>>
>
>Where <<tex 'G = - \dfrac{dp}{dx}'>>, the pressure gradient.
*This gives a parabolic flow profile:
[img[Parabolic Flow Profile|images/1210605794.jpg]]
*With volume flux:
><<tex '\displaystyle{\int_{-h}^h} u dz = \frac{2}{3} \left( - \dfrac{dp}{dx} \right) \dfrac{h^3}{\mu}'>>
*Gives intuitive result, higher volume flux if:
**Higher pressure gradient;
**Lower viscosity. 
*The space-time invariant interval is:
><<tex 'ds^2 = dx^2 = dy^2 + dz^2 - c^2 dt^2'>>
*Three types of interval:
**<<tex 'ds^2 > 0'>>: Space components are bigger than time components.. ''space-like'' interval. It is impossible for a light ray to travel between these two points in spacetime in the given time;
**<<tex 'ds^2 = 0'>>: The path traced by a light ray;
**<<tex 'ds^2 < 0'>>: A ''time-like'' interval, light can travel between the two points.
*We can express <<tex '\textbf{ds}'>> = <<tex '(cdt, dx, dy, dz)'>>, and <<tex 'ds^2 = \textbf{ds}^T g \textbf{ds}'>>;
**For normal Euclidean space:
><<tex 'g = \left(\begin{array}{cccc} -1&0&0&0 \\ 0&1&0&0 \\ 0&0&1&0 \\ 0&0&0&1 \end{array}\right)'>>
**and in spherical coordinates:
><<tex 'g = \left(\begin{array}{cccc} -1&0&0&0 \\ 0&1&0&0 \\ 0&0&r^2&0 \\ 0&0&0&r^s \sin^2 \theta \end{array}\right)'>>
*For the cosmological principle (homogeneity and isotropy) to apply, g can only have a few forms, giving:
**Flat (Euclidean) space, (<<tex 'k = 0'>>);
**Spherical space, (<<tex 'k > 0'>>);
**Hyperbolic space, (<<tex 'k < 0'>>);
*Using spherical polars, we can write the metric for these spaces, with the parameter k as:
><<tex 'ds^2 = -c^2 dt^2 + a^2(t) \left[\dfrac{d^2r}{1 - kr^2} + r^2(d\theta^2 + \sin^2 \theta d \phi^2)\right]'>>
*Clearly <<tex 'k'>> can be expressed as <<tex '\sim 1/R^2'>>, giving <<tex 'R'>> as the characteristic scale at which the curvature can be detected:
**If <<tex 'R'>> is too large, it will be difficult to detect the geometry of the space.
*This is the same <<tex 'k'>> as in the [[FRM Equations|ii. The Friedmann Equations]].
*Electrons attracted rigidly to nucleus - the "adiabatic approximation";
*Amplitude of vibrations is small:
[img[images/1211379604.png]]
*Here:
**<<tex 'x'>> is the displacement from the origin;
**<<tex 'a'>> is the lattice spacing;
**<<tex 'u'>> is an atom's displacement from it's equilibrium position;
**This gives <<tex 'x = a*n + u'>>.
*For <<tex 'u_2 - u_1 \ll a'>>, we can expand <<tex '\phi'>> about <<tex 'x_2 - x_1 = a'>>...:
><<tex '\phi(x_2 - x_1) = \phi(a) + (u_2 - u_1) \dot{\phi}(a) + \frac{1}{2} (u_2 - u_1)^2 \ddot{\phi}(a) + ...'>>
*<<tex '\dot{\phi}(a) = 0'>> by definition (as <<tex 'a'>> is constant), and neglect terms higher than <<tex '(u_2 - u_1)^2'>> (the harmonic approximation);
*Include forces between nearest neighbour atoms only.





*Apparent magnitudes of two stars (relative between the two stars):
><<tex 'm_1 - m_2 = 2.5 log(f_2 / f_1)'>>
5 magnitudes is <<tex '\therefore'>> a factor of 100 brightness.
*Historically, Vega is the 'zero point' of the magnitude system, gives Sun's magnitude as: <<tex 'm_{\odot} = -26.82'>>
*Absolute magnitude, <<tex 'M'>> is the apparent magnitude if it were at a distance of 10pc.
*Bolometric magnitude - absolute magnitude for luminosity integrated over all wavebands. <<tex 'M_{\odot}^{bol} = 4.72'>>
*Magnitude usually defined over limited wavelength bands due to difficulty of measuring entire spectrum:
>*Ultraviolet, apparent <<tex 'U'>> or <<tex 'm_U'>>, absolute <<tex 'M_U'>>.
>*Blue, apparent <<tex 'B'>> or <<tex 'm_B'>>, absolute <<tex 'M_B'>>.
>*Visual, apparent <<tex 'V'>> or <<tex 'm_V'>>, absolute <<tex 'M_V'>>.
*Colours are relative magnitudes in different wavebands, <<tex 'B - V'>>, <<tex 'U - B'>>.
*Bolometric correction: <<tex 'B.C. = M_{bol} - M_V'>>
*Visual extinction: correction due to absorption of light due to gas en-route: <<tex 'A_V'>>, can be up to 30 magnitudes.
*Distance modulus: <<tex '(m - M)_V = 5 \times \textrm{log} (D / 10 \textrm{pc})'>>
*Summary:
><<tex 'M_V = -2.5 \textrm{log} L / L_{\odot} + 4.72 - \textrm{B.C.} + A_V'>>
*For an ideal gas:
><<tex 'P = N k T = \dfrac{\rho}{\mu m_H} k T'>>
**<<tex '\mu'>> is average particle massin a gas, can use X, Y, Z and number of electrons from each to get a value:
><<tex 'N = (2 X + 3 Y / 4 + Z / 2) \rho / m_H'>>
>
><<tex '(1 / \mu) = 2X + 3Y/4 + Z/2'>>
>
>This is a good approximation apart from in cooler, outer regions.
**Can include radiation pressure term (useful for massive stars):
><<tex 'P = \dfrac{\rho}{\mu m_H} k T + \dfrac{a T^4}{3}'>>
*Degenerate gas:
**Deviation from ideal gas law;
**Number density limited by Pauli exclusion principle;
**In a totally degenerate gas, ALL states up to Fermi energy/momentum are filled:
><<tex 'N_e = \displaystyle{\int_0^{p_0}} \dfrac{2}{h^3} 4 \pi p^2 dp = \dfrac{2}{h^3}\dfrac{4 \pi}{3} p_0^3'>>
**From kinetic theory, pressure <<tex 'P'>> is related to momentum <<tex 'p'>> by:
><<tex 'P_e = \frac{1}{3} \int_0^{\infty} p v(p) n(p) dp'>>
**For a non-relativistic, completely degenerate electron gas:
***<<tex 'v(p) = p / m_e'>> for all <<tex 'p'>>:
><<tex '\begin{array}{ll} P_e & = \dfrac{1}{3} \int_0^{p_0} \dfrac{p^2}{m_e} \dfrac{2}{h^3} 4 \pi p^2 dp \\ & \\ & = \dfrac{8 \pi}{15 m_e h^3} p_0^5 \\ & \\ & = \dfrac{h^2}{20 m_e} (3 / \pi)^{2/3} N_e^{5/3} \end{array}'>>
**For a relativistic, completely degenerate electron gas:
***<<tex 'v(p) \sim c'>>
><<tex '\begin{array}{ll} P_e & = \dfrac{1}{3} \int_0^{p_0} pc \dfrac{2}{h^3} 4 \pi p^2 dp \\ & \\ & = \dfrac{8 \pi c}{3 h^3} \dfrac{p_0^4}{4}\\ & \\ & = \dfrac{hc}{8} (3 / \pi)^{1/3} N_e^{4/3} \end{array}'>>
**For ions we can use the normal expression;
**For intermediate electrons, relativistic momentum expression is used.
*Stars are self-gravitating bodies in dynamic equilibrium - gravity must be balanced by internal pressure.
**Force due to pressure from above: <<tex 'P_{r+\delta r} A'>>
**Force due to pressure from below: <<tex '-P_r A'>>
**Force due to gravity: <<tex '(\rho_r A \delta r) G M_r / r^2'>>
**Equate:
><<tex '(P_{r + \delta r} - P_r).A = -\dfrac{G M_r \rho_r}{r^2} \delta r A'>>
><<tex '\dfrac{\partial P_r}{\partial r} = - \dfrac{G M_r \rho_r}{r^2}'>>
*Mass relation:
><<tex 'dM = 4 \pi r^2 \rho_r dr'>>
*Can estimate central pressure using:
><<tex 'P_r = \dfrac{\rho_r}{\mu m_H} k T_r'>>
combined with integrated equation 1, to get:
><<tex 'k T_c \approx \dfrac{G M_s \mu m_H}{R_s}'>>

*Aside: mean molecular weight <<tex '\mu'>> for hydrogen gas is 1/2, due to half the particles being hydrogen and half of them being electrons.
*Pre-main sequence:
**Dust cloud collapses until deuterium fusion can occur (<<tex 'T_c \sim 10^6 K'>>);
**After burning further contraction until H burning (<<tex 'T_c \sim 10^7 K'>>) and main sequence begins.
(Thanks to Will for the table format):
|!Mass / <<tex 'M_{\odot}'>>|!Temperature|!Energy Generation|!Opacity Laws|!Convection Zones|
| < 0.3 | ''Hydrostatic'': <html><br /><br /></html> <<tex '\dfrac{dP}{dr} = - G \dfrac{M \rho}{r^2}'>> <html><br /><br /></html> Can replace with charactersitic quantities: <html><br /><br /></html> <<tex '\dfrac{P_c}{R_S} = - G \dfrac{M_S \rho_c}{R_S^2}'>> <html><br /><br /></html> ''Ideal gas equation'': <html><br /><br /></html> <<tex 'P(r) = \dfrac{\rho(r)}{\mu m_H} kT(r)'>> <html><br /><br /></html> giving: <html><br /><br /></html> <<tex 'kT_c \approx \dfrac{G M_s \mu m_H}{R_S}'>> <html><br /><br /></html> <<tex '\textbf{Core Temp.} \propto \textbf{Mass}'>> | Lower temp -> ''PP Chains'':  <html><br /><br /></html> <<tex '\epsilon_{pp} \propto T^4'>> <html><br /><br /></html> <<tex 't_{nuc} \approx 10^{10} \textrm{years}'>> | ''Kramer's Opacity Law'',<html><br /><br /></html> <<tex '\kappa = \kappa_0 \dfrac{\rho}{T^{3.5}}'>> | Extremely high surface opacities cause ''entire star'' to be convective |
| < 1.2 |~|~|~| ''Radiative core'' but opaque surface requires ''convective envelope'' |
| < 1.3 |~| Higher temp -> ''CNO Cycle'' <html><br /><br /></html> Energy generation: <html><br /><br /></html> <<tex '\epsilon_{cno} \propto T^{20}'>> <html><br /><br /></html> Slowest reaction determines cycle speed, second slowest determines time to equilibrium <html><br /><br /></html> <<tex 't_{eqm} \approx 10^6 \textrm{years}'>> |~|~|
| > 1.3 |~|~| High T ''electron scattering'' gives: <html><br /><br /></html> <<tex '\kappa = \textrm{const}.'>> | Vast energy generation can't be transported by radiation -> ''convective cores''. <html><br /><br /></html> In envelope high T leads to H ionisation and low opacity: ''radiative envelope''. |
*Longest phase of star;
*<<tex '\mu'>> increases as fusion occurs and nuclei get heavier, increasing density to prevent collapse, so T increases;
*As T increases, reaction rate increases (<<tex 'T^4'>>) until all H is used up in core, but burning continues in a shell around the core.
*Core is isothermal because there are no reactions and no luminosity, and <<tex 'L \propto dT/dr'>>
*The Ruby Laser is a good example of a 3 level laser. 
**Pumping occurs from a low level to a higher level. The high level has a very short lifetime and atoms drop down to the top of the lasing level rapidly, to attempt to cause population inversion.
**If population inversion is achieved, lasing can occur between the middle and lower levels.
**It is therefore hard to acheive population inversion however, unless the pump rate is very high, as there is no drain from the lower level.
**We need over half of the population to be in the upper two levels for lasing to have any chance of happening.
*Analysis of the 3 level laser - PULSED laser operation:
**For small cavity losses:
><<tex '2 \alpha_0 L_g = \delta_{loss} + T_2'>>
>
><<tex '2 \sigma_{21} N^*_{thresh} L_g = \delta_{loss} + T_2'>>
**Level 3 has a very short lifetime, so <<tex 'N_3 \approx 0'>>
><<tex 'N_T = N_2 + N_1'>>
>
><<tex 'N_{thresh}^* = N_2^{thresh} + N_1^{thresh}'>>
*This gives:
><<tex 'N_2^{thresh} = \dfrac{N_T + N_{thresh}^*}{2}'>>
*However, the threshold population inversion density will be small comared to the total ion density, so:
><<tex 'N_2^{thresh} = \dfrac{N_T}{2}'>>
*To achieve lasing, we need an ''absorbed'' pump energy of:
><<tex 'E_{abs}^{thresh} = \dfrac{N_T}{2} \pi a^2 L_g \dfrac{hc}{\lambda_p}'>>
>
>where <<tex 'a, L'>> are the radius and length of the laser rod, and <<tex 'hc/\lambda'>> is the energy required to raise an ion from the lower to upper level.
*This is the //absorbed// energy however, the real factor is around 60x greater:
**2x for uniform pumping - if too much is absorbed only ions on the surface will be raised, no ions in the center of the rod will be.
**8x as only <<tex '\sim 12%'>> of the flashlamp output will be in the bulb bands;
**2x as not all the light from the bulb will hit the rod;
**1.7x as only 60% of the electrical energy is converted to light.
*An example pump energy for this case is around 360J, for a=5mm, L=20mm.
*For CONTINUOUS laser operation:
**The pumping now has to compete with the upper lasing level's spontaneous decay rate, <<tex 'N_2 / \tau_2'>>.
**The pump power is just the single pulse pump energy divided by this level's lifetime, giving a 100kW pumping power.
**This can be decreased with a smaller rod size but is still difficult.
*Two dimensional flow, with:
**<<tex '\mathbf{u} = [ u(x,y,u), v(x,y,t), 0 ]'>>;
**<<tex '\boldsymbol{\omega} = (0, 0, \omega)'>>.
*If <<tex 'curl \mathbf{u} = 0'>>, the vector <<tex '\mathbf{u}'>> can be expressed as the gradient of a potential:
><<tex '\mathbf{u} = \nabla \phi'>>
*In this case, the incompressibility condition becomes ''Laplace's equation'':
><<tex '\nabla^2 \phi = 0'>>
[img[Deep Water Waves|images/1210760045.png]]
*Assumptions:
**Inviscid, <<tex '\nu = 0'>>;
**Irrotational, <<tex '\boldsymbol{\omega} = 0'>>;
**Incompressible, <<tex '\nabla \cdot \mathbf{u} = 0'>>;
**2D (independent of z);
**<<tex 'p = p_0'>> at the surface of the water (atmospheric pressure).
*Laplace's equation:
><<tex '\dfrac{\partial^2 \phi}{\partial x^2} + \dfrac{\partial^2 \phi}{\partial y^2} = 0'>>
*Bernoulli's equation:
><<tex '\dfrac{\partial \phi}{\partial t} = \frac{1}{2} | \mathbf{u} |^2 + \dfrac{p}{\rho} + gy = 0'>>
*Assume <<tex '\mathbf{u}, \phi, \eta'>> are small, so can first neglect <<tex '\mathbf{u}^2'>>, and at the boundary <<tex 'y = \eta'>>:
><<tex '\dfrac{\partial \phi(x, \eta, t)}{\partial t} + \dfrac{p_0}{\rho} + g \eta = 0'>>
*Can redefine <<tex '\phi'>> up to a constant to get rid of the <<tex 'p_0 / \rho'>> term.
*Also we have been solving at the boundary but can get solution at <<tex 'y=0'>> using an expansion:
><<tex '\dfrac{\partial \phi(x, \eta, t)}{\partial t} = \dfrac{\partial \phi(x, 0, t)}{\partial t} + ...}'>>
*Giving at <<tex 'y=0'>>:
><<tex '\dfrac{\partial \phi}{\partial t} + g \eta = 0'>>
*and also the vertical velocity at <<tex 'y=0'>>:
><<tex 'v = \dfrac{\partial \phi}{\partial y} + \dfrac{\partial \eta}{\partial t}'>>
*Guess a travelling wave solution, and substitute into Laplace's equation above:
><<tex '\phi(x,y,t) = f(y) \sin(kx - \sigma t)'>>
>
><<tex "f'' - k^2 f = 0">>
>
><<tex 'f(y) = Ce^{ky} + De^{-ky}'>>
*Boundary condition <<tex 'f(y=\infty) \not= \infty \Rightarrow D = 0'>>
*Using the expressions which differentiate <<tex '\phi'>> with respect to t and y, we get:
><<tex 'C = A \sigma / k'>>
>
><<tex '\sigma^2 = gk'>>
*The second formula is the dispersion relation.

*''Ionic'' bonding:
**Transfer of electrons from one atom to another, to fill atomic shells. Electrostatic force then attracts the ions.
*''Covalent'' bonding:
**Unpaired electron orbitals hybridize to give a lower energy state. Very directional (e.g diamond, silicon). 
*''Metallic'' bonding:
**Outer orbitals overlap many other atoms;
**Electrons become mobile, KE reduced by delocalisation;
**Not directional, and weaker than covalent bonding leading to soft and ductile properties.
*''Hydrogen'' bonding:
**Covalent bond between atoms of different atomic species;
**Partial seperation of charge, very weak;
**Can be seen in water/ice.
*''Van der Waals Forces'':
**Force due to fluctuations in dipole moments;
**One atom's dipole moment can induce a dipole in a neighbouring atom - resulting attractive force between the two dipoles;
**Very weak, only important when no other bonds are present;
**Seen in noble gases.
*Translational symmetry can be represented by a lattice of points that fills space. Each lattice point is in an identical environment.
*''Unit cell'':
**Perfect tessellation: when many identical cells are stacked together they fill all of space.
**''Conventional'' unit cell:
***Chosen to display the full symmetry of the crystal;
***Not always the smallest possible choice - can contain more than one lattice point.
**''Primitive'' unit cell:
***Smallest possible unit cell - only contains one lattice point.
*Unit cells are usually 6-faceted polyhedra, formed from 3 primitive translation vectors, 
><<tex '\vec{a}, \vec{b}, \vec{c}'>>.
*The length of these vectors are the ''lattice parameters'';
*Volume of unit cell:
><<tex '\vec{a} \cdot (\vec{b} \times \vec{c})'>>
*Starting with [[NS Equation|6. Navier-Stokes equation]]:
**Neglect gravity;
**Steady state solution <<tex '(\partial \mathbf{u} / \partial t = 0)'>>;
**<<tex '\rho = \textrm{const}'>>;
**<<tex '\nu = \textrm{const}'>>;
><<tex '\mathbf{u} \cdot \nabla \mathbf{u} + \dfrac{1}{\rho} \nabla p = \nu \nabla^2 \mathbf{u}'>>
**Oh and negelect the non-linear term compared to the viscous term due to small Reynolds number.
*We get Stoke's flow, which is when the Reynolds number is small (<<tex 'Re = UL / \nu \ll 1'>>, so can be one of the following:
**<<tex '\nu \gg UL'>> (large viscosity);
**<<tex 'L \ll \nu/U'>> (small lengths);
**<<tex 'U \ll \nu/L'>> (small velocity);
**any combination of the above.
*Modified NS gives:
><<tex '\nabla p = \mu \nabla^2 \mathbf{u}'>>
*Take divergence of this, and use incompressibility:
><<tex '\nabla \cdot \mathfb{u} = 0'>>
*and the commutatability of 'div' and 'del-squared' to get:
><<tex '\nabla^2 p = \mu \nabla^2 (\nabla \cdot \mathbf{u}) = 0'>>
*This is Laplace's equation for <<tex 'p'>>, but can't be used very often as the boundary conditions are hard to come by.
*Can take curl instead to get:
><<tex '\mu \nabla^2 (\nabla \times \mathbf{u}) = \mu \nabla^2 \boldsymbol{\omega} = 0'>>
**This is Laplace's equation for all the components of the vorticity.
**Gives reversible solutions - fish swimming in treacle, flap one way moves it forwards, flap back moves it backwards.
[img[Lattice Vibration|images/1211381660.png]]
*Potential energy of nth atom is:
><<tex 'V_n = \phi(x_{n+1} - x_n) + \phi (x_n - x_{n-1})'>> 
>
>(Nearest neighbours)
>
><<tex 'V_n = \frac{1}{2} (u_{n+1} - u_n)^2 \ddot{\phi}}(a) + \frac{1}{2} (u_n - u_{n-1})^2 \ddot{\phi}'>>
>
>(Harmonic approximation)
*Using Newton's 2nd Law:
><<tex '\begin{array}{rl} m \dfrac{ \partial^2 u_n}{\partial t^2} &= - \dfrac{\partial V_n}{\partial u_n} \\ & \\ &= C [(u_{n+1} - u_n) - (u_n - u_{n-1})] \end{array}'>>
>
>Here, <<tex 'C = \ddot{\phi}'>>, the force, which is constant.
*Wave-like trial solution:
><<tex 'u_n = A e^{i(k x_n - \omega t)}'>>, where <<tex 'x_n = na'>>.
*Subs into equation of motion:
><<tex '\begin{array}{lr} -m \omega^2 u_n &= C(e^{ika} + e^{-ika} - 2)u_n \\ & \\ &=C(2(\cos(ka) - 1))u_n \end{array}'>>
*Gives the ''dispersion relation'':
><<tex '\Rightarrow \omega = 2 \sqrt{\dfrac{c}{m}} | \sin(ka/2) |'>>
>[img[Dispersion Relation|images/1211389173.png]]
*Notes:
**In the long wavelength limit, <<tex '\omega \simeq ka \sqrt{c/m} '>>. The speed of sound in the medium <<tex 'v_s \equiv a \sqrt{c/m}'>>, so we can write:
><<tex '\omega = v_s k'>>
**The relation is periodic, so all distinct solutions are contained in the range <<tex '-\pi/a \leq k \leq \pi/a'>> (1st Brillouin Zone).
**Normal modes: Each allowed value of <<tex 'k'>> describes a state of motion in which all atoms vibrate with the same frequency.


*Time, age of the universe. Quick estimate:
><<tex 't_0 = H_0^{-1} = 10 - 20 \textrm{Gyr}'>>
*More generally:
><<tex '\dfrac{\dot{a}}{a} = H '>>
>
><<tex 'dt = \dfrac{da}{aH}'>>
>
><<tex 't_0 = \displaystyle{\int_0^1} \dfrac{da}{aH}'>>
>
>From FRW:
><<tex 'H^2 = H_0^2 \left( \dfrac{8 \pi G \rho_{M0}}{3 H_0^2} \dfrac{1}{a^3} - \dfrac{k c^2}{H_0^2} \dfrac{1}{a^2} + \dfrac{\Lambda}{3 H_0^2} \right)'>>
>
>Or:
><<tex 'H = H_0 \sqrt{\dfrac{\Omega_{M0}}{a^3} + \dfrac{\Omega_{K0}}{a^2} + \Omega_{\Lambda0}}'>>
>
>So (for a flat universe):
><<tex 't_0 = H_0^{-1} \displaystyle{\int_0^1} \dfrac{da}{a \sqrt{\Omega_{M0}/a^3 + \Omega_{\Lambda0}}}'>>
*This shows a larger cosmological constant relates to an older universe. This can be seen from the [[Raychauduri equation|2. Raychauduri Equation]]:
><<tex '\dfrac{\ddot{a}}{a} = - \dfrac{4 \pi G}{3} \rho + \dfrac{\Lambda}{3}'>>
*For two universes with the same expansion rate today, one with a larger cosmological constant relates to larger present accelleartion, so the speed of expansion in the past must have been slower, and it must therefore be older.
*General
**''Visual'' binaries: can see larger of the pair 'wobbling' due to interaction of unseen other;
**''Spectroscopic'' binaries: Can see periodic doppler shift of spectral lines:
***Can see movement of lines of either one star or both;
**''Photometric'' binaries: periodic variation of flux/colour;
**''Eclipsing'' binaries: if the plane of orbit is facing earth, stars can pass in front of each other changing luminosity.
*Close binaries:
**Roche lobe is a surface of constant potential = 0 for both stars (forms a kinda figure of 8);
**''Detached'' binaries:
***Both stars underfill their lobes, and do not spill past the potential = 0 boundary;
***Therefore only gravitational interactions can occur.
**''Semidetached'' binaries:
***One star fills its lobe and can transfer mass to ther other lobe;
**''Contact'' binaries:
***Both stars fill their lobes and transfer mass to each other;
***A common photosphere surrounding both components will form.
*Unit cells can be of a bunch of different types, the Bravais lattices cover all possible systems, divided into 7 groups.
*Locations etc:
**Atomic positions (from origin) can be defined inside a unit cell using fractional coordinates:
><<tex 'xyz = x\vec{a} + y\vec{b} + z\vec{c}'>>
**Direction vectors:
><<tex '[uvw] = u\vec{a} + v\vec{b} + w\vec{c}'>>
**Lattice planes:
><<tex '(hkl) = \dfrac{\vec{a}}{h} + \dfrac{\vec{b}}{k} + \dfrac{\vec{c}}{l}'>>
*Spacing
**Distance between two planes can be found by dotting a lattice vector with a unit normal, e.g between <<tex '(110)'>> planes:
><<tex 'd_{110} = \vec{a} \cdot \vec{\hat{n}}'>>
>
><<tex '\vec{a} = (a, 0, 0)'>>
>
><<tex '\vec{\hat{n}} = \dfrac{1}{\sqrt{a^2 + b^2}} (b, a, 0)'>>
>
><<tex '\vec{a} \cdot \vec{\hat{n}} = \dfrac{ab}{\sqrt{a^2 + b^2}} = \dfrac{1}{\sqrt{\dfrac{1}{a^2} + \dfrac{1}{b^2}}}'>>
**''Generally'':
><<tex 'd_{hkl} = \dfrac{1}{\sqrt{h^2/a^2 + k^2/b^2 + l^2/c^2}}'>>




* In a periodic structure: 
><<tex '\psi (x) = \psi (x + L)'>>
><<tex 'e^{ikx} = e^{ik(x + L)}'>>
><<tex '\therefore e^{ikL} = 1'>>
* So in a crystal of size <<tex 'L'>>:
><<tex 'k = 0, \pm \dfrac{2 \pi}{L}, \pm \dfrac{4 \pi}{L}, ...'>>
* Density of states = Number of states / Volume per state, (where the factor of 2 is for polarization states):
><<tex 'g(k)dk = 2 \times \dfrac{4 \pi k^2 dk}{(\frac{2 \pi}{L})^3}'>>
*Can equate the Fermi energy to a number density:
><<tex '\int_{0}^{k_F} g(k)dk = N'>>, gives: 
><<tex 'E_F = \dfrac{\hbar^2}{2m} (3 \pi^2 n)^{2/3}'>>
*Occupation per mode is ~Fermi-Dirac (~Bose-Einstein) distrubution:
><<tex 'F(p) = \dfrac{g}{exp(\frac{E - \mu}{k T} \frac{-}{(+)} 1})'>>
*Can calculate:
**Number density: <<tex 'n = \dfrac{1}{h^3} \int F(p) d^3 p'>>
**Energy density: <<tex '\rho = \dfrac{1}{h^3} \int E(p) F(p) d^3 p'>>
*Using these relations we can work out that:
**At high temperature, <<tex 'P = \frac{1}{3} \rho c^2'>>, which is the expression for radiation pressure: at high enough temperature matter behaves like radiation.
**At low temperature <<tex 'T \ll M'>> and the quantities are as expected (e.g <<tex 'P = n k T'>>).
*At <<tex 'a(t) =1 '>> (today), we know only the 3 neutrino types behave relativistically, but at earlier times, more particles would exhibit this behavior.
*Can define "relativistic degrees of freedom", <<tex 'g_*'>> as a way of describing the number of particles that behave relativistically, and therefore contribute to radiation terms. This takes the place of <<tex 'g'>>, the degeneracy in the case for a single type of particle, and gives an expression for all particles.
*Today, <<tex 'g_* = 7.25'>> (see problem set q8).
[img[Circular Pipe|images/1210606167.jpg]]
*As in [[rectilinear flow|1. Rectilinear Flow Between Parallel Plates]] except in cylindrical polars, so:
**Flow independent of <<tex '\theta, t'>>
*End up with differential equation:
><<tex '\dfrac{\mu}{r} \dfrac{d}{dr} \left( r \dfrac{du}{dr} \right) = \dfrac{dp}{dx} = -G'>>
*Boundary conditions:
**<<tex 'u(r=a) = 0'>>
**<<tex 'u(r=0) \not= \infty'>>
*Gives:
><<tex 'u = \dfrac{G}{4 \mu}(a^2 - r^2)'>>
*Assume Sun emits as a black body, can use increasing area of a sphere with distance to find the flux at the ~Sun-Earth distance, <<tex '\sim 1367 \textrm{W m}^{-2}'>>;
*Albedo of the Earth is <<tex '\alpha = 0.3'>>, so 30% of the incident energy is reflected away;
*For global energy balance, the Earth must emit as much as a black body as it recieves, so:
><<tex '\sigma T_e^4 = \dfrac{S_0 (1 - \alpha)}{4}'>>
>
>//where the factor of 4 arises due to the fact the Earth emits radiation from a sphere, but only recieves it on a flux projection disk.//
*Gives <<tex 'T_e \sim 255K'>>, compared to surface temperature of <<tex 'T_s = 288K'>>
*For an expression for <<tex 'T_s'>>, see [[transmittance|4. Transmittance, Absorptance and Optical Depth]] page.
*Growth of a beam of finite spectral width;
*We currently have:
><<tex '\dfrac{\partial I}{\partial z} = N^* \sigma_{21} (\omega - \omega_0) I (\omega, z)'>>
*Integrate both sides over the beam's bandwidth:
><<tex '\displaystyle\int_0^\infty \dfrac{\partial I}{\partial z} d \omega = \displaystyle\int_0^\infty N^* \sigma_{21} (\omega - \omega_0) I (\omega, z) d \omega'>>
>
><<tex '\Rightarrow \dfrac{\partial}{\partial z} \displaystyle\int_0^\infty I(\omega, z) d \omega = \displaystyle\int_0^\infty N^* \sigma_{21} (\omega - \omega_0) I (\omega, z) d \omega'>>
>
><<tex '\Rightarrow \dfrac{\partial I_T}{\partial z} = \displaystyle\int_0^\infty N^* \sigma_{21} (\omega - \omega_0) I (\omega, z) d \omega'>>
*Can again bring the cross section outside the integral for narrow-band radiation:
><<tex '\dfrac{\partial I_T}{\partial z} = N^* \sigma_{21} (\omega_L - \omega_0) I_T'>>
*All atoms will interact with a beam of radiation of frequency <<tex '\omega'>> by the same amount, but the strength of this interaction depends on the deviation of this from the peak frequency, <<tex '\omega_0'>>.
*Einstein's postulates are modified, and become (where <<tex 'g_x(\omega - \delta \omega)'>> is the lineshape for that transition, and looking at the range <<tex '\omega \rightarrow \omega + \delta \omega)'>>:
**Spontaneous emission rate: <<tex 'N_2 A_{21} g_A(\omega - \omega_0) \delta \omega'>>;
**Absorption rate: <<tex 'N_1 B_{12} g_B(\omega - \omega_0) \rho(\omega) \delta \omega'>>;
**Stimulated emission rate: <<tex "N_2 B_{21} g_{B'}(\omega - \omega_0) \rho(\omega) \delta \omega">>
*The lineshapes must be normalised, fulfilling the conditions such as:
><<tex '\displaystyle\int_0^\infty N_2 A_{21} g_A(\omega - \omega_0) d \omega = N_2 A_{21}'>>
*Equating these in a similar manner as before, we achieve the same result relations, only with the appropriate lineshape function added to the end of each expression. But, for this to be the case, each lineshape must be identical for all three processes, and we call the single lineshape <<tex 'g_H(\omega - \omega_0)'>>.
*This lineshape will be the lineshape of the frequency spectrum for each level, for example the Lorentzian frequency distribution for lifetime broadening.
*The ''Particle Horizon'':
**Furthest a light ray can travel from between<<tex 't=0'>> and <<tex 't=t'>>:
><<tex "r_p(t) = a(t)c \displaystyle{\int_0^t} \dfrac{dt'}{a(t')}">>
*The ''Event Horizon'':
**All parts of the universe which can ever be reached (<<tex '\rightarrow \infty'>> in e.g radiation/matter universes)
><<tex "r_e(t) = a(t) c \displaystyle{\int_0^{\infty}} \dfrac{dt'}{a(t')}">>
[img[Light Cones|images/1210513786.png]]
*Vertical force on a small cylinder of air, unit area, thickness <<tex '\delta z'>>, density <<tex '\rho'>>:
**Downward pressure on top: <<tex 'p(z + \delta z)'>>;
**Upward pressure on bottom: <<tex 'p(z)'>>
**Force due to gravity: <<tex 'g \rho \delta z'>>
*Equate:
><<tex 'g \rho \delta z + p (z + \delta z) = p(z)'>>
*Expand and such:
><<tex '\dfrac{dp}{dz} = - g \rho'>>
*Next we use the ideal gas law, <<tex 'pV = RT'>> (R is the specific gas constant for dry air <<tex '=R*/m_a'>>, V is the specific volume):
><<tex '\dfrac{dp}{dz} = - \dfrac{gp}{RT}'>>
*Write <<tex 'T = T(z)'>>:
><<tex "ln(p) - ln(p_0) = -\dfrac{g}{R} \displaystyle{\int_0^z} \dfrac{dz'}{T(z')}">>
*Or if over the range T is roughly constant, <<tex 'T \simeq T_0'>>:
><<tex 'p = p_0 exp\left(- \dfrac{gz}{RT_0} \right) = p_0 e^{-\frac{z}{H}}'>>
*Here H is the pressure scale height.


*Background radiation:
**Thermal isotropic bath of cold radiation, the microwave background;
**Black body spectrum:
><<tex '\rho(\nu) d \nu = \dfrac{8 \pi h}{c^3} \dfrac{ \nu^3 d \nu}{ e^{h \nu / k T_0} - 1} }'>>
**Using <<tex 'T_0 = 2.725 K'>> gives a good fit to measured data.
*Abundances of elements:
**3/4 H, 1/4 He, rest negligible.
**At hotter times, everything was seperate due to high energy, as it cools they remain seperate so mostly H.
*''Cosmological Principle'', universe is:
**Homogeneous: everywhere looks the same. Will always measure the same values for any quantity (tempreature, energy, pressure) wherever we are;
**Isotropic: every direction we look looks the same.
**This is clearly not true, but on large enough scales it is a good approximation.
*Using [[Hubble's law|1. Hubble's Law]], can calculate age of universe:
**<<tex 't_0 = r / v = r / (H_0 r) = H_0^{-1}'>>
*Scattered waves from two electrons are superimposed, observing the different paths from source to detector.
[img[Laue Diffraction|images/1211325816.png]]
*One wave scatters off electron at <<tex 'O'>>, extra path difference <<tex '\vec{OB}'>>;
*One wave scatters off electron at <<tex 'j'>>, extra path difference <<tex '\vec{Aj}'>>;
*Phase difference:
><<tex "\begin{array}{rl} \phi_j &= \dfrac{2 \pi}{\lambda} (\vec{Aj} - \vec{OB}) \\ & \\ &= \mathbf{k} \cdot \mathbf{r}_j - \mathbf{k'} \cdot \mathbf{r}_j \\ & \\ &= (\mathbf{k} - \mathbf{k'})\cdot \mathbf{r}_j \\ & \\ &= \mathbf{Q} \cdot \mathbf{r}_j \end{array}">>
*Clearly the total scattered wave is:
><<tex '\psi \propto \displaystyle\sum_j e^{i \mathbf{Q} \cdot \mathbf{r}_j}'>>
*Now:
><<tex '\begin{array}{rl} \displaystyle\sum_j e^{i \mathbf{Q} \cdot \mathbf{r}_j} &= \displaystyle{\int \sum_j} \delta(\mathbf{r} - \mathbf{r}_j) e^{i \mathbf{Q} \cdot \mathbf{r}} d^3 \mathbf{r} \\ & \\ &= \displaystyle\int n (\mathbf{r}) e^{i \mathbf{Q} \cdot \mathbf{r}} d^3 \mathbf{r} \end{array}'>>
>
><<tex '\Rightarrow \psi \propto \textrm{F.T} \left\{ n(\mathbf{r}) \right\}'>>
*Let <<tex '\mathbf{r}_j = \mathbf{l} + \mathbf{d} + \mathbf{s}_d'>>, where:
**<<tex '\mathbf{l}'>> is the nearest lattice vector;
**<<tex '\mathbf{d}'>> is displacement to nearest lattice point
**<<tex '\mathbf{s}_d'>> is electron's displacement relative to nucleus of atom d.
><<tex '\psi \propto \left( \displaystyle\sum_{\mathbf{l}} e^{i \mathbf{Q} \cdot \mathbf{l}} \right) \left( \displaystyle\sum_{\mathbf{d}} [ \displaystyle\sum_{\mathbf{s}_d} e^{i \mathbf{Q} \cdot \mathbf{s}_d} ] e^{i \mathbf{Q} \cdot \mathbf{d}} \right)'>> 
*This can be thought of as the FT of the lattice multiplied by the FT of the electron density in a unit cell. But the lattice FT is just the reciprocal lattice! So:
><<tex '\psi \propto \displaystyle\sum_{\mathbf{G}_{hkl}} \delta (\mathbf{Q} - \mathbf{G}_{hkl} )'>>
*Diffraction amplitude is large from a crystal when:
><<tex '\Delta \mathbf{k} \equiv \mathbf{Q} \equiv \mathbf{G}_{hkl}'>>
*This is the ''Laue Condition'', and is identical to the Bragg condition:
**Let <<tex '\mathbf{Q} = \mathbf{G}_{hkl}'>>
><<tex '\begin{array}{rl} \Rightarrow |\mathbf{Q}| &= |\mathbf{G}_{hkl} | \\ & \\ &= \dfrac{2 \pi}{d_{hkl}} \end{array}'>>
>
><<tex '\Rightarrow 2 |\mathbf{k}| \sin \theta = 2 \pi / d_{hkl}'>>

><<tex '\lambda = 2 d_{hkl} \sin \theta'>>, Bragg's Law.






*For smaller stars (<<tex 'M \sim M_{\odot}'>>):
**Core contracts as H starts to run out;
**Higher density increases temperature and shell burning rate increases;
**Luminosity increases causing the envelope to expand, decreasing <<tex 'T_{\textrm{eff}}'>>.
*Bigger stars (<<tex 'M \sim 5 M_{\odot}'>>):
**Whole star contracts as H runs out;
**GPE is released, increasing <<tex 'L, T_{\textrm{eff}}'>> slightly;
**After enough contraction, shell burning begins causing expansion and drop of <<tex 'T_{\textrm{eff}}'>> again.
*Time spent on the MS:
**Due to [[mass-luminosity relationship|5. Mass Luminosity Relationship]], bigger stars life shorter lives;
**Turn off 'peels away' from MS over time;
**Can calculate the age of a cluster by the position of the turn off - age of star at the turn off is approx. the age of the cluster.
**Using:
><<tex 't_{MS} \approx 10^{10} \left( \dfrac{M_{\odot}}{M}} \right)^{3}'>> 
(see mass-luminosity page, and plug in numbers for Sun and divide), the age of a star can be determined from its luminosity:
><<tex 't_{MS} \approx 10^{10} \left( \dfrac{L_{\odot}}{L} \right)^{3/4}'>>
*Use periodic boundary condition, <<tex "\psi (x) = \psi (x + L)">>, //(Crystal of length L)//.
*<<tex "\psi (x) = e^{ikx} u_K(x)">>, and <<tex "u_K(x) = u_K(x + ma)">>, where <<tex "m">> is an integer. ( <<tex "u_K (x)">> is a Bloch function).
*<<tex "L = N_x a">>, where <<tex "N_x">> is the number of unit cells in the x-direction, and //a// is the lattice constant and therefore an integer, so <<tex "u_K (x + L) = u_K (x)">>.
*<<tex "\therefore e^{ikL} = 1">>, and so <<tex "kL = 2 \pi n">>, giving <<tex "\Delta k = 2 \pi / N_x a">>.
*In k-space, 1 BZ has a 1-D dimension of <<tex "2 \pi / a">>.
*Number of states is <<tex "2 \times \dfrac{\frac{2 \pi}{a}}{\Delta k} = 2 N_x">>, or in 3D, <<tex "2 \times N_x^3 = 2N">>, the number of unit cells in the crystal.
*''Collimated beam'':

[img[Collimated|images/1211455283.png]]

**Here, <<tex '\rho(\omega) = \langle n_\omega \rangle g(\omega) \hbar \omega = n(\omega) \hbar \omega'>> is the //spectral// photon density;
**So in time <<tex '\delta t'>>, we have <<tex 'n(\omega) \cdot c \delta t \cdot A'>> photons per unit bandwidth corssing area A;
**This gives a ''spectral intensity'' <<tex 'I(\omega) = c n (\omega) \hbar \omega = c \rho(\omega)'>>

*''Isotropic Radiation'':
**Small area, A, within an isotropic radiation field of <<tex 'n(\omega)'>> photons per unit volume per unit frequency interval. 
**Assume photons behave as an ideal gas;
**From kinetic theory, num of photons in interval with <<tex '\delta \omega'>> that strikes a side per unit area per second is <<tex '\frac{1}{4} n(\omega) \delta \omega c'>>;
**This gives intensity:
><<tex 'I(\omega) = \frac{1}{4} n(\omega) \hbar \omega c = \frac{1}{4} \rho (\omega) c'>>

><<tex 'V = \frac{4}{3} \pi (a x)^3, E = (\rho V) c^2'>>
>
><<tex '\dfrac{dE}{dt} = c^2 \dfrac{4 \pi}{3} x^3 \left( \dfrac{d \rho}{dt} a^3 + 3 \dfrac{a}{dt} a^2 \rho \right)'>>
>
><<tex '\dfrac{dV}{dt} = \dfrac{4 \pi}{3} x^3 3 \dot{a} a^2'>>
*Using <<tex 'dE + PdV = TdS'>> and assuming adiabatic, <<tex 'dS = 0'>>:
><<tex 'c^2(\dot{\rho} a^3 + 3a^2 \dot{a} \rho) + 3 P \dot{a} a^2 = 0'>>
*Divide by <<tex 'c^2 a^3'>>, ''conservation equation'':
><<tex '\dot{\rho} + 3 \dfrac{\dot{a}}{a}\left(\rho + \dfrac{P}{c^2} \right) = 0'>>
*Differentiate FRM equation, ''ancilliary equation'':
><<tex '\ddot{a} = \dfrac{8 \pi G}{3} a (\dot{\rho} a^2 + 2 \dot{a} a \rho)'>>
*Subs conservation equation in to get ''Raychauduri equation'':
><<tex '\dfrac{\ddot{a}}{a} = - \dfrac{4 \pi G}{3} \left( \rho + \dfrac{P}{c^2} \right)'>>
*Reaction rate is proportional to:
**Number density of particles (<<tex 'n_1, n_2'>>)
**Frequency of collisions <<tex '\rightarrow'>> relative velocity <<tex 'v'>>:
><<tex 'r_{1+2} = n_1 n_2 <\sigma(v) v>'>>
**Probability of penetrating Coulomb barrier:
><<tex 'P_p(v) \propto e^{- 4 \pi^2 Z_1 Z_2 e^2 / h \nu}'>>
**Reaction cross section <<tex '\sigma'>>:
***Usually requires laboratory data
***Can be calculated for p-p theoretically
**Velocity distribution (Maxwell), A is reduced mass:
><<tex 'D(T,v) \propto \frac{v^2}{T^{3/2}} e^{- m_H A v^2 / 2 k T}'>>
*High temperature leads to more collisions and faster rate (except very high temperatures, usually not concerned with this)
*Rate decreases as Z increases, therefore low temperature favours lower Z nuclei.
*Selection rules for lattice types for reflection to be present:
| !Lattice Type | !Condition on <<tex '(hkl)'>> for reflection |
| P (corners) | no constraint. |
| I (interior, BCC etc.) | <<tex 'h+k+l'>> is even integer |
| F (face, FCC etc. ) | <<tex 'h,k,l'>> all even or all odd |
*Effective temperature, <<tex 'T_{\textrm{eff}}'>>:
><<tex 'L_S = 4 \pi R_S^2 \sigma T_{\textrm{eff}}^4'>>
Usually not measurable as <<tex 'R_S'>> is not measurable.
*Colour temperature: use black body spectrum characteristics and it's peak wavelength to determine temperature, can obtain <<tex 'T_{\textrm{eff}}'>> and <<tex 'R_{ph}'>> (the radiating sphere's radius, or photospheric radius).
>Wien's law:
><<tex '\lambda_{max} = \dfrac{b}{T}'>>
*Luminosity classes are based on width of spectral lines, narrower lines correspond to a lower surface pressure and gravity and therefore a bigger star. White dwarfs have very broad lines.
*Absorption lines are caused by cooler material above the photosphere.
*Emission lines are caused by hotter material above the photosphere.
*Spectral lines can tell us:
**Temperature where lines are produced - spectral type
**Chemical composition
**Pressure / Surface gravity
**Rotation (lines are doppler broadened by rotation)
**Orbital velocities (periodic doppler shifts in spectra).
*Viscous fluid moving past a stationary sphere:
**Radius <<tex 'a'>>;
**Flow velocity <<tex '\rightarrow U \mathbf{k}'>> far from the sphere, with <<tex '\mathbf{k}'>> being the direction of flow.
*Interesting to calculate viscous drag if <<tex 'Re \ll 1'>>, i.e Stoke's flow.
*Boundary conditions:
**<<tex '\mathbf{u} \rightarrow U \mathbf{k}'>> far from the sphere;
**<<tex '\mathbf{u} = 0'>> on the surface of the sphere (no slip).
**<<tex 'p \rightarrow p_{\infty} = \textrm{const}'>> far from the sphere
*Can use Stoke's Law for drag on a sphere to calculate this, and from dimensional analysis:
><<tex 'D = K \mu a U'>>
*Here, K is a constant that depends on the geometry of the object, in the case of a sphere from solving Laplace's equation get <<tex 'K = 6 \pi'>>.

*Characteristic timescale it takes for a star to respond to a dynamic change.
*Can be defined in terms of the time it would take the star to collapse completely if pressure forces were negligible:
><<tex 's = \frac{1}{2} g t^2 = \frac{1}{2} (GM_r / r^2)t^2'>>
and with <<tex 's \approx R_S, r \approx R_S, M_r \approx M_s'>>:
><<tex 't_{\textrm{dyn}} \approx \left(\dfrac{2 R_s^3}{GM_s}\right)^{\frac{1}{2}} \approx \left(\dfrac{3}{2 \pi G \bar{\rho}}\right)^{\frac{1}{2}}'>>
*This gives a value of <<tex '(t_{\textrm{dyn}})_{\odot} \approx 40 \textrm{mins}'>>.
*Stars therefore adjust very quickly to changes in pressure and gravity and maintain stability.
*Start with the expression for the heat capacity.
><<tex 'C = \dfrac{\partial}{\partial T} \displaystyle\int_0^\infty \dfrac{\hbar \omega}{e^{\beta \hbar \omega} - 1} g(\omega) d \omega'>>
*The Einstein Model is one method to calculate the density of states, <<tex 'g(\omega)'>>.
*All N atoms vibrate with the same frequencey, the Einstein frequency, <<tex '\omega_E'>>. This gives:
><<tex 'g(\omega) = 3 N \delta(\omega - \omega_E)'>>
*This leads to a heat capacity:
><<tex 'C = 3 N k_B \left( \dfrac{\Theta_E }{T} \right)^2 \dfrac{ e^{\Theta_E / T} }{(e^{\Theta_E / T} - 1)^2}'>>
>
><<tex '\Theta_E = \dfrac{\hbar \omega_E}{k_B}'>>

[img[Einstein Model|images/1211406862.png]]

*At <<tex 'T < \Theta_E'>>, the functional form is:
><<tex '\dfrac{e^{- \Theta_E / T}}{T^2}'>>


*In this laser, the low lasing level lies quite a long way above the ground state, so the thermal population will be small, even during lasing, due to rapid decay to the ground state.
*This is therefore a good example of a four level laser. It is easy to achieve population inversion in this system.
*As before:
><<tex 'N_{thresh}^* = N_2^{thresh} - N_1^{thres}'>>
*however, as <<tex 'N_1 \approx 0'>>
><<tex 'N_2^{thresh} = N_{thresh}^*'>>
*This value is often around 3 orders of magnitude smaller than that for the Ruby 3-level laser.
*The only problem is overcoming losses in the cavity: 
**This was easy before in the 3-level laser, as over half the population needed to be in the upper level, so high energy output could easily be obtained by allowing them to drop.
**Here however, any number of ions in the upper level constitutes population inversion, so small levels of inversion will lose all their energy.
**The threshold energy is still small however, <<tex '150 \rm{mJ}'>>, and a CW operation absorbed power of <<tex '11W'>>, and operation power of <<tex '650 \rm{W}'>>. Easily achievable.
*Practical devices can even be pumped by highly efficient diode lasers:
**electrical efficiency near 50%
**large proportion of the output power is in the correct pump band and not other parts of the spectrum
**uni-directional so easier to couple to laser rod.
*Overall efficiency of Nd:YAG can exceed 1% using a diode pump.
*See [[Radiation|6. Energy Transport - Radiation]], where we have (rearranged):
><<tex '\dfrac{dT}{dr} = - \dfrac{3 \kappa L_r \rho}{16 \pi a c r^2 T^3}'>>
*This describes temperature profile dependence on opacity etc. 
*Approximate analytical forms for opacity:
**High temperature (constant): <<tex '\kappa = \kappa_1 = 0.020 \textrm{m}^2 \textrm{kg}^{-1} (1+X)'>>
**Intermediate temperature (inverse): <<tex '\kappa = \kappa_2 \rho T^{-3.5}'>> (Kramer's law)
**Low temperature (power): <<tex '\kappa = \kappa_3 \rho^{1/2} T^4'>>
*<<tex '\kappa_1, \kappa_2, \kappa_3'>> are constants for a given chemical composition.
*From the ever useful incompressibility condition on a standard 2D flow:
><<tex '\dfrac{\partial u}{\partial x} + \dfrac{\partial v}{\partial y} = 0'>>
so we can write:
><<tex 'u = \dfrac{\partial \psi}{\partial y}'>>
>
><<tex 'v = - \dfrac{\partial \psi}{\partial x}'>>
*Where <<tex '\psi'>> is the streamfunction. 
*Streamlines mark out a path a blob would take.
*If the flow is also irrotational, we get Laplace's equation again:
><<tex '\nabla^2 \psi = 0'>>
*Also:
><<tex '\mathbf{u} \cdot \nabla \psi = 0'>>
>
>//The velocity is parallel to lines of constant <<tex '\psi'>>, or perpendicular to lines of constant <<tex '\phi'>>.//
>''N.S.:'' 
>
><<tex '\dfrac{D \textbf{u}}{Dt} \equiv \dfrac{\partial \textbf{u}}{\partial t} + ( \textbf{u} \cdot \nabla) \textbf{u} = - \dfrac{1}{\rho} \nabla p + \dfrac{\mu}{\rho} \nabla^2 \textbf{u}'>>
*Using compressibility, and the vector identity:
><<tex '(\textbf{u} \cdot \nabla) \textbf{u} = \frac{1}{2} \nabla |\textbf{u}|^2 - \textbf{u} \times (\nabla \times \textbf{u})'>>
*This gives:
><<tex '\dfrac{\partial \textbf{u}}{\partial t} + \nabla (\frac{1}{2} |\textbf{u} |^2 = \dfrac{p}{\rho} + gz) - \textbf{u} \times (\nabla \times \textbf{u}) = \nu \nabla^2 \textbf{u}'>>
*Now using
**Vorticity [[definition|1. Definition and Interpretation]]
**<<tex 'curl(grad) = 0'>>
**<<tex '\nabla \times (\nabla^2 \textbf{u}) = \nabla^2(\nabla \times \textbf{u})'>>
*Gives the ''vorticity equation'':
><<tex '\dfrac{\partial \boldsymbol{\omega}}{\partial t} - \nabla \times (\boldsymbol{u} \times \boldsymbol{\omega}) = \nu \nabla^2 \boldsymbol{\omega}'>>
*or:
><<tex '\dfrac{D \boldsymbol{\omega}}{D t} - (\boldsymbol{\omega} \cdot \nabla)\textbf{u} = \nu \nabla^2 \boldsymbol{\omega}'>>
*Using the dispersion relation:
><<tex '\sigma^2 = gk'>>
**Phase and group velocities:
><<tex 'c_p = \dfrac{\sigma}{k} = \sqrt{\dfrac{g}{k}}'>>
>
><<tex 'c_g = \dfrac{\partial \sigma}{\partial k} = \frac{1}{2} \sqrt{\dfrac{g}{k}} = \frac{1}{2} c_p'>>
**We see that these waves are dispersive as <<tex 'c_p'>> depends on <<tex 'k'>>.

*Assume a bulk fluid velocity component in the x-direction, that only depends on z, <<tex 'u(z)'>>.
*Tangential viscous stress in x, (this defines <<tex '\mu'>>, ''dynamic viscosity''):
><<tex '\tau_{xz} = \mu \dfrac{d u }{d z}'>>
*Net viscous force on blob:
><<tex '\delta F= (\tau(z) - \tau(z + dz))\delta A'>>
>
><<tex '\delta F = -\delta z \dfrac{\partial \tau}{\partial z} \delta A = \delta V \dfrac{\partial \tau}{\partial z}'>>
>
><<tex '\delta F_v = \mu \dfrac{d^2 u}{dz^2} \delta V'>>
*More complicated 3d derivation gives:
><<tex '\delta \textbf{F}_v = \delta V \mu [\nabla^2 \textbf{u} + \frac{1}{3} \nabla(\nabla \cdot \textbf{u})]'>>
*<<tex '\nu = \mu / \rho'>> is the ''kinematic viscosity''
*Can calculate number of photons per mode for two examples. General steps:
**Relate ''total'' intensity of the source to the spectral intensity, <<tex 'I_T = I(\omega) \Delta \omega'>>, where <<tex '\Delta \omega'>> is the bandwidth of the source. 
**From spectral intensity can find spectral number density of photons, from [[photons per mode for common sources|2. Photons Per Mode for Common Sources]], then photons per mode is given by <<tex '\langle n_\omega \rangle = n(\omega) / g(\omega)'>>.
*''Example 1'' - Single-isotope mercury lamp:
**Single isotope means broadening is only from Doppler effect;
**Bandwidth of <<tex '\sim 0.2 \rm{nm}'>> at <<tex '253.7 \rm{nm}'>>, with intensity of <<tex '1 \rm{W cm}^{-2}'>>.
*''Example 2'' - Frequency stabilized argon-ion laser:
**Delivers <<tex '5 \rm{W}'>> of power in a beam <<tex '2 \rm{mm}'>> in diameter;
**Linewidth of <<tex '0.002 \rm{nm}'>> at <<tex '488 \rm{nm}'>>.

| ! | ! | !<<tex 'Hg'>> lamp | !<<tex 'Ar^+'>> laser |
| Wavelength (nm) | <<tex '\lambda'>> | 253.7 | 488 |
| Bandwidth (nm) | <<tex '\Delta \lambda'>> | 0.2 | 0.0002 |
| Frequency bandwidth (<<tex '\omega = 2 \pi c / \lambda'>>) | <<tex '\Delta \omega'>> | <<tex '6 \times 10^{12}'>> | <<tex '2 \times 10^{10}'>> |
| Intensity <<tex 'W m^{-2}'>> | <<tex 'I_T'>> | <<tex '10^4'>> | <<tex '1.6 \times 10^6'>> |
| Spectral Intensity | <<tex 'I(\omega) = I_T / \Delta \omega'>> | <<tex '1.7 \times 10^{-9}'>> | <<tex '1.0 \times 10^{-4}'>> |
| Spectral Photon Density (using expression for different sources) | <<tex 'n(\omega)'>> | <<tex '7.3'>> | <<tex '8.3 \times 10^5'>> |
| Spectral Mode Density | <<tex 'g (\omega) = \dfrac{\omega^2}{\pi^2 c^3}'>> | <<tex '2.1 \times 10^5'>> | <<tex '5.6 \times 10^4'>> |
| Photons Per Mode | <<tex '\langle n_\omega \rangle = n(\omega) / g(\omega)'>> | <<tex '3 \times 10^{-5}'>> | <<tex '\textbf{15}'>> |

*Here we see that the photons per mode, <<tex '\langle n_\omega \rangle'>> is much higher for lasers, in fact:
**<<tex '\langle n_\omega \rangle \gg 1'>> for laser sources in general;
**<<tex '\langle n_\omega \rangle \ll 1'>> for non-laser sources.
*This is due to the difference of stimulated and spontaneous emission in the sources.
*This time there are two different atoms, with two different masses.
*Nearest neighbour forces only:
><<tex 'm_1 \dfrac{\partial^2 u_n}{\partial t^2} = C(u_{n+1} - 2 u_n + u_{n-1})'>>
>
><<tex 'm_2 \dfrac{\partial^2 u_{n-1}}{\partial t^2} = C(u_n - 2 u_{n-1} + u_{n-2})'>>
*Trial solutions of the form:
**For <<tex 'm_1'>>:
><<tex 'u_n = Ae^{i (kn(a/2) - \omega t)}'>>
**For <<tex 'm_2'>>:
><<tex 'u_{n-1} = \alpha A e^{i (k [n-1] (a/2) - \omega t)}'>>
*Here <<tex '\alpha'>> is the complex amplitude ratio. Subs. into equations of motion, ''dispersion relation'':
><<tex '\omega^2 = \dfrac{C(m_1 + m_2)}{m_1 m_2} \pm C \left[ \left( \dfrac{m_1 + m_2}{m_1m_2}\right)^2 - \dfrac{4}{m_1 m_2} \sin^2 \left( \dfrac{ka}{2} \right) \right]^{1/2}'>>

[img[Dispersion|images/1211403534.png]]

*Consider behavoir at following points:
**''Point 0'':
***<<tex 'ka \ll 1'>>;
***<<tex '\omega \simeq 0'>>;
***<<tex '\alpha \simeq 1'>>;
***''Sound Waves'': both masses oscillate in phase because <<tex '\alpha \simeq 1'>>.
**''Point A'':
***<<tex 'ka \ll 1'>>;
***<<tex '\omega \simeq \sqrt{\dfrac{2 C (m_1 + m_2)}{m_1 m_2}}'>>;
***<<tex '\alpha = - m_1 / m_2'>>;
***Here, both masses oscillate in anti-phase.
**''Points B & C'':
***<<tex 'ka = \pi'>>;
***At B, <<tex '\omega = \sqrt{\dfrac{2 C}{m_2}}'>> and at C <<tex '\omega = \sqrt{\dfrac{2 c}{m_1}}'>>;
***At B, <<tex '\alpha = \infty'>>, and at C <<tex '\alpha = 0'>>;
***At B, <<tex 'm_2'>> is oscillating and <<tex 'm_1'>> is ar rest, and visa versa for C.
*All modes on the accoustic branch are oscillating in the same direction. Near the origin, they're oscillating within a unit cell.
*On the optic branch, near A, atoms oscillate in antiphase in a unit cell.
*Oxygen and Nitrogen do not absorb heavily in the visible or infrared - diatomic.
*Radiatively active constituents:
**Water vapour (IR)
**Carbon dioxide (IR)
**Methane (IR)
**Nitrous Oxide (IR)
**Ozone (IR and UV)
**~CFCs (IR)
**Aerosols and clouds (Visible and IR)
*Using the 1D model, there are 2N states available. For monovalent metals, electrons will fill up half the states, allowing observed conducting behavior as the electrons are free to move around into the empty states.
*But for divalent metals, all 2N states are taken up - the band is full and there is no space to conduct so insulating behavior should be observed. However, this is not the case for many group 2 metals such as Calcium.
*This problem is rectified in 2D:
>[img[Monovalent and Divalent metals in 2D|images/1209140696.png]]
>The hashed area is the Brillouin zone, the white area depicts the filled Fermi states.
*The 'corners' of the 1st band actually lie at higher anergy than the bottom states of the 2nd band (by a factor of <<tex "\sqrt{2}">>) - and therefore the bands overlap, so the electrons still have space to move.
*As electron-lattice interaction strength increases, the Fermi circle deforms into a square, filling the first BZ completely. Here a band gap forms between the 1st and 2nd bands, the electrons have nowhere to go and the material is an insulator.
*30-50% of stars experience mass transfer from Roche-lobe overflow, but usually during late phases of lifetime;
*Quasi-conservative mass transfer:
**One star loses mass, other experiences accretion. 
**Mass loser loses its envelope and forms a 'helium star';
**The accretor is rejuvenated with lighter elements and behaves as if its evolutionary clock has been reset;
**The orbit usually widens.
*Dynamic mass transfer:
**Common envelope between two stars (one is usually a red giant);
**Accretor also fills its lobe;
**Donor engulfs accretor;
**Two cores spiraling inside a common envelope;
**Envelope can be ejected forming a very close binary, or
**Two cores can merge into a single, rapidly rotating star.
 
*Can be observed baryon fraction is <<tex '\Omega_B \sim 0.04'>>;
*Large galaxies rotate much faster than they should! ''Dark matter'', <<tex '\Omega_{DM} \sim 0.25'>>;
*Total <<tex '\Omega = 1 \pm 0.05'>> (measured) meaning the Universe is flat.
**But we only have 0.3, and we need 1 to get a flat universe:
**''Dark energy'' <<tex '\Omega_{DE} \simeq 0.7'>>
*These estimates, with believed <<tex 'H_0 = 67 \textrm{Km s}^{-1} \textrm{Mpc}^{-1}'>>, give age of the universe of <<tex '15 \textrm{Gyr}'>>.
*At early times, before recombination (at 0.308eV - not 13.6eV due to Saha equation), radiation is in thermal equilibrium, and creates a Planck spectrum. 
*After recombination, photons are left to propagate freely:
**Only effect is redshifting due to expansion;
**Spectrum is just shifted, indicating the change in temperature.
*History of a photon's lifetime:
**Early universe, hot temperature all in thermal equilibrium;
**Suddenly at recombination, photon is 'released' from ''surface of last scattering'' - moves on its current path in a straight line, but original spectrum is maintained;
**We see today a 'photograph' of the universe at recombination time, age of the universe of around 380,000 years. 
*Can be described in terms of a ''lattice'' - the network of points that fills space, and a ''basis'' - a group of atoms assosciated with each lattice point.
*Mathematically:
**A lattice represented by a set of delta functions:
><<tex '\displaystyle\sum_{\vec{l}} \delta (\vec{r} - \vec{l})'>>
**A basis represented as a function of position:
><<tex 'f(\vec{r})'>>
**A crystal structure represented by their convolution:
><<tex '\displaystyle\sum_{\vec{l}} \delta (\vec{r} - \vec{l}) * f(\vec{r}) '>>
>
><<tex "= \displaystyle\sum_{\vec{l}} \int \delta (\vec{r} - \vec{l} - \vec{r}') * f(\vec{r}) d^3 \vec{r}'">>
>
><<tex '= \displaystyle\sum_{\vec{l}} f(\vec{r} - \vec{l})'>>


*Form factor:
**Consider again <<tex '\displaystyle\sum_{\mathbf{s}_d} ... '>> from the derivation of [[Laue diffraction|2. Laue Diffraction Theory]].
><<tex '\begin{array}{rl} \displaystyle\sum_{\mathbf{s}_d} e^{i \mathbf{Q} \cdot \mathbf{s}_d} &= \int n_d (\mathbf{r}) e^{i \mathbf{Q} \cdot \mathbf{r}} d^3 \mathbf{r} \\ & \\ &= f_d (\mathbf{Q}) \end{array}'>>
**Here, <<tex 'f_d(\mathbf{Q})'>> is called the ''atomic form factor'' of d.
*Structure factor:
**Now consider <<tex '\displaystyle\sum_{\mathbf{d}} ...'>> from the same derivation.
**Assume <<tex '\mathbf{Q} = \mathbf{G}_{hkl}'>> for some <<tex '(hkl)'>>:
><<tex '\begin{array}{rl} \mathbf{Q} \cdot \mathbf{d} &= \mathbf{G}_{hkl} \cdot \mathbf{d} \\ & \\ &= (h \mathbf{a}^* + k \mathbf{b}^* + l \mathbf{c}^*) \cdot (x_d \mathbf{a} + y_d \mathbf{b} + z_d \mathbf{c}) \end{array}'>>
**For an orthogonal lattice: 
***<<tex '\mathbf{a}^* \cdot \mathbf{a} = \mathbf{b}^* \cdot \mathbf{b} = \mathbf{c}^* \cdot \mathbf{c} = 2 \pi'>>;
***<<tex '\mathbf{a}^*.\mathbf{b} = 0'>>, etc.
><<tex '\mathbf{Q} \cdot \mathbf{d} = 2 \pi (h x_d + k y_d + l z_d)'>>
**This leads to the ''structure factor'', the scattering amplitude:
><<tex 'S_{hkl} = \displaystyle\sum_{d} f_d (\mathbf{G}_{hkl}) e^{ i 2 \pi (h x_d + k y_d + l z_d)}'>>
**N.B. Remember multiplicity of reflection for amplitude...
*''Intensity'':
><<tex 'I_{hkl} \propto | \psi |^2'>>
>
><<tex 'I_{hkl} \propto | S_{hkl} |^2 \delta(\mathbf{Q} - \mathbf{G}_{hkl})'>>
*Example 1:
**Lattice: Primitive Cubic
**Basis: Cs <<tex '000'>>, Cl <<tex '\frac{1}{2}, \frac{1}{2}, \frac{1}{2}'>>
><<tex 'S_{hkl} = f_{Cs} (\mathbf{G}_{hkl}) + f_{Cl} (\mathbf{G}_{hkl}) e^{i \pi (h + k + l)}'>>
**This gives intensities:
***<<tex '(f_{Cs} + f_{Cl})^2'>> if h+k+l is even;
***<<tex '(f_{Cs} - f_{Cl})^2'>> if h+k+l is odd.
*Example 2:
**Lattice: FCC
**Basis: Cu <<tex '000, \frac{1}{2}\frac{1}{2}0, \frac{1}{2}0\frac{1}{2}, 0\frac{1}{2}\frac{1}{2}'>>
><<tex 'S_{hkl} = f_{Cu} (\mathbf{G}_{hkl})\left[1 + e^{i \pi(h+k)} + e^{i \pi(h+l)} + e^{i \pi(k+l)}\right]'>>
**This gives intensities:
***<<tex '16 f_{Cu}^2'>> if h,k,l are all even or all odd;
***<<tex '0'>> otherwise.





[img[Rate Analysis|images/1211552184.png]]

*Rate equations for the laser levels are (where <<tex 'I'>> is the //total// (not spectral) intensity):
><<tex '\dfrac{d N_2}{dt} = R_2 - N^* \sigma_{21} (\omega_L - \omega_0) \dfrac{I}{\hbar \omega_L} - \dfrac{N_2}{\tau_2}'>>
>
><<tex '\dfrac{d N_1}{dt} = R_1 + N^* \sigma_{21} (\omega_L - \omega_0) \dfrac{I}{\hbar \omega_L} + N_2 A_{21} - \dfrac{N_1}{\tau_1}'>>
*The Einstein A term is the spontaneous emission between the levels, and the two sigma terms are the stimulated emission rates. Absorption is included in other terms.
*Steady state solutions:
><<tex 'N_2 = R_2 \tau_2 - N^* \sigma_{21} \dfrac{I}{\hbar \omega_L} \tau_2'>>
>
><<tex 'N_1 = R_1 \tau_1 + N^* \sigma_{21} \dfrac{I}{\hbar \omega_L} \tau_1 + N_2 A_{21} \tau_1'>>
*Can obtain an expression for <<tex 'N^*'>>:
><<tex 'N^* = \dfrac{R_2 \tau_2 [1 - (g_2 / g_1) A_{21} \tau_1] - (g_2/g_1) R_1 \tau_1}{1 + \sigma_{21} \frac{I}{\hbar \omega_L} [ \tau_2 + (g_2 / g_1) \tau_1 - (g_2 / g_1) A_{21} \tau_1 \tau_2]}'>>
*When <<tex 'I = 0'>>, the denominator is equal to 1, so the numerator is the population inversion from pumping in the abscence of the beam, so we can simplify the expression to:
><<tex 'N^*(I) = \dfrac{N^*(0)}{1 + I/I_s}'>>
*where the ''saturation intensity'' is given by:
><<tex 'I_s = \dfrac{\hbar \omega}{\sigma_{21}} \left(\tau_2 + \dfrac{g_2}{g_1} \tau_1 - \dfrac{g_2}{g_1} A_{21} \tau_1 \tau_2 \right)^{-1} = \dfrac{\hbar \omega}{\sigma_{21} \tau_R}'>>
*where the ''recovery time'' is given by:
><<tex '\tau_R = \tau_2 + \dfrac{g_2}{g_1} \tau_1 [1 - A_{21} \tau_2]'>>
*Qualitatively, the expression for <<tex 'N^*(I)'>> tells us that an intense beam 'burns down' the population inversion. The saturation intensity will give a population inversion of <<tex '1/2'>> of that achieved without the beam present. It is therefore a marker to indicate the intensity to which the beam may be amplified before level populations are significantly affected, and marks the boundary between 'high' and 'low' intensity.
*Various approximations to the saturation intensity can be made:
**For four-level lasers, the lifetime of the lower level is much shorter than for the upper level, so <<tex '\tau_2 \gg \tau_1'>>;
**If the upper level's main decay is to the lower level, then <<tex '\tau_2 \approx A_{21}^{-1}'>>;
**For both of these cases:
><<tex '\tau_R \approx \tau_2'>>
>
><<tex 'I_S \approx \dfrac{\hbar \omega_L}{\sigma_{21} \tau_2}'>>
*The saturated gain coefficient can be found from earlier looks at the [[small signal gain coefficient|4. Small Signal Gain Coefficient]]:
><<tex '\alpha_I (\omega - \omega_0) = N^*(I) \sigma_{21} (\omega - \omega_0)'>>
*Or, written in terms of the small signal gain coefficient, <<tex '\alpha_0 (\omega - \omega_0)'>>:
><<tex '\alpha_I (\omega - \omega_0) = \dfrac{\alpha_0 (\omega- \omega_0)}{1 + I/I_s}'>>

><<tex 'H = \left( \dfrac{\dot{a}}{a} \right)^2 = \dfrac{8 \pi G}{3} \rho - \dfrac{k c^2}{a^2}'>>
*Can be seen that if <<tex '\rho \propto 1/a^3'>> or <<tex '1/a^4'>>, the curvature term dominates at late times.
**For <<tex 'k < 1'>>:
><<tex '\left( \dfrac{\dot{a}}{a} \right)^2 = \dfrac{|k|c^2}{a^2}'>>
>
><<tex 'a \propto t'>>, the scale factor grows at <<tex 'c'>>.
**For <<tex 'k > 0'>>:
***Universe grows until:
><<tex '\dfrac{8 \pi G}{3} \rho = \dfrac{k c^2}{a^2}'>>
***Then it stars to shrink... ''big crunch''.
*Can think of this in terms of a ''critical density'':
**When <<tex 'k = 0'>> we have:
><<tex '\rho = \rho_c \equiv \dfrac{3H^2}{8 \pi G}'>>
>
>This corresponds to a balance between gravitational and kinetic energy.
**If <<tex 'k < 0'>>, then <<tex '\rho < \rho_c'>>:
***Kinetic energy is larger, and the universe keeps expanding
**If <<tex 'k >0'>> then <<tex '\rho > \rho_c'>>:
***GPE is larger, and eventually universe collapses.
*This can be summarised with the [[density parameter|4. The Density Parameter]].
* Using <<tex 'E = k_B T'>>, a change in temperature from absolute zero excites electrons just below <<tex 'E_F'>> to just above <<tex 'E_F'>>, by energy <<tex '~ k_B T'>>.
* Number of electrons which are excited = density of electrons at that energy <<tex '\times'>> the energy:
><<tex 'E_F g(E_F) = k_B T g(E_F)'>>
* <<tex '\therefore'>> Total energy change = energy per electron <<tex '\times'>> number of electrons:
><<tex '\Delta E \approx k_B^2 T^2 g(E_F)'>>
*Classically, using the equipartition theorem, <<tex 'C_v = \frac{3}{2} n k_B'>>, but because everything has been 'shifted along' by <<tex 'T_F'>>, the additional term can be seen as scaling the heat capacity.
*More rigorously:
><<tex 'C_v = \frac{\pi^2}{2} n k_B \frac{T}{T_F}'>>
*PPI Chain (times for the Sun, <<tex 'T = 3 \times 10^7 K'>>):
**<<tex '1) {}^1\textrm{H} + {}^1\textrm{H} \rightarrow {}^2\textrm{D} + \textrm{e}^+ + \nu + 1.44\textrm{MeV}, (\tau \approx 14 \times 10^9 \textrm{years}) '>> 
**<<tex '2) {}^2\textrm{D} + {}^1\textrm{H} \rightarrow {}^3\textrm{He} + \gamma + 5.49\textrm{MeV}, (\tau \approx 6 \textrm{s})'>>
**<<tex '3) {}^3\textrm{He} + {}^3\textrm{He} \rightarrow {}^4\textrm{He} + {}^1\textrm{H} + {}^1\textrm{H} + 12.85\textrm{MeV}, (\tau \approx 10^6 \textrm{years})'>>
**First two occur twice, second once for each <<tex '4 \textrm{H} \rightarrow {}^4\textrm{He}'>>
**0.26MeV lost by the neutrino, so total of 26.2MeV is luminosity energy.
**First reaction very slow as it's a weak process, and bottlenecks the chain.
**Second reaction by far the quickest, deuterium burns very quickly.
*If there's enough Helium we can also have:
**PPII chain:
***<<tex '3a) {}^3\textrm{He} + {}^4\textrm{He} \rightarrow {}^7\textrm{Be} + \gamma + 1.59\textrm{MeV}'>>
***<<tex '4a) {}^7\textrm{Be} + \textrm{e}^- \rightarrow {}^7\textrm{Li} + \nu + 0.86\textrm{MeV}'>>
***<<tex '5a) {}^7\textrm{Li} + {}^1\textrm{H} \rightarrow {}^4\textrm{He} + {}^4\textrm{He} + 17.35\textrm{MeV}'>>
**PPIII chain:
***<<tex '4b) {}^7\textrm{Be} + {}^1\textrm{H} \rightarrow {}^8\textrm{B} + \gamma + 0.14\textrm{MeV}'>>
***<<tex '5b) {}^8\textrm{B} \rightarrow {}^8\textrm{Be} + \textrm{e}^+ + \nu'>>
***<<tex '6b) {}^8\textrm{Be} \rightarrow {}^4\textrm{He} + {}^4\textrm{He} + 18.07\textrm{MeV}'>>
*Total energy is the same in each case but the neutrino carries away different energies from each.
*All chains operate simultaneously, the second two chains act as catalysts for the conversion of <<tex '{}^3\textrm{He} + {}^1\textrm{H} \rightarrow {}^4\textrm{He}'>>.
*''Multiplicity'':
**planes with the same spacing contribute to the same diffraction peak, so multiplicity makes some peaks larger than others:
**cubic system (<<tex 'a=b=c'>>):
| !<<tex '(hkl)'>> | !multiplicity |
| <<tex '(\pm 1 0 0), (0 \pm 1 0), (0 0 \pm 1)'>> | 6 |
| <<tex '(\pm 1 \pm 1 0), (0 \pm 1 \pm 1), (\pm 1 0 \pm 1)'>> | 12 |
| <<tex '(\pm 1 \pm 1 \pm 1)'>> | 8 |
**similarly tetragonal system (<<tex 'a=b\not=c'>>):
| !<<tex '(hkl)'>> | !multiplicity |
| <<tex '(100), (010)'>> | 4 |
| <<tex '(001)'>> | 2 |
| <<tex '(110)'>> | 4 |
| <<tex '(101)'>> | 8 |
*Circulation definition:
><<tex '\Gamma_C \equiv \displaystyle{\oint_C} \mathbf{u} \cdot d\mathbf{l}'>>
*After a jaunty derivation, ''Kelvin's Circulation Theorem'' comes out as:
><<tex '\dfrac{d \Gamma_C}{dt} = \nu \displaystyle{\oint_C}(\nabla^2 \mathbf{u}) \cdot d \mathbf{l}'>>
>
>Or for an inviscid (non-viscous) flow:
>
><<tex '\dfrac{d \Gamma_C}{dt} =0'>>
*The circulation is constant for an inviscid, uniform-density flow following a closed moving material circuit.
*Atmosphere cooled from 'top down' by radiation, due to layers of atmosphere emitting infrared both up and down, hard for IR on surface to escape.
*''Lapse rate'' defined as:
><<tex '\Gamma = - \dfrac{dT}{dz}'>>
*Using First Law of Thermodynamics, and <<tex 'c_v = (dU / dT)'>>, and for adiabatic (<<tex 'dQ = 0'>>):
><<tex 'dQ = c_v dT + p dV = 0'>>
*Using ideal gas law:
><<tex pdV + Vdp = RdT = (c_p - c_v)dT'>>
*Combining all these:
><<tex 'c_p dT = V dp = - g dz'>>
*So for ''DRY'' air (as we haven't accounted for phase changes), we defined the //dry// adiabatic lapse rate:
><<tex '\Gamma_d = - \dfrac{dT}{dz} = \dfrac{g}{c_p} \simeq 9.7 \textrm{K km}^{-1}'>>
*Stability:
**If ambient rate <<tex '\Gamma < \Gamma_d'>>, the air cools faster than surroundings, is less dense, and gets restored back down - column is stable.
**If <<tex '\Gamma > \Gamma_d'>>, the parcel just accelerates upwards - but this mixes the atmosphere. If there is a cold parcel somewhere, it is heated by IR until <<tex '\Gamma = \Gamma_d'>>, and this is maintained due to mixing.
*Can get oscillations of lapse rate about <<tex '\Gamma_d'>> at the ''buoyancy frequency''.
*In reality, <<tex '\Gamma \simeq 6-7 \textrm{K km}^{-1}'>> (less than the dry lapse rate) because:
**Air contains moisture;
**The dry lapse rate is a limit.


*Deep water is defined as <<tex 'd \gg \lambda / 2 \pi'>>, which allows us to get this far.
*If the water is not deep, say <<tex 'd = h'>> then we have a 'no slip' condition, giving:
><<tex 'v(y=-h) = \dfrac{\partial \phi}{\partial y} = 0'>>
*We get the same expression as before for f, but different boundary conditions gives a different result:
><<tex 'f = C e^{ky} + De^{-ky}'>>
>
><<tex 'f = E \cosh k (y+h)'>>
*And the dispersion relation is:
><<tex '\sigma^2 = gk \tanh (kh)'>>
*''Shallow, long waves'' (e.g tsunami in open ocean):
**<<tex '\tanh kh \approx kh'>>;
**Giving <<tex 'c_p \approx c_0 = \sqrt{gh}'>>, which is independant of <<tex 'k \rightarrow'>> non dispersive;
**Also <<tex 'c_g = (d/dk)(c_0 k) = c_p'>>.
*''Fairly long waves'':
**<<tex '\tanh kh \approx kh - k^3 h^3 / 3'>>
><<tex 'c_p \approx \sqrt{hh - \dfrac{g}{3}k^2 h^3} = c_0 \sqrt{1 - \dfrac{k^2 h^2}{3}} \approx c_0 \left( 1 - \dfrac{k^2 h^2}{6} \right)'>>
>
><<tex 'c_g \approx \dfrac{d}{dk}(k c_p) = c_0 (1 - \frac{1}{2} k^2 h^2) \not= c_p'>>
**Therefore, 'slightly dispersive'.

*For a homogenously broadened laser transition, we consider amplification of a beam as it passes through a region <<tex 'z \rightarrow z + \delta z'>>, area <<tex 'A'>>, and the beam described by a spectral intensity <<tex 'I(\omega, z)'>>, and energy density <<tex '\rho(\omega, z)'>>;
*As the beam travels, energy is lost by absorption, but gained by stimulated and emission:
><<tex '[N_2 B_{21} - N_1 B_{12}] g_H(\omega - \omega_0) \rho(\omega, z) \delta \omega \cdot A \delta z \cdot \hbar \omega'>>
*This can also be written in terms of the intensity:
><<tex '[I(\omega, z + \delta z) - I(\omega, z)]A \delta \omega'>>
*Equating these two expressions yields (using <<tex 'I(\omega, z) = \rho(\omega, z) \cdot c'>>:
><<tex '\dfrac{\partial I}{\partial z} = [N_2 B_{21} - N_1 B_{12}] g_H(\omega - \omega_0) \dfrac{\hbar \omega}{c} I(\omega, z)'>>
>
><<tex '\dfrac{\partial I}{\partial z} = N^* \sigma_{21} (\omega - \omega_0) I(\omega,z)'>>
*This defines ''population inversion density'':
><<tex 'N^* = N_2 - \dfrac{g_2}{g_1} N_1'>>
*and the ''optical gain cross-section'':
><<tex '\sigma_{21} (\omega - \omega_0) = \dfrac{\hbar \omega_0}{c} B_{21} g_H(\omega - \omega_0)'>>
>
><<tex '\Rightarrow \sigma_{21}(\omega - \omega_0) = \dfrac{\pi^2 c^2}{\omega_0^2} A_{21} g_H (\omega - \omega_0)'>>
><<tex 'H = \left( \dfrac{\dot{a}}{a} \right)^2 = \dfrac{8 \pi G}{3} \rho - \dfrac{k c^2}{a^2}'>>
>
>Solutions to the derived equations, for simplicity set <<tex 'k = 0'>>.
*''Non Relativistic Matter'' (matter or dust):
**<<tex 'E = Mc^2'>>
**<<tex '\rho \propto E/V \propto 1/a^3'>>.
><<tex '\left( \dfrac{\dot{a}}{a} \right)^2 = \dfrac{8 \pi G}{3} \dfrac{\rho_0}{a^3}'>>
>
><<tex 'a^{1/2} \textrm{d}a = \sqrt{\dfrac{8 \pi G \rho_0}{3}} \textrm{d}t'>>
**<<tex '\rightarrow t \propto a^{3/2}'>>
**<<tex '\Rightarrow a \propto t^{2/3}'>>
*''Relativistic Matter'' (photons, neutrinos or //radiation//):
**<<tex 'E = h \nu = h 2 \pi / \lambda'>>
**<<tex '\lambda \propto a'>>
**Energy density, <<tex '\rho = E/V \propto 1/(V \lambda) \propto 1/a^4'>>
><<tex '\left( \dfrac{\dot{a}}{a} \right)^2 = \dfrac{8 \pi G}{3} \dfrac{\rho_0}{a^4}'>>
>
><<tex 'a . \textrm{d}a = \sqrt{\dfrac{8 \pi G \rho_0}{3}} \textrm{d}t'>>
**<<tex '\rightarrow t \propto a^{2}'>>
**<<tex '\Rightarrow a \propto t^{1/2}'>>
*''Cosmological Constant'' (background vacuum fluctuations-?):
**<<tex 'P = - \rho c^2'>>
**<<tex '\rho = \textrm{const}.'>>
**Gives <<tex 'a \propto \textrm{exp}(Ht)'>>
>[img[Energy Densities|images/1210440304.png]]
*Kepler's third law relates semi-major axis, <<tex 'a'>> (in AU) with the period, <<tex 'P'>> (in years):
><<tex '\dfrac{M_1 + M_2}{M_{\odot}} = \dfrac{a^3}{P^2}'>>
or more general form (not using Solar info):
><<tex '\left(\dfrac{P}{2 \pi}\right)^2 = \dfrac{a^3}{G(M+m)}'>>
*Visual binary stars:
**Sum of masses can be obtained from above
**If orbital radii are known relative to CM, then <<tex 'M_1 a_1 = M_2 a_2'>> can yield individual masses.
**Only works in very rare cases.
*Spectroscopic binary stars:
**Can measure radial velocity by observing doppler shifts.
**Can calculate inclination.
*Low and medium mass stars burning H in a shell, adding to He core;
*Growth of core until <<tex 'M_{\textrm{core}} / M \sim 0.1'>> (~Schonberg-Chandrasekhar limit), where core is too massive to be supported by thermal pressure and the core contracts releasing gravitational energy.
*Envelope expands from new energy surge, effective temperature decreases, star moves along the [[red giant|4. Red Giant Branch]] branch.
*Contraction stops when electron degeneracy pressure can take over to support the core at high enough density.
*Above <<tex '\sim 2 M_{\odot}'>>, He ignites before degeneracy pressure takes over.
*If <<tex 'M > 1.5 M_{\odot}'>> transition to red giant branch is very quick and few stars can be seen in this region, "Hertzsprung gap".
*Start with the expression for the heat capacity.
><<tex 'C = \dfrac{\partial}{\partial T} \displaystyle\int_0^\infty \dfrac{\hbar \omega}{e^{\beta \hbar \omega} - 1} g(\omega) d \omega'>>
*The Debye Model approximates the dispersion curve as linear, that is, it is effective in the low <<tex 'k'>> region of the dispersion relation:
><<tex '\omega = v_s k'>>
*We assume 3 degenerate acoustic branches in 3D (x, y, z vibrations):
><<tex '\begin{array}{rl} \Rightarrow g(\omega) &= \dfrac{3V}{(2 \pi)^3} 4 \pi k^2 \dfrac{\partial k}{\partial \omega} \\ & \\ &= \dfrac{3 V \omega^2}{2 \pi^2 V_s^3} \end{array}'>>
>
>True for <<tex '\omega \leq \omega_D'>>
>0 otherwise.
*<<tex '\omega_D'>> is determined by:
><<tex '3N = \displaystyle\int_0^{\omega_D} g(\omega) d \omega'>>
>
><<tex '\Rightarrow C = \dfrac{\partial}{\partial T} \left( \displaystyle\int_0^{\omega_D} \dfrac{3 V \hbar \omega^3}{2 \pi^2 V_s^3} \dfrac{d \omega}{e^{\hbar \omega / k_B T} - 1} \right)'>>
>
>Can subs <<tex 'x = \hbar \omega / k_B T'>>, and also define <<tex '\Theta_D \equiv \hbar \omega_D / k_B'>>
*When <<tex 'T \ll \Theta_D'>>, the upper limit <<tex '\rightarrow \infty'>> and the integral is doable, goes to <<tex '4 \pi^4 / 15'>>:
><<tex 'C \approx \dfrac{12 N k_B \pi^4}{5} \left( \dfrac{T}{\Theta_D} \right)^3'>>
*Similar looking plot  to the Einstein model, only with <<tex '\Theta_D'>> instead of <<tex '\Theta_E'>>:

[img[Debye Model|images/1211407779.png]]

*In this case however, the functional form for <<tex 'T < \Theta_D \rightarrow T^3'>>.
*Was seen earlier the [[mass conservation|5. Mass Conservation]] equation has a magnetostatic analogy with the charge conservation equation.
*In an inviscid, irrotational flow:
><<tex '\mathbf{u} = \dfrac{B}{r}\mathbf{i}_{\theta}, r \ge a'>>
>
>//N.B. This flow has macroscopic rotation but its vorticity is still zero//.
*The circulation is defined as :
><<tex '\Gamma_C = \displaystyle{\oint_C} \mathbf{u}.\textrm{d} \mathbf{l}'>>
*and for this flow:
><<tex '\Gamma_C = 2 \pi B'>>
*However, using Stoke's theorem:
><<tex '\Gamma_C = \displaystyle{\oint_S} \boldsymbol{\omega} . dS'>>
*As <<tex 'a \rightarrow 0'>> in this flow, we must define <<tex '\boldsymbol{\omega}'>> using a delta function at the origin to prevent <<tex '1/r \rightarrow \infty'>>:
><<tex '\boldsymbol{\omega} = 2 \pi B \delta(x) \delta(y) \mathbf{i}_z'>>
*We again get a magnetostatic analogy with this setup, the delta function is a wire, and the circulation is the B field around a wire, calculated using Ampere's law.
><<tex 'Re \equiv \dfrac{UL}{\nu}'>>
*The Reynolds number is a dimensionless number useful for looking at the importance of viscosity, as it is the ratio of inertial force / viscous force:
**For <<tex 'Re \gg 1'>> viscosity is relatively small;
**For <<tex 'Re \ll 1'>> viscosity is important;
*Due to this, as <<tex 'Re'>> increases, flow becomes more turbulant:
**e.g. As in pipe flow models, an increased pressure gradient and higher speed at constant viscosity will be more turbulant, as <<tex 'U'>> increases.
*Experimentally determined critical value for <<tex 'Re \sim 1200'>>, above which flow becomes turbulant, although flow can remain laminar above this if care is taken (an initial disturbance is required).
*Starting with hydrostatic equilibrium:
><<tex '\dfrac{dP_r}{dr} = - GM_r \rho_r / r^2'>>
multiply through by <<tex '4 \pi r^3 dr'>>:
><<tex '4 \pi r^3 dP_r = -(GM_r / r) 4 \pi r^2 \rho_r dr'>>
Integrate by parts:
><<tex '4 \pi [r^3 P_r]_{r=0, P=P_c}^{r=R_s, P \approx 0} - 3 \int_0^{R_s} P_r 4 \pi r^2 dr = - \int_0^{R_s} (G M_r / r) 4 \pi r^2 \rho_r dr'>>
*First term of LHS = 0.
*RHS is just gravitational potential energy, <<tex '\Omega'>>.
*For an ideal gas, <<tex 'u = P / (\gamma - 1)'>>:
><<tex '\begin{array}{l l} \int_0^R P_r 4 \pi r^2 dr & = (\gamma - 1) \int_0^R u 4 \pi r^2 dr \\ & = (\gamma - 1) U \end{array}'>>
>
><<tex '\triangleright 3(\gamma - 1) + \Omega = 0'>>
>
><<tex '\triangleright \gamma = 5/3'>> for an ideal gas,
>
><<tex '\triangleright E = U + \Omega'>>
>
><<tex '\triangleright E = -U = \Omega / 2'>>
*This shows that as the energy of a star decreases, the thermal energy increases, and hence the kinetic energy of the star increases. Stars have a negative heat capacity due to this; they heat up as the total energy decreases.
*Self-regulating behavior of stars: a sudden increase in nuclear burning causes the star to expand and cool, slowing the burning. 
*[img[Thin Film|images/1210787079.png]]
*Height of fluid much less than length scale of flow, <<tex 'h \ll L'>>.
*Scales:
><<tex '\dfrac{\partial^2 u}{\partial z^2} \sim \dfrac{U}{h^2}'>>
>
><<tex '\dfrac{\partial^2 u}{\partial x^2} \sim \dfrac{U}{L^2} \ll \dfrac{\partial^2 u}{\partial z^2}'>>
*Incompressible:
><<tex '\dfrac{\partial u}{\partial x} + \dfrac{\partial v}{\partial y} + \dfrac{\partial w}{\partial z} = 0 \Rightarrow \dfrac{W}{h} \sim {U}{L}'>>
*And:
><<tex '(\mathbf{u} \cdot \nabla)u = \left( u \dfrac{\partial}{\partial x} + v \dfrac{\partial}{\partial y} + w \dfrac{\partial}{\partial z} \right) u \sim \dfrac{U^2}{L} + \dfrac{UW}{h} \sim \dfrac{U^2}{L}'>>
*Comparing inertial and viscous terms:
><<tex '\dfrac{|(\mathbf{u} \cdot \nabla)u|}{|\nu \nabla^2 u|} \sim \dfrac{U L}{\nu} \left(\dfrac{h}{L}\right)^2 = Re \left( \dfrac{h}{L} \right)^2'>>
*As <<tex 'h \ll L'>> and Re is small due to viscousness, we can ignore the inertial nonlinear term:
><<tex '\nabla p = \mu \dfrac{\partial^2 \mathbf{u}}{\partial z^2}'>>
*But because <<tex '\partial p / \partial z'>> is so small, we can write <<tex 'p \approx p(x,y)'>> ignoring z-dependence giving:
><<tex '\mu \dfrac{\partial^2 u}{\partial z^2} = \dfrac{\partial p(x,y)}{\partial x}'>>
>
><<tex 'u(x,y,z) = \dfrac{1}{2 \mu} \dfrac{\partial p}{\partial x} z^2 + A(x,y) z + B(x,y)'>>

*Include force downwards due to gravity (<<tex '\textbf{k}'>> is the vertical unit vector):
><<tex '\delta \textbf{F}_g = - \rho \delta V g \textbf{k}'>>
*Total:
><<tex '\begin{array}{rl} \delta \textbf{F}_{\textrm{tot}} & = \delta \textbf{F}_p + \delta \textbf{F}_v + \delta \textbf{F}_g \\ & \\ & = - \delta V (\nabla p + \mu [\nabla^2 \textbf{u} - \frac{1}{3} \nabla(\nabla \cdot \textbf{u})] + \rho g \mathbf{k}) \\ & \\ \delta m & = \rho \delta V \\ & \\ \textbf{a} & = \delta \textbf{F} / \delta m \\ & \\ \Rightarrow \textbf{a} & = - \dfrac{1}{\rho} \nabla p + \nu [\nabla^2 \textbf{u} + \frac{1}{3} \nabla (\nabla \cdot \textbf{u} )] - g \textbf{k} \end{array}'>>
*Here, <<tex '\nu'>> is the [[kinematic viscosity|2. Viscous Forces]].



*Lagrangian system:
**Working with a single blob. Follow position of a blob at time <<tex 't \rightarrow \textbf{r}(t) = (x(t), y(t), z(t))'>>;
**It's velocity will be the value of the velocity field at the blob's position at time t:
><<tex '\dfrac{d\textbf{r}}{dt} = \textbf{u}(\textbf{r}(t), t)'>>
**To get acceleration can differentiate this (x-component):
><<tex '\dfrac{d^2x}{dt^2} = \dfrac{\partial u}{\partial t} + \dfrac{\partial u}{\partial x} \dfrac{d x}{d t} + \dfrac{\partial u}{\partial y} \dfrac{d y}{d t} + \dfrac{\partial u}{\partial z} \dfrac{d z}{d t}'>>
**<<tex 'dx/dt'>> etc. are just <<tex 'u, v, w'>>, the scalar components of vector <<tex '\textbf{u}'>>, so:
><<tex 'a_x = \dfrac{\partial u}{\partial t} + \textbf{u} \cdot \nabla u \equiv \dfrac{D u}{D t}'>>
**This defines the ''advective'' or ''material'' derivative (capital D) -the rate of change following the blob;
**Vector form:
><<tex '\textbf{a} = \dfrac{d^2 \textbf{r}}{dt^2} = \dfrac{\partial \textbf{u}}{\partial t} + (\textbf{u} \cdot \nabla)\textbf{u} = \dfrac{D \textbf{u}}{D t}'>>
*~Non-Linear! 
*Using the saturated gain coefficient, we know that a narrow band radiation beam's intensity will vary according to:
><<tex '\dfrac{dI}{dz} = \alpha_I I = \dfrac{\alpha_0}{1 + I/I_s} I'>>
*Can integrate this to give transcendental equation:
><<tex '\rm{ln} \left[ \dfrac{I(z)}{I(0)} \right] + \dfrac{I(z) - I(0)}{I_s} = \alpha_0 z'>>
**In the weak beam limit, the fractional term disappears as <<tex 'I(z) \ll I_s'>>, and this gives the same exponential dependence as before:
><<tex 'I(z) = I(0) e^{\alpha_0 z}'>>
**In the heavy beam limit, the logarithmic term is neglected as <<tex 'I(0) \gg I_s'>>, and this gives a linear dependence:
><<tex 'I(z) = I(0) + \alpha_0 I_s z'>>
*''Vorticity equation'':
><<tex '\dfrac{D \boldsymbol{\omega}}{D t} - (\boldsymbol{\omega} \cdot \nabla)\textbf{u} = \nu \nabla^2 \boldsymbol{\omega}'>>
*Assume:
**Inviscid, <<tex '\nu \rightarrow 0'>>;
**Flow of the form <<tex '\mathbf{u} = (u,v,0), \boldsymbol{\omega}=(0,0,\omega)'>>;
*Plugging this in gives:
><<tex '\dfrac{D \omega}{D t} = 0'>>
*Following a blob, vorticity is conserved;
*If the fluid is totally irrotational at <<tex 't = 0'>>, it will remain so;
*An [[inviscid, irrotational flow|iv. Inviscid, Irrotational Flows]]
*Starting from modified first law again:
><<tex 'dQ = T dS = c_v dT + p dV'>>
><<tex '\rightarrow c_p dT - V dp = c_p dT - \dfrac{RT}{p} dp'??
*Leads to:
><<tex 'dS = c_p \dfrac{dT}{T} - R \dfrac{dp}{p}'>>
*Can integrate this to get S:
><<tex 'S = c_p \textrm{ln} T - R \textrm{ln}p + S_0 = c_p \textrm{ln} (T p^{-\kappa}) + S_0'>>
*<<tex '\kappa = R / c_p = 1 - (1/\gamma)'>>, and <<tex '\gamma = c_p/c_v'>>, the heat capacity ratio. 
*We can bring a parcel of air down adiabatically, so <<tex 'S = 0'>>, moving from <<tex 'p = p_0'>>:
><<tex 'c_p \textrm{ln} T - R \textrm{ln} p = c_p \textrm{ln} \Theta - R \textrm{ln} p_0'>>
*Here,<<tex '\Theta'>> is the temperature the parcel would reach at the surface, and is called ''potential temperature'':
><<tex '\Theta = T \left( \dfrac{p_0}{p} \right)^{\kappa}'>>
*Potential temperature decreases with height, as shown in the diagram (the adiabats are parallel to the dry lapse rate):
[img[Potential Temperature|images/1210888109.png]] 
*Isentropes follow down to the axis, where the potential temperature is the intersection.
*Isentropes can be a useful coordinate system, as movement along isentropes is very fast, whereas descent between them it can be quite slow, however:
**Clouds can move rapidly up through isentropes;
**Radiation is the only mechanism for going back down.
*With an inviscid flow, irrotational flow, the vorticity equation can be written:
><<tex '\nabla \left(\dfrac{\partial \phi}{\partial t} + \frac{1}{2} |\mathbf{u}|^2 + \dfrac{p}{\rho} + gy \right) = 0'>>
*Integrating this and using the fact that <<tex '\mathbf{u} = \nabla \phi'>> is invariant under constant translation of <<tex '\phi'>> gives a form of Bernoulli's equation:
><<tex '\dfrac{\partial \phi}{\partial t} + \frac{1}{2} |\mathbf{u}|^2 + \dfrac{p}{\rho} + gy = 0'>>
*''Flow around a cyliner'': solving Laplace's equation in cylindrical polars, with boundary conditions:
**<<tex 'u_r(r=a) = 0'>> //(Normal velocity - The tangential velocity is non-zero as viscoscity is zero and the fluid does not follow the no-slip condition)//.
**<<tex '\phi \rightarrow Ux = U r \cos \theta'>> as <<tex 'r \rightarrow \infty'>> //The fluid is smooth and planar in the <<tex 'x'>> direction away from the cylinder//.
*Gives solution:
><<tex '\phi = U \left( r + \dfrac{a^2}{r} \right) \cos \theta'>> for <<tex 'r \ge a'>>
*Velocity components can be calculated using <<tex '\mathbf{u} = \nabla \phi'>> again, and substituting these into Bernoulli's equation at <<tex 'r=a'>>:
><<tex '\dfrac{p}{\rho} = \textrm{constant} - 2 U^2 \sin^2 \theta'>>

*//Couette Flow//
[img[Rotating Cylinders|images/1210608351.jpg]]
*Inner cylinder fixed, outer cylinder rotates with angular velocity <<tex '\Omega'>>.
*We want ''steady'', ''incompressible'' flow, with ''circular symmetry'' (<<tex '\partial / \partial \theta = 0'>>), and neglecting end effects, giving the form:
><<tex '\textbf{u} = u_{\theta}(r) \textbf{i}_{\theta}'>>
*NS Equation in polar form comes out with some horrible expression, and the <<tex '\theta'>> and <<tex 'r'>> parts of it must vanish seperately. Vanish requirement of <<tex '\theta'>> component gives:
><<tex '\dfrac{d^2 u_{\theta}}{dr^2} + \dfrac{1}{r} \dfrac{d u_{\theta}}{dr} - \dfrac{u_{\theta}}{r^2} = 0'>>
*Solutions of the form:
><<tex 'u_{\theta} = r^n \rightarrow n = \pm 1'>>
>
><<tex 'u_{\theta} = Ar + Br^{-1}'>>
*Boundary conditions:
**<<tex 'u_{\theta}(r=a) = 0'>> (Inner cylinder)
**<<tex 'u_{\theta}(r=b) = \Omega b'>> (Outer cylinder)
*Gives:
><<tex 'A = \dfrac{\Omega b^2}{b^2 - a^2}'>>
>
><<tex 'B = -\dfrac{\Omega a^2 b^2}{b^2 - a^2}'>>
>
><<tex 'u_{\theta} = \left(\dfrac{\Omega b^2}{b^2 - a^2} \right) r - \left(\dfrac{\Omega a^2 b^2}{b^2 - a^2} \right) \dfrac{1}{r}'>>
*Example question: What torque is needed to keep inner cylinder at rest to balance viscous forces?
**Use analogue of <<tex '\tau = \mu du/dz'>>:
><<tex '\tau = \mu \left[r \dfrac{d}{dr} \left( \dfrac{u_{\theta}}{r} \right) \right]_{r=a}'>>
*Notes:
**Pressure distribution can be found from the vanish requirement of the <<tex 'r'>> component.

*When a magnetic field is applied, the density of states for the <<tex '\uparrow'>> electrons is different to that of the <<tex '\downarrow'>> electrons, and the energy of each is shifted by <<tex '\pm \frac{1}{2} g \mu_B B'>>, where <<tex 'g = 2'>>.
*The 'top' of the density of states therefore has an excess of <<tex '\uparrow'>> states, as the dipole moment is anti-parallel to the spin angular momentum, and energy is therefore shifted downwards.
[img[g(k) is shifted by different amounts for the two spin states.|images/1209082567.png]]
*The imbalance of moments, <<tex '\Delta n = \frac{1}{2} g(E_F) \times 2 \mu_B B'>>.
*This gives a magnetisation, <<tex 'M = \mu_B \Delta n = \mu_B^2 g(E_F) B'>>.
*Magnetic susceptibilty, <<tex '\chi = M / H = \mu_0 \mu_B^2 g(E_F) = \frac{3}{2} n \mu_0 \mu_B^2 / E_F'>>
*Neutrons scatter from:
**Nuclei, good for crystal structure determination;
**Magnetic moments of electrons, good for magnetic structure determination.
*For X-rays:
><<tex 'f_d (\textbf{Q}) = \int n(r) e^{i \mathbf{Q} \cdot \mathbf{r}} d^3 \mathbf{r}'>>
>
>the FT of the electron density <<tex 'n(r)'>>.
*For neutrons, <<tex 'n(r)'>> is replaced by <<tex 'V_N(r)'>>, the nuclear potential. 
><<tex 'V_N(r) = b_d \delta(\mathbf{r})'>>
**<<tex 'b_d'>> is the scattering length of nucleus <<tex 'd'>>. This gives:
><<tex 'f_d(\mathbf{Q}) = \int b_d \delta(\mathbf{r}) e^{i \mathbf{Q} \cdot \mathbf{r}} d^3 \mathbf{r} = b_d'>>
**Basically, the atomic form factor for x-rays becomes the scattering length for neutrons, so:
><<tex 'S_{hkl} = \displaystyle\sum_d b_d e^{2 \pi i (h x_d + k y_d + l z_d)}'>>
*Non-dispersive waves obey wave equation:
><<tex '\dfrac{\partial^2 \eta}{\partial x^2} = \dfrac{1}{c_0^2} \dfrac{\partial^2 \eta}{\partial t^2}'>>
>
><<tex '\eta = F(x - c_0 t) + G(x + c_0 t)'>>
*One right moving part of the solution satisfies the equation
><<tex '\dfrac{\partial \eta}{\partial t} + c_0 \dfrac{\partial \eta}{\partial x} = 0'>>
*and plugging in a single fourier component <<tex '\eta = Re \eta_0 e^{i (kx - \sigma t)}'>> gives the dispersion relation:
><<tex '-i \sigma \eta_0 + c_0 i k \eta_0 = 0'>>
><<tex '\sigma = c_0 k'>>
*However, for [[slightly dispersive waves|3. Non-Deep Water: Dispersion]] the relation is:
><<tex '\sigma = c_p k = c_0 \left( k - \dfrac{k^3 h^3}{6} \right)'>>
*which would arise from:
><<tex '-i \sigma + c_0 ik + \dfrac{c_0 h^2}{6}(ik)^2 = 0'>>
*This implies an operator acting on <<tex 'e^{i(kx - \sigma t)}'>> of the form:
><<tex '\dfrac{\partial}{\partial t} + c_0 \dfrac{\partial}{\partial x} + \dfrac{c_0 h^2}{6} \left( \dfrac{\partial}{\partial x} \right)^3'>>
*We get the ''Korteweg-de Vries equation'' by using this and adding in a term for non-linearity (analogous to <<tex '\mathbf{u} \cdot \nabla \mathbf{u}'>>):
><<tex '\dfrac{\partial \eta}{\partial t} + c_0 \dfrac{\partial \eta}{\partial x} + \dfrac{3 c_0}{2h} \eta \dfrac{\partial \eta}{\partial x} + \gamma \dfrac{\partial^3 \eta}{\partial x^3} = 0'>>


*Using expression for number density:
><<tex 'n_i = g_i \left( \dfrac{2 \pi}{h^2} \right)^{3/2} (M_i k T)^{3/2} exp\left(\dfrac{\mu_i - M_i c^2}{k T}\right)'>>
*If we assume thermal equilibrium it all goes a bit wrong... :
**<<tex ' \mu_n = \mu_p'>>;
**With <<tex 'Q = 1.293\textrm{MeV}'>>, the mass difference between n and p:
><<tex '\dfrac{n_n^{eq}}{n_p^{eq}} = exp \left( - \dfrac{Q}{kT} \right)'>>
**This implies that as the universe cools, all neutrons disappear - clearly not the case;
**Must use non-equilibrium conditions instead!
*Instead assume weak interactions converting n to p and p to n occur at a rate <<tex '\Gamma'>>:
**If <<tex '\Gamma \gg H'>> then the protons and neutrons convert very fast, and approach the equilibrium condition... no neutrons.
**If <<tex '\Gamma \ll H'>> then the universe expands too quickly, stopping the conversions before too many can happen;
**'Freezing out' of conversions occurs when <<tex 'n_n^{eq} / n_p^{eq} \approx \frac{1}{6}'>>, although post freeze out neutron decays brings this to <<tex '\frac{1}{7}'>>.
*For a universe with <<tex '1/8'>> neutrons and <<tex '7/8'>> protons, and all the neutrons pairing with protons and making Helium, we get the observed <<tex '\sim 75\% \textrm{H}'>> and <<tex '\sim 25\% \textrm{He}'>>.
*It can therefore be seen that relics of lighter elements is left from <<tex 'T \sim \textrm{MeV}'>>, just as the relic bath of photons is left from <<tex 'T \sim \textrm{eV}'>>
*Any branch of dispersion curve (optic or acoustic) is periodic in the reciprocal lattice. 
><<tex 'u \propto e^{i (\mathbf{k}.\mathbf{l} - \omega t)}'>>
*Consider a wavevector value in the first period, and add a multiple of lattice space:
><<tex 'e^{i (\mathbf{k} + \mathbf{G}) \cdot \mathbf{l} = e^{i \mathbf{k} \cdot \mathbf{l}} e^{i \mathbf{G} \cdot \mathbf{l}}'>>
*Using definitions of <<tex '\mathbf{G}'>> and <<tex '\mathbf{l}'>>:
><<tex '\mathbf{G} = h \mathbf{a}^* + k \mathbf{b}^* + l \mathbf{c}^*'>>
>
><<tex '\mathbf{l} = n_1 \mathbf{a} + n_2 \mathbf{b} + n_3 \mathbf{c}'>>
*Dotting these two together yeilds an integer multiple of <<tex '2 \pi'>> from the definitions of the reciprocal lattice vectors.
*Thus: <<tex 'e^{i \mathbf{G} \cdot \mathbf{l}} = 1'>>
*Giving:
><<tex 'e^{i(\mathbf{k} + \mathbf{G})\cdot \mathbf{l}} = e^{i \mathbf{k} \cdot \mathbf{l}} e^{i \mathbf{G} \cdot \mathbf{l}} = e^{i \mathbf{k} \cdot \mathbf{l}}'>>
*Any normal mode can be represented by a wavevector in the first Brillouin Zone.
*''Brillouin Zone'': Wigner - Seitz primitive unit cell in reciprocal space.
*'p' different types of atoms in primitive unit (basis) gives 3p branches to the dispersion curve.
*3 of these are acoustic branches, 3p -3 of these are optic branches.
*Powered by H burning in shell above degenerate core;
*Core mass grows, temperature increases, luminosity increases, star climbs red giant branch.
*When core mass for <<tex 'M < 2 M_{\odot}'>> is <<tex '\sim 0.48 M_{\odot}'>> He ignites under degenerate conditions, ''Helium flash''!
**The pressure is independent of T and no self-regulation;
**Higher and higher T just increases rate, thermonuclear runaway until degeneracy breaks at <<tex 'T \sim T_{\textrm{fermi}}'>>
**The core expands again, decrease in energy generation and luminosity and the star falls onto the horizontal branch, (perpendicular to red giant branch).
*Helium burns until it's also used up leaving C and O in the core, with He burning in a shell. 
**Core contracts, degenerate core (as before)
**[[Asymptotic giant branch|5.Asymptotic Giant Branch]].
*Can express the intesntisy increase with <<tex 'z'>> as:
><<tex '\dfrac{1}{I} \dfrac{\partial I}{\partial z} = \alpha_{21}(\omega - \omega_0) = N^* \sigma_{21} (\omega - \omega_0)'>>
*Here, <<tex '\alpha'>> is the small signal gain coefficient. This is useful for later dicussions of gain saturation (where a very high intensity increases the rate of stimulated emission so much, that it decreases the population inversion.)
*We can now write:
><<tex 'I(\omega, z) = I(\omega, 0) e^{\alpha_{21}(\omega - \omega_0) \cdot z}'>>
*This shows the intensity increses exponentially with distance (ignoring gain saturation).
*The small signal gain coefficient is therefore useful for determining the performance of a laser as it is proportional to the population inversion density. 
*The optical gain coefficient is however a more fundamental quantity, but depends on the physics of the transition rather than the pumping conditions.



*Energy is radiated away by stars, and they are supported by thermal pressure, so an energy source is required to avoid collapse.
*Gravitational energy:
**Total GPE available, <<tex 'GM_s^2 / 2R_s'>>
**Would last for time:
><<tex 't_{\textrm{th}} \approx \dfrac{GM_s^2}{2R_s L_s}'>>
><<tex '(t_{\textrm{th}})_{\odot} \approx 0.5 \times 10^{15} \textrm{sec} \sim 10^7 \textrm{years}'>>
**The Sun's luminosity <<tex 'L_{\odot}'>> has not changed significantly in <<tex '10^9'>> years (geological evidence).
**Sun cannot be powered by gravitational and thermal energy alone.
*Nuclear energy can support stars:
**Up to <<tex '10^{45} J'>> in the Sun, which would last <<tex '10^{11}'>> years.
**<<tex '\epsilon_r'>> is the nuclear energy released per unit mass per sec, and will depend on <<tex 'T_r, \rho_r'>> and the concentration, and:
><<tex '\dfrac{dL_r}{dr} = 4 \pi r^2 \rho_r \epsilon_r'>>
**During rapid evolutionary phases, energy is used up as gravitational energy as well:
><<tex '\dfrac{dL_r}{dr} = 4 \pi r^2 \rho_r \left(\epsilon_r - T \dfrac{dS}{dt}\right)'>>
><<tex 'R_{\odot} = 6.96 \times 10^5 \textrm{km}'>>
*In general diameters are too small to be measured, but nearby ones can be measured by:
**Interferometers: Michelson interferometer for <<tex 'R_s \gg R_{\odot}'>>, intensity interferometer for hot main sequence stars with <<tex 'R_s \sim R_{\odot}'>>.
**Eclipsing binaries: can calculate relative radii from the period and length of eclipses.
**Lunar occulatations: as the moon passes in front of a star, diffraction on its edge causes a pattern which can be measured and infer the radii of the star.
**Indirect methods include using <<tex 'L_s = 4 \pi R_s^2 \sigma T^4_{\textrm{eff}}'>> and estimating the luminosity and temperature.
*(For <<tex 'T < 10^8 K'>>)
*Carbon, Nitrogen, Oxygen catalyze conversion of H to He, seed nuclei are believed to be Carbon-12 and Oxygen-16 and are found when some Helium burning has occured.
><<tex '
\begin{array}{rcl}
{}^{12}\textrm{C}+{}^1\textrm{H} & \rightarrow & {}^{13}\textrm{N}+\gamma \\
{}^{13}\textrm{N} & \rightarrow & {}^{13}\textrm{C} + \textrm{e}^++\nu\\
{}^{13}\textrm{C}+{}^1\textrm{H} & \rightarrow & {}^{14}\textrm{N}+\gamma \\
{}^{14}\textrm{N}+{}^1\textrm{H} & \rightarrow & {}^{15}\textrm{O}+\gamma \\
{}^{15}\textrm{O} & \rightarrow & {}^{15}\textrm{N} + \textrm{e}^++\nu\\
{}^{15}\textrm{N}+{}^1\textrm{H} & \rightarrow & {}^{12}\textrm{C} +{}^4\textrm{He} \end{array}'>>
*Timescale determined by slowest, (<<tex '{}^{14}\textrm{N} + {}^1\textrm{H}'>>)
*Time to equilibrium by second slowest, (<<tex '{}^{12}\textrm{C} + {}^1\textrm{H}'>>)
*In equilibrium, <<tex '\lambda_{12} n_{12} = \lambda_{13} n_{13} = \lambda_{14} n_{14} = \lambda_{15} n_{15}'>>, where <<tex '\lambda_x'>> is the rate and <<tex 'n_x'>> is the number density fo each chemical.
*Using the [[critical density|3. Geometry and Density]], we can define the ''density parameter'' or ''fractional energy density'':
><<tex '\Omega \equiv \dfrac{\rho}{\rho_c}'>>
**Value today, <<tex '\Omega_0'>>;
**Different contributions... matter, radiation etc.: <<tex '\Omega_M, \Omega_R ...'>>
*Geometries:
**<<tex '\Omega < 1 : \rho < \rho_c : k < 0'>>, the universe is open (hyperbolic);
**<<tex '\Omega = 0 : \rho = \rho_c : k = 0'>>, the universe is flat (Euclidean);
**<<tex '\Omega > 1 : \rho > \rho_c : k > 0'>>, the universe is closed (spherical).
*Can also be written (by dividing FRM by <<tex 'H^2'>>):
><<tex '\Omega - 1 = \dfrac{kc^2}{a^2 H^2} \propto kt'>>
*Einstein description is valid for virtually all lasers, and leads to the use of the ''rate equation''.
*Einstein pictures two energy levels, <<tex 'E_2''>>, which is above <<tex 'E_1'>>;
*Three ways for a photon to interact with atoms in these levels:
**''Spontaneous emission'': An atom decays from the higher energy level to the lower energy level, releasing a photon of energy <<tex '\hbar \omega_{21} = E_2 - E_1'>>;
***The rate at which this occurs is independent of conditions of the radiation field.
**''Absorption'': An atom in the lower energy level absorbes a photon of energy <<tex '\hbar \omega_{21}'>>, and is raised to the upper level.
**''Stimulated emission'': an incident photon of energy <<tex '\hbar \omega_{21}'>> stimulates an atom in the upper level to decay to the lower level - both photons emerge out of the other side.
***These last two processes both clearly depend on the density of the radiation field at the correct frequency.
*This third process is the key to laser operation.
*''Einstein's postulates'':
**Spontaneous emission rate per unit volume is equal to <<tex 'N_2 A_{21}'>> where <<tex 'N_2'>> represents the number of atoms per unit volume;
**Absorption rate per unit volume is equal to <<tex 'N_1 B_{12} \rho(\omega_{21})'>> where <<tex '\rho(\omega_{21})'>> is the energy density at that frequency;
**Stimulated emission rate per unit volume is equal to <<tex 'N_2 B_{21} \rho(\omega_{21})'>>.
*The <<tex 'A, B'>> with their subscripts are constants characteristic to each transition, called the Einstein A and B coefficients. Due to the different expressions, A and B have different units.
*When two atoms bond, their wavefunctions overlap. This can happen in two ways; via either a ''bonding'' state, or an ''antibonding'' state.
>The bonding state:
>>[img[The bonding state|images/1209142811.png]]
>The antibonding state:
>>[img[The antibonding state|images/1209142866.png]]
*The bonding state has symmetric single particle wavefunctions, and lies at a lower energy than the antibonding state, which is antisymmetric. The energy differences are the origin of the exchange integral/interaction.
*With more and more atoms, there are more and more ways the antisymmetric and symmetric states can combine, giving rise to a range of energies: the band.
*The different angular momentum states give rise to the different bands, and inter-atomic spacing adjusts both band width and band gaps.
*Overlapping bands can give metallic behaviour, but full bands or weakly overlapping ones are insulators.
*The core states are narrow and don't overlap much, wheras the higher states are tightly bound and give rise to most of the electronic properties in the solid.
><<tex 'u(x,y,z) = \dfrac{1}{2 \mu} \dfrac{\partial p}{\partial x} z^2 + A(x,y) z + B(x,y)'>>
[img[Slider Bearing|images/1210789688.png]]
*Boundary conditions:
**<<tex 'u(z=0) = U \Rightarrow B = U'>>;
**<<tex "u(z=h(x)) = 0 \Rightarrow A = - \dfrac{h(x)}{2 \mu} p'(x) - \dfrac{U}{h}">>
><<tex "u(x,z) = \left[\dfrac{U}{h} - \dfrac{z}{2 \mu} p'(x) \right] (h - z)">>
*Incompressibility implies volume flux <<tex 'Q = \int_0^{h(x)} u dz'>> is independent of <<tex 'x'>>:
><<tex "Q = \textrm{const.} = -\dfrac{h^3}{12 \mu} p'(x) + \frac{1}{2} U h(x)">>
>
><<tex '\Rightarrow \dfrac{dp}{dx} = \dfrac{12 \mu}{h^3} ( \frac{1}{2} U h - Q)'>> 
*Using boundary condition <<tex 'p(x=0) = p_0'>> (x position arbitrary):
><<tex "\dfrac{p - p_0}{6 \mu} = U \displaystyle{\int_0^x} \dfrac{d x'}{h^2 (x')} - 2Q \displaystyle{\int_0^x} \dfrac{d x'}{h^3 (x')}">>
*Same BC at <<tex 'x=L'>> leads to an expression for Q relating to U.
*h must now be defined, and as in the picture we can say the height decreases linearly with x, e.g <<tex 'h(x) = h_1 - \alpha x, \alpha = \dfrac{h_1 - h_2}{L}'>>
><<tex 'Q = \dfrac{U h_1 h_2}{(h_1 + h_2)}'>>
>
><<tex '\dfrac{p(x) - p_0}{6 \mu U L} = \dfrac{(h_1 - h(x)) \times (h_2 - h(x))}{(h_2^2 - h_1^2)[h(x)]^2}'>>
*If <<tex 'h_2 < h_1'>> (block height decreases in flow direction) then this implies net upward force on the block as expected.
*''Spectral transmittance'', <<tex '\mathcal{T}_{\nu}'>>: Ratio of transmitted over incident radiance:
><<tex '\mathcal{T}_{\nu} = \dfrac{L_\nu (\rm{transmitted})}{L_\nu (\rm{incident})}'>>
*''Spectral absorbtance'':
><<tex 'A_\nu = 1 - \mathcal{T}_\nu'>>
*''Optical depth'' (can be added linearly):
><<tex '\chi_\nu = - \rm{log}(\mathcal{T}_\nu)'>>
>
>//where transmittance is calculated between that location and space. Special case of ''optical path''//.
*and a rearrangement thrown in for good measure:
><<tex '\dfrac{I}{I_0} = e^{- \chi_\nu}'>>
*and another definition for change in optical depth, (i.e absorption through mass/thickness of air):
><<tex 'd \chi_\nu = -\kappa_\nu \rho_a dz'>>
*Also, with an expression for the density:
><<tex '\rho_a = \rho_0 e^{-z / H}'>>
*we can get a nice expression for the optical depth:
><<tex '\chi_\nu = H \kappa_\nu \rho_0 e^{-z / H}'>>
*For incident flux, <<tex 'F_0'>>, solar transmittance <<tex '\mathcal{T}_{\rm{solar}}'>>, IR transmittance <<tex '\mathcal{T}_{therm}'>>, we can calculate surface temperature <<tex 'T_s'>>:
**Flux (down) at the top of that atmosphere: <<tex 'F_0 - \sigma T_s^4 \mathcal{T}_{\rm{therm}}'>>;
**Flux (up) at the surface: <<tex '\sigma T_s^4 - F_0 \mathcal{T}_{\rm{solar}}'>>;
**Fluxes must balance for global energy balance:
><<tex '\sigma T_s^4 = F_0 \dfrac{1 + \mathcal{T}_{\rm{solar}}}{1 + \mathcal{T}_{\rm{therm}}}'>>

*Force on a cylinder calculated by integrating normal pressure over its surface:
[img[Pressure on a Cylinder|images/1210756994.png]]
*Force in <<tex 'y'>> direction:
><<tex '-a \displaystyle{\int_{- \pi}^{\pi} p(\theta) \sin \theta d \theta'>>
*From [[flow around a cylinder|4. Flow Around a Cylinder]], there is no normal pressure as the fluid is inviscid.
*Can compensate for this by adding a 'swirl term' to the potential to get:
><<tex '\phi = U\left( r + \dfrac{a^2}{r} \right) \cos \theta - \underbrace{A \theta}'>>
*Which leads to a new expression as in flow around a cylinder:
><<tex '\dfrac{p}{\rho} = \textrm{constant} - 2 U^2 \sin^2 \theta - \underbrace{\dfrac{2 U A}{a} \sin \theta}'>>
*Or in terms of the circulation using:
><<tex '\Gamma_c = \int_0^{2 \pi} u_{\theta} r d \theta'>>
>
><<tex '\Gamma_c = -2 \pi A'>>
>
><<tex '\dfrac{p}{\rho} = \textrm{constant} - 2 U^2 \sin^2 \theta - \underbrace{\dfrac{U \Gamma_c}{\pi a} \sin \theta}'>>
>
*This can then be subsituted into the expression for the force above, giving Lift:
><<tex '\textrm{Lift} = -a\left(\displaystyle{\int_{- \pi}^{\pi}} \left( \rho k \sin \theta - 2 U^2 \sin^3 \theta + \rho \dfrac{U \Gamma_c}{\pi a} \sin^2 \theta \right) d \theta \right)'>>
*The first two terms of the integral are odd and disappear:
><<tex '\textrm{Lift} = - \rho U \Gamma_c'>>
*If flow speeds are faster above the wing than below, the circulation line integral looks like this:
[img[Negative circulation|images/1210758516.png]]
*The circulation is negative, lift is positive, and an upwards force can generate flight.

*If this were to be applied to absorption instead, we would write the intensity equation of section 4 as:
><<tex 'I(\omega, z) = I(\omega, 0) e^{- \kappa(\omega - \omega_0) \cdot z}'>>
*Where the ''absorption coefficient'' is given by:
><<tex '\kappa_{12}(\omega - \omega_0) = N^{**} \sigma_{12}^{abs} (\omega - \omega_0)'>>
*Where:
><<tex '\rightarrow N^{**} = N_1 - \dfrac{g_1}{g_2}N_2'>>
>
><<tex '\rightarrow \sigma_{21}^{abs} (\omega - \omega_0) = \dfrac{\hbar \omega}{c} B_{12} g_H (\omega - \omega_0)'>>
*The exponential decrease in intensity as it propagates is ''Beer's Law''.
*We begin by expressing the transverse modes of the cavity by <<tex 'u_{\pm}(r, \omega, t)'>> where the <<tex '\pm'>> denotes the mode in the positive and negative z direction respectively;
*We express the amplitude of these waves by <<tex 'a_{\pm}(z, \omega)'>>.
*Considering a cavity of length <<tex 'L_c'>> with mirrors at <<tex 'z = 0, L'>>, first of all filled with no gain medium:
**At <<tex 'z=0'>>, the forward and reverse modes must equate, accounting for the reflection amplitude and phase at the mirror boundary:
><<tex 'a_+(0, \omega) u_+(r, \omega, t) = a_-(0, \omega) \cdot r_1 e^{i \phi_1} u_-(r, \omega, t)'>>
**This must be true for all points in the <<tex 'z=0'>> plane, so the modes are equal, giving:
><<tex 'a_+(0, \omega) = a_-(0, \omega) r_1 e^{i \phi_1}'>>
**But, the reverse mode must have bounced off the second mirror at <<tex 'z=L'>>, so the negative mode must equal the positive mode having completed one round trip:
><<tex 'u_-(0, \omega) = a_+(0, \omega) r_2 e^{i (\delta_{rt} - \phi_2)}'>>
**Here, the delta term is the phase form one round trip, and the subscript 2 terms are the phase and amplitude from the second mirror, and the phase changes caused by the two mirrors are the same.
**Combining we get:
><<tex 'u_+(0, \omega) = a_+(0, \omega)r_1 r_2 e^{i \delta_{rt}}'>>
**This means that:
><<tex 'r_1 r_2 e^{i \delta_{rt}} = 1'>>
>
>which can only be satisfied if <<tex '\delta_{rt} = 2 \pi p, p = 0,1,2,3,...'>> and also if <<tex 'r_1 = r_2 = 1'>>, i.e perfect mirrors. 
**For real mirrors which arent perfect, steady-state conditions can therefore only be achieved via the introduction of gain into the cavity.
*Temperature gradient determines flux for each transport method.
*''Conduction'':
**Does not seriously contribute to energy transport
**Mean free path of particles <<tex '\ll'>> mean free path of photons due to high density.
**NB: For degenerate matter (white dwarf cores), heat is conducted very effectively by the electrons.
*A normal mode is a composite harmonic oscillator with all atoms vibrating at the same frequency.
*QM states all energy in a mode is quantised:
><<tex 'E(k) = (n + \frac{1}{2}) \hbar \omega(k)'>>
>
>where <<tex 'n'>> is the number of quanta in the mode.
*A ''phonon'' is the quantum of vibrational energy in a normal mode.
*More phonons give a larger amplitude of vibration (implying two phonons can have the same wavefunction - bosonic behaviour)
*Average number of phonons in thermal equilibrium:
><<tex '\langle n \rangle = \dfrac{\displaystyle\sum_{n=0}^\infty n e^{- \beta n \hbar \omega}}{\displaystyle\sum_{n=0}^\infty e^{- \beta n \hbar \omega}} = \dfrac{1}{e^{\beta \hbar \omega} - 1}'>>
*This is the ''Planck distribution'', a special case of the ''Bose-Einstein distribution'' when the chemical potential is 0. This is because no energy is expended creating phonons (or similarly photons, hence the Planck distribution).
**We see that phonons are boson quasiparticles.
*Usually phonons are localised to some extent. 
*Wavepackets (groups of waves) travel at the group velocity:
><<tex 'v_g = \dfrac{\partial \omega}{\partial k}'>>


*Net mass change in a box related to density and velocity on each side:
><<tex '= [\rho(x)u(x) - \rho(x + \Delta x)u(x + \Delta x)] \Delta y \Delta z'>>
*And equal to the mass increase in the box:
><<tex ' \dfrac{\partial}{\partial t} (\rho \Delta V) \simeq - \dfrac{\partial}{\partial x}(\rho u) \Delta x \cdot \Delta y \Delta z = - \dfrac{\partial}{\partial x}(\rho u) \Delta V '>>
*Giving mass conservation equation (in 3D now):
><<tex '\dfrac{\partial \rho}{\partial t} + \nabla \cdot(\rho \textbf{u}) = 0'>>
>
>(Similarity to charge conservation equation):
>><<tex '\dfrac{\partial \rho_c}{\partial t} + \nabla \cdot(\rho \textbf{J}) = 0'>>
*Can also be written:
><<tex '\dfrac{D \rho}{D t} + \rho \nabla \cdot \textbf{u} = 0'>>
**For a constant <<tex '\rho'>> or ''incompressible flow'':
><<tex '\nabla \cdot \textbf{u} = 0'>>
*Usually observed that:
><<tex 'L_s \propto M_s^{\nu}'>>
where <<tex '3 < \nu < 5'>>.
*Heavier stars are much brighter, and have a shorter lifetime as <<tex 'T \propto M / L = M / M^{\nu}'>>
*Evapouration and condensation is very important in the atmosphere and has been neglected so far.
*Key property: ''saturation vapour pressure'', <<tex 'e_s'>> varying with temperature by ~Clausius-Clapeyron equation (liquid and vapour exist in equilibrium along a transition line given by):
><<tex '\dfrac{de_s}{dT} = \dfrac{L}{T V_v}'>>
*Can use ideal gas formula (even though the whole point this isn't ideal, but it's mostly air so it's ok):
><<tex '\dfrac{d e_s}{dT} = \dfrac{L e_s}{R_v T^2}'>>
*Can integrate to:
><<tex 'e_s(T) = e_0 \textrm{exp}\left[\dfrac{L}{R_v} \left( \dfrac{1}{273} - \dfrac{1}{T} \right) \right]'>>
*<<tex 'e_0'>> here is the saturation vapour pressure at 273K, hence the expression in the exponential.
*The percentage of water vapour in the atmosphere at saturation, or ''saturation specific humidity'', <<tex 'q*'>> is given by:
><<tex 'q* = \epsilon \dfrac{e_s}{p}'>>
*If an air parcel's q exceeds q*, we add an aditional term on First Law, representing heat released from latent heat:
><<tex 'dQ = c_v dT + p dV + L dq*'>>
*Although this is no longer reversible due to water condensing, it's adiathermal <<tex 'dQ = 0'>>.
*Also we still call the derived lapse rate, the ''saturated adiabatic lapse rate'':
><<tex 'dQ = 0 = c_p dT - g dz + L dq*'>>
>
>//Divide by <<tex 'c_p dT'>>, rearrange://
>
><<tex '\dfrac{dT}{dz} = \Gamma_s = \dfrac{\Gamma_d}{1 + \dfrac{L}{c_p} \dfrac{dq*}{dT}}'>>

*Weak interactions slow the reaction rates
*When a supply of one burning fuel is depleted, gravitational contractions raise the core temperature until the next fusion process can begin.
*<<tex '{}^4\textrm{He}'>> burning is difficult as there is no stable A=8 nucleus (<<tex '{}^{8}\textrm{Be}'>> is v unstable); nothing to bridge the gap to <<tex '{}^{12}\textrm{C}'>>.
**<<tex '{}^{12}\textrm{C}'>> and <<tex '{}^{16}\textrm{O}'>> are multiples of <<tex '{}^4\textrm{He}'>>;
**Triple-<<tex '\alpha'>> reaction can make <<tex '{}^{12}\textrm{C}'>> (requires a resonance at stellar temperatures).
**Small amount of <<tex '{}^{8}\textrm{Be}'>> can bridge part of the gap if this is also resonant.
*If a core is supported by electron degeneracy, sudden onset of He burning leads to ''Helium flash''.
*Depletion of Helium in core leads to heavier elements burning - Carbon etc., although most energy has already been extracted when H and He have been used up.
*Main sequence is the H burn phase.
*X-rays:
**X-ray tube:
***Electron fired at an electrode, e.g. Copper
***X-rays produced.
**Synchotron sources:
***Electrons in a synchotron produce synchotron radiation in the form of x-rays;
***E.g. the diamond light source, Oxfordshire.
*Neutrons:
**Nuclear Reactors:
***Neutrons from the reactor core are cooled by the reactor moderator;
***Moderated neutrons can then be used in a diffractor.
**Pulsed (spellation) Sources:
***Protons (e.g from synchotron) bombard a heavy metal target;
***Neutrons are released as a product of collisions/reactions.
*Monochromatic radiance <<tex 'L_\nu'>> passing upwards vertically, through thin slab of atmosphere, thickness <<tex '\delta z'>>;
*Single radiatively active gas, absorption coefficient <<tex '\kappa_\nu'>>, density <<tex '\rho_a'>>.
*''Lambert's Law of Absorption'':
><<tex 'd L_{\nu a} = - \kappa_\nu \rho_a L_\nu dz'>>
*''Kirchoff's Law of Emission'':
><<tex 'd L_{\nu e} = \kappa_\nu \rho_a B_\nu (T) dz'>>
*Total:
><<tex 'd L_{\nu tot} = \kappa_\nu \rho_a (B - L_\nu) dz'>>
*Using a definition of change in optical depth (i.e absorption through mass/thickness of air):
><<tex 'd \chi_\nu = -\kappa_\nu \rho_a dz'>>
*We get ''Schwarzchild's equation for radiance'' in the direction of //decreasing <<tex '\chi'>>//:
><<tex '- \dfrac{d L_\nu}{d \chi_\nu} + L_\nu = B_\nu \simeq 0'>>
*This expression only works in a single direction however - the vertical direction. Normally we talk about ''diffuse'' IR radiation, taking multiple optical paths. So we over a hemisphere, we get the //irradiance// instead of the radiance. And a random factor of <<tex '\pi'>>:
><<tex '- \dfrac{d I_\nu}{d \chi_\nu} + I_\nu = \pi B_\nu'>>


*Consider an ensemble of stationary atoms immersed in a bath of blackbody radiation of temperature, <<tex 'T'>> and energy density <<tex '\rho(\omega)'>>. This means that we know:
**Distribution of the population over the energy levels (Boltzmann distribution);
**Energy density of radiation (Planck's Law);
*Can compare these two results with that predicted by Einstein's description.
*If there are lots of energy levels, it is expected that an atom will be transistioning between them all rapidly, however the system will be in dynamical equilibrium so that the total number of atoms in each level remains more or less constant.
*''The Principle of Detailed Balance'' also states that in thermal equilibrium, the transitions between any //pair// of levels is also in dynamical equilibirum. 
**This is because the radiation field is in thermal equilibrium, and to maintain this, the field must lose photons of a specific frequency at the same rate it gains them.
*This gives the following expression:
><<tex 'N_2 B_{21} \rho_B(\omega_{21}) + N_2 A_{21} = N_1 B_{12} \rho_B({\omega_{21})'>>
>
><<tex '\rho_B(\omega_{21}) = \dfrac{A_{21} / B_{21}}{\dfrac{N_1}{N_2} \dfrac{B_{12}}{B_{21}} - 1}'>>
*The population ratio is given by the Boltzmann equation, and the energy density expression must equate with Planck's law, so:
><<tex '\dfrac{N_2}{N_1} = \dfrac{g_2}{g_1} \rm{exp}\left( - \dfrac{\hbar \omega_{21}}{k_B T}\right)'>>
>
><<tex '\rho_B(\omega_{21}) = \dfrac{A_{21} / B_{21}}{\dfrac{g_1}{g_2} \dfrac{B_{12}}{B_{21}} \rm{exp} \left(\dfrac{\hbar \omega_{21}}{k_B T}\right) - 1} = \left(\dfrac{\hbar \omega^3}{\pi^2 c^3}\right) \dfrac{1}{\rm{exp}(\hbar \omega / k_B T) - 1}'>>
*For the Einstein and Planck expressions to marry, we require:
><<tex 'g_1 B_{12} = g_2 B_{21}'>>
>
><<tex 'A_{21} = \dfrac{\hbar \omega_{21}^3}{\pi^2 c^3} B_{21}'>>
*These are the ''Einstein Relations''.
*Solitons are a balance between the ''non-linear'' and ''dispersion'' terms in the [[KdV equation|4. Non-Deep Water: Non-Linearity]]:
><<tex '\gamma \dfrac{\partial^3 \eta}{\partial x^3} = \eta \dfrac{\partial \eta}{\partial x}'>>
*Can be found by using a trial solution of the form:
><<tex '\eta = F(x - c_0 t - Vt)'>>
*This can look something like:
><<tex '\eta = \left( \dfrac{2 h V}{c_0}\right) \textrm{sech}^2 \left\{ \frac{1}{2} \sqrt{\dfrac{V}{\gamma}} (x - c_0 t - V t) \right\}'>>

[img[Soliton|images/1210775706.png]]
*As KdV equation is non-linear, can't superpose solitons.

Successes:
*Explains metals, insulators and semiconductors.
*Relation between atomic and material properties (why same group materials have similar properties).
*Explains positive charge, negative mass particles (holes), and effective mass.
Failures:
*Can't explain collective effects such as superconductivity, ferromangetism etc., and effects due to total electron energy.
*Using <<tex 'E = \hbar^2 k^2 / 2m = \frac{1}{2} m v^2'>> a "Fermi velocity", <<tex 'v_F = \hbar k_F / m = \frac{\hbar}{m} (3 \pi^2 n)^{1/3}'>> can be discovered.
*The mean free path is determined by this speed. With an average scattering time, or 'momentum relaxation time' <<tex '\tau'>>, the mean free path is <<tex '\lambda = v_F \tau'>>. All electrons are traveling in random directions with speed <<tex 'v_F'>>.
*However, if an external force is applied, e.g. an electric field, then this biases the net direction of the electrons, and gives them a drift speed <<tex 'v_d'>>, in the direction of the force.
*Rate of change of momentum <<tex '\dfrac{m v_d}{\tau} = F_{applied} = -e E'>> from electric field.
*Current, <<tex 'j = n e v_d = \dfrac{m e^2 \tau}{m} E'>>, giving conductivity, <<tex '\sigma = j / E = \dfrac{n e^2 \tau}{m} = \dfrac{n e^2 \lambda}{m v_F}'>>.
[img[Drift velocity on an E-k diagram|images/1209118885.png]]
*To cause scattering, the wave vector, <<tex 'k'>> must be changed by <<tex '~k_F'>>, not just the <<tex '\delta k'>> caused by the applied force. Therefore high energy phonons with large <<tex 'k'>> are needed. But as the phonon energy is usually small, only a small fraction of electrons can be scattered.
*Scattering occurs due to deviations from the perfect crystal arrangement:
**From crystal vibrations / phonons.
**From impurities in the crystal.
**Charged impurities cause Rutherford scattering.
*H and He burning do not occur simultaneously but alternate causing thermal pulsations.
*Burning in a shell around C core, causing envelope expansion.
*Smaller/Mid stars (<<tex 'M < 8 M_{\odot}'>>) do not burn much past He (although small amounts of heavier elements can form, O, Ne, Mg), and the envelope is lost by solar winds, causing an end to the star's evolution.
**Envelope ejection is the planetary nebula ejection phase;
**Core cools and becomes degenerate - a [[white dwarf|6. White Dwarfs]].
*More massive stars (<<tex 'M > M_{\odot}'>>):
**Reactions can continue all the way up to Fe if hot enough;
**Onion-like shell structure of heavier and heavier elements up to Fe core;
**Electron degeneracy pressure can support the core for a bit, but above the [[Chandrasekhar mass|7. The Chandrasekhar Mass Limit]] the core collapses to a neutron star (neutron degeneracy pressure) or even a black hole, and its gravitational energy release on collapse can lead to a supernova.
*For very small viscoscity, <<tex '\nu'>> is only important on a thin boundary layer of thickness order of <<tex 'L/Re^{1/2}'>>. Outside this layer the flow is effectively inviscid.
*Instead of seeing the smooth flow of a completely inviscid fluid, we see the boundary layer 'breaking away' from the object, creating turbulence:
[img[BL Separation|images/1210759112.png]]
*In aircraft, the aerofoil shape only creates this turbulence at the trailing edge, increasing efficiency.
*This also sheds a 'starting vortex':
[img[Starting Vortex|images/1210759403.png]]
*By [[Kelvin's Circulation Theorem|3. Kelvin's Circulation Theorem]], the vorticity must remain zero, so an opposite vortex must be generated. This creates the swirl and circulation around the wing which generates lift.



*The ''laser threshold condition'' - near the threshold for laser oscillation, the intensity of the circulating radiation in the cavity is very small, meaning unsaturated gain, and amplification via the small gain coefficient (exponential).
*We go back to the optical cavity equation:
><<tex 'a_- (0, \omega ) = a_+ (0, \omega) \rm{exp} [ \frac{1}{2} \alpha_0^{th}(\omega) L_g ] \rm{exp}[-\frac{1}{2} \kappa(\omega) L_c] \times r_2 \cdot '>><<tex '\rm{exp} [\frac{1}{2} \alpha_0^{th}(\omega) L_g] \rm{exp}[-\frac{1}{2} \kappa(\omega) L_c] \rm{exp}[i(\delta_{rt} - \phi_1)]'>>
*In this case, <<tex '\kappa'>> is the absorption coefficient for unwanted losses in the cavity and the mirrors.
*This time the 'reflection phase condition' similar to that obtained before is:
><<tex 'r_2 r_1 \rm{exp} [ \alpha_0^{th} (\omega) L_g ] \rm{exp} [ - \kappa (\omega) L_c ] \rm{exp} (i \delta_{rt}) = 1'>>
*As before, the condition <<tex 'e^{i \delta_{rt}} = 1'>> means the frequency of the radiation must correspond to a cavity mode, which we denote <<tex '\omega_p'>>.
*The rest of the expression (real parts) gives the ''threshold condition'':
><<tex 'R_1 R_2 \rm{exp}[2 \alpha_0^{th} (\omega_p) L_g] \exp [- 2 \kappa (\omega_p) L_c] = 1'>>
*This means, that unless the expression on the left is greater than or equal to one, the beam will be smaller than when it started after a round trip, and lasing is impossible.
*It can also be expressed as:
><<tex '2 \alpha_0^{th}(\omega_p) L_g = 2 \kappa (\omega_p) L_c - \rm{ln}(R_1 R_2)'>>
*''Operation above threshold'':
**If the round trip saturated gain is small, we can rewrite the threshold condition with <<tex '\alpha_I'>>, the saturated gain coefficient in place of <<tex '\alpha_0'>>.
**As pumping is increased from below the threshold, a very large increase in the energy density of the radiation field is observed at first.
**However, if pumping is increased further, neither population inversion or <<tex '\alpha_I(\omega)'>> increase much - this is because the round-trip gain must be balanced by the round-trip loss. 
**In other words, although the pumping rate is increased, the higher level's population is rapidly burnt down by the lasing. The gain becomes locked at the threshold value and does not increase above it.
**Note that increased power in, still gives more power out, but there is no gain value derived from it.
*''Spacial hole burning'':
**As one mode of oscillation operates in the cavity, it will cause burn downs of population at specific nodes in the gain medium, due to its standing wave nature. 
**There will however be holes of high population at the antinodes of the wave. These allow a wave of a slightly different frequency to feed off these high population areas - an unwanted effect.
**This can be reduced via the use of a ring cavity, and only allowing oscillation round one direction of the ring to prevent formation of standing waves.
*Obtained from spectra. Agreement between this value and that observed in meteorites gives some validation.
*Normal Stars:
><<tex '\begin{tabular}{|c | c || c | c|} \hline & By Number & & By Mass \\ \hline H_2 & 0.9 & X & 0.7 \\ He & 0.1 & Y & 0.28 \\ Metals & 0.01 & Z & 0.02  \\ \hline \end{tabular}'>>
*Globular clusters have lower metallicity than Sun, and assuming uniform initial composition this gives evidence for nucleosynthesis in stars.
*Surface composition is usually retained, but can change due to:
**mixing
**mass loss of outer layers revealing core
**mass transfer in a binary system
**pollution from supernovae material.
*For LASER operation, the rate of stimulated emission must be greater than the rate of absorption:
><<tex 'N_2 B_{21} \rho(\omega_{21}) > N_1 B_{12} \rho(\omega_{21})'>>
>
><<tex '\Rightarrow \dfrac{N_2}{g_2} > \dfrac{N_1}{g_1}'>>
*This is the condition for optical gain, and it describes ''population inversion''.
**Population inversion is unusual - in a system in thermal equilibrium, the populations in upper states is always lower than those below.

[img[2 Level Rate Analysis|images/1211541454.png]]

*For ''steady-state inversion'', we require something like pumping. 
**Upper level:
***Pumping rate, <<tex 'R_2'>>;
***Lifetime, <<tex '\tau_2'>> - decay rate to all other levels, including lower level (flourescence lifetime);
**Lower level:
***Pumping rate, <<tex 'R_1'>> - this does not include spontaneous emission from the level above however;
***Lifetime, <<tex '\tau_1'>>;
><<tex '\dfrac{d N_2}{dt} = R_2 - \dfrac{N_2}{\tau_2}'>>
>
><<tex '\dfrac{d N_1}{dt} = R_1 + N_2 A_{21} - \dfrac{N_1}{\tau_1}'>>
>
>The symmetry of equations is broken by the spontaenous emission term.
*In steady state, the time derivatives are zero, and so:
><<tex 'N_2 = R_2 \tau_2'>>
>
><<tex 'N_1 = R_1 \tau_1 + R_2 \tau_2 A_{21} \tau_1'>>
*Using the condition for optical gain, (population inversion), gives ''steady state inversion condition'':
><<tex '\dfrac{R_2}{R_1} \dfrac{\tau_2}{\tau_1} \dfrac{g_1}{g_2} \left[ 1 - \dfrac{g_2}{g_1} A_21 \tau_1 \right] > 1'>>
*Consequences, need at least one of the following:
**''Selective pumping'', <<tex 'R_2 > R_1'>>: the upper level is pumped more rapidly than the lower level;
**''Favourable lifetime ratio'', <<tex '\tau_2 > \tau_1'>>: the lower level decays more rapidly than the upper level, keeping its population small;
**''Favourable degeneracy ratio'', <<tex 'g_1 > g_2'>>: the population per state of the lower laser level is small.
*There is also the necessary but not sufficient condition - the term in square brackets in the condition equation above. Even if all the above conditions are true, if the square bracket term is not positive, then lasing is impossible:
><<tex '\Rightarrow A_{21} > \dfrac{g_1}{g_2} \dfrac{1}{\tau_1}'>>

*''Radiation'':
**Mainly X-ray photons in thermal equilibrium with particles inside a star.
**High density of interior makes it opaque to X-rays.
**Poisson distribution gives a distance of <<tex 'x \approx \sqrt{N} L'>> after <<tex 'N'>> steps of size <<tex 'L'>>, gives a diffusion time:
><<tex 't_{\textrm{diff}} = N \times \dfrac{L}{c} \approx \dfrac{R_s^2}{Lc}'>>
**Mean free path is ~ 1cm, gives diffusion time of <<tex ' t_{\textrm{diff}} \sim 5 \times 10^3'>> years for the Sun.
**Energy transport:
***Spherical shell of area <<tex 'A = 4 \pi r^2'>> at radius <<tex 'r'>>, thickness <<tex 'dr'>>.
***Radiation pressure = <<tex 'P_{\textrm{rad}} = \frac{1}{3} a T^4'>> = momenum flux.
***Momentum deposited in region at rate:
><<tex '- \dfrac{dP_{\textrm{rad}}}{dr} dr 4 \pi r^2'>>
***Star's [[opacity|2. The Opacity]] <<tex '\kappa'>> attenuates intensity for a given density by:
><<tex '\dfrac{dI}{I} = - \kappa \rho dx'>>
***Define optical depth, <<tex '\tau'>>, where <<tex 'I = I_0 e^{- \tau}'>>:
><<tex '\tau \equiv \int \kappa \rho dx'>>
****<<tex '1 / \kappa \rho'>>: mean free path.
****<<tex '\tau \gg 1'>>: optically thick.
****<<tex '\tau \ll 1'>>: optically thin.
***Rate of momentum absorption is <<tex '(L(r) / c) \kappa \rho dr'>>, so combine with deposition rate:
><<tex 'L_r = - 4 \pi r^2 \dfrac{4 a c}{3 \kappa \rho} T^3 \dfrac{dT}{dr}'>>
><<tex '\dfrac{dT}{dz} = \Gamma_s = \dfrac{\Gamma_d}{1 + \dfrac{L}{c_p} \dfrac{dq*}{dT}}'>>
*Need <<tex '\frac{dq*}{dT}'>>..
><<tex 'q* = \epsilon \dfrac{e_s}{p}'>>
>
>Now:
>
><<tex '\dfrac{d e_s}{dT} = \dfrac{L e_s}{R_v T^2}'>>
>
>And: (from <<tex 'p = p_0 e^{- z g/R T_0}'>>)
>
><<tex '\dfrac{dp}{dT} = \dfrac{g}{RT \Gamma}'>>
>
>Gives:
>
><<tex '\dfrac{dq*}{dT} = \dfrac{L q*}{R_v T^2} - \dfrac{g q*}{R T \Gamma}'>>
*The CC term dominates the pressure term in general, so <<tex '\frac{dq*}{dT}'>> is positive. This makes <<tex '\Gamma_s < \Gamma_d'>>, i.e Temperature decreases more slowly with height for the moist adiabat.
*''Stability'':
**<<tex '\Gamma > \Gamma_d'>> - Absolutely unstable, never observed (atmosphere would fly away);
**<<tex '\Gamma < \Gamma_s'>> - Absolutely stable;
**<<tex '\Gamma_s < \Gamma < \Gamma_d'>> (in between the two gradients):
***Stable to small perturbations;
***Unstable to large pertubations that would trigger cloud formation.
*[[Accelleration|3. Total Force - Accelleration]]:
><<tex '\textbf{a} & = - \dfrac{1}{\rho} \nabla p + \nu [\nabla^2 \textbf{u} + \frac{1}{3} \nabla (\nabla \cdot \textbf{u} )] - g \textbf{k}'>>
>
>and
><<tex '\textbf{a} = \dfrac{D \textbf{u}}{D t}'>>
*[[Incompressibility|5. Mass Conservation]]:
><<tex '\nabla \cdot \textbf{u} = 0'>>
*Gives the NS equation for incompressible fluid flow under gravity:
><<tex '\dfrac{D \textbf{u}}{Dt} + \dfrac{1}{\rho} \nabla p + g \textbf{k} = \dfrac{\mu}{\rho} \nabla^2 \textbf{u}'>>
*Adding more ~CO2, from hydrostatic balance and the fact ~CO2 is well mixed, just increases the scale height - doubling atmospheric concentration of ~CO2 displaces <<tex 'p_a(z)'>> upwards by <<tex 'H \rm{log}(2)'>>.
*This means that there are more layers of atmosphere for photons to penetrate before they can escape it space, but the temperature of the atmosphere layers at these higher temperatures are lower by <<tex '\Gamma H \rm{log}2'>>.
*As the temperature is lower, less energy is radiated out due to Stephan's law;
*The same amount enters in however, so the global energy budget is unbalanced - global warming!
*When a magnetic field, <<tex 'B_z'>>, is applied to a sample, the Lorentz Force pushes the electron perpendicular to the field and to the motion.
*As the electrons can't flow out the sides of the sample, a force is experienced by the electron to counteract the Lorentz force, <<tex '-e(\textbf{E} + \textbf{v}_d \times \textbf{B} ) = 0'>>.
*Looking at <<tex 'E_y'>> for an applied field <<tex 'B_z'>>, we have <<tex 'E_y = (v_d)_x B_z'>>.
*The Hall Coefficient is defined as:
><<tex 'R_H = \dfrac{E_y}{j_x B_z}'>>
><<tex '\therefore j_x = -ne(v_d)_x'>>
><<tex '\Rightarrow R_H = \dfrac{1}{n (-e)}'>>
*<<tex 'j_x , E_y , B_z'>> can all be measured, so can calculate carrier number density of a sample using this method.
*Hall Voltage <<tex 'V_H = \frac{E_y}{d}'>>, used to measure <<tex 'E_y'>>, can be very small. Can use an oscillating B field and measure voltage component with the same frequency as the B field to distinguish <<tex 'V_H'>> from interference/noise.
*To measure the low voltage, a 4-probe measurement is used to overcome the contact resistance.
*<<tex 'M \sim M_{\odot}'>>
*<<tex 'R \sim R_{E}'>>
*Maximum mass is <<tex '1.4 M_{\odot}'>> due to [[Chandrasekhar limit|7. The Chandrasekhar Mass Limit]].
*Convection occurs when the temperature gradient reaches a critical value, the ''Schwarzschild criterion'':
**A bubble at <<tex '\rho_1, P_1'>> rises to an area <<tex 'dr'>> higher where ambient <<tex '\rho = \bar{\rho}_2, P = \bar{P}_2'>>.
**Bubble's own <<tex '\rho , P'>> become:
><<tex 'P_2 = P_1 \left(\dfrac{\rho_2}{\rho_1}\right)^{\gamma}'>>
**Now, can expand pressure:
><<tex 'P_2 = \bar{P}_2 = P(r + dr) \approx P_1 + \dfrac{dP}{dr} dr'>>
**and density:
><<tex '\begin{array}{l l}\rho_2 = \rho_1 \left(\dfrac{P_2}{P_1}\right)^{1/\gamma} & \approx \rho_1 \left( 1 + \dfrac{1}{P} \dfrac{dP}{dr} dr \right)^{1/\gamma} \\ & \approx \rho_1 + \dfrac{\rho_1}{\gamma P} \dfrac{dP}{dr} dr \end{array}'>>
>
><<tex '\bar{\rho}_2 \approx \bar{\rho}_1 + \dfrac{d \bar{\rho}}{dr} dr = \rho_1 + \dfrac{d \bar{\rho}}{dr} dr'>>
**The system is convectively stable is the risen bubble is denser than the ambient medium, i.e <<tex '\rho_2 - \bar{\rho}_2 > 0'>>, so for convective stability:
><<tex '\rho_2 - \bar{\rho}_2 > 0'>>
>
><<tex '\rho_1 + \dfrac{\rho_1}{\gamma P} \dfrac{dP}{dr} dr - \rho_1 + \dfrac{d \bar{\rho}}{dr} dr > 0'>>
>
>><<tex '\dfrac{\rho}{\gamma P} \dfrac{d P}{d r} - \dfrac{d \rho}{d r} > 0'>>
*Can use the relation:
><<tex 'P = \dfrac{\rho}{\mu m_H} k T'>>
to obtain:
><<tex '\dfrac{P}{T} \dfrac{dT}{dP} < \dfrac{\gamma - 1}{\gamma}'>>
*Stability can be broken by:
**V. large opacities and very concentrated burning in the core leading to very large temperature gradients;
**Small value of <<tex '\gamma - 1, ( < 2/3 )'>> in monatomic gas regions, such as hydrogen ionization zones.
*Round trip gain must be balanced by round trip losses:
><<tex '2 \alpha_I L_c = 2 \kappa_I L_g - \rm{ln} (R_1 R_2)'>>
*For gain only (ignoring loses), we write the fractional gain as:
><<tex '\delta_{gain} = \rm{exp}(2 \alpha_I L_g) - 1 \approx 2 \alpha_I L_g'>>
*and similarly the fractional absorption:
><<tex '\delta_{abs} = 1 - \rm{exp}(- 2 \kappa_I L_c) \approx 2 \kappa L_c'>>
*reflectivity can be written in terms of <<tex 'R+T+A=1'>>, and R must be near 1 for good laser operation. So for small T, A:
><<tex '\begin{array}{rl}\rm{ln}(R_1 R_2) &= \rm{ln}[(1-T_1-A_1)(1-T_2-A_2)] \\&\\ &\approx -T_1 - A_1 - T_2 - A_2 \end{array}'>>
*Power must be extracted from one of the mirrors, so we need this as a 'useful loss'. Can now write the ''low-loss threshold condition'':
><<tex '2 \alpha_I L_g = \delta_{loss} + T_2'>>
>
>where <<tex '\delta_{loss} = \delta_{abs} + T_1 + A_1 + A_2'>>, and the <<tex '\alpha_I'>> is the ''saturated'' gain coefficient.
*For a low gain system, the left and right travelling beams will have approximately the same intensity, so <<tex 'I = I_+ + I_- \approx 2 I_+'>>
><<tex '2 \dfrac{\alpha_0}{1 + 2 I_+/I_s} L_g = \delta_{loss} + T_2'>>
*This yields an expression for the right going beam power:
><<tex 'I_+ = \frac{1}{2} I_s \left( \dfrac{2 \alpha_0 L_g}{T_2 + \delta_{loss}} -1 \right)'>>
*Output power of the laser is product of intensity, second mirror's transmission coefficient, and area of the beam:
><<tex 'P = T_2 I_+ A_{mode} = \frac{1}{2} I_s A_{mode} T_2 \left( \dfrac{ 2 \alpha_0 L_g}{T_2 + \delta_{loss}} - 1 \right)'>>

[img[Power Output|images/1211560101.png]]

*At large values of <<tex 'T_2'>>, there is too much cavity loss and no laser oscillation occurs.
*As <<tex 'T_2'>> is decreased, eventually the losses are balanced past the threshold for oscillation, <<tex 'T_2^{thresh}'>>
*As <<tex 'T_2'>> decreases further, higher intensity in the cavity causes more gain and higher power, until the fraction of power that can escape the cavity is too small for any useful amount to be extracted.
*Distance modulus:
><<tex '(m - M)_V = 5 \textrm{log} D / 10\textrm{pc}'>>
*Absolute V magnitude:
><<tex 'M_V = -2.5 \textrm{log} L / L_{\odot} + 4.72 + B.C + A_V'>>
*Salpeter initial mass function (less likely to have higher mass stars etc.)
><<tex 'N(M) dM \propto M^{-2.35} dM'>>
*Black-body relation:
><<tex 'L = 4 \pi R_S^2 \sigma T_{\textrm{eff}}^4'>>
*Kepler's law:
><<tex '\left(\dfrac{P}{2 \pi} \right)^2 = \dfrac{a^3}{G(M_1 + M_2)}'>>
or (in AU and years)
><<tex '\dfrac{(M_1 + M_2)}{M_{\odot}} = \dfrac{a^3}{P^2}'>>
*~Mass-Luminosity relationship:
><<tex 'L \propto M^{\nu}'>>, where <<tex '3 < \nu < 5'>>
*Stable configuration at E = 0, so <<tex '\textrm{E}_{\textrm{grav}} = \textrm{E}_{\textrm{therm.}}'>>
*Gravitational energy:
><<tex '\textrm{E}_{\textrm{grav}} = \displaystyle{\int_0^M} \dfrac{GM}{r} dm'>>
>
><<tex '\textrm{E}_{\textrm{grav}} = \displaystyle{\int_V} \dfrac{G \frac{4}{3} \pi \rho_0 r^3}{r} . \rho_0 dV'>>
>
><<tex '\textrm{E}_{\textrm{grav}} = 4 \pi \displaystyle{\int_0^R} G \frac{4}{3} \pi r^4 \rho_0^2 dr'>>
>
><<tex '\textrm{E}_{\textrm{grav}} = \frac{4 \pi}{5} G \frac{4}{3} \pi R^5 \rho_0^2 dr'>>
>
>Subs back in <<tex '\rho_0'>>:
><<tex '\textrm{E}_{\textrm{grav}} = \dfrac{3}{5} \dfrac{G M^2}{R}'>>
>
><<tex '\textrm{E}_{\textrm{grav}} = \dfrac{3}{5} \dfrac{G (N \mu m_H)^2}{R}'>>
*Thermal energy:
><<tex 'N = \displaystyle{\int_0^{k_F}} g(k) dk'>>
>
><<tex 'N = \displaystyle{\int_0^{k_F}} 2 \times \dfrac{\frac{1}{8} 4 \pi k^2 }{(\pi / L)^3}dk'>>
>
><<tex 'N = \displaystyle{\int_0^{k_F}} \dfrac{V k^2}{\pi^2} dk'>>
>
>Using <<tex 'k = p / \hbar'>>:
>
><<tex 'N = \displaystyle{\int_0^{p_F}} \dfrac{V p^2}{\pi^2 \hbar^3} dp'>>
>
><<tex 'p_F = (3 \pi^2)^{1/3} \hbar \left( \dfrac{N}{\frac{4}{3} \pi R^3} \right)^{1/3}'>>

Can convert this to Energy per particle using <<tex 'E_F = p_F c'>>, and multiply by number of particles to get the total energy:
><<tex 'E_{\textrm{therm}} \sim \dfrac{N^{4/3} \hbar c}{R}'>>

*Using <<tex 'E_{\textrm{total}} = 0 = |E_{\textrm{therm}}| - |E_{\textrm{grav}}|'>>, can get an expression for N, then <<tex 'M = N \times \mu m_H'>>:
><<tex 'M_{\textrm{max}} \approx \dfrac{1.8 M_{\odot}}{\mu^2}}'>>
Which yeilds (for a precise value of <<tex '\mu'>>):
><<tex 'M_{\textrm{max}} = 1.44 M_{\odot}'>>
*Using kinetic theory formula for thermal conductivity, <<tex 'K = \frac{1}{3} C \lambda v_F'>>:
><<tex 'C = \frac{\pi^2}{3} m n k_B^2 T / E_F'>>
><<tex '\lambda = v_F \tau'>>
><<tex 'E_F = \frac{1}{2} m v_F^2'>>
*Gives <<tex 'K = \frac{\pi^2}{3} m n k_B^2 \tau T'>>.
*Various scattering processes affect the value of <<tex '\tau'>>:
**At low temperatures, scattering is affected only by defects, <<tex '\tau'>> independent of <<tex 'T'>>.
**Intermediate: Low temp. phonons fir the Debye model: <<tex '\tau \propto T^{-3}'>>.
**High temp: 'Classical' phonons fit: <<tex '\tau \propto T^{-1}'>>
*From Fe core collapse of massive stars (<<tex '8 \sim 20 M_{\odot}'>>);
*Nuclei are dissociated to produce a compact remnant of neutrons (and some protons/electrons);
**Dissociation is endothermic, undoing all previous fusions from using gravitational energy;
*Neutron star maximum mass similar to Chandrasekhar mass, only for <<tex 'M \sim 1.5 - 3 M_{\odot}'>>
*Typical radius <<tex ' R \sim 10km'>>
*The electrical and thermal conductivities of electrons, both <<tex '\propto \tau'>>
*Can define 'Lorenz number', <<tex 'L = K / (\sigma T) = \pi^2 k_B^2 / (3 e^2)'>>
*As it is only dependent on constants, it should be the same for all metals.
*Works well for low/high temp, breaks down in Debye region.
*Escape velocity is:
><<tex 'v_{\textrm{esc}} = \sqrt{\dfrac{2GM}{R}}'>>
*Assume photons have <<tex 'm \propto E'>>
*If <<tex 'v_{\textrm{esc}} > v'>>, photon can't escape.
*Schwarzschild radius (black hole if mass M in radius smaller than <<tex 'R_s'>>):
><<tex 'R_s \equiv \dfrac{2GM}{c^2}'>>
>
><<tex 'R_s = 3\textrm{km} (M / M_{\odot})'>>
Successes:
*[[Heat capacity|3. Heat Capacity]]'s temperature dependence.
*Pauli [[paramagnetism|4. Magnetic Susceptibility]].
*[[Lorenz number|8. Wiedeman-Franz Ratio]].
*Heat capacity and magnitude of [[Hall effect|6. The Hall Effect]] in simple metals.
Failures:
*Heat capacities and Hall effects are often wronge.
*Hall effect can be positive!
*Does not explain insulators / semiconductors.
We need [[Band Theory|ii. Band Theory]]...

/***
|Name|AliasPlugin|
|Source|http://www.TiddlyTools.com/#AliasPlugin|
|Documentation|http://www.TiddlyTools.com/#AliasPluginInfo|
|Version|1.1.0|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides||
|Description|Create text-substitution macros|
Define macros for abbreviations and other "aliases", and then embed them in the rest of your tiddler content to quickly insert common terms, phrases and links without a lot of repetitive typing.
!!!!!Documentation
> see [[AliasPluginInfo]]
!!!!!Revisions
<<<
2008.03.11 [*.*.*] plugin size reduction - documentation moved to [[AliasPluginInfo]]
2007.03.21 [1.1.0] added support for parameter substitution into alias macros, using format() method and%0..%9 markers
| Please see [[AliasPluginInfo]] for previous revision details |
2005.08.12 [1.0.0] initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.alias= {major: 1, minor: 1, revision: 0, date: new Date(2007,3,21)};
config.macros.alias= { };
config.macros.alias.handler = function(place,macroName,params) {
	var alias=params.shift(); if (!alias) return; alias=alias.replace(/ /g,"_"); // don't allow spaces in alias
	if (config.macros[alias]==undefined) // create new macro (as needed)
		{	 
		config.macros[alias] = { };
		config.macros[alias].handler =
			function (place,macroName,params) { wikify(config.macros[macroName].text.format(params),place,null,null); }
		}
	config.macros[alias].text = params[0]?params.join(' '):alias;	// set alias text
}
//}}}

Type the text for 'New Tiddler'
Type the text for 'New Tiddler'
List of B1 topics.
List of B2 topics.
List of B3 topics.


/***
|''Name:''|CryptoFunctionsPlugin|
|''Description:''|Support for cryptographic functions|
***/
//{{{
if(!version.extensions.CryptoFunctionsPlugin) {
version.extensions.CryptoFunctionsPlugin = {installed:true};

//--
//-- Crypto functions and associated conversion routines
//--

// Crypto "namespace"
function Crypto() {}

// Convert a string to an array of big-endian 32-bit words
Crypto.strToBe32s = function(str)
{
	var be = Array();
	var len = Math.floor(str.length/4);
	var i, j;
	for(i=0, j=0; i<len; i++, j+=4) {
		be[i] = ((str.charCodeAt(j)&0xff) << 24)|((str.charCodeAt(j+1)&0xff) << 16)|((str.charCodeAt(j+2)&0xff) << 8)|(str.charCodeAt(j+3)&0xff);
	}
	while (j<str.length) {
		be[j>>2] |= (str.charCodeAt(j)&0xff)<<(24-(j*8)%32);
		j++;
	}
	return be;
};

// Convert an array of big-endian 32-bit words to a string
Crypto.be32sToStr = function(be)
{
	var str = "";
	for(var i=0;i<be.length*32;i+=8)
		str += String.fromCharCode((be[i>>5]>>>(24-i%32)) & 0xff);
	return str;
};

// Convert an array of big-endian 32-bit words to a hex string
Crypto.be32sToHex = function(be)
{
	var hex = "0123456789ABCDEF";
	var str = "";
	for(var i=0;i<be.length*4;i++)
		str += hex.charAt((be[i>>2]>>((3-i%4)*8+4))&0xF) + hex.charAt((be[i>>2]>>((3-i%4)*8))&0xF);
	return str;
};

// Return, in hex, the SHA-1 hash of a string
Crypto.hexSha1Str = function(str)
{
	return Crypto.be32sToHex(Crypto.sha1Str(str));
};

// Return the SHA-1 hash of a string
Crypto.sha1Str = function(str)
{
	return Crypto.sha1(Crypto.strToBe32s(str),str.length);
};

// Calculate the SHA-1 hash of an array of blen bytes of big-endian 32-bit words
Crypto.sha1 = function(x,blen)
{
	// Add 32-bit integers, wrapping at 32 bits
	add32 = function(a,b)
	{
		var lsw = (a&0xFFFF)+(b&0xFFFF);
		var msw = (a>>16)+(b>>16)+(lsw>>16);
		return (msw<<16)|(lsw&0xFFFF);
	};
	// Add five 32-bit integers, wrapping at 32 bits
	add32x5 = function(a,b,c,d,e)
	{
		var lsw = (a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF)+(e&0xFFFF);
		var msw = (a>>16)+(b>>16)+(c>>16)+(d>>16)+(e>>16)+(lsw>>16);
		return (msw<<16)|(lsw&0xFFFF);
	};
	// Bitwise rotate left a 32-bit integer by 1 bit
	rol32 = function(n)
	{
		return (n>>>31)|(n<<1);
	};

	var len = blen*8;
	// Append padding so length in bits is 448 mod 512
	x[len>>5] |= 0x80 << (24-len%32);
	// Append length
	x[((len+64>>9)<<4)+15] = len;
	var w = Array(80);

	var k1 = 0x5A827999;
	var k2 = 0x6ED9EBA1;
	var k3 = 0x8F1BBCDC;
	var k4 = 0xCA62C1D6;

	var h0 = 0x67452301;
	var h1 = 0xEFCDAB89;
	var h2 = 0x98BADCFE;
	var h3 = 0x10325476;
	var h4 = 0xC3D2E1F0;

	for(var i=0;i<x.length;i+=16) {
		var j,t;
		var a = h0;
		var b = h1;
		var c = h2;
		var d = h3;
		var e = h4;
		for(j = 0;j<16;j++) {
			w[j] = x[i+j];
			t = add32x5(e,(a>>>27)|(a<<5),d^(b&(c^d)),w[j],k1);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}
		for(j=16;j<20;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a>>>27)|(a<<5),d^(b&(c^d)),w[j],k1);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}
		for(j=20;j<40;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a>>>27)|(a<<5),b^c^d,w[j],k2);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}
		for(j=40;j<60;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a>>>27)|(a<<5),(b&c)|(d&(b|c)),w[j],k3);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}
		for(j=60;j<80;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a>>>27)|(a<<5),b^c^d,w[j],k4);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}

		h0 = add32(h0,a);
		h1 = add32(h1,b);
		h2 = add32(h2,c);
		h3 = add32(h3,d);
		h4 = add32(h4,e);
	}
	return Array(h0,h1,h2,h3,h4);
};


}
//}}}
Type the text for 'New Tiddler'
[[Welcome]]
/***
|''Name:''|DeprecatedFunctionsPlugin|
|''Description:''|Support for deprecated functions removed from core|
***/
//{{{
if(!version.extensions.DeprecatedFunctionsPlugin) {
version.extensions.DeprecatedFunctionsPlugin = {installed:true};

//--
//-- Deprecated code
//--

// @Deprecated: Use createElementAndWikify and this.termRegExp instead
config.formatterHelpers.charFormatHelper = function(w)
{
	w.subWikify(createTiddlyElement(w.output,this.element),this.terminator);
};

// @Deprecated: Use enclosedTextHelper and this.lookaheadRegExp instead
config.formatterHelpers.monospacedByLineHelper = function(w)
{
	var lookaheadRegExp = new RegExp(this.lookahead,"mg");
	lookaheadRegExp.lastIndex = w.matchStart;
	var lookaheadMatch = lookaheadRegExp.exec(w.source);
	if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
		var text = lookaheadMatch[1];
		if(config.browser.isIE)
			text = text.replace(/\n/g,"\r");
		createTiddlyElement(w.output,"pre",null,null,text);
		w.nextMatch = lookaheadRegExp.lastIndex;
	}
};

// @Deprecated: Use <br> or <br /> instead of <<br>>
config.macros.br = {};
config.macros.br.handler = function(place)
{
	createTiddlyElement(place,"br");
};

// Find an entry in an array. Returns the array index or null
// @Deprecated: Use indexOf instead
Array.prototype.find = function(item)
{
	var i = this.indexOf(item);
	return i == -1 ? null : i;
};

// Load a tiddler from an HTML DIV. The caller should make sure to later call Tiddler.changed()
// @Deprecated: Use store.getLoader().internalizeTiddler instead
Tiddler.prototype.loadFromDiv = function(divRef,title)
{
	return store.getLoader().internalizeTiddler(store,this,title,divRef);
};

// Format the text for storage in an HTML DIV
// @Deprecated Use store.getSaver().externalizeTiddler instead.
Tiddler.prototype.saveToDiv = function()
{
	return store.getSaver().externalizeTiddler(store,this);
};

// @Deprecated: Use store.allTiddlersAsHtml() instead
function allTiddlersAsHtml()
{
	return store.allTiddlersAsHtml();
}

// @Deprecated: Use refreshPageTemplate instead
function applyPageTemplate(title)
{
	refreshPageTemplate(title);
}

// @Deprecated: Use story.displayTiddlers instead
function displayTiddlers(srcElement,titles,template,unused1,unused2,animate,unused3)
{
	story.displayTiddlers(srcElement,titles,template,animate);
}

// @Deprecated: Use story.displayTiddler instead
function displayTiddler(srcElement,title,template,unused1,unused2,animate,unused3)
{
	story.displayTiddler(srcElement,title,template,animate);
}

// @Deprecated: Use functions on right hand side directly instead
var createTiddlerPopup = Popup.create;
var scrollToTiddlerPopup = Popup.show;
var hideTiddlerPopup = Popup.remove;

// @Deprecated: Use right hand side directly instead
var regexpBackSlashEn = new RegExp("\\\\n","mg");
var regexpBackSlash = new RegExp("\\\\","mg");
var regexpBackSlashEss = new RegExp("\\\\s","mg");
var regexpNewLine = new RegExp("\n","mg");
var regexpCarriageReturn = new RegExp("\r","mg");

}
//}}}
#install [[download.php]] as a file on the webserver in the TiddlyWiki folder. Perhaps near by store.php
#Simply put {{{[[download|download.php?]]}}} in the SideBarOptions of TiddlyWiki* 
#download as an attachement in one click on this link when viewed over HTTP

 * If it is named index.html else put {{{[[download|download.php?file=yourTW.html]]}}}

----
/*{{{*/
 
/*}}}*/
/*{{{*/
a {color:#0044BB;font-weight:bold}
/*}}}*/
/***
|''Name:''|EasyEditPlugin|
|''Description:''|Lite and extensible Wysiwyg editor for TiddlyWiki.|
|''Version:''|1.3.3|
|''Date:''|Dec 21,2007|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0|
!Demo
*On the plugin [[homepage|http://visualtw.ouvaton.org/VisualTW.html]], see [[WysiwygDemo]] and use the {{{write}}} button.
!Installation
#import the plugin,
#save and reload,
#use the <<toolbar easyEdit>> button in the tiddler's toolbar (in default ViewTemplate) or add {{{easyEdit}}} command in your own toolbar.
! Useful Addons
*[[HTMLFormattingPlugin|http://www.tiddlytools.com/#HTMLFormattingPlugin]] to embed wiki syntax in html tiddlers.<<br>>//__Tips__ : When this plugin is installed, you can use anchor syntax to link tiddlers in wysiwyg mode (example : #example). Anchors are converted back and from wiki syntax when editing.//
*[[TaggedTemplateTweak|http://www.TiddlyTools.com/#TaggedTemplateTweak]] to use alternative ViewTemplate/EditTemplate for tiddler's tagged with specific tag values.
!Configuration
|Buttons in the toolbar (empty = all).<<br>>//Example : bold,underline,separator,forecolor//<<br>>The buttons will appear in this order.| <<option txtEasyEditorButtons>>|
|EasyEditor default height | <<option txtEasyEditorHeight>>|
|Stylesheet applied to the edited richtext |[[EasyEditDocStyleSheet]]|
|Template called by the {{{write}}} button |[[EasyEditTemplate]]|
!How to extend EasyEditor
*To add your own buttons, add some code like the following in a systemConfig tagged tiddler (//use the prompt attribute only if there is a parameter//) :
**{{{EditorToolbar.buttons.heading = {label:"H", toolTip : "Set heading level", prompt: "Enter heading level"};}}} 
**{{{EditorToolbar.buttonsList +=",heading";}}}
*To get the list of all possible commands, see the documentation of the [[Gecko built-in rich text editor|http://developer.mozilla.org/en/docs/Midas]] or the [[IE command identifiers|http://msdn2.microsoft.com/en-us/library/ms533049.aspx]].
*To go further in customization, see [[Link button|EasyEditPlugin-LinkButton]] as an example.
!Code
***/

//{{{

var geckoEditor={};
var IEeditor={};

config.options.txtEasyEditorHeight = config.options.txtEasyEditorHeight ? config.options.txtEasyEditorHeight : "500px";
config.options.txtEasyEditorButtons = config.options.txtEasyEditorButtons ? config.options.txtEasyEditorButtons : "";

// TW2.1.x compatibility
config.browser.isGecko = config.browser.isGecko ? config.browser.isGecko : (config.userAgent.indexOf("gecko") != -1); 
config.macros.annotations = config.macros.annotations ? config.macros.annotations : {handler : function() {}}


// EASYEDITOR MACRO

config.macros.easyEdit = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		var field = params[0];
		var height = params[1] ? params[1] : config.options.txtEasyEditorHeight;
		var editor = field ? new easyEditor(tiddler,field,place,height) : null;
	},
	gather: function(element){
		var iframes = element.getElementsByTagName("iframe");
		if (iframes.length!=1) return null
		var text = "<html>"+iframes[0].contentWindow.document.body.innerHTML+"</html>";
		text = config.browser.isGecko ? geckoEditor.postProcessor(text) : (config.browser.isIE ? IEeditor.postProcessor(text) : text);
		return text;
	}
}

// EASYEDITOR CLASS

function easyEditor(tiddler,field,place,height) {
	this.tiddler = tiddler;
	this.field = field;
	this.browser = config.browser.isGecko ? geckoEditor : (config.browser.isIE ? IEeditor : null);
	this.wrapper = createTiddlyElement(place,"div",null,"easyEditor");
	this.wrapper.setAttribute("easyEdit",this.field);
	this.iframe = createTiddlyElement(null,"iframe");
	this.browser.setupFrame(this.iframe,height,contextualCallback(this,this.onload));
	this.wrapper.appendChild(this.iframe);
}

easyEditor.prototype.onload = function(){
	this.editor = this.iframe.contentWindow;
	this.doc = this.editor.document;
	if (!this.browser.isDocReady(this.doc)) return null;
	
	if (!this.tiddler.isReadOnly() && this.doc.designMode.toLowerCase()!="on") {
		this.doc.designMode = "on";
		if (this.browser.reloadOnDesignMode) return false;	// IE fire readystatechange after designMode change
	}
	
	var internalCSS = store.getTiddlerText("EasyEditDocStyleSheet");
	setStylesheet(internalCSS,"EasyEditDocStyleSheet",this.doc);
	this.browser.initContent(this.doc,store.getValue(this.tiddler,this.field));

	var barElement=createTiddlyElement(null,"div",null,"easyEditorToolBar");
	this.wrapper.insertBefore(barElement,this.wrapper.firstChild);
	this.toolbar = new EditorToolbar(this.doc,barElement,this.editor);

	this.browser.plugEvents(this.doc,contextualCallback(this,this.scheduleButtonsRefresh));
	this.editor.focus();
}

easyEditor.SimplePreProcessoror = function(text) {
	var re = /^<html>(.*)<\/html>$/m;
	var htmlValue = re.exec(text);
	var value = (htmlValue && (htmlValue.length>0)) ? htmlValue[1] : text;
	return value;
}

easyEditor.prototype.scheduleButtonsRefresh=function() { //doesn't refresh buttons state when rough typing
	if (this.nextUpdate) window.clearTimeout(this.nextUpdate);
	this.nextUpdate = window.setTimeout(contextualCallback(this.toolbar,EditorToolbar.onUpdateButton),easyEditor.buttonDelay);
}

easyEditor.buttonDelay = 200;

// TOOLBAR CLASS

function EditorToolbar(target,parent,window){
	this.target = target;
	this.window=window;
	this.elements={};
	var row = createTiddlyElement(createTiddlyElement(createTiddlyElement(parent,"table"),"tbody"),"tr");
	var buttons = (config.options.txtEasyEditorButtons ? config.options.txtEasyEditorButtons : EditorToolbar.buttonsList).split(",");
	for(var cpt = 0; cpt < buttons.length; cpt++){
		var b = buttons[cpt];
		var button = EditorToolbar.buttons[b];
		if (button) {
			if (button.separator)
				createTiddlyElement(row,"td",null,"separator").innerHTML+="&nbsp;";
			else {
				var cell=createTiddlyElement(row,"td",null,b+"Button");
				if (button.onCreate) button.onCreate.call(this, cell, b);
				else EditorToolbar.createButton.call(this, cell, b);
			}
		}
	}
}

EditorToolbar.createButton = function(place,name){
	this.elements[name] = createTiddlyButton(place,EditorToolbar.buttons[name].label,EditorToolbar.buttons[name].toolTip,contextualCallback(this,EditorToolbar.onCommand(name)),"button");
}

EditorToolbar.onCommand = function(name){
	var button = EditorToolbar.buttons[name];
	return function(){
		var parameter = false;
		if (button.prompt) {
			var parameter = this.target.queryCommandValue(name);
			parameter = prompt(button.prompt,parameter);
		}
		if (parameter != null) {
			this.target.execCommand(name, false, parameter);
			EditorToolbar.onUpdateButton.call(this);
		}
		return false;
	}
}

EditorToolbar.getCommandState = function(target,name){
	try {return target.queryCommandState(name)}
	catch(e){return false}
}

EditorToolbar.onRefreshButton = function (name){
	if (EditorToolbar.getCommandState(this.target,name)) addClass(this.elements[name].parentNode,"buttonON");
	else removeClass(this.elements[name].parentNode,"buttonON");
	this.window.focus();
}

EditorToolbar.onUpdateButton = function(){
	for (b in this.elements) 
		if (EditorToolbar.buttons[b].onRefresh) EditorToolbar.buttons[b].onRefresh.call(this,b);
		else EditorToolbar.onRefreshButton.call(this,b);
}

EditorToolbar.buttons = {
	separator : {separator : true},
	bold : {label:"B", toolTip : "Bold"},
	italic : {label:"I", toolTip : "Italic"},
	underline : {label:"U", toolTip : "Underline"},
	strikethrough : {label:"S", toolTip : "Strikethrough"},
	insertunorderedlist : {label:"\u25CF", toolTip : "Unordered list"},
	insertorderedlist : {label:"1.", toolTip : "Ordered list"},
	justifyleft : {label:"[\u2261", toolTip : "Align left"},
	justifyright : {label:"\u2261]", toolTip : "Align right"},
	justifycenter : {label:"\u2261", toolTip : "Align center"},
	justifyfull : {label:"[\u2261]", toolTip : "Justify"},
	removeformat : {label:"\u00F8", toolTip : "Remove format"},
	fontsize : {label:"\u00B1", toolTip : "Set font size", prompt: "Enter font size"},
	forecolor : {label:"C", toolTip : "Set font color", prompt: "Enter font color"},
	fontname : {label:"F", toolTip : "Set font name", prompt: "Enter font name"},
	heading : {label:"H", toolTip : "Set heading level", prompt: "Enter heading level (example : h1, h2, ...)"},
	indent : {label:"\u2192[", toolTip : "Indent paragraph"},
	outdent : {label:"[\u2190", toolTip : "Outdent paragraph"},
	inserthorizontalrule : {label:"\u2014", toolTip : "Insert an horizontal rule"},
	insertimage : {label:"\u263C", toolTip : "Insert image", prompt: "Enter image url"}
}

EditorToolbar.buttonsList = "bold,italic,underline,strikethrough,separator,increasefontsize,decreasefontsize,fontsize,forecolor,fontname,separator,removeformat,separator,insertparagraph,insertunorderedlist,insertorderedlist,separator,justifyleft,justifyright,justifycenter,justifyfull,indent,outdent,separator,heading,separator,inserthorizontalrule,insertimage";

if (config.browser.isGecko) {
	EditorToolbar.buttons.increasefontsize = {onCreate : EditorToolbar.createButton, label:"A", toolTip : "Increase font size"};
	EditorToolbar.buttons.decreasefontsize = {onCreate : EditorToolbar.createButton, label:"A", toolTip : "Decrease font size"};
	EditorToolbar.buttons.insertparagraph = {label:"P", toolTip : "Format as paragraph"};
}

// GECKO (FIREFOX, ...) BROWSER SPECIFIC METHODS

geckoEditor.setupFrame = function(iframe,height,callback) {
	iframe.setAttribute("style","width: 100%; height:" + height);
	iframe.addEventListener("load",callback,true);
}

geckoEditor.plugEvents = function(doc,onchange){
	doc.addEventListener("keyup", onchange, true);
	doc.addEventListener("keydown", onchange, true);
	doc.addEventListener("click", onchange, true);
}

geckoEditor.postProcessor = function(text){return text};

geckoEditor.preProcessor = function(text){return easyEditor.SimplePreProcessoror(text)}

geckoEditor.isDocReady = function() {return true;}

geckoEditor.reloadOnDesignMode=false;

geckoEditor.initContent = function(doc,content){
	if (content) doc.execCommand("insertHTML",false,geckoEditor.preProcessor(content));
}

// INTERNET EXPLORER BROWSER SPECIFIC METHODS
	
IEeditor.setupFrame = function(iframe,height,callback) {
	iframe.width="99%";  //IE displays the iframe at the bottom if 100%. CSS layout problem ? I don't know. To be studied...
	iframe.height=height.toString();
	iframe.attachEvent("onreadystatechange",callback);
}

IEeditor.plugEvents = function(doc,onchange){
	doc.attachEvent("onkeyup", onchange);
	doc.attachEvent("onkeydown", onchange);
	doc.attachEvent("onclick", onchange);
}

IEeditor.isDocReady = function(doc){
	if (doc.readyState!="complete") return false;
	if (!doc.body) return false;
	return (doc && doc.getElementsByTagName && doc.getElementsByTagName("head") && doc.getElementsByTagName("head").length>0);
}

IEeditor.postProcessor = function(text){return text};

IEeditor.preProcessor = function(text){return easyEditor.SimplePreProcessoror(text)}

IEeditor.reloadOnDesignMode=true;

IEeditor.initContent = function(doc,content){
	if (content) doc.body.innerHTML=IEeditor.preProcessor(content);
}
	
function contextualCallback(obj,func){
    return function(){return func.call(obj)}
}
	
Story.prototype.previousGatherSaveEasyEdit = Story.prototype.previousGatherSaveEasyEdit ? Story.prototype.previousGatherSaveEasyEdit : Story.prototype.gatherSaveFields; // to avoid looping if this line is called several times
Story.prototype.gatherSaveFields = function(e,fields){
	if(e && e.getAttribute) {
		var f = e.getAttribute("easyEdit");
		if(f){
			var newVal = config.macros.easyEdit.gather(e);
			if (newVal) fields[f] = newVal;
		}
		this.previousGatherSaveEasyEdit(e, fields);
	}
}

config.commands.easyEdit={
	text: "write",
	tooltip: "Edit this tiddler in wysiwyg mode",
	readOnlyText: "view",
	readOnlyTooltip: "View the source of this tiddler",
	handler : function(event,src,title) {
		clearMessage();
		var tiddlerElem = document.getElementById(story.idPrefix + title);
		var fields = tiddlerElem.getAttribute("tiddlyFields");
		story.displayTiddler(null,title,"EasyEditTemplate",false,null,fields);
		return false;
	}
}

config.shadowTiddlers.ViewTemplate = config.shadowTiddlers.ViewTemplate.replace(/\+editTiddler/,"+editTiddler easyEdit");

config.shadowTiddlers.EasyEditTemplate = config.shadowTiddlers.EditTemplate.replace(/macro='edit text'/,"macro='easyEdit text'");

config.shadowTiddlers.EasyEditToolBarStyleSheet = "/*{{{*/\n";
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar {font-size:0.8em}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".editor iframe {border:1px solid #DDD}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar td{border:1px solid #888; padding:2px 1px 2px 1px; vertical-align:middle}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar td.separator{border:0}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .button{border:0;color:#444}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .buttonON{background-color:#EEE}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar {margin:0.25em 0}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .boldButton {font-weight:bold}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .italicButton .button {font-style:italic;padding-right:0.65em}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .underlineButton .button {text-decoration:underline}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .strikeButton .button {text-decoration:line-through}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .unorderedListButton {margin-left:0.7em}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .justifyleftButton .button {padding-left:0.1em}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .justifyrightButton .button {padding-right:0.1em}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .justifyfullButton .button, .easyEditorToolBar .indentButton .button, .easyEditorToolBar .outdentButton .button {padding-left:0.1em;padding-right:0.1em}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .increasefontsizeButton .button {padding-left:0.15em;padding-right:0.15em; font-size:1.3em; line-height:0.75em}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .decreasefontsizeButton .button {padding-left:0.4em;padding-right:0.4em; font-size:0.8em;}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .forecolorButton .button {color:red;}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += ".easyEditorToolBar .fontnameButton .button {font-family:serif}\n" ;
config.shadowTiddlers.EasyEditToolBarStyleSheet +="/*}}}*/";

store.addNotification("EasyEditToolBarStyleSheet", refreshStyles); 

config.shadowTiddlers.EasyEditDocStyleSheet = "/*{{{*/\n \n/*}}}*/";
if (config.annotations) config.annotations.EasyEditDocStyleSheet = "This stylesheet is applied when editing a text with the wysiwyg easyEditor";

//}}}
/***
!Link button add-on
***/
//{{{
EditorToolbar.createLinkButton = function(place,name) {
	this.elements[name] = createTiddlyButton(place,EditorToolbar.buttons[name].label,EditorToolbar.buttons[name].toolTip,contextualCallback(this,EditorToolbar.onInputLink()),"button");
}

EditorToolbar.onInputLink = function() {
	return function(){
		var browser = config.browser.isGecko ? geckoEditor : (config.browser.isIE ? IEeditor : null);
		var value = browser ? browser.getLink(this.target) : "";
		value = prompt(EditorToolbar.buttons["createlink"].prompt,value);
		if (value) browser.doLink(this.target,value);
		else if (value=="") this.target.execCommand("unlink", false, value);
		EditorToolbar.onUpdateButton.call(this);
		return false;
	}
}

EditorToolbar.buttonsList += ",separator,createlink";

EditorToolbar.buttons.createlink = {onCreate : EditorToolbar.createLinkButton, label:"L", toolTip : "Set link", prompt: "Enter link url"};


geckoEditor.getLink=function(doc){
	var range=doc.defaultView.getSelection().getRangeAt(0);
	var container = range.commonAncestorContainer;
	var node = (container.nodeType==3) ? container.parentNode : range.startContainer.childNodes[range.startOffset];
	if (node && node.tagName=="A") {
		var r=doc.createRange();
		r.selectNode(node);
		doc.defaultView.getSelection().addRange(r);
		return (node.getAttribute("tiddler") ? "#"+node.getAttribute("tiddler") : node.href);
	}
	else return (container.nodeType==3 ? "#"+container.textContent.substr(range.startOffset, range.endOffset-range.startOffset).replace(/ $/,"") : "");
}

geckoEditor.doLink=function(doc,link){ // store tiddler in a temporary attribute to avoid url encoding of tiddler's name
	var pin = "href"+Math.random().toString().substr(3);
	doc.execCommand("createlink", false, pin);
	var isTiddler=(link.charAt(0)=="#");
	var node = doc.defaultView.getSelection().getRangeAt(0).commonAncestorContainer;
	var links= (node.nodeType!=3) ? node.getElementsByTagName("a") : [node.parentNode];
	for (var cpt=0;cpt<links.length;cpt++) 
			if (links[cpt].href==pin){
				links[cpt].href=isTiddler ? "javascript:;" : link; 
				links[cpt].setAttribute("tiddler",isTiddler ? link.substr(1) : "");
			}
}

geckoEditor.beforeLinkPostProcessor = geckoEditor.beforelinkPostProcessor ? geckoEditor.beforelinkPostProcessor : geckoEditor.postProcessor;
geckoEditor.postProcessor = function(text){
	return geckoEditor.beforeLinkPostProcessor(text).replace(/<a tiddler="([^"]*)" href="javascript:;">(.*?)(?:<\/a>)/gi,"[[$2|$1]]").replace(/<a tiddler="" href="/gi,'<a href="');
}

geckoEditor.beforeLinkPreProcessor = geckoEditor.beforeLinkPreProcessor ? geckoEditor.beforeLinkPreProcessor : geckoEditor.preProcessor
geckoEditor.preProcessor = function(text){
	return geckoEditor.beforeLinkPreProcessor(text).replace(/\[\[([^|\]]*)\|([^\]]*)]]/g,'<a tiddler="$2" href="javascript:;">$1</a>');
}


IEeditor.getLink=function(doc){
	var node=doc.selection.createRange().parentElement();
	if (node.tagName=="A") return node.href;
	else return (doc.selection.type=="Text"? "#"+doc.selection.createRange().text.replace(/ $/,"") :"");
}

IEeditor.doLink=function(doc,link){
	doc.execCommand("createlink", false, link);
}

IEeditor.beforeLinkPreProcessor = IEeditor.beforeLinkPreProcessor ? IEeditor.beforeLinkPreProcessor : IEeditor.preProcessor
IEeditor.preProcessor = function(text){
	return IEeditor.beforeLinkPreProcessor(text).replace(/\[\[([^|\]]*)\|([^\]]*)]]/g,'<a ref="#$2">$1</a>');
}

IEeditor.beforeLinkPostProcessor = IEeditor.beforelinkPostProcessor ? IEeditor.beforelinkPostProcessor : IEeditor.postProcessor;
IEeditor.postProcessor = function(text){
	return IEeditor.beforeLinkPostProcessor(text).replace(/<a href="#([^>]*)">([^<]*)<\/a>/gi,"[[$2|$1]]");
}

IEeditor.beforeLinkInitContent = IEeditor.beforeLinkInitContent ? IEeditor.beforeLinkInitContent : IEeditor.initContent;
IEeditor.initContent = function(doc,content){
	IEeditor.beforeLinkInitContent(doc,content);
	var links=doc.body.getElementsByTagName("A");
	for (var cpt=0; cpt<links.length; cpt++) {
		links[cpt].href=links[cpt].ref; //to avoid IE conversion of relative URLs to absolute
		links[cpt].removeAttribute("ref");	
	}
}

config.shadowTiddlers.EasyEditToolBarStyleSheet += "\n/*{{{*/\n.easyEditorToolBar .createlinkButton .button {color:blue;text-decoration:underline;}\n/*}}}*/";

config.shadowTiddlers.EasyEditDocStyleSheet += "\n/*{{{*/\na {color:#0044BB;font-weight:bold}\n/*}}}*/";

//}}}
<!--{{{-->
<div class='toolbar' macro='toolbar +saveTiddler -cancelTiddler deleteTiddler'></div>
<div class='title' macro='view title'></div>
<div class='editor' macro='edit title'></div>
<div macro='annotations'></div>
<div class='editor' macro='edit text'></div> 
<!-- <div macro='editFieldInFrame text editor.html'></div> -->
<div class='editor' macro='edit tags'></div><div class='editorFooter'><span macro='message views.editor.tagPrompt'></span><span macro='tagChooser'></span></div>
<!--}}}-->
Type the text for 'New Tiddler'
/***
|Name|HTMLFormattingPlugin|
|Source|http://www.TiddlyTools.com/#HTMLFormattingPlugin|
|Documentation|http://www.TiddlyTools.com/#HTMLFormattingPluginInfo|
|Version|2.1.5|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides|'HTML' formatter|
|Description|embed wiki syntax formatting inside of HTML content|
The shorthand Wiki-style formatting syntax of ~TiddlyWiki is very convenient and enables most content to be reasonably well presented. However, there are times when tried-and-true HTML formatting syntax allows more more precise control of the content display.  When HTML formatting syntax is embedded within a tiddler (in between {{{<}}}{{{html>}}} and {{{<}}}{{{/html>}}} markers) TiddlyWiki passes this content to the browser for processing as 'native' HTML.  However, TiddlyWiki does not also process the HTML source content for any embedded wiki-formatting syntax it may contain.  This means that while you can use HTML formatted content, you cannot mix wiki-formatted content within the HTML formatting.

The ~HTMLFormatting plugin allows you to freely ''mix wiki-style formatting syntax within HTML formatted content'' by extending the action of the standard TiddlyWiki formatting handler.
!!!!!Documentation
>see [[HTMLFormattingPluginInfo]]
!!!!!Revisions
<<<
2008.01.08 [*.*.*] plugin size reduction: documentation moved to HTMLFormattingInfo
2007.12.04 [*.*.*] update for TW2.3.0: replaced deprecated core functions, regexps, and macros
2007.06.14 [2.1.5] in formatter, removed call to e.normalize().  Creates an INFINITE RECURSION error in Safari!!!!
2006.09.10 [2.1.4] update formatter for 2.1 compatibility (use this.lookaheadRegExp instead of temp variable)
2006.05.28 [2.1.3] in wikifyTextNodes(), decode the *value* of TEXTAREA nodes, but don't wikify() its children.  (thanks to "ayj" for bug report)
2006.02.19 [2.1.2] in wikifyTextNodes(), put SPAN element into tiddler DOM (replacing text node), BEFORE wikifying the text content.  This ensures that the 'place' passed to any macros is correctly defined when the macro is evaluated, so that calls to story.findContainingTiddler(place) will work as expected. (Thanks for bug report from GeoffSlocock)
2006.02.05 [2.1.1] wrapped wikifier hijack in init function to eliminate globals and avoid FireFox 1.5.0.1 crash bug when referencing globals
2005.12.01 [2.1.0] don't wikify #TEXT nodes inside SELECT and TEXTAREA elements
2005.11.06 [2.0.1] code cleanup
2005.10.31 [2.0.0] replaced hijack wikify() with hijack config.formatters["html"] and simplified recursive WikifyTextNodes() code
2005.10.09 [1.0.2] combined documentation and code into a single tiddler
2005.08.05 [1.0.1] moved HTML and CSS definitions into plugin code instead of using separate tiddlers
2005.07.26 [1.0.1] Re-released as a plugin. Added <{{{html}}}>...</{{{nohtml}}}> and <{{{hide newlines}}}> handling
2005.06.26 [1.0.0] Initial Release (as code adaptation - pre-dates TiddlyWiki plugin architecture!!)
<<<
!!!!!Code
***/
//{{{
version.extensions.HTMLFormatting = {major: 2, minor: 1, revision: 5, date: new Date(2007,6,14)};

// find the formatter for HTML and replace the handler
initHTMLFormatter();
function initHTMLFormatter()
{
	for (var i=0; i<config.formatters.length && config.formatters[i].name!="html"; i++);
	if (i<config.formatters.length)	config.formatters[i].handler=function(w) {
		if (!this.lookaheadRegExp)  // fixup for TW2.0.x
			this.lookaheadRegExp = new RegExp(this.lookahead,"mg");
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source)
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			var html=lookaheadMatch[1];
			// optionally suppress wiki-style literal handling of newlines
			// strip any carriage returns added by Internet Explorer's textarea edit field
			// encode newlines as \n so Internet Explorer's HTML parser won't eat them
			// encode macro brackets (<< and >>) so HTML parser won't eat them
			if (html.indexOf('<hide linebreaks>')!=-1) html=html.replace(/\n/g,' ');
			html=html.replace(/\r/g,'');
			html=html.replace(/\n/g,'\\n');
			html=html.replace(/<</g,'%%(').replace(/>>/g,')%%');
			// create span to hold HTML
			// parse HTML and normalize the results
			// walk node tree and call wikify() on each text node
			var e = createTiddlyElement(w.output,"span");
			e.innerHTML=html;
			// REMOVED: e.normalize();  // THIS CAUSED INFINITE RECURSION IN SAFARI
			wikifyTextNodes(e);
			// advance to next parse position
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
}

// wikify text nodes remaining after HTML content is processed (pre-order recursion)
function wikifyTextNodes(theNode)
{
	// textarea node doesn't get wikified, just decoded... 
	if (theNode.nodeName.toLowerCase()=='textarea')
		theNode.value=theNode.value.replace(/\%%\(/g,'<<').replace(/\)\%%/g,'>>').replace(/\\n/g,'\n');
	else for (var i=0;i<theNode.childNodes.length;i++) {
		var theChild=theNode.childNodes.item(i);
		if (theChild.nodeName.toLowerCase()=='option') continue;
		if (theChild.nodeName.toLowerCase()=='select') continue;
		wikifyTextNodes(theChild);
		if (theChild.nodeName=='#text') {
			var txt=theChild.nodeValue;
			// decode macro brackets and newlines
			txt=txt.replace(/\%%\(/g,'<<').replace(/\)\%%/g,'>>').replace(/\\n/g,'\n');
			// replace text node with wikified() span
			var newNode=createTiddlyElement(null,"span");
			theNode.replaceChild(newNode,theChild);
			wikify(txt,newNode);
		}
	}
}
//}}}
<html><div align="center"><iframe src ="img_upload.php" width="80%" align="center" height="150"></iframe></div></html>
//{{{
config.macros.tex = {};
 config.macros.tex.handler = function (place,macroName,params,wikifier,paramString,tiddler) {
 
     var code = encodeURIComponent(params[0]);
     wikify("<html><img class=\"teximg\" alt=\"" + params[0] + "\" title=\"" + params[0] + "\" src=\"latexrender/render.php?l=" + code + "\"></html>", place);
 }
//}}}
This uses [[LatexRender|http://www.mayer.dial.pipex.com/tex.htm]], my simple ~TiddlyWiki macro, LatexRenderPlugin, and a custom script I created for the purpose, render.php, which renders ~LaTeX fed to it as an argument.

First you need access to a server with the ability to run ~LatexRender. Download the [[latexrender.zip|http://www.mayer.dial.pipex.com/latexrender.zip]], and extract the "otherPHP" directory. Copy the class.latexrender.php, and latex.php files to a folder on your webserver. Set up the directories in each file accordingly. For example, I have my wiki set up like so:
>webroot/physiwiki/latexrender:
>//class.latexrender.php//
>//latex.php//
and two subdirectories (which the webserver needs write access to, chmod 777):
>webroot/physiwiki/latexrender/pictures
>webroot/physiwiki/latexrender/tmp

So in //class.latexrender.php//, I have:
{{{
    var $_picture_path = "/absolue/directory/to/physiwiki/latexrender/pictures";
    var $_picture_path_httpd = "/physiwiki/latexrender/pictures";
    var $_tmp_dir = "/absolute/directory/to/physiwiki/latexrender/tmp";
}}}
Also, make sure the paths to ''latex'', ''dvips'', ''convert'', ''identify'' are setup correctly on the lines below. You can also make changes to the other settings in this file if you want including image format. The default is ''gif'', I changed it to ''png''.

Now //latex.php// by default generates the html to show an image, like:
{{{
<img src="blah">
}}}
We dont want this. So some changes to //latex.php// are required. First adjust the paths in //latex.php//:
{{{
    $latexrender_path = "/absolute/directory/to/physiwiki/latexrender";
    $latexrender_path_http = ".";
}}}
The '.' is used as //latex.php// resides in the same directory as class.latexrender.php.
Next, scroll right to the bottom of the file, and you can comment out/delete the last few lines, and change the return value to $url instead of $text as below:
{{{
        $url = $latex->getFormulaURL($latex_formula);

        /*
        $alt_latex_formula = htmlentities($latex_formula, ENT_QUOTES);
        $alt_latex_formula = str_replace("\r","&#13;",$alt_latex_formula);
        $alt_latex_formula = str_replace("\n","&#10;",$alt_latex_formula);

        if ($url != false) {
            $text = substr_replace($text, "<img src='".$url."' title='".$alt_latex_formula."' alt='".$alt_latex_formula."' align=absmiddle>",$pos,strlen($tex_matches[0][$i]));
        } else {
            $text = substr_replace($text, "[Unparseable or potentially dangerous latex formula. Error $latex->_errorcode $latex->_errorextra]",$pos,strlen($tex_matches[0][$i]));
        }
         */
    }
    return $url;
}
}}}

Right, that's ~LatexRender all setup. Now we need to make the //render.php// file. Put the code in a file and save it in the same directory as //class.latexrender.php// and //latex.php//.
//render.php//:
{{{
<?
header("Content-type: image/png");
include_once('latex.php');

if (isset($_GET['l'])){

        $text = $_GET['l'];
        $text = stripslashes($text);
        $text = "[tex]" . $text . "[/tex]";
        
        $latex_img_file = latex_content($text);
        $handle = fopen($latex_img_file, "r");
        $contents = fread($handle, filesize($latex_img_file));
        fclose($handle);

        echo $contents;
}
?>
}}}
Obviously change the header function to match the content type you specified in //class.render.php//. This file accepts ~LaTeX formula code as an argument render.php?l=<formula>, puts it between [tex] tags so it can be messed around by //latex.php// and then renders it as the image file. 

Now all that is left is to incorporate this into ~TiddlyWiki, using a simple macro. (Just change the src= section to match the location of your script):
{{{
config.macros.tex = {};
 config.macros.tex.handler = function (place,macroName,params,wikifier,paramString,tiddler) {
 
     var code = encodeURIComponent(params[0]);
     wikify("<html><img class=\"teximg\" title=\"" + params[0] + "\" src=\"latexrender/render.php?l=" + code + "\"></html>", place);
 }
}}}

To use this plugin just call it like so:
{{{
<<tex '\int_{-5}^{5} x^2 dx'>>
}}}
which gives:
><<tex '\int_{-5}^{5} x^2 dx'>>
For more examples see just browse my wiki!
The macro also gives all equations the "teximg" css class, so they can be adjusted to be inline "nicely", using the following CSS in the StyleSheet tiddler:
{{{
.viewer {line-height: 2.0 ;}
.viewer img.teximg { vertical-align: middle;}
}}}
/***
|''Name:''|LegacyStrikeThroughPlugin|
|''Description:''|Support for legacy (pre 2.1) strike through formatting|
|''Version:''|1.0.2|
|''Date:''|Jul 21, 2006|
|''Source:''|http://www.tiddlywiki.com/#LegacyStrikeThroughPlugin|
|''Author:''|MartinBudden (mjbudden (at) gmail (dot) com)|
|''License:''|[[BSD open source license]]|
|''CoreVersion:''|2.1.0|
***/

//{{{
// Ensure that the LegacyStrikeThrough Plugin is only installed once.
if(!version.extensions.LegacyStrikeThroughPlugin) {
version.extensions.LegacyStrikeThroughPlugin = {installed:true};

config.formatters.push(
{
	name: "legacyStrikeByChar",
	match: "==",
	termRegExp: /(==)/mg,
	element: "strike",
	handler: config.formatterHelpers.createElementAndWikify
});

} //# end of "install only once"
//}}}
<<tagsTree Menu "" 3 4 index label>>
Type the text for 'New Tiddler'
Type the text for 'New Tiddler'
/***
|''Name:''|PasswordOptionPlugin|
|''Description:''|Extends TiddlyWiki options with non encrypted password option.|
|''Version:''|1.0.2|
|''Date:''|Apr 19, 2007|
|''Source:''|http://tiddlywiki.bidix.info/#PasswordOptionPlugin|
|''Author:''|BidiX (BidiX (at) bidix (dot) info)|
|''License:''|[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D ]]|
|''~CoreVersion:''|2.2.0 (Beta 5)|
***/
//{{{
version.extensions.PasswordOptionPlugin = {
	major: 1, minor: 0, revision: 2, 
	date: new Date("Apr 19, 2007"),
	source: 'http://tiddlywiki.bidix.info/#PasswordOptionPlugin',
	author: 'BidiX (BidiX (at) bidix (dot) info',
	license: '[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D]]',
	coreVersion: '2.2.0 (Beta 5)'
};

config.macros.option.passwordCheckboxLabel = "Save this password on this computer";
config.macros.option.passwordInputType = "password"; // password | text
setStylesheet(".pasOptionInput {width: 11em;}\n","passwordInputTypeStyle");

merge(config.macros.option.types, {
	'pas': {
		elementType: "input",
		valueField: "value",
		eventName: "onkeyup",
		className: "pasOptionInput",
		typeValue: config.macros.option.passwordInputType,
		create: function(place,type,opt,className,desc) {
			// password field
			config.macros.option.genericCreate(place,'pas',opt,className,desc);
			// checkbox linked with this password "save this password on this computer"
			config.macros.option.genericCreate(place,'chk','chk'+opt,className,desc);			
			// text savePasswordCheckboxLabel
			place.appendChild(document.createTextNode(config.macros.option.passwordCheckboxLabel));
		},
		onChange: config.macros.option.genericOnChange
	}
});

merge(config.optionHandlers['chk'], {
	get: function(name) {
		// is there an option linked with this chk ?
		var opt = name.substr(3);
		if (config.options[opt]) 
			saveOptionCookie(opt);
		return config.options[name] ? "true" : "false";
	}
});

merge(config.optionHandlers, {
	'pas': {
 		get: function(name) {
			if (config.options["chk"+name]) {
				return encodeCookie(config.options[name].toString());
			} else {
				return "";
			}
		},
		set: function(name,value) {config.options[name] = decodeCookie(value);}
	}
});

// need to reload options to load passwordOptions
loadOptionsCookie();

/*
if (!config.options['pasPassword'])
	config.options['pasPassword'] = '';

merge(config.optionsDesc,{
		pasPassword: "Test password"
	});
*/
//}}}
[[download|download.php?]]
<<saveChanges>>
<<search>><<closeAll>><<permaview>><<newTiddler>><<newJournal "DD MMM YYYY" "journal">><<upload store.php>><<slider imgUpload ImageUpload 'image »' 'Image Upload'>><<slider LocalSlider SideBarLocalSlider 'local »' 'Local Editing Options'>><<slider chkSliderOptionsPanel OptionsPanel "options »" "Change TiddlyWiki advanced options">>
<<tabs txtMainTab "Timeline" "Timeline" TabTimeline "All" "All tiddlers" TabAll "Tags" "All tags" TabTags "More" "More lists" TabMore>>
dave's physics revision wiki.
[[PhysiWiki|Welcome]]
/***
|''Name:''|SparklinePlugin|
|''Description:''|Sparklines macro|
***/
//{{{
if(!version.extensions.SparklinePlugin) {
version.extensions.SparklinePlugin = {installed:true};

//--
//-- Sparklines
//--

config.macros.sparkline = {};
config.macros.sparkline.handler = function(place,macroName,params)
{
	var data = [];
	var min = 0;
	var max = 0;
	var v;
	for(var t=0; t<params.length; t++) {
		v = parseInt(params[t]);
		if(v < min)
			min = v;
		if(v > max)
			max = v;
		data.push(v);
	}
	if(data.length < 1)
		return;
	var box = createTiddlyElement(place,"span",null,"sparkline",String.fromCharCode(160));
	box.title = data.join(",");
	var w = box.offsetWidth;
	var h = box.offsetHeight;
	box.style.paddingRight = (data.length * 2 - w) + "px";
	box.style.position = "relative";
	for(var d=0; d<data.length; d++) {
		var tick = document.createElement("img");
		tick.border = 0;
		tick.className = "sparktick";
		tick.style.position = "absolute";
		tick.src = "data:image/gif,GIF89a%01%00%01%00%91%FF%00%FF%FF%FF%00%00%00%C0%C0%C0%00%00%00!%F9%04%01%00%00%02%00%2C%00%00%00%00%01%00%01%00%40%02%02T%01%00%3B";
		tick.style.left = d*2 + "px";
		tick.style.width = "2px";
		v = Math.floor(((data[d] - min)/(max-min)) * h);
		tick.style.top = (h-v) + "px";
		tick.style.height = v + "px";
		box.appendChild(tick);
	}
};


}
//}}}
Type the text for 'New Tiddler'
*''Model Assumptions'':
**Incompressibility: 
><<tex '\nabla \cdot \textbf{u} = 0'>> 
>
>gives:
>
><<tex '\dfrac{\partial u}{\partial x} = \dfrac{\partial v}{\partial y} = \dfrac{\partial w}{\partial z} = 0'>>
**Steady flow (e.g.):
><<tex '\dfrac{\partial u}{\partial t} = 0'>>
*''Boundary Conditions'':
**"No-slip" - The fluid comes to rest at walls (e.g. <<tex 'u = 0'>>)

/*{{{*/
.viewer {line-height: 2.0 ;}
.viewer img.teximg { vertical-align: middle;}
.viewer blockquote { 
    border: 1px solid #000; 
    background: #F9F9F9; 
    padding: 5px;
    margin: 5px;
}
iframe { border:none; }

.tagging {font-size: 14px;}

/*}}}*/
*Dynamical timescale (around 45 mins for the Sun):
><<tex 't_{\textrm{dyn}} \approx \dfrac{1}{\sqrt{4 G \rho}}'>>
*Thermal timescale (around <<tex '1.5 \times 10^7'>> years for the sun:
><<tex 't_{\textrm{th}} \approx \dfrac{GM^2}{2RL}'>>
*Nuclear timescale (around <<tex '10^{10}'>> years for the Sun):
><<tex 't_{\textrm{nucl.}} \approx \dfrac{M_{\textrm{burn}}}{M_{\textrm{tot}}} \eta \dfrac{(Mc^2)}{L}'>>
><<tex '\eta = '>> efficiency.
*Gravity and internal pressure are in hydrostatic equilibrium;
*Energy is lost from the surface, so an energy source is required to prevent collapse;
*Temperature profile is determined by energy transport mechanisms;
*Central temperature determined by characteristic temperature of core fusion process;
*Negative heat capacity and therefore feedback from Virial theorem leads to self-regulating behavior in non-degenerate cores;
*Star's global structure is determined by satisfaction of the above, and local structure depends on global structure.
<<timeline modified 10>>
/***
|''Name:''|TagsTreePlugin|
|''Description:''|Displays tags hierachy as a tree of tagged tiddlers.<br>Can be used to create dynamic outline navigation.|
|''Version:''|1.0.1|
|''Date:''|Jan 04,2008|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0|
!Demo
On the plugin [[homepage|http://visualtw.ouvaton.org/VisualTW.html]] :
*Try to tag some <<newTiddler>> with a tag displayed in the menu and edit MainMenu.
*Look at some tags like [[Plugins]] or [[menu]].
!Installation
#import the plugin,
#save and reload,
#optionally, edit TagsTreeStyleSheet.
! Usage
{{{<<tagsTree>>}}} macro accepts the following //optional// parameters.
|!#|!parameter|!description|!by default|
|1|{{{root}}}|Uses {{{root}}} tag as tree root|- In a //tiddler// content or template : uses the tiddler as root tag.<br>- In the //page// content or template (by ex MainMenu) : displays all untagged tags.|
|2|{{{excludeTag}}}|Excludes all such tagged tiddlers from the tree|Uses default excludeLists tag|
|3|{{{level}}}|Expands nodes until level {{{level}}}.<br>Value {{{0}}} hides expand/collapse buttons.|Nodes are collapsed on first level|
|4|{{{depth}}}|Hierachy depth|6 levels depth (H1 to H6 header styles)|
|5|{{{sortField}}}|Alternate sort field. By example : "index".|Sorts tags and tiddlers alphabetically (on their title)|
|6|{{{labelField}}}|Alertnate label field. By example : "label".|Displays tiddler's title|

!Useful addons
*[[FieldsEditorPlugin]] : //create//, //edit//, //view// and //delete// commands in toolbar <<toolbar fields>>.
*[[TaggerPlugin]] : Provides a drop down listing current tiddler tags, and allowing toggling of tags.
!Advanced Users
You can change the global defaults for TagsTreePlugin, like default {{{level}}} value or level styles, by editing or overriding the first config.macros.tagsTree attributes below.
!Code
***/
//{{{
config.macros.tagsTree = {
	expand : "+",
	collapse : "–",
	depth : 6,
	level : 1,
	sortField : "",	
	labelField : "",
	styles : ["h1","h2","h3","h4","h5","h6"],
	trees : {}
}

config.macros.tagsTree.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var root = params[0] ? params[0] : (tiddler ? tiddler.title : null);
	var excludeTag = params[1] ? params[1] : "excludeTagsTree";
	var level = params[2] ? params[2] : config.macros.tagsTree.level;
	var depth = params[3] ? params[3] : config.macros.tagsTree.depth;
	var sortField = params[4] ? params[4] : config.macros.tagsTree.sortField;
	var labelField = params[5] ? params[5] : config.macros.tagsTree.labelField;
	var showButtons = (level>0);
	var id = config.macros.tagsTree.getId(place);
	if (config.macros.tagsTree.trees[id]==undefined) config.macros.tagsTree.trees[id]={};
	config.macros.tagsTree.createSubTree(place,id,root,excludeTag,[],level>0 ? level : 1,depth, sortField, labelField,showButtons);
}

config.macros.tagsTree.createSubTree = function(place, id, root, excludeTag, ancestors, level, depth, sortField, labelField,showButtons){
	var childNodes = root ? this.getChildNodes(root, ancestors) : this.getRootTags(excludeTag);
	var isOpen = (level>0) || (!showButtons);
	if (root && this.trees[id][root]!=undefined) isOpen = this.trees[id][root]; 
	if (root && ancestors.length) {
		var t = store.getTiddler(root);
		if (childNodes.length && depth>0) {
			var wrapper = createTiddlyElement(place , this.styles[Math.min(Math.max(ancestors.length,1),6)-1],null,"branch");
			if (showButtons) {
				b = createTiddlyButton(wrapper, isOpen ? config.macros.tagsTree.collapse : config.macros.tagsTree.expand, null, config.macros.tagsTree.onClick);
				b.setAttribute("treeId",id);
				b.setAttribute("tiddler",root);					
			}
			createTiddlyText(createTiddlyLink(wrapper, root),t&&labelField ? t.fields[labelField] ? t.fields[labelField] : root : root);
		}
		else 
			createTiddlyText(createTiddlyLink(place, root,false,"leaf"),t&&labelField ? t.fields[labelField] ? t.fields[labelField] : root : root);
	}
	if (childNodes.length && depth) {
		var d = createTiddlyElement(place,"div",null,"subtree");
		d.style.display= isOpen ? "block" : "none";
		if (sortField)
			childNodes.sort(function(a, b){
				var fa=a.fields[sortField];
				var fb=b.fields[sortField];
				return (fa==undefined && fb==undefined) ? a.title < b.title ? -1 : a.title > b.title ? 1 : 0 : (fa==undefined && fb!=undefined) ? 1 :(fa!=undefined && fb==undefined) ? -1 : fa < fb ? -1 : fa > fb ? 1 : 0;
			})
		for (var cpt=0; cpt<childNodes.length; cpt++)
			this.createSubTree(d, id, childNodes[cpt].title, excludeTag, ancestors.concat(root), level-1, depth-1, sortField, labelField, showButtons);	
	}	
}

config.macros.tagsTree.onClick = function(e){
	var id = this.getAttribute("treeId");
	var tiddler = this.getAttribute("tiddler");	
	var n = this.parentNode.nextSibling;
	var isOpen = n.style.display != "none";
	if(config.options.chkAnimate && anim && typeof Slider == "function")
		anim.startAnimating(new Slider(n,!isOpen,null,"none"));
	else
		n.style.display = isOpen ? "none" : "block";
	this.firstChild.nodeValue = isOpen ? config.macros.tagsTree.expand : config.macros.tagsTree.collapse;
	config.macros.tagsTree.trees[id][tiddler]=!isOpen;
	return false;
}

config.macros.tagsTree.getChildNodes = function(root ,ancestors){
	var childs = store.getTaggedTiddlers(root);
	var result = new Array();
	for (var cpt=0; cpt<childs.length; cpt++)
		if (childs[cpt].title!=root && ancestors.indexOf(childs[cpt].title)==-1) result.push(childs[cpt]);
	return result;
}

config.macros.tagsTree.getRootTags = function(excludeTag){
	var tags = store.getTags(excludeTag);
	tags.sort(function(a,b) {return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : (a[0].toLowerCase() == b[0].toLowerCase() ? 0 : +1);});
	var result = new Array();
	for (var cpt=0; cpt<tags.length; cpt++) {
		var t = store.getTiddler(tags[cpt][0]);
		if (!t || t.tags.length==0) result.push(t ? t : {title:tags[cpt][0],fields:{}});
	}
	return result;
}

config.macros.tagsTree.getId = function(element){
	while (!element.id && element.parentNode) element=element.parentNode;
	return element.id ? element.id : "<html>";
}

config.shadowTiddlers.TagsTreeStyleSheet = "/*{{{*/\n";
config.shadowTiddlers.TagsTreeStyleSheet +=".leaf, .subtree {display:block; margin-left : 0.5em}\n";
config.shadowTiddlers.TagsTreeStyleSheet +=".subtree {margin-bottom:0.5em}\n";
config.shadowTiddlers.TagsTreeStyleSheet +="#mainMenu {text-align:left}\n";
config.shadowTiddlers.TagsTreeStyleSheet +=".branch .button {border:1px solid #DDD; color:#AAA;font-size:9px;padding:0 2px;margin-right:0.3em;vertical-align:middle;text-align:center;}\n";
config.shadowTiddlers.TagsTreeStyleSheet +="/*}}}*/";

store.addNotification("TagsTreeStyleSheet", refreshStyles); 

config.shadowTiddlers.MainMenu="<<tagsTree>>"

config.shadowTiddlers.PageTemplate = config.shadowTiddlers.PageTemplate.replace(/id='mainMenu' refresh='content' /,"id='mainMenu' refresh='content' force='true' ")

//}}}
/*{{{*/
.leaf, .subtree {display:block; margin-left : 0.5em;font-size:10px;}
.subtree {margin-bottom:0.5em}
#mainMenu {text-align:left}
.branch .button {border:1px solid #DDD; color:#AAA;font-size:9px;padding:0 2px;margin-right:0.3em;vertical-align:middle;text-align:center;}
/*}}}*/
/***
|''Name:''|TiddlersBarPlugin|
|''Description:''|A bar to switch between tiddlers through tabs (like browser tabs bar).|
|''Version:''|1.2.5|
|''Date:''|Jan 18,2008|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0, others|
!Demos
On [[homepage|http://visualtw.ouvaton.org/VisualTW.html]], open several tiddlers to use the tabs bar.
!Installation
#import this tiddler from [[homepage|http://visualtw.ouvaton.org/VisualTW.html]] (tagged as systemConfig)
#save and reload
#''if you're using a custom [[PageTemplate]]'', add {{{<div id='tiddlersBar' refresh='none' ondblclick='config.macros.tiddlersBar.onTiddlersBarAction(event)'></div>}}} before {{{<div id='tiddlerDisplay'></div>}}}
#optionally, adjust StyleSheetTiddlersBar
!Tips
*Doubleclick on the tiddlers bar (where there is no tab) create a new tiddler.
*Tabs include a button to close {{{x}}} or save {{{!}}} their tiddler.
*By default, click on the current tab close all others tiddlers.
!Configuration options 
<<option chkDisableTabsBar>> Disable the tabs bar (to print, by example).
<<option chkHideTabsBarWhenSingleTab >> Automatically hide the tabs bar when only one tiddler is displayed. 
<<option txtSelectedTiddlerTabButton>> ''selected'' tab command button.
<<option txtPreviousTabKey>> previous tab access key.
<<option txtNextTabKey>> next tab access key.
!Code
***/
//{{{
config.options.chkDisableTabsBar = config.options.chkDisableTabsBar ? config.options.chkDisableTabsBar : false;
config.options.chkHideTabsBarWhenSingleTab  = config.options.chkHideTabsBarWhenSingleTab  ? config.options.chkHideTabsBarWhenSingleTab  : false;
config.options.txtSelectedTiddlerTabButton = config.options.txtSelectedTiddlerTabButton ? config.options.txtSelectedTiddlerTabButton : "closeOthers";
config.options.txtPreviousTabKey = config.options.txtPreviousTabKey ? config.options.txtPreviousTabKey : "";
config.options.txtNextTabKey = config.options.txtNextTabKey ? config.options.txtNextTabKey : "";
config.macros.tiddlersBar = {
	tooltip : "see ",
	tooltipClose : "click here to close this tab",
	tooltipSave : "click here to save this tab",
	promptRename : "Enter tiddler new name",
	currentTiddler : "",
	previousState : false,
	previousKey : config.options.txtPreviousTabKey,
	nextKey : config.options.txtNextTabKey,	
	tabsAnimationSource : null, //use document.getElementById("tiddlerDisplay") if you need animation on tab switching.
	handler: function(place,macroName,params) {
		var previous = null;
		if (config.macros.tiddlersBar.isShown())
			story.forEachTiddler(function(title,e){
				if (title==config.macros.tiddlersBar.currentTiddler){
					var d = createTiddlyElement(null,"span",null,"tab tabSelected");
					config.macros.tiddlersBar.createActiveTabButton(d,title);
					if (previous && config.macros.tiddlersBar.previousKey) previous.setAttribute("accessKey",config.macros.tiddlersBar.nextKey);
					previous = "active";
				}
				else {
					var d = createTiddlyElement(place,"span",null,"tab tabUnselected");
					var btn = createTiddlyButton(d,title,config.macros.tiddlersBar.tooltip + title,config.macros.tiddlersBar.onSelectTab);
					btn.setAttribute("tiddler", title);
					if (previous=="active" && config.macros.tiddlersBar.nextKey) btn.setAttribute("accessKey",config.macros.tiddlersBar.previousKey);
					previous=btn;
				}
				var isDirty =story.isDirty(title);
				var c = createTiddlyButton(d,isDirty ?"!":"x",isDirty?config.macros.tiddlersBar.tooltipSave:config.macros.tiddlersBar.tooltipClose, isDirty ? config.macros.tiddlersBar.onTabSave : config.macros.tiddlersBar.onTabClose,"tabButton");
				c.setAttribute("tiddler", title);
				if (place.childNodes) {
					place.insertBefore(document.createTextNode(" "),place.firstChild); // to allow break line here when many tiddlers are open
					place.insertBefore(d,place.firstChild); 
				}
				else place.appendChild(d);
			})
	}, 
	refresh: function(place,params){
		removeChildren(place);
		config.macros.tiddlersBar.handler(place,"tiddlersBar",params);
		if (config.macros.tiddlersBar.previousState!=config.macros.tiddlersBar.isShown()) {
			story.refreshAllTiddlers();
			if (config.macros.tiddlersBar.previousState) story.forEachTiddler(function(t,e){e.style.display="";});
			config.macros.tiddlersBar.previousState = !config.macros.tiddlersBar.previousState;
		}
	},
	isShown : function(){
		if (config.options.chkDisableTabsBar) return false;
		if (!config.options.chkHideTabsBarWhenSingleTab) return true;
		var cpt=0;
		story.forEachTiddler(function(){cpt++});
		return (cpt>1);
	},
	selectNextTab : function(){  //used when the current tab is closed (to select another tab)
		var previous="";
		story.forEachTiddler(function(title){
			if (!config.macros.tiddlersBar.currentTiddler) {
				story.displayTiddler(null,title);
				return;
			}
			if (title==config.macros.tiddlersBar.currentTiddler) {
				if (previous) {
					story.displayTiddler(null,previous);
					return;
				}
				else config.macros.tiddlersBar.currentTiddler=""; 	// so next tab will be selected
			}
			else previous=title;
			});		
	},
	onSelectTab : function(e){
		var t = this.getAttribute("tiddler");
		if (t) story.displayTiddler(null,t);
		return false;
	},
	onTabClose : function(e){
		var t = this.getAttribute("tiddler");
		if (t) {
			if(story.hasChanges(t) && !readOnly) {
				if(!confirm(config.commands.cancelTiddler.warning.format([t])))
				return false;
			}
			story.closeTiddler(t);
		}
		return false;
	},
	onTabSave : function(e) {
		var t = this.getAttribute("tiddler");
		if (!e) e=window.event;
		if (t) config.commands.saveTiddler.handler(e,null,t);
		return false;
	},
	onSelectedTabButtonClick : function(event,src,title) {
		var t = this.getAttribute("tiddler");
		if (!event) event=window.event;
		if (t && config.options.txtSelectedTiddlerTabButton && config.commands[config.options.txtSelectedTiddlerTabButton])
			config.commands[config.options.txtSelectedTiddlerTabButton].handler(event, src, t);
		return false;
	},
	onTiddlersBarAction: function(event) {
		var source = event.target ? event.target.id : event.srcElement.id; // FF uses target and IE uses srcElement;
		if (source=="tiddlersBar") story.displayTiddler(null,'New Tiddler',DEFAULT_EDIT_TEMPLATE,false,null,null);
	},
	createActiveTabButton : function(place,title) {
		if (config.options.txtSelectedTiddlerTabButton && config.commands[config.options.txtSelectedTiddlerTabButton]) {
			var btn = createTiddlyButton(place, title, config.commands[config.options.txtSelectedTiddlerTabButton].tooltip ,config.macros.tiddlersBar.onSelectedTabButtonClick);
			btn.setAttribute("tiddler", title);
		}
		else
			createTiddlyText(place,title);
	}
}

story.coreCloseTiddler = story.coreCloseTiddler? story.coreCloseTiddler : story.closeTiddler;
story.coreDisplayTiddler = story.coreDisplayTiddler ? story.coreDisplayTiddler : story.displayTiddler;

story.closeTiddler = function(title,animate,unused) {
	if (title==config.macros.tiddlersBar.currentTiddler)
		config.macros.tiddlersBar.selectNextTab();
	story.coreCloseTiddler(title,false,unused); //disable animation to get it closed before calling tiddlersBar.refresh
	var e=document.getElementById("tiddlersBar");
	if (e) config.macros.tiddlersBar.refresh(e,null);
}

story.displayTiddler = function(srcElement,tiddler,template,animate,unused,customFields,toggle){
	story.coreDisplayTiddler(config.macros.tiddlersBar.tabsAnimationSource,tiddler,template,animate,unused,customFields,toggle);
	var title = (tiddler instanceof Tiddler)? tiddler.title : tiddler;  
	if (config.macros.tiddlersBar.isShown()) {
		story.forEachTiddler(function(t,e){
			if (t!=title) e.style.display="none";
			else e.style.display="";
		})
		config.macros.tiddlersBar.currentTiddler=title;
	}
	var e=document.getElementById("tiddlersBar");
	if (e) config.macros.tiddlersBar.refresh(e,null);
}

var coreRefreshPageTemplate = coreRefreshPageTemplate ? coreRefreshPageTemplate : refreshPageTemplate;
refreshPageTemplate = function(title) {
	coreRefreshPageTemplate(title);
	if (config.macros.tiddlersBar) config.macros.tiddlersBar.refresh(document.getElementById("tiddlersBar"));
}

ensureVisible=function (e) {return 0} //disable bottom scrolling (not useful now)

config.shadowTiddlers.StyleSheetTiddlersBar = "/*{{{*/\n";
config.shadowTiddlers.StyleSheetTiddlersBar += "#tiddlersBar .button {border:0}\n";
config.shadowTiddlers.StyleSheetTiddlersBar += "#tiddlersBar .tab {white-space:nowrap}\n";
config.shadowTiddlers.StyleSheetTiddlersBar += "#tiddlersBar {padding : 1em 0.5em 2px 0.5em}\n";
config.shadowTiddlers.StyleSheetTiddlersBar += ".tabUnselected .tabButton, .tabSelected .tabButton {padding : 0 2px 0 2px; margin: 0 0 0 4px;}\n";
config.shadowTiddlers.StyleSheetTiddlersBar += ".tiddler, .tabContents {border:1px [[ColorPalette::TertiaryPale]] solid;}\n";
config.shadowTiddlers.StyleSheetTiddlersBar +="/*}}}*/";
store.addNotification("StyleSheetTiddlersBar", refreshStyles);

config.refreshers.none = function(){return true;}
config.shadowTiddlers.PageTemplate=config.shadowTiddlers.PageTemplate.replace(/<div id='tiddlerDisplay'><\/div>/m,"<div id='tiddlersBar' refresh='none' ondblclick='config.macros.tiddlersBar.onTiddlersBarAction(event)'></div>\n<div id='tiddlerDisplay'></div>");

//}}}
| !date | !user | !location | !storeUrl | !uploadDir | !toFilename | !backupdir | !origin |
| 23/05/2008 16:30:27 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ | ok |
| 23/05/2008 16:47:17 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ | ok |
| 23/05/2008 16:52:14 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ | ok |
| 23/05/2008 17:04:29 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ | ok |
| 23/05/2008 17:18:10 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ | ok |
| 23/05/2008 17:22:57 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ | ok |
| 23/05/2008 17:29:06 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ | ok |
| 23/05/2008 17:32:39 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ | ok |
| 23/05/2008 17:55:43 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ |
| 23/05/2008 19:15:37 | actionshrimp | [[/|http://localhost/~dave/physiwiki/]] | [[store.php|http://localhost/~dave/physiwiki/store.php]] | . | [[index.html | http://localhost/~dave/physiwiki/index.html]] | backup/ |
/***
|''Name:''|UploadPlugin|
|''Description:''|Save to web a TiddlyWiki|
|''Version:''|4.1.3|
|''Date:''|Feb 24, 2008|
|''Source:''|http://tiddlywiki.bidix.info/#UploadPlugin|
|''Documentation:''|http://tiddlywiki.bidix.info/#UploadPluginDoc|
|''Author:''|BidiX (BidiX (at) bidix (dot) info)|
|''License:''|[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D ]]|
|''~CoreVersion:''|2.2.0|
|''Requires:''|PasswordOptionPlugin|
***/
//{{{
version.extensions.UploadPlugin = {
	major: 4, minor: 1, revision: 3,
	date: new Date("Feb 24, 2008"),
	source: 'http://tiddlywiki.bidix.info/#UploadPlugin',
	author: 'BidiX (BidiX (at) bidix (dot) info',
	coreVersion: '2.2.0'
};

//
// Environment
//

if (!window.bidix) window.bidix = {}; // bidix namespace
bidix.debugMode = false;	// true to activate both in Plugin and UploadService
	
//
// Upload Macro
//

config.macros.upload = {
// default values
	defaultBackupDir: '',	//no backup
	defaultStoreScript: "store.php",
	defaultToFilename: "index.html",
	defaultUploadDir: ".",
	authenticateUser: true	// UploadService Authenticate User
};
	
config.macros.upload.label = {
	promptOption: "Save and Upload this TiddlyWiki with UploadOptions",
	promptParamMacro: "Save and Upload this TiddlyWiki in %0",
	saveLabel: "save to web", 
	saveToDisk: "save to disk",
	uploadLabel: "upload"	
};

config.macros.upload.messages = {
	noStoreUrl: "No store URL in parmeters or options",
	usernameOrPasswordMissing: "Username or password missing"
};

config.macros.upload.handler = function(place,macroName,params) {
	if (readOnly)
		return;
	var label;
	if (document.location.toString().substr(0,4) == "http") 
		label = this.label.saveLabel;
	else
		label = this.label.uploadLabel;
	var prompt;
	if (params[0]) {
		prompt = this.label.promptParamMacro.toString().format([this.destFile(params[0], 
			(params[1] ? params[1]:bidix.basename(window.location.toString())), params[3])]);
	} else {
		prompt = this.label.promptOption;
	}
	createTiddlyButton(place, label, prompt, function() {config.macros.upload.action(params);}, null, null, this.accessKey);
};

config.macros.upload.action = function(params)
{
		// for missing macro parameter set value from options
		if (!params) params = {};
		var storeUrl = params[0] ? params[0] : config.options.txtUploadStoreUrl;
		var toFilename = params[1] ? params[1] : config.options.txtUploadFilename;
		var backupDir = params[2] ? params[2] : config.options.txtUploadBackupDir;
		var uploadDir = params[3] ? params[3] : config.options.txtUploadDir;
		var username = params[4] ? params[4] : config.options.txtUploadUserName;
		var password = config.options.pasUploadPassword; // for security reason no password as macro parameter	
		// for still missing parameter set default value
		if ((!storeUrl) && (document.location.toString().substr(0,4) == "http")) 
			storeUrl = bidix.dirname(document.location.toString())+'/'+config.macros.upload.defaultStoreScript;
		if (storeUrl.substr(0,4) != "http")
			storeUrl = bidix.dirname(document.location.toString()) +'/'+ storeUrl;
		if (!toFilename)
			toFilename = bidix.basename(window.location.toString());
		if (!toFilename)
			toFilename = config.macros.upload.defaultToFilename;
		if (!uploadDir)
			uploadDir = config.macros.upload.defaultUploadDir;
		if (!backupDir)
			backupDir = config.macros.upload.defaultBackupDir;
		// report error if still missing
		if (!storeUrl) {
			alert(config.macros.upload.messages.noStoreUrl);
			clearMessage();
			return false;
		}
		if (config.macros.upload.authenticateUser && (!username || !password)) {
			alert(config.macros.upload.messages.usernameOrPasswordMissing);
			clearMessage();
			return false;
		}
		bidix.upload.uploadChanges(false,null,storeUrl, toFilename, uploadDir, backupDir, username, password); 
		return false; 
};

config.macros.upload.destFile = function(storeUrl, toFilename, uploadDir) 
{
	if (!storeUrl)
		return null;
		var dest = bidix.dirname(storeUrl);
		if (uploadDir && uploadDir != '.')
			dest = dest + '/' + uploadDir;
		dest = dest + '/' + toFilename;
	return dest;
};

//
// uploadOptions Macro
//

config.macros.uploadOptions = {
	handler: function(place,macroName,params) {
		var wizard = new Wizard();
		wizard.createWizard(place,this.wizardTitle);
		wizard.addStep(this.step1Title,this.step1Html);
		var markList = wizard.getElement("markList");
		var listWrapper = document.createElement("div");
		markList.parentNode.insertBefore(listWrapper,markList);
		wizard.setValue("listWrapper",listWrapper);
		this.refreshOptions(listWrapper,false);
		var uploadCaption;
		if (document.location.toString().substr(0,4) == "http") 
			uploadCaption = config.macros.upload.label.saveLabel;
		else
			uploadCaption = config.macros.upload.label.uploadLabel;
		
		wizard.setButtons([
				{caption: uploadCaption, tooltip: config.macros.upload.label.promptOption, 
					onClick: config.macros.upload.action},
				{caption: this.cancelButton, tooltip: this.cancelButtonPrompt, onClick: this.onCancel}
				
			]);
	},
	options: [
		"txtUploadUserName",
		"pasUploadPassword",
		"txtUploadStoreUrl",
		"txtUploadDir",
		"txtUploadFilename",
		"txtUploadBackupDir",
		"chkUploadLog",
		"txtUploadLogMaxLine"		
	],
	refreshOptions: function(listWrapper) {
		var opts = [];
		for(i=0; i<this.options.length; i++) {
			var opt = {};
			opts.push();
			opt.option = "";
			n = this.options[i];
			opt.name = n;
			opt.lowlight = !config.optionsDesc[n];
			opt.description = opt.lowlight ? this.unknownDescription : config.optionsDesc[n];
			opts.push(opt);
		}
		var listview = ListView.create(listWrapper,opts,this.listViewTemplate);
		for(n=0; n<opts.length; n++) {
			var type = opts[n].name.substr(0,3);
			var h = config.macros.option.types[type];
			if (h && h.create) {
				h.create(opts[n].colElements['option'],type,opts[n].name,opts[n].name,"no");
			}
		}
		
	},
	onCancel: function(e)
	{
		backstage.switchTab(null);
		return false;
	},
	
	wizardTitle: "Upload with options",
	step1Title: "These options are saved in cookies in your browser",
	step1Html: "<input type='hidden' name='markList'></input><br>",
	cancelButton: "Cancel",
	cancelButtonPrompt: "Cancel prompt",
	listViewTemplate: {
		columns: [
			{name: 'Description', field: 'description', title: "Description", type: 'WikiText'},
			{name: 'Option', field: 'option', title: "Option", type: 'String'},
			{name: 'Name', field: 'name', title: "Name", type: 'String'}
			],
		rowClasses: [
			{className: 'lowlight', field: 'lowlight'} 
			]}
};

//
// upload functions
//

if (!bidix.upload) bidix.upload = {};

if (!bidix.upload.messages) bidix.upload.messages = {
	//from saving
	invalidFileError: "The original file '%0' does not appear to be a valid TiddlyWiki",
	backupSaved: "Backup saved",
	backupFailed: "Failed to upload backup file",
	rssSaved: "RSS feed uploaded",
	rssFailed: "Failed to upload RSS feed file",
	emptySaved: "Empty template uploaded",
	emptyFailed: "Failed to upload empty template file",
	mainSaved: "Main TiddlyWiki file uploaded",
	mainFailed: "Failed to upload main TiddlyWiki file. Your changes have not been saved",
	//specific upload
	loadOriginalHttpPostError: "Can't get original file",
	aboutToSaveOnHttpPost: 'About to upload on %0 ...',
	storePhpNotFound: "The store script '%0' was not found."
};

bidix.upload.uploadChanges = function(onlyIfDirty,tiddlers,storeUrl,toFilename,uploadDir,backupDir,username,password)
{
	var callback = function(status,uploadParams,original,url,xhr) {
		if (!status) {
			displayMessage(bidix.upload.messages.loadOriginalHttpPostError);
			return;
		}
		if (bidix.debugMode) 
			alert(original.substr(0,500)+"\n...");
		// Locate the storeArea div's 
		var posDiv = locateStoreArea(original);
		if((posDiv[0] == -1) || (posDiv[1] == -1)) {
			alert(config.messages.invalidFileError.format([localPath]));
			return;
		}
		bidix.upload.uploadRss(uploadParams,original,posDiv);
	};
	
	if(onlyIfDirty && !store.isDirty())
		return;
	clearMessage();
	// save on localdisk ?
	if (document.location.toString().substr(0,4) == "file") {
		var path = document.location.toString();
		var localPath = getLocalPath(path);
		saveChanges();
	}
	// get original
	var uploadParams = new Array(storeUrl,toFilename,uploadDir,backupDir,username,password);
	var originalPath = document.location.toString();
	// If url is a directory : add index.html
	if (originalPath.charAt(originalPath.length-1) == "/")
		originalPath = originalPath + "index.html";
	var dest = config.macros.upload.destFile(storeUrl,toFilename,uploadDir);
	var log = new bidix.UploadLog();
	log.startUpload(storeUrl, dest, uploadDir,  backupDir);
	displayMessage(bidix.upload.messages.aboutToSaveOnHttpPost.format([dest]));
	if (bidix.debugMode) 
		alert("about to execute Http - GET on "+originalPath);
	var r = doHttp("GET",originalPath,null,null,username,password,callback,uploadParams,null);
	if (typeof r == "string")
		displayMessage(r);
	return r;
};

bidix.upload.uploadRss = function(uploadParams,original,posDiv) 
{
	var callback = function(status,params,responseText,url,xhr) {
		if(status) {
			var destfile = responseText.substring(responseText.indexOf("destfile:")+9,responseText.indexOf("\n", responseText.indexOf("destfile:")));
			displayMessage(bidix.upload.messages.rssSaved,bidix.dirname(url)+'/'+destfile);
			bidix.upload.uploadMain(params[0],params[1],params[2]);
		} else {
			displayMessage(bidix.upload.messages.rssFailed);			
		}
	};
	// do uploadRss
	if(config.options.chkGenerateAnRssFeed) {
		var rssPath = uploadParams[1].substr(0,uploadParams[1].lastIndexOf(".")) + ".xml";
		var rssUploadParams = new Array(uploadParams[0],rssPath,uploadParams[2],'',uploadParams[4],uploadParams[5]);
		var rssString = generateRss();
		// no UnicodeToUTF8 conversion needed when location is "file" !!!
		if (document.location.toString().substr(0,4) != "file")
			rssString = convertUnicodeToUTF8(rssString);	
		bidix.upload.httpUpload(rssUploadParams,rssString,callback,Array(uploadParams,original,posDiv));
	} else {
		bidix.upload.uploadMain(uploadParams,original,posDiv);
	}
};

bidix.upload.uploadMain = function(uploadParams,original,posDiv) 
{
	var callback = function(status,params,responseText,url,xhr) {
		var log = new bidix.UploadLog();
		if(status) {
			// if backupDir specified
			if ((params[3]) && (responseText.indexOf("backupfile:") > -1))  {
				var backupfile = responseText.substring(responseText.indexOf("backupfile:")+11,responseText.indexOf("\n", responseText.indexOf("backupfile:")));
				displayMessage(bidix.upload.messages.backupSaved,bidix.dirname(url)+'/'+backupfile);
			}
			var destfile = responseText.substring(responseText.indexOf("destfile:")+9,responseText.indexOf("\n", responseText.indexOf("destfile:")));
			displayMessage(bidix.upload.messages.mainSaved,bidix.dirname(url)+'/'+destfile);
			store.setDirty(false);
			log.endUpload("ok");
		} else {
			alert(bidix.upload.messages.mainFailed);
			displayMessage(bidix.upload.messages.mainFailed);
			log.endUpload("failed");			
		}
	};
	// do uploadMain
	var revised = bidix.upload.updateOriginal(original,posDiv);
	bidix.upload.httpUpload(uploadParams,revised,callback,uploadParams);
};

bidix.upload.httpUpload = function(uploadParams,data,callback,params)
{
	var localCallback = function(status,params,responseText,url,xhr) {
		url = (url.indexOf("nocache=") < 0 ? url : url.substring(0,url.indexOf("nocache=")-1));
		if (xhr.status == httpStatus.NotFound)
			alert(bidix.upload.messages.storePhpNotFound.format([url]));
		if ((bidix.debugMode) || (responseText.indexOf("Debug mode") >= 0 )) {
			alert(responseText);
			if (responseText.indexOf("Debug mode") >= 0 )
				responseText = responseText.substring(responseText.indexOf("\n\n")+2);
		} else if (responseText.charAt(0) != '0') 
			alert(responseText);
		if (responseText.charAt(0) != '0')
			status = null;
		callback(status,params,responseText,url,xhr);
	};
	// do httpUpload
	var boundary = "---------------------------"+"AaB03x";	
	var uploadFormName = "UploadPlugin";
	// compose headers data
	var sheader = "";
	sheader += "--" + boundary + "\r\nContent-disposition: form-data; name=\"";
	sheader += uploadFormName +"\"\r\n\r\n";
	sheader += "backupDir="+uploadParams[3] +
				";user=" + uploadParams[4] +
				";password=" + uploadParams[5] +
				";uploaddir=" + uploadParams[2];
	if (bidix.debugMode)
		sheader += ";debug=1";
	sheader += ";;\r\n"; 
	sheader += "\r\n" + "--" + boundary + "\r\n";
	sheader += "Content-disposition: form-data; name=\"userfile\"; filename=\""+uploadParams[1]+"\"\r\n";
	sheader += "Content-Type: text/html;charset=UTF-8" + "\r\n";
	sheader += "Content-Length: " + data.length + "\r\n\r\n";
	// compose trailer data
	var strailer = new String();
	strailer = "\r\n--" + boundary + "--\r\n";
	data = sheader + data + strailer;
	if (bidix.debugMode) alert("about to execute Http - POST on "+uploadParams[0]+"\n with \n"+data.substr(0,500)+ " ... ");
	var r = doHttp("POST",uploadParams[0],data,"multipart/form-data; ;charset=UTF-8; boundary="+boundary,uploadParams[4],uploadParams[5],localCallback,params,null);
	if (typeof r == "string")
		displayMessage(r);
	return r;
};

// same as Saving's updateOriginal but without convertUnicodeToUTF8 calls
bidix.upload.updateOriginal = function(original, posDiv)
{
	if (!posDiv)
		posDiv = locateStoreArea(original);
	if((posDiv[0] == -1) || (posDiv[1] == -1)) {
		alert(config.messages.invalidFileError.format([localPath]));
		return;
	}
	var revised = original.substr(0,posDiv[0] + startSaveArea.length) + "\n" +
				store.allTiddlersAsHtml() + "\n" +
				original.substr(posDiv[1]);
	var newSiteTitle = getPageTitle().htmlEncode();
	revised = revised.replaceChunk("<title"+">","</title"+">"," " + newSiteTitle + " ");
	revised = updateMarkupBlock(revised,"PRE-HEAD","MarkupPreHead");
	revised = updateMarkupBlock(revised,"POST-HEAD","MarkupPostHead");
	revised = updateMarkupBlock(revised,"PRE-BODY","MarkupPreBody");
	revised = updateMarkupBlock(revised,"POST-SCRIPT","MarkupPostBody");
	return revised;
};

//
// UploadLog
// 
// config.options.chkUploadLog :
//		false : no logging
//		true : logging
// config.options.txtUploadLogMaxLine :
//		-1 : no limit
//      0 :  no Log lines but UploadLog is still in place
//		n :  the last n lines are only kept
//		NaN : no limit (-1)

bidix.UploadLog = function() {
	if (!config.options.chkUploadLog) 
		return; // this.tiddler = null
	this.tiddler = store.getTiddler("UploadLog");
	if (!this.tiddler) {
		this.tiddler = new Tiddler();
		this.tiddler.title = "UploadLog";
		this.tiddler.text = "| !date | !user | !location | !storeUrl | !uploadDir | !toFilename | !backupdir | !origin |";
		this.tiddler.created = new Date();
		this.tiddler.modifier = config.options.txtUserName;
		this.tiddler.modified = new Date();
		store.addTiddler(this.tiddler);
	}
	return this;
};

bidix.UploadLog.prototype.addText = function(text) {
	if (!this.tiddler)
		return;
	// retrieve maxLine when we need it
	var maxLine = parseInt(config.options.txtUploadLogMaxLine,10);
	if (isNaN(maxLine))
		maxLine = -1;
	// add text
	if (maxLine != 0) 
		this.tiddler.text = this.tiddler.text + text;
	// Trunck to maxLine
	if (maxLine >= 0) {
		var textArray = this.tiddler.text.split('\n');
		if (textArray.length > maxLine + 1)
			textArray.splice(1,textArray.length-1-maxLine);
			this.tiddler.text = textArray.join('\n');		
	}
	// update tiddler fields
	this.tiddler.modifier = config.options.txtUserName;
	this.tiddler.modified = new Date();
	store.addTiddler(this.tiddler);
	// refresh and notifiy for immediate update
	story.refreshTiddler(this.tiddler.title);
	store.notify(this.tiddler.title, true);
};

bidix.UploadLog.prototype.startUpload = function(storeUrl, toFilename, uploadDir,  backupDir) {
	if (!this.tiddler)
		return;
	var now = new Date();
	var text = "\n| ";
	var filename = bidix.basename(document.location.toString());
	if (!filename) filename = '/';
	text += now.formatString("0DD/0MM/YYYY 0hh:0mm:0ss") +" | ";
	text += config.options.txtUserName + " | ";
	text += "[["+filename+"|"+location + "]] |";
	text += " [[" + bidix.basename(storeUrl) + "|" + storeUrl + "]] | ";
	text += uploadDir + " | ";
	text += "[[" + bidix.basename(toFilename) + " | " +toFilename + "]] | ";
	text += backupDir + " |";
	this.addText(text);
};

bidix.UploadLog.prototype.endUpload = function(status) {
	if (!this.tiddler)
		return;
	this.addText(" "+status+" |");
};

//
// Utilities
// 

bidix.checkPlugin = function(plugin, major, minor, revision) {
	var ext = version.extensions[plugin];
	if (!
		(ext  && 
			((ext.major > major) || 
			((ext.major == major) && (ext.minor > minor))  ||
			((ext.major == major) && (ext.minor == minor) && (ext.revision >= revision))))) {
			// write error in PluginManager
			if (pluginInfo)
				pluginInfo.log.push("Requires " + plugin + " " + major + "." + minor + "." + revision);
			eval(plugin); // generate an error : "Error: ReferenceError: xxxx is not defined"
	}
};

bidix.dirname = function(filePath) {
	if (!filePath) 
		return;
	var lastpos;
	if ((lastpos = filePath.lastIndexOf("/")) != -1) {
		return filePath.substring(0, lastpos);
	} else {
		return filePath.substring(0, filePath.lastIndexOf("\\"));
	}
};

bidix.basename = function(filePath) {
	if (!filePath) 
		return;
	var lastpos;
	if ((lastpos = filePath.lastIndexOf("#")) != -1) 
		filePath = filePath.substring(0, lastpos);
	if ((lastpos = filePath.lastIndexOf("/")) != -1) {
		return filePath.substring(lastpos + 1);
	} else
		return filePath.substring(filePath.lastIndexOf("\\")+1);
};

bidix.initOption = function(name,value) {
	if (!config.options[name])
		config.options[name] = value;
};

//
// Initializations
//

// require PasswordOptionPlugin 1.0.1 or better
bidix.checkPlugin("PasswordOptionPlugin", 1, 0, 1);

// styleSheet
setStylesheet('.txtUploadStoreUrl, .txtUploadBackupDir, .txtUploadDir {width: 22em;}',"uploadPluginStyles");

//optionsDesc
merge(config.optionsDesc,{
	txtUploadStoreUrl: "Url of the UploadService script (default: store.php)",
	txtUploadFilename: "Filename of the uploaded file (default: in index.html)",
	txtUploadDir: "Relative Directory where to store the file (default: . (downloadService directory))",
	txtUploadBackupDir: "Relative Directory where to backup the file. If empty no backup. (default: ''(empty))",
	txtUploadUserName: "Upload Username",
	pasUploadPassword: "Upload Password",
	chkUploadLog: "do Logging in UploadLog (default: true)",
	txtUploadLogMaxLine: "Maximum of lines in UploadLog (default: 10)"
});

// Options Initializations
bidix.initOption('txtUploadStoreUrl','');
bidix.initOption('txtUploadFilename','');
bidix.initOption('txtUploadDir','');
bidix.initOption('txtUploadBackupDir','');
bidix.initOption('txtUploadUserName','');
bidix.initOption('pasUploadPassword','');
bidix.initOption('chkUploadLog',true);
bidix.initOption('txtUploadLogMaxLine','10');


// Backstage
merge(config.tasks,{
	uploadOptions: {text: "upload", tooltip: "Change UploadOptions and Upload", content: '<<uploadOptions>>'}
});
config.backstageTasks.push("uploadOptions");


//}}}

<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers editTiddler +jsvi > fields syncing permalink references jump'></div>
<div class='title' macro='view title'></div>
<div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='tagging' macro='tagging'></div>
<div class='tagged' macro='tags'></div>
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
Welcome to Dave's ~PhysiWiki. Powered by [[TiddlyWiki|http://www.tiddlywiki.com/]]. Now with added <<tex '\LaTeX'>>.
This wiki is designed to hold my revision notes, and therefore can't be edited by anyone else.





*Fluids are considered:
**In ''bulk'';
**Over length scales <<tex 'L \gg \lambda'>>, the mean free path;
**This smooths out molecular properties - a continuum.


/***
|Location|http://visualtw.ouvaton.org/VisualTW.html|
|Version|1.0|
|Requires|~TW2.2.x|
|Browsers|Firefox 2.0.x, IE 6.0+, others|
!Description:
Integrate external editor in TiddlyWiki by iframe.

!Demo:
see [[homepage|http://visualtw.ouvaton.org/VisualTW.html]] examples for demo

!Installation:
See [[Download]] on [[homepage|http://visualtw.ouvaton.org/VisualTW.html]]
***/
//{{{
config.options.txtiFrameHeight = config.options.txtiFrameHeight ? config.options.txtiFrameHeight : "600px";
//}}}
/***
Configure iFrame height : <<option txtiFrameHeight>>

!History:
*07-06-07: ver 1.0

!Code
***/
//{{{

/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Ultimater | http://webdeveloper.com/forum/member.php?u=30185 */
function html_entity_decode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}

Story.prototype.previousGatherSaveFields = Story.prototype.gatherSaveFields;
Story.prototype.gatherSaveFields = function(e,fields) {
	if(e && e.getAttribute) {
		var f = e.getAttribute("iFrameEdit");
		if(f) fields[f] = html_entity_decode(e.contentWindow.getContent());
		else Story.prototype.previousGatherSaveFields(e,fields);
	}
}

config.macros.editFieldInFrame = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		var field = params[0];
		var editor = params[1] ? params[1] :"editor.html" //default value
		if((tiddler instanceof Tiddler) && field) {
			story.setDirty(tiddler.title,true);
			var e = createTiddlyElement(null,"iframe");
			if(tiddler.isReadOnly()) e.setAttribute("readOnly","readOnly");
			e.setAttribute("iFrameEdit",field);
			e.setAttribute("type","iFrame");
			var v = store.getValue(tiddler,field);
			v = v ? v : "";
			e.src=editor+"?tiddler="+escape(tiddler.title)+"&field="+escape(field);
			e.height=config.options.txtiFrameHeight;
			e.width="100%";
			place.appendChild(e);
		}
	}
}

config.macros.viewHtmlField = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		if((tiddler instanceof Tiddler) && params[0]) {
			var value = tiddler.fields[params[0]];
			if(value != undefined) {
				e=createTiddlyElement(null,"div");
				e.innerHTML=value;
				place.appendChild(e);
			}
		}
	}
}


getContent=function(tiddler, field) {
	var t,f;
	t=store.getTiddler(tiddler); 
	f = t ? t.fields[field] : "";
	f = f ? f : "";
	return f;
}

getContentText=function(tiddler) {
	var t,f;
	t=store.getTiddler(tiddler); 
	f = t ? t.text : "";
	f = f ? f : "";
	return f;
}

//}}}








*This section looks at modifying the Einstein approach from infinitely sharp atomic levels, to realistic, broadened levels.
*Although stars change, the timescale is very large so many rates can be neglected.
*Assuming perfectly spherically symmetric stars (not always true).










/***
''Note:'' This plugin only provides access to a button to vi on the toolbar, nothing else, so installing the plugin on it's own won't give you vi! For full installation instructions please refer to http://www.actionshrimp.com/2008/05/jsvi-and-tiddlywiki/
***/
//{{{
config.commands.jsvi={
	text: "vi",
	tooltip: "Edit this tiddler with jsvi",
	handler : function(event,src,title) {
		clearMessage();
		var tiddlerElem = document.getElementById(story.idPrefix + title);
		var fields = tiddlerElem.getAttribute("tiddlyFields");
		story.displayTiddler(null,title,"jsviEditTemplate",false,null,fields);
		return false;
	}
}

config.shadowTiddlers.ViewTemplate = config.shadowTiddlers.ViewTemplate.replace(/\+editTiddler/,"+editTiddler jsvi");
config.shadowTiddlers.jsviEditTemplate = config.shadowTiddlers.EditTemplate.replace(/macro='edit text'/,"macro='editFieldInFrame text editor.html'");
//}}}


Working out the numbers.