<!--{{{-->
<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]];}

.wizard .notChanged {background:transparent;}
.wizard .changedLocally {background:#80ff80;}
.wizard .changedServer {background:#8080ff;}
.wizard .changedBoth {background:#ff8080;}
.wizard .notFound {background:#ffff80;}
.wizard .putToServer {background:#ff80ff;}
.wizard .gotFromServer {background:#80ffff;}

#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 0 1em 1em; left:-1px; top:-1px;}
.headerForeground {position:absolute; padding:4.5em 0 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:0 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 0.3em 0;}
#sidebarTabs .tabContents {width:15em; overflow:hidden;}

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

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

.tiddlerPopupButton {padding:0.2em;}
.popupTiddler {position: absolute; z-index:300; padding: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 0;}
.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 0 0 0.5em;}
.tab {margin:0 0 0 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 0 14em;}

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

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

.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:0 0.25em; padding:0 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 0; font-size:.9em;}
.editorFooter .button {padding-top:0px; padding-bottom:0px;}

.fieldsetFix {border:0; padding:0; margin: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;}
#backstageToolbar {position:relative;}
#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em;}
#backstageButton {display:none; position:absolute; z-index:175; top:0; right:0;}
#backstageButton a {padding:0.1em 0.4em; margin:0.1em;}
#backstage {position:relative; width:100%; z-index:50;}
#backstagePanel {display:none; z-index:100; position:absolute; width:90%; margin-left:3em; padding:1em;}
.backstagePanelFooter {padding-top:0.2em; float:right;}
.backstagePanelFooter a {padding: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;}
noscript {display:none;} /* Fixes a feature in Firefox 1.5.0.2 where print preview displays the noscript content */
}
/*}}}*/
<!--{{{-->
<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 [[ToolbarCommands::ViewToolbar]]'></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 [[ToolbarCommands::EditToolbar]]'></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 excludeLists'></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>>
* ~KE1 Einführung
* ~KE2 [[Theorie des Haushalts]]
* ~KE3 [[Theorie der Firma]]
If $$\mathbb{C}\ni a = u + iv ~"\!=\!"~ u\hat x + v \hat y \in\mathbb{R}^2$$
and $$\mathbb{C}\ni b = x + iy ~"\!=\!"~ x\hat x + y \hat y \in\mathbb{R}^2$$
where the "=" denotes, by abuse of notation, the obvious isomorphism $\mathbb{C} \to\mathbb{R}^2$,
''show'' that $$a^*b = \mathbf{a}\cdot\mathbf{b} + i\hat z\cdot\mathbf{a}\times\mathbf{b}$$

This is clear from the following calculation:
$$
a^*b = (u-iv)(x+iy) = (ux+vy) + i (ux-vy) = \mathbf{a}\cdot\mathbf{b}
  + i \hat z \cdot \left | \begin{array}{ccc} \hat x & \hat y & \hat z \\ u & v & 0 \\  x & y &0 \end{array} \right|
 = \mathbf{a}\cdot\mathbf{b} + i \hat z \cdot \hat z  \left | \begin{array}{cc}u & v  \\  x & y  \end{array} \right|
$$
''Show'' that

$$
\sum_{n=0}^{N-1}\!\cos(nx) = \frac{\sin(Nx/2)}{\sin(x/2)}\cos(N-1)\frac{x}{2}
$$
and
$$
\sum_{n=0}^{N-1}\!\sin(nx) = \frac{\sin(Nx/2)}{\sin(x/2)}\sin(N-1)\frac{x}{2}
$$

''Indeed'', consider
\begin{eqnarray}
\sum_0^{N-1} \cos(nx) + i \sum_0^{N-1} \sin(nx) &= \sum_0^{N-1}\!e^{i\,nx} = \frac{1-e^{i\,Nx}}{1-e^{i\,x}}
  = \frac{(1-e^{i\,Nx})(1-e^{-i\,x})}{2[1-\frac{e^{ix}+e^{-ix}}{2}]} \\
 &=  \frac{1+e^{i\,(N-1)x}-(e^{i\,Nx}+e^{-i\,x})}{4\sin^2(x/2)}
\end{eqnarray}
!! Classical ~Black-Scholes Model
$
\begin{align}
  dB_t &= rB_t\,dt \\
  dS_t &= S_t (\mu\,dt+\sigma\,dW_t)
\end{align}
$

Generalize: $dt \to dh_t$, $\mu\,dt+\sigma\,dW_t \to dH_t$.

!! ~Black-Scholes semimartingale model

assets $B,S$, $B$ predictable, $S$ semimartingale.
$
\begin{align}
   dB_t &= B_{t^-}\,dh_t \quad & B_0=1 \\
   dS_t &= S_{t^-}\,dH_t \quad & S_0 > 0 \\
\end{align}
$
Where $h_t, H_t$ semimartingales.

!!! Solutions of the Semimartingale ~Black-Scholes Model

Each SDE in the system is a linear SDEs wrt semimartingale $H_t$, with solution in the form
$
 X_t-X_0 = \int_0^t\!X_{s^-}\,dH_s \quad H_t = H_0 + A_t + M_t
$

@@ Claim @@
$
 X_t = X_0 \mathcal{E}_t(H)
$

Where $ \mathcal{E}_t(H) := exp \left\{  H_t-H_0-\frac{1}{2}\langle H^c \rangle_t \right\}\prod_{0\leq s\leq t}(1+\Delta H_s)e^{-\Delta H_s}$ is the [[stochastic exponential|Stochastic Exponential]] of $H$.

Equivalently,
$$
   d\mathcal{E}_t(H) = \mathcal{E}_{t^-}(H)\,dH_t \quad \mathcal{E}_0(H) = 1
$$

Since the stock price is restricted to be positive, require the jumps $\Delta\!H_t, \Delta\!h_t > -1$
Take a bond with maturity $T$, face value $F$ and coupon $C$. Its present value is
\[
B = \sum_{t=1}^{T}\!Cd^t \, +Fd^T 
\]
where $d:=\frac{1}{1+r}$ is the discount factor (for simplicity, we are assuming annual compounding).

Then the sensitivity of $B$ to changes in $d$ is given by
\[
 \frac{\partial_d B}{F} = \xi \sum_{t=1}^{T}\!td^{t-1} \, + Td^{T-1}
\]
* Computational Metric Geometry: 3D shapes are represented as metric spaces, similarity is expressed as similarity of metrics; Video Genome project http://v-nome.org
Let the tax rate be $\tau$, interest rate $r$, depreciation rate $d$. Suppose a capital investment (such as a piece of machinery) $I$ has useful life $T>1$, after which time it is salvaged for (market-determined) value of $RS_T$, but the corresponding pool is not liquidated, so that the terminal loss and CCA recapture rules are not triggered. 

We are interested in the present value of the tax shield, in the cases where $(1-d)^T>\alpha:=\frac{I}{RS_T}$, and otherwise.

!! Proof of TS formula

Let us define the relative rate of interest to depreciation $\xi := \frac{r}{d}$, the 'tax-to-market ratio' $\sigma:=\frac{\tau}{1+\xi}$, and the 'half-year rule' correction $F:=\frac{1+r/2}{1+r}$; so that the (normalized by $I$) PV of the tax shield stream $$X_T = \sigma(F - \alpha^*),$$ where $\alpha^*$ denotes discounting.


From finance perspective, we can benchmark it as follows: compare this to buying a bond now that will only repay $\alpha$ in the future, but has
coupons. 

The difference between the normalized market-given and government-scheduled  PV CCA ~TSs is then
$$\Delta := \sigma ((1-d)^T-\alpha)^* , $$
i.e. it is more profitable (within the extent of this calculation) to under-depreciate the asset before retiring it: the difference between its scheduled and market values will remains in the pool and continues to be tax-shielded.
!!Definition
Outer extension $\mu^*$ of a measure $\mu$ is the function
$$
   \mu^* = \inf \left\{ \sum_{n=1}^{\infty} \mu(A_n) \right\}
$$
where the $\inf$ is taken over all Caratheodory covers $(A_n): \cup_n A_n=A$
!!Theorem: 

a measure $\mu$ on a field $\mathcal{C}$ can be extended to a measure $\mu^*$ on $\sigma(\mathcal{C})$ so that 
$$\forall A\in \mathcal{C}\quad \mu(A) = \mu^*(A) $$ 
Furthermore, if $\mu$ is $\sigma$-[[finite|sigma-finite]] on $\mathcal{C}$, then its extension $\mu^*$ is unique and $\sigma$-finite.

!!Proof:

!!!Lemma1
$\mu^*$ is an [[outer measure]] on $(\Omega,2^\Omega)$.
version.extensions.CheckboxPlugin = {major: 2, minor: 4, revision:0 , date: new Date(2008,1,5)};

config.checkbox = { refresh: { tagged:true, tagging:true, container:true } };
config.formatters.push( {
	name: "checkbox",
	match: "\\[[xX_ ][\\]\\=\\(\\{]",
	lookahead: "\\[([xX_ ])(=[^\\s\\(\\]{]+)?(\\([^\\)]*\\))?({[^}]*})?({[^}]*})?({[^}]*})?\\]",
	handler: 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) {
			// get params
			var checked=(lookaheadMatch[1].toUpperCase()=="X");
			var id=lookaheadMatch[2];
			var target=lookaheadMatch[3];
			if (target) target=target.substr(1,target.length-2).trim(); // trim off parentheses
			var fn_init=lookaheadMatch[4];
			var fn_clickBefore=lookaheadMatch[5];
			var fn_clickAfter=lookaheadMatch[6];
			var tid=story.findContainingTiddler(w.output);  if (tid) tid=tid.getAttribute("tiddler");
			var srctid=w.tiddler?w.tiddler.title:null;
			config.macros.checkbox.create(w.output,tid,srctid,w.matchStart+1,checked,id,target,config.checkbox.refresh,fn_init,fn_clickBefore,fn_clickAfter);
			w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
		}
	}
} );
config.macros.checkbox = {
	handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		if(!(tiddler instanceof Tiddler)) { // if no tiddler passed in try to find one
			var here=story.findContainingTiddler(place);
			if (here) tiddler=store.getTiddler(here.getAttribute("tiddler"))
		}
		var srcpos=0; // "inline X" not applicable to macro syntax
		var target=params.shift(); if (!target) target="";
		var defaultState=params[0]=="checked"; if (defaultState) params.shift();
		var id=params.shift(); if (id && !id.length) id=null;
		var fn_init=params.shift(); if (fn_init && !fn_init.length) fn_init=null;
		var fn_clickBefore=params.shift();
		if (fn_clickBefore && !fn_clickBefore.length) fn_clickBefore=null;
		var fn_clickAfter=params.shift();
		if (fn_clickAfter && !fn_clickAfter.length) fn_clickAfter=null;
		var refresh={ tagged:true, tagging:true, container:false };
		this.create(place,tiddler.title,tiddler.title,0,defaultState,id,target,refresh,fn_init,fn_clickBefore,fn_clickAfter);
	},
	create: function(place,tid,srctid,srcpos,defaultState,id,target,refresh,fn_init,fn_clickBefore,fn_clickAfter) {
		// create checkbox element
		var c = document.createElement("input");
		c.setAttribute("type","checkbox");
		c.onclick=this.onClickCheckbox;
		c.srctid=srctid; // remember source tiddler
		c.srcpos=srcpos; // remember location of "X"
		c.container=tid; // containing tiddler (may be null if not in a tiddler)
		c.tiddler=tid; // default target tiddler 
		c.refresh = {};
		c.refresh.container = refresh.container;
		c.refresh.tagged = refresh.tagged;
		c.refresh.tagging = refresh.tagging;
		place.appendChild(c);
		// set default state
		c.checked=defaultState;
		// track state in config.options.ID
		if (id) {
			c.id=id.substr(1); // trim off leading "="
			if (config.options[c.id]!=undefined)
				c.checked=config.options[c.id];
			else
				config.options[c.id]=c.checked;
		}
		// track state in (tiddlername|tagname) or (fieldname@tiddlername)
		if (target) {
			var pos=target.indexOf("@");
			if (pos!=-1) {
				c.field=pos?target.substr(0,pos):"checked"; // get fieldname (or use default "checked")
				c.tiddler=target.substr(pos+1); // get specified tiddler name (if any)
				if (!c.tiddler || !c.tiddler.length) c.tiddler=tid; // if tiddler not specified, default == container
				if (store.getValue(c.tiddler,c.field)!=undefined)
					c.checked=(store.getValue(c.tiddler,c.field)=="true"); // set checkbox from saved state
			} else {
				var pos=target.indexOf("|"); if (pos==-1) var pos=target.indexOf(":");
				c.tag=target;
				if (pos==0) c.tag=target.substr(1); // trim leading "|" or ":"
				if (pos>0) { c.tiddler=target.substr(0,pos); c.tag=target.substr(pos+1); }
				if (!c.tag.length) c.tag="checked";
				var t=store.getTiddler(c.tiddler);
				if (t && t.tags)
					c.checked=t.isTagged(c.tag); // set checkbox from saved state
			}
		}
		// trim off surrounding { and } delimiters from init/click handlers
		if (fn_init) c.fn_init="(function(){"+fn_init.trim().substr(1,fn_init.length-2)+"})()";
		if (fn_clickBefore) c.fn_clickBefore="(function(){"+fn_clickBefore.trim().substr(1,fn_clickBefore.length-2)+"})()";
		if (fn_clickAfter) c.fn_clickAfter="(function(){"+fn_clickAfter.trim().substr(1,fn_clickAfter.length-2)+"})()";
		c.init=true; c.onclick(); c.init=false; // compute initial state and save in tiddler/config/cookie
	},
	onClickCheckbox: function(event) {
		window.place=this;
		if (this.init && this.fn_init) // custom function hook to set initial state (run only once)
			{ try { eval(this.fn_init); } catch(e) { displayMessage("Checkbox init error: "+e.toString()); } }
		if (!this.init && this.fn_clickBefore) // custom function hook to override changes in checkbox state
			{ try { eval(this.fn_clickBefore) } catch(e) { displayMessage("Checkbox onClickBefore error: "+e.toString()); } }
		if (this.id)
			// save state in config AND cookie (only when ID starts with 'chk')
			{ config.options[this.id]=this.checked; if (this.id.substr(0,3)=="chk") saveOptionCookie(this.id); }
		if (this.srctid && this.srcpos>0 && (!this.id || this.id.substr(0,3)!="chk") && !this.tag && !this.field) {
			// save state in tiddler content only if not using cookie, tag or field tracking
			var t=store.getTiddler(this.srctid); // put X in original source tiddler (if any)
			if (t && this.checked!=(t.text.substr(this.srcpos,1).toUpperCase()=="X")) { // if changed
				t.set(null,t.text.substr(0,this.srcpos)+(this.checked?"X":"_")+t.text.substr(this.srcpos+1),null,null,t.tags);
				if (!story.isDirty(t.title)) story.refreshTiddler(t.title,null,true);
				store.setDirty(true);
			}
		}
		if (this.field) {
			if (this.checked && !store.tiddlerExists(this.tiddler))
				store.saveTiddler(this.tiddler,this.tiddler,"",config.options.txtUserName,new Date());
			// set the field value in the target tiddler
			store.setValue(this.tiddler,this.field,this.checked?"true":"false");
			// DEBUG: displayMessage(this.field+"@"+this.tiddler+" is "+this.checked);
		}
		if (this.tag) {
			if (this.checked && !store.tiddlerExists(this.tiddler))
				store.saveTiddler(this.tiddler,this.tiddler,"",config.options.txtUserName,new Date());
			var t=store.getTiddler(this.tiddler);
			if (t) {
				var tagged=(t.tags && t.tags.indexOf(this.tag)!=-1);
				if (this.checked && !tagged) { t.tags.push(this.tag); store.setDirty(true); }
				if (!this.checked && tagged) { t.tags.splice(t.tags.indexOf(this.tag),1); store.setDirty(true); }
			}
			// if tag state has been changed, update display of corresponding tiddlers (unless they are in edit mode...)
			if (this.checked!=tagged) {
				if (this.refresh.tagged) {
					if (!story.isDirty(this.tiddler)) // the TAGGED tiddler in view mode
						story.refreshTiddler(this.tiddler,null,true); 
					else // the TAGGED tiddler in edit mode (with tags field)
						config.macros.checkbox.refreshEditorTagField(this.tiddler,this.tag,this.checked);
				}
				if (this.refresh.tagging)
					if (!story.isDirty(this.tag)) story.refreshTiddler(this.tag,null,true); // the TAGGING tiddler
			}
		}
		if (!this.init && this.fn_clickAfter) // custom function hook to react to changes in checkbox state
			{ try { eval(this.fn_clickAfter) } catch(e) { displayMessage("Checkbox onClickAfter error: "+e.toString()); } }
		// refresh containing tiddler (but not during initial rendering, or we get an infinite loop!) (and not when editing container)
		if (!this.init && this.refresh.container && this.container!=this.tiddler)
			if (!story.isDirty(this.container)) story.refreshTiddler(this.container,null,true); // the tiddler CONTAINING the checkbox
		return true;
	},
	refreshEditorTagField: function(title,tag,set) {
		var tagfield=story.getTiddlerField(title,"tags");
		if (!tagfield||tagfield.getAttribute("edit")!="tags") return; // if no tags field in editor (i.e., custom template)
		var tags=tagfield.value.readBracketedList();
		if (tags.contains(tag)==set) return; // if no change needed
		if (set) tags.push(tag); // add tag
		else tags.splice(tags.indexOf(tag),1); // remove tag
		for (var t=0;t<tags.length;t++) tags[t]=String.encodeTiddlyLink(tags[t]);
		tagfield.value=tags.join(" "); // reassemble tag string (with brackets as needed)
		return;
	}
}
* Uniform
* Normal
* Bernoulli
* Binomial
* Gamma
* Beta
* Exponential

!! Families
!!! Exp Familiy
\[ p_\theta (x) = \exp \left\{ \sum_1^s \eta_i(\theta) T_i(x) - B(\theta) \right\}
\]
Gamma, Chi-sq, Beta, Binomial, Poisson, Neg. Binomial, and Normal are examples of exp. family.

!!! Scale Family
!!! Location Family
!!! ~Scale-Location Family
Normal, double exponential, Cauchy, Logistic, Exp, uniform are examples.
!! Syllabus
DynkinSystem
SigmaAlgebra
PiSystem
PiBarSystem
GeneratedSigmaAlgebra
GeneratedDynkinSystem
MonotoneClass
BorelAlgebra
CountablyAdditiveMeasure
FinitelyAdditiveMeasure
[[Measure]]
MonotonicityOfMeasures
ContinuityOfMeasures
InnerLimit
OuterLimit
LambdaSystem
DynkinPiLabmbdaTheorem
MinimalMonotoneClassTheorem
OuterMeasure

Casella & Berger "Statistical Inference"

!! Easy Identities

If $(C_j)_{j\in\Lambda}$ is a partition of $\Omega$, for any (countable or uncountable) index set $\Lambda$, then for any $A\subseteq\Omega$, $\prob(A)=\prob(\cup_j (A\cap C_j))$

!! Inequalities

* Boole's inequality: $ \prob(\cup_{j\in\natural}A_j) = \prob (\cup_j (A_j\backslash \cap_{i<j}A_i)) \leq \sum_j \prob(A_j)$ 
* Applying Boole's inequality to $A_j^c$: $1-\prob(\cap_{j=1}^n A_j) = \prob(\cup_j A_j^c) \leq n-\sum_j\prob(A_j)$, so we obtain Bonferroni's inequality: $$
\prob(\cap_{j=1}^n A_j)\geq \sum_{j=1}^n\prob(A_j)-(n-1).
$$
! ~UofA Course

Text: 'Corporate Finance' by Berk, ~DeMarzo & Stangeland (2009)

!! Lectures 1+2: Time Value of Money
Chapters 1-5

No arbitrage in efficient markets: see [[here|math515 Mathematical Finance 1]] .

APR $r$. Compounded $k$ times per year: EAR = $(1+\frac{r}{k})^k$. 
Discount factor $d=\frac{1}{1+r}$
Annuity(-immediate): payments at the end of each period. $PV=C \sum_{t=1}^{N} \! d^t = C\frac{1-d^N}{r}$
Annuity-due: payments at the ''beginning'' of each period: first one at $t=0$, last at $t=N-1$. $$\ddot PV=C\sum_{t=0}^{N-1}=PV/d=C\frac{1-d^N}{rd}$$
Perpetuity: $PV_\infty = C/r$
Increasing annuity-immediate: $C_t=C(1+g)^N$ for some $0\leq g$. $PV_g = C\sum_{t=1}^{N}\! \left(\frac{1+g}{1+r}\right)^t = C(1+r)\frac{1-\xi^N}{r-g}$
Where $RS_T$ is the resale value.

!! Lecture 3: NPV and Alternative Investment Rules
Chap. 6

payback period
WACC = weighted average cost of capital
RRR = required rate of return

Accruals ?

!! Lecture 4: Capital Budgeting
Chap. 7

!!! Notation
NWC = Net working capital 
RC = receivables collected
EP = expenses paid
AR = accounts receivable
AP = accounts payable
I = Inventory

$ NWC = CA - CL $
$  S-RC = \Delta(AR)  $
OCF = operating cash flow
$S_t$ = sales
$E_t$ = operating expenses (excl. depreciation)
$D_t$ = Depreciation (in Canada, CCA = capital cost allowance)
$T_c$ = marginal corporate tax rate
$EBIT_t$ = Earnings before interest and taxes = $S_t-E_t-D_t$ 

!!! ~Capital-Cost Allowance - Canadian Rules
$OCF_t = EBIT + D_t - Tax_t = (S_t-E_t)\times(1-T_c)+D_t\times T_c $ = sales-operational costs after taxes + tax shield

Cash flows: $CF_t = OCF_t -I_t +RS_t -\Delta(NWC)$
I+RS = capital expenditure

$$
CCA_t = \begin{cases}\frac{1}{2}\times I\times d & 1^{st} yr \\ d\times UCC_t & \geq2^{nd} yr \end{cases}
$$

$d$ = depreciation rate, $UCC_t$ = undepreciated capital cost
''Ignoring half-year rule'', the value of the tax shield as a perpetuity is $PV(tax\ shield) = \frac{I d T_c}{r+d}$
Taking into account the half-year rule, $PV=\frac{I d T_c}{r+d}\times\frac{1+\frac{r}{2}}{1+r}$
If we sell the asset after time $T$,
\[  PV = \frac{I d T_c}{r+d}\times\frac{1+\frac{r}{2}}{1+r} -\frac{1}{(1+r)^T}\frac{RS_Td T_c}{r+d} \]
Note that as long as the pool is not liquidated, we do not encounter terminal loss and ACC recapture corrections.

!! Lecture 5: Valuing Bonds
Chap 8 + 30.4

!! Lecture 6: Valuing Stocks
Chapter 9

!!! Dividend-discount model
''The total return'' of a stock is the dividend yield plus the capital gain: $\frac{P_1}{P_0}+\frac{{\rm Div}_1}{P_0}$, and should equal its
''equity cost of capital'': \[ r_E = \frac{P_1}{P_0}+\frac{{\rm Div}_1}{P_0} \] Since the stock price at the end of '''any''' period $P_N$ includes the expectation of future dividends, we must have \[ P_0 = \sum_{k=1}^\infty\!\frac{{\rm Div_k}}{(1+r_E)^k}. \] If we assume constant dividend growth rate ${\rm Div}_k = {\rm Div}_1(1+g)^k,$ the price is simply \[
P_0 = {\rm Div}_1 \, \sum_1^\infty \left( \frac{1+g}{1+r_E}\right)^k =  \frac{{\rm Div}_1}{r_E-g},
\] in other words, $r_E = \frac{{\rm Div}}{P_0} + g$; the capital gain is given by $g$.

!!! Dividends vs Investment and Growth
Let $n$ denote the number of outstanding shares, $E$ be earnings, $\xi$ be dividend payout rate, $1-\xi$ retention rate. We have $
n\times {\rm Div} = \xi E$. Define ''return on new investment'' ${\rm RNI} = \frac{\delta E}{I}$, where $I=(1-\xi)E$ is the investment amount. Then \[
\frac{\delta E}{E} = (1-\xi) \times {\rm RNI}, \] and \[ g = (1-\xi) \times {\rm RNI} \]

!!! Changing Growth Rates
Suppose the company pays different dividend stream $D_k$ in the first $N$ years, and dividend $D(1+g)^{N+1-g}$ (growing at a fixed rate) for perpetuity thereafter. The stock price will then be \[ P_0 = \sum_{k=1}^{N}\frac{D_k}{(1+r_E)^k} + \frac{1}{(1+r_E)^N}\times \frac{D}{r_E-g} \]
!! Lecture 7: Risk, Return and Capital Markets Portfolio Choice
Chap 10 & 11

!! CAPM, Intro to Options
Chap 12 & 20

!! Options Pricing, Capital Structure 1
Chap 21, 14, 15

!! Capital Structure 2; Dividend Policy
Chap 16,17

!! Capital Budgeting & Financial Leverage
Chap 18

!! Valuation and Financial Modeling
Chap 19

!! Long Term Financing
Chaps 23, 24
! FernUniversiät Hagen: Mikroökonimik Kurseinheit 2
!! Theorie des Haushalts

''Haushalt'': eine Wirtschaftseinheit, die ausschliesslich Güter für den eigenen Konsum produziert.
''Rationales Verhalten'': Konsistenz; 
Four turtles are placed at the vertices of a square with side $2a$. At $t=0$ they start crawling towards each other at the same constant speed in such a way that each turtle always points to its counter-clockwise neighbour. Find the equation of their paths, and the distance travelled by each turtle before they meet at the centre.
/***
|Name|FramedLinksPlugin|
|Source|http://www.TiddlyTools.com/#FramedLinksPlugin|
|Version|1.1.1|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|plugin|
|Description|clicking an external link opens an IFRAME following the link instead of opening a new tab/window|
This plugin causes clicks on external links to be rendered as inline frames (~IFRAMEs) instead of opening new browser tabs/windows.
!!!!!Usage
<<<
Use standard TiddlyWiki external link syntax into your tiddler content. If {{{chkFramedLinks}}} is enabled or the tiddler is tagged with 'framedLinks' (see Configuration), then whenever you click the external link an IFRAME will be dynamically added to the content.  Clicking on the link again removes the IFRAME.  Hold down any modifier (shift, control, or alt) while clicking a link ''temporarily'' bypasses the IFRAME handling and use the standard link handling behavior.
<<<
!!!!!Configuration
<<<
<<option chkFramedLinks>> display inline frames for all external links
&nbsp; &nbsp; {{{<<option chkFramedLinks>>}}}
<<option chkFramedLinksTag>> display inline frames for external links in tiddlers tagged with: <<option txtFramedLinksTag>> 
&nbsp; &nbsp; {{{<<option chkFramedLinksTag>> <<option txtFramedLinksTag>>}}}
IFRAME size (CSS units: %, em, px, cm, in) - width: <<option txtFrameWidth>> height: <<option txtFrameHeight>>
&nbsp; &nbsp; {{{<<option txtFrameWidth>> <<option txtFrameHeight>>}}}
<<<
!!!!!Examples
<<<
Try these links:
*http://www.TiddlyWiki.com
*http://www.TiddlyTools.com
*http://groups.google.com/group/TiddlyWiki/topics
<<<
!!!!!Revisions
<<<
2008.11.14 [1.1.1] fixed handling for external links embedded in //shadow// tiddlers
2008.09.13 [1.1.0] added support to selectively enable embedded IFRAMEs if the containing tiddler is tagged with 'framedLinks'
2007.11.29 [1.0.5] added slider animation and improved CSS handling for IFRAME height/width to maximize display area
2007.11.29 [1.0.0] initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.FramedLinksPlugin= {major: 1, minor: 1, revision: 1, date: new Date(2008,11,14)};

var co=config.options; // abbreviation
if (co.chkFramedLinks==undefined) co.chkFramedLinks=false;
if (co.chkFramedLinksTag==undefined) co.chkFramedLinksTag=true;
if (co.txtFramedLinksTag==undefined) co.txtFramedLinksTag="framedLinks";
if (co.txtFrameWidth==undefined) co.txtFrameWidth="100%";
if (co.txtFrameHeight==undefined) co.txtFrameHeight="80%";

window.framedLinks_createExternalLink=createExternalLink;
window.createExternalLink=function(place,url)
{
	var link=this.framedLinks_createExternalLink.apply(this,arguments);
	link.onclick=function(ev) { var e=ev?ev:window.event;
		var co=config.options; // abbreviation
		var here=story.findContainingTiddler(this);
		if (here) var tid=store.getTiddler(here.getAttribute("tiddler"));
		var enabled=co.chkFramedLinks || co.chkFramedLinksTag && tid && tid.isTagged(co.txtFramedLinksTag);
		if (!enabled || e.ctrlKey || e.shiftKey || e.altKey) return; // BYPASS
		var p=this.parentNode; 
		var f=this.nextSibling?this.nextSibling.firstChild:null; // get the IFRAME... maybe...
		var w=co.txtFrameWidth; if (!w || !w.length) w="100%";
		var h=co.txtFrameHeight; if (!h || !h.length) h="80%";
		if (h.indexOf("%")) h=(findWindowHeight()*h.replace(/%/,"")/100)+"px"; // calc height as % of window
		var showing=f && f.nodeName.toUpperCase()=="IFRAME"; // does IFRAME really exist?
		var stretchCell=p.nodeName.toUpperCase()=="TD" && w.indexOf("%")!=-1 && w.replace(/%/,"")>=100;
		if (!showing) { // create an iframe
			link.style.display="block"; // force IFRAME onto line following link
			if (stretchCell) { p.setAttribute("savedWidth",p.style.width); p.style.width="100%"; } // adjust TD so IFRAME stretches
			var wrapper=createTiddlyElement(null,"span"); // wrapper for slider animation
			wrapper.setAttribute("url",this.href); // for async loading of frame after animation completes
			var f=createTiddlyElement(wrapper,"iframe"); // create IFRAME
			f.style.backgroundColor="#fff"; f.style.width=w; f.style.height=h;
			p.insertBefore(wrapper,this.nextSibling);
			function loadURL(wrapper) { var f=wrapper.firstChild; var url=wrapper.getAttribute("url");
				var d=f.contentDocument?f.contentDocument:(f.contentWindow?f.contentWindow.document:f.document);
				d.open(); d.writeln("<html>connecting to "+url+"</html>"); d.close();
				try { f.src=url; } // if the iframe can't handle the href
				catch(e) { alert(e.description?e.description:e.toString()); } // ... then report the error
				window.scrollTo(0,ensureVisible(wrapper));
			}
			if (!co.chkAnimate) loadURL(wrapper);
			else {
				var morph=new Slider(wrapper,true);
				morph.callback=loadURL;
				morph.properties.push({style: 'width', start: 0, end: 100, template: '%0%'});
				anim.startAnimating(morph);
			}
		} else { // remove iframe
			link.style.display="inline"; // restore link style
			if (stretchCell) p.style.width=p.getAttribute("savedWidth"); // restore previous width of TD
			if (!co.chkAnimate) p.removeChild(f.parentNode);
			else {
				var morph=new Slider(f.parentNode,false,false,"all");
				morph.properties.push({style: 'width', start: 100, end: 0, template: '%0%'});
				anim.startAnimating(morph);
			}
		}
		e.cancelBubble=true; if (e.stopPropagation) e.stopPropagation(); return false;
	}
	return link;
}
//}}}
!! Generalizations
If $Z^* := \frac{dP_t^*}{dP_t}$ is the local density, we have

$$
  X\in\Mloc(\prob^*) \iff Z^* X\in \Mloc(P)
$$
We also know that $Z^*_t = \stexp_t(N) \in\Mloc$, where $N_t:=\int_0^t\!(Z^*_{u^-})^{-1}\,dZ^*_u$.

Thus
$$X_tZ^* = X_0\stexp_t(\tilde\Psi(h,H))\stexp(N) = X_0 \stexp(\Psi(h,H,N))$$
where, using the [[multiplication rule|Stochastic Exponential]], we have
$ \Psi_t(h,H,N) = $ @@ finish! @@

If we can show $\Psi_t(h,H,N)\in\Mloc(\prob)$, then $\prob^* \in\Mart(X,\prob)$

/***
|''Name:''|abego.IncludePlugin|
|''Version:''|1.0.0 (2007-02-08)|
|''Type:''|plugin|
|''Source:''|http://tiddlywiki.abego-software.de/#IncludePlugin|
|''Author:''|Udo Borkowski (ub [at] abego-software [dot] de)|
|''Documentation:''|[[IncludePlugin Documentation|http://tiddlywiki.abego-software.de/#%5B%5BIncludePlugin%20Documentation%5D%5D]]|
|''Community:''|([[del.icio.us|http://del.icio.us/post?url=http://tiddlywiki.abego-software.de/index.html%23IncludePlugin]]) ([[Support|http://groups.google.com/group/TiddlyWiki]])|
|''Copyright:''|&copy; 2007 [[abego Software|http://www.abego-software.de]]|
|''Licence:''|[[BSD open source license (abego Software)|http://www.abego-software.de/legal/apl-v10.html]]|
|''~CoreVersion:''|2.1.3|
|''Browser:''|Firefox 1.5.0.9 or better; Internet Explorer 6.0|
***/
//{{{

// Ensure the global abego namespace is set up.
if (!window.abego) window.abego = {};

var invokeLater = function(func, delay, priority) {
	return abego.invokeLater ? abego.invokeLater(func, delay, priority) : setTimeout(func,delay);
};

// Asynchronously load the given (local or remote) file.
// 
// @param url 		either an URL or a local file path to a file
//					Examples:
//						* http://www.abego-software.de/index.html
//						* file:///C:/abegoWebSite-Copy/index.html
//						* C:\abegoWebSite-Copy\index.html    (for Windows machines)
//							(Notice: backslashes in JavaScript string constants must be escaped, 
//							 i.e. the last example must be written as: "C:\\abegoWebSite-Copy\\index.html"
//							 when "hardcoded" in JavaScript source code)
// 
// @param callback 
//					function(content,url,params,errorMessage) 
//					called at the end of the operation. 
//					On success content holds the content of the loaded file. 
//					On error content is undefined and errorMessage holds an error message. 
//					params is the params passed into abego.loadFile.
//
// @param params 	passed through to the callback function
// 
abego.loadFile = function(url,callback,params) {

	var onLoad = function(status,params,responseText,url,xhr) {
		return status 
				? callback(responseText, url, params)
				: callback(undefined, url, params, "Error loading %0".format([url]));
	};
	
	// Make sure the URL is a real URL, with protocol prefix etc.
	if (url.search(/^((http(s)?)|(file)):/) != 0) {
		
		// no protocol specified. 
		if (url.search(/^((.\:\\)|(\\\\)|(\/))/) == 0) {
			// "url" is an "absolute" path to a local file. Prefix it with file://
			url = "file://"+url;
			
		} else {
			// "url" is a "relative" URL. Make it absolute
			
			// prefix the url with the directory containing the current document
			// (This also includes the protocol prefix)
			var documentPath = document.location.toString();
			var i = documentPath.lastIndexOf("/");
			url = documentPath.substr(0,i+1)+url;
		}
		// replace every \ by a /, to cover Windows style pathes
		url = url.replace(/\\/mg,"/");
	}
	
	loadRemoteFile(url,onLoad,params);

};

// Asynchronously load the given (local or remote) TiddlyWiki store.
// 
// @param url 		either an URL or a local file path to a TiddlyWiki file (absolute or relative)
//					Examples:
//						* http://www.abego-software.de/index.html
//						* file:///C:/abegoWebSite-Copy/index.html
//						* include/beta.html
//						* C:\abegoWebSite-Copy\index.html    (for Windows machines)
//							(Notice: backslashes in JavaScript string constants must be escaped, 
//							 i.e. the last example must be written as: "C:\\abegoWebSite-Copy\\index.html"
//							 when "hardcoded" in JavaScript source code)
// 
// @param callbackWithStore 
//					function(theStore,url,params,errorMessage) 
//					called at the end of the operation. 
//					On success theStore holds the loaded store (a TiddlyWiki object). 
//					On error theStore is undefined and errorMessage holds an error message. 
//					params is the params passed into abego.loadTiddlyWikiStore
//
// @param params 	passed through to the callbackWithStore
//
// @progress		[optional] function(message, sender, state, url, params) called in various situations during the operation,
//								typically used to show "the progress" of the operation.
//								sender: the constant "abego.loadTiddlyWikiStore"
//								state: one of these: "Started", "Processing", "Done", "Failed"
//									"Processing" means the data has been received and in now processed.
// 
abego.loadTiddlyWikiStore = function(url,callbackWithStore,params,progress) {
	
	var sendProgress = function(message, state) {
		if (progress)
			progress(message,"abego.loadTiddlyWikiStore",state,url,params);
	};
	
	// Load contents of a TiddlyWiki from a string
	//# Returns null on success, an error message otherwise.
	//# based on code from TiddlyWiki 2.2 alpha
	var importTiddlyWiki = function(store,text)
	{
		// Crack out the content - will be refactored to share code with saveChanges()
		var posOpeningDiv = text.indexOf(startSaveArea);
		var limitClosingDiv = text.indexOf("<!--POST-BODY-END--"+">");
		var posClosingDiv = text.lastIndexOf(endSaveArea,limitClosingDiv == -1 ? text.length : limitClosingDiv);
		if((posOpeningDiv == -1) || (posClosingDiv == -1))
			return config.messages.invalidFileError.format([url]);
		var content = "<html><body>" + text.substring(posOpeningDiv,posClosingDiv + endSaveArea.length) + "</body></html>";
		// Create the iframe
		var iframe = document.createElement("iframe");
		iframe.style.display = "none";
		document.body.appendChild(iframe);
		var doc = iframe.document;
		if(iframe.contentDocument)
			doc = iframe.contentDocument; // For NS6
		else if(iframe.contentWindow)
			doc = iframe.contentWindow.document; // For IE5.5 and IE6
		// Put the content in the iframe
		doc.open();
		doc.writeln(content);
		doc.close();
		// Load the content into a TiddlyWiki() object
		var storeArea = doc.getElementById("storeArea");
		store.loadFromDiv(storeArea,"store");
		// Get rid of the iframe
		iframe.parentNode.removeChild(iframe);
		return null;
	};
	
	var sendError = function(message) {
		sendProgress("Error when loading %0".format([url]),"Failed");
		callbackWithStore(undefined, url,params, message);
		return message;
	};
	
	var sendStore = function(store) {
		sendProgress("Loaded %0".format([url]),"Done");
		callbackWithStore(store, url, params);
		return null;
	};
	
	
	var callback = function(content,theURL,params,errorMessage) {
		if (content === undefined) {
			sendError(errorMessage);
			return;
		}
		
		sendProgress("Processing %0".format([url]),"Processing");
		var orig_invalidFileError = config.messages.invalidFileError;
		config.messages.invalidFileError = "The file '%0' does not appear to be a valid TiddlyWiki file";
		try {
			// Load the content into a TiddlyWiki() object
			var importStore = new TiddlyWiki();
			var errorText = importTiddlyWiki(importStore,content);
			if (errorText)
				sendError(errorText);
			else
				sendStore(importStore);

		} catch (ex) {
			sendError(exceptionText(ex));
		} finally {
			config.messages.invalidFileError = orig_invalidFileError;
		}
	};
	
	sendProgress("Start loading %0".format([url]),"Started");
	abego.loadFile(url,callback,params);
};


//==============================================================================
// Include Plugin 

(function(){

// only install once
if (abego.TiddlyWikiIncluder) return;


// --------------------------------------------------
// Constants

var WAITING = "waiting";
var LOADING = "loading";

var ANI_DURATION_HIDE_STATE = 1000;

var REFRESH_PRIORITY = -200;
var ANIMATION_PRIORITY = -100;
var UPDATE_STATE_PRIORITY = -300;

// --------------------------------------------------
// Variables

var useInclude;
var includes = []; // [] of Strings. the urls of the stores to include, in the sequence of the calls.
var includedStores = {}; // url(String) -> TiddlyWiki or String; when not (yet) loaded a status or error string.
var pendingOnLoadURLs = []; // [] of String. a list of urls that should be passed with the next "notifyListeners".
var refreshTiddlyWikiTimerID; // for delayed refresh
var listeners = [];
var progress;

// --------------------------------------------------
// Helper functions

var isIncludeEnabled = function() {
	if (useInclude === undefined)
		useInclude = config.options.chkUseInclude === undefined || config.options.chkUseInclude;
	return useInclude;
};

var getMissingIncludeMsg = function(url) {
	return "No include specified for %0".format([url])
};

// Called after one or more included TiddlyWikis are loaded
//
var notifyListeners = function() {
	var urls = pendingOnLoadURLs;
	pendingOnLoadURLs = [];
	if (urls.length) {
		for (var i= 0; i < listeners.length; i++)
			listeners[i](urls);
	}
};

var idleCount; // Reset to 0 when the system is "not idle", incremented inside refreshTiddlyWiki

var refreshTiddlyWiki = function() {
	// To avoid to much refreshing/flickering don't refresh immediately 
	// but wait until the system was idle for a certain time.
	
	if (refreshTiddlyWikiTimerID !== undefined) clearInterval(refreshTiddlyWikiTimerID);
	
	idleCount = 0;
	
	var sendDone = function() {
		abego.TiddlyWikiIncluder.sendProgress("","","Done");
	};
	
	refreshTiddlyWikiTimerID = setInterval(function() {
		idleCount++;
		if (idleCount <= 10)
			return;
			
		clearInterval(refreshTiddlyWikiTimerID);
		refreshTiddlyWikiTimerID = undefined;
			
		abego.TiddlyWikiIncluder.sendProgress("Refreshing...","","");
		refreshDisplay();
		invokeLater(sendDone,0,REFRESH_PRIORITY);
	},0);
};

// Calls callback for every loaded store and returns the first non-false/null.. value returned by callback.
//
// @param callback  function(store, url)
//
var forEachLoadedStore = function(callback) {
	var result;
	for (var i = 0; i < includes.length; i++) {
		var theStore = abego.TiddlyWikiIncluder.getStore(includes[i]);
		if (theStore && (result = callback(theStore, includes[i])))
			return result;
	}
};

var attachToStore = function() {
	if (!window.store)
		return invokeLater(attachToStore,100);
		
	var orig_fetchTiddler = store.fetchTiddler;
	
	store.fetchTiddler = function(title) {
		var t = orig_fetchTiddler.apply(this,arguments);
		if (t) return t;
		
		// When there is a shadowtiddler with that name done look for
		// any included tiddler since these would hide the shadow
		if (config.shadowTiddlers[title] !== undefined) return undefined;
		
		// Don't look for the "New Tiddler" tiddler in the included TiddlyWikis,
		// since returning such a tiddler (that is readonly) will make it impossible
		// in the Main TiddlyWiki to create new tiddlers.
		if (title == config.macros.newTiddler.title) return undefined;

		return forEachLoadedStore(
				function(theStore, url) {
					var t = theStore.fetchTiddler(title);
					if (t) 
						t.includeURL = url;
					return t;
				});
	};

	// We also refresh TiddlyWiki to reflect the new included Tiddlers (if we have any).
	if (includes.length)
		refreshTiddlyWiki();
};

var includeFromIncludeList = function() {
	if (!window.store)
		return invokeLater(includeFromIncludeList,100);
		
	var includeListText = store.getTiddlerText("IncludeList");
	if (includeListText) 
		wikify(includeListText,document.createElement("div"));
};

var getFunctionUsingForReallyEachTiddler = function(func) {
	var wrapper = function() {
		var orig_forEachTiddler = store.forEachTiddler;

		var forEachTiddlerWithIncludes = function(callback) {
			var done = {};
			var includeURL;

			var callbackWrapper = function(title, tiddler) {
				// ensure every title is only processed once
				if (done[title]) 
					return;
				done[title] = 1;
				
				// for "included tiddlers" set the includeURL;
				if (includeURL)
					tiddler.includeURL = includeURL;
				
				callback.apply(this,arguments);
			};
			
			// forEachTiddler over the original tiddlers
			orig_forEachTiddler.call(store, callbackWrapper);
			
			// add all shadowTiddler titles to done 
			// (to avoid an included store hides a shadow tiddler)
			for (var n in config.shadowTiddlers)
				done[n] = 1;

			// add all the "New Tiddler" tiddlerto done 
			// (to avoid an included store (with "New Tiddler") makes it impossible to create new tiddlers)
			done[config.macros.newTiddler.title] = 1;

			// forEachTiddler over every included store
			forEachLoadedStore(
					function(theStore, url) {
						includeURL = url;
						theStore.forEachTiddler(callbackWrapper);
					});
		};
		
		store.forEachTiddler = forEachTiddlerWithIncludes;
		try {
			return func.apply(this,arguments);
		} finally {
			store.forEachTiddler = orig_forEachTiddler;
		}
	};
	
	return wrapper;
};

var useForReallyEachTiddler = function(object,property) {
	return object[property] = getFunctionUsingForReallyEachTiddler(object[property]);
};


//================================================================================
// abego.TiddlyWikiIncluder

abego.TiddlyWikiIncluder = {};

abego.TiddlyWikiIncluder.setProgressFunction = function(func) {
	progress = func;
};

abego.TiddlyWikiIncluder.getProgressFunction = function(func) {
	return progress;
};

abego.TiddlyWikiIncluder.sendProgress = function(message, sender, state) {
	if (progress)
		progress.apply(this,arguments);
};


// Called when an included TiddlyWiki could not be loaded.
//
// By default an error message is displayed.
//
abego.TiddlyWikiIncluder.onError = function(url, errorMessage) {
	displayMessage("Error when including '%0':\n%1".format([url, errorMessage]));
};


// Returns true when there are "pending" includes, i.e. TiddlyWiki that are not yet loaded.
//
// A TiddlyWiki that failed loading is not pending.
//
abego.TiddlyWikiIncluder.hasPendingIncludes = function() {
	for (var i = 0; i < includes.length; i++) {
		var state = abego.TiddlyWikiIncluder.getState(includes[i]);
		if (state == WAITING || state == LOADING)
			return true;
	}
	return false;
};


// @return [] of Strings, the URLs of the includes
//
abego.TiddlyWikiIncluder.getIncludes = function() {
	return includes.slice();
};


// @return [may be null] a state/error text of the store with the given URL, or null when the store is already loaded
//
abego.TiddlyWikiIncluder.getState = function(url) {
	var s = includedStores[url];
	if (!s)
		return getMissingIncludeMsg(url);
	return typeof s == "string" ? s : null;
};


// @return [may be null] the (TiddlyWiki) store  with the given URL, null if not (yet) loaded.
//
abego.TiddlyWikiIncluder.getStore = function(url) {
	var s = includedStores[url];
	if (!s)
		return getMissingIncludeMsg(url);
	return s instanceof TiddlyWiki ? s : null;
};


// Includes the (local or remote) TiddlyWiki store with the given url.
// 
// stores with urls already already included are ignored.
//
// @param url	see url@abego.loadTiddlyWikiStore
// @param delayMilliSeconds [optional] if defined loading starts delayMilliSeconds later, otherwise "immediately"
//
abego.TiddlyWikiIncluder.include = function(url, delayMilliSeconds) {
	if (!isIncludeEnabled() || includedStores[url])
		return;
	var self = this;
	
	includes.push(url);
	includedStores[url] = WAITING;

	var loadStoreCallback = function(theStore,urlInCallback,params,errorMessage) {
		if (theStore === undefined) {
			includedStores[url] = errorMessage;
			self.onError(url, errorMessage);
			return;
		}
		includedStores[url] = theStore;
		pendingOnLoadURLs.push(url);
		invokeLater(notifyListeners);
	};
	
	var loadStore = function() {
		includedStores[url] = LOADING;
		abego.loadTiddlyWikiStore(url,loadStoreCallback,null,progress);
	};
	
	if (delayMilliSeconds)
		invokeLater(loadStore, delayMilliSeconds);
	else
		loadStore();
};


// iterates over all tiddlers of "the store" and all tiddlers of included (and loaded) stores
//
abego.TiddlyWikiIncluder.forReallyEachTiddler = function(callback) {
	var caller = function() {
		store.forEachTiddler(callback);
	};
	
	getFunctionUsingForReallyEachTiddler(caller).call(store);
};


// function abego.TiddlyWikiIncluder.getFunctionUsingForReallyEachTiddler(func)
//
// Returns a function that behaves as func, but every call to store.forEachTiddler will actually 
// be a call to forReallyEachTiddler, i.e. iterate over the tiddlers the main store and of the 
// included TiddlyWikis
//
// @return the patched function
//
abego.TiddlyWikiIncluder.getFunctionUsingForReallyEachTiddler = getFunctionUsingForReallyEachTiddler;


// function abego.TiddlyWikiIncluder.useForReallyEachTiddler(object,property)
//
// Patches the function hold in the given property of the object in such a way that every call
// to store.forEachTiddler will actually be a call to forReallyEachTiddler, i.e. iterate over the
// tiddlers the main staire and of the included TiddlyWikis
//
// @param object
// @param property the name of the property of the object containing the function to be patched.
// @return the patched function
//
abego.TiddlyWikiIncluder.useForReallyEachTiddler = useForReallyEachTiddler;


// Add a listener function to the TiddlyWikiIncluder.
//
// @param listener function(urls)
//							url: [] of Strings, containing the urls of the TiddlyWiki just included
//									(see url@abego.TiddlyWikiIncluder.include)
//						called whenever one or more TiddlyWiki store are successfully included.
//
abego.TiddlyWikiIncluder.addListener = function(listener) {
	listeners.push(listener);
};

// -------------------------------------------------------------------------------
// TiddlyWikiIncluder initialization code

abego.TiddlyWikiIncluder.addListener(refreshTiddlyWiki);

//----------------------------------------------------------------------------
// Options Support

if (config.options.chkUseInclude === undefined) config.options.chkUseInclude = true;

config.shadowTiddlers.AdvancedOptions += "\n<<option chkUseInclude>> Include ~TiddlyWikis (IncludeList | IncludeState | [[help|http://tiddlywiki.abego-software.de/#%5B%5BIncludePlugin%20Documentation%5D%5D]])\n^^(Reload this ~TiddlyWiki to make changes become effective)^^";
config.shadowTiddlers.IncludeState = "<<includeState>>";

//================================================================================
// Default Progress Handling for abego.TiddlyWikiIncluder

var showAnimated = function(e, showing, duration) {
	if (!anim || !abego.ShowAnimation) {
		e.style.display = showing ? "block" : "none";
		return;
	}
	
	anim.startAnimating(new abego.ShowAnimation(e,showing,duration));
};

abego.TiddlyWikiIncluder.getDefaultProgressFunction = function() {

	setStylesheet(
		".includeProgressState{\n"+
		"background-color:#FFCC00;\n"+
		"position:absolute;\n"+
		"right:0.2em;\n"+
		"top:0.2em;\n"+
		"width:7em;\n"+
		"padding-left:0.2em;\n"+
		"padding-right:0.2em\n"+
		"}\n",
		"abegoInclude");

	var createStateElem = function() {
		var e = document.createElement("div");
		e.className = "includeProgressState";
		e.style.display = "none";
		document.body.appendChild(e);
		return e;
	};
	
	var stateElem = createStateElem();


	var showState = function(message) {
		removeChildren(stateElem);
		createTiddlyText(stateElem,message);
		showAnimated(stateElem,true,0);
	};

	var hideState = function() {
		// hide the state the next idle time 
		invokeLater(function() {
			showAnimated(stateElem,false,ANI_DURATION_HIDE_STATE);
		},100,ANIMATION_PRIORITY);
	};
	
	var myProgressFunction = function(message, sender, state, url, params) {
		
		if (state == "Done" || state == "Failed") {
			hideState();
			return;
		}
		
		if (sender == "abego.loadTiddlyWikiStore") {
			idleCount = 0;
			if (state == "Processing")
				showState("Including...");
		} else {
			showState(message);
		}
	};
	return myProgressFunction;
};

abego.TiddlyWikiIncluder.setProgressFunction(abego.TiddlyWikiIncluder.getDefaultProgressFunction());


//================================================================================
// The "include" macro
//
// Syntax: <<include {url}* [delay: {milliSeconds}] [hide: true] >>
//

config.macros.include = {};
config.macros.include.handler = function(place,macroName,params,wikifier,paramString,tiddler) {
    params = paramString.parseParams("url",null,true,false,true); // allowEval, cascadeDefaults, names allowed
	var delay = parseInt(getParam(params,"delay","0"));
	var urls = params[0]["url"];
	var hide = getFlag(params, "hide", false);
	if (!hide)
		createTiddlyText(createTiddlyElement(place,"code"),wikifier.source.substring(wikifier.matchStart, wikifier.nextMatch));
	for (var i = 0; urls && i < urls.length; i++)
		abego.TiddlyWikiIncluder.include(urls[i],delay);
};


//================================================================================
// The "includeState" macro
//
// Syntax: <<includeState>>

config.macros.includeState = {};
config.macros.includeState.handler = function(place,macroName,params,wikifier,paramString,tiddler) {
	var getFullState = function () {
		var s = "";
		var includes = abego.TiddlyWikiIncluder.getIncludes();
		if (!includes.length)
			return "{{noIncludes{\nNo includes or 'include' is disabled (see AdvancedOptions)\n}}}\n";
			
		s += "|!Address|!State|\n";
		for (var i = 0; i < includes.length; i++) {
			var inc = includes[i];
			s += "|{{{"+inc+"}}}|";
			var t = abego.TiddlyWikiIncluder.getState(inc);
			s += t ? "{{{"+t+"}}}" : "included";
			s += "|\n"
		}
		s += "|includeState|k\n";
		return s;
	};
	
	var updateState = function(){
		removeChildren(div);
		wikify(getFullState(),div);
		if (abego.TiddlyWikiIncluder.hasPendingIncludes())
			invokeLater(updateState,500,UPDATE_STATE_PRIORITY);
	};

	var div = createTiddlyElement(place,"div");
	
	invokeLater(updateState,0,UPDATE_STATE_PRIORITY);
};

//================================================================================
// Tiddler extension/modification

var orig_Tiddler_isReadOnly = Tiddler.prototype.isReadOnly;

// Includes tiddlers are readonly.
Tiddler.prototype.isReadOnly = function() {
	return orig_Tiddler_isReadOnly.apply(this,arguments) || this.isIncluded();
}

Tiddler.prototype.isIncluded = function() {
	return this.includeURL != undefined;
};

Tiddler.prototype.getIncludeURL = function() {
	return this.includeURL;
};


//================================================================================
// TiddlyWiki modifications

// In some TiddlyWiki functions the "forEachTiddler" should work on all tiddlers, also those from 
// included store. (E.g. TiddlyWiki.prototype.getTags)
//
// But not for all (e.g. TiddlyWiki.prototype.getTiddlers is used for saving, but only the "own" tiddlers should be saved)
//
// Therefore explicitly list the functions that should be "wrapped" to use the "forReallyEachTiddler".
//
var tiddlyWikiFunctionsUsingForReallyEachTiddler = {
	getMissingLinks: 1, getOrphans: 1,getTags:1, reverseLookup: 1, updateTiddlers: 1};
	
for (var n in tiddlyWikiFunctionsUsingForReallyEachTiddler)
	useForReallyEachTiddler(TiddlyWiki.prototype,n);


//================================================================================
// Make IntelliTagger "Include-aware"

var patchIntelliTagger = function() {
	if (abego.IntelliTagger)
		useForReallyEachTiddler(abego.IntelliTagger,"assistTagging");
};

//================================================================================
// Perform plugin startup tasks

attachToStore();
invokeLater(includeFromIncludeList,100);
invokeLater(patchIntelliTagger,100);

})();

//}}}
Jaynes' papers, #1 and #2

[[TodoList]]
/***
|''Name:''|MathSVGPlugin|
|''Description:''|This plugin translates a subset of the LaTeX math notation to MathML with a customisable  image fallback when MathML is not supported. It also provides an easy way to produce mathematical SVG graphics with dynamical features and animation.|
|''Version:''|1.4.1|
|''Date:''|2010-04-01|
|''Source:''|http://www.math.ist.utl.pt/~psoares/MathSVG.html|
|''Author:''|Paulo Soares|
|''License:''|[[GNU Lesser General Public License|http://www.gnu.org/licences/lgpl.html]]|
|''~CoreVersion:''|2.5.0|
!Original copyright notice
{{{
ASCIIMathML.js
==============
Version 2.1 Oct 8, 2008, (c) Peter Jipsen http://www.chapman.edu/~jipsen
This version extends ASCIIMathML.js with LaTeXMathML.js and ASCIIsvg.js.
Latest version at http://www.chapman.edu/~jipsen/mathml/ASCIIMathML.js
If you use it on a webpage, please send the URL to jipsen@chapman.edu

The LaTeXMathML modifications were made by Douglas Woodall, June 2006.
(for details see header on the LaTeXMathML part in middle of file)
Extensive clean-up and improvements by Paulo Soares, Oct 2007.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 
(at http://www.gnu.org/licences/lgpl.html) for more details.
}}}
!~MathSVG code (minified)
***/
//{{{
Math.sec=function(a){return 1/Math.cos(a)};Math.csc=function(a){return 1/Math.sin(a)};Math.cot=function(a){return 1/Math.tan(a)};Math.asec=function(a){return Math.acos(1/a)};Math.acsc=function(a){return Math.asin(1/a)};Math.acot=function(a){return Math.atan(1/a)};Math.sinh=function(a){return(Math.exp(a)-Math.exp(-a))/2};Math.cosh=function(a){return(Math.exp(a)+Math.exp(-a))/2};Math.tanh=function(a){return(Math.exp(a)-Math.exp(-a))/(Math.exp(a)+Math.exp(-a))};Math.sech=function(a){return 1/Math.cosh(a)};Math.csch=function(a){return 1/Math.sinh(a)};Math.coth=function(a){return 1/Math.tanh(a)};Math.asinh=function(a){return Math.log(a+Math.sqrt(a*a+1))};Math.acosh=function(a){return Math.log(a+Math.sqrt(a*a-1))};Math.atanh=function(a){return Math.log((1+a)/(1-a))/2};Math.sech=function(a){return 1/Math.cosh(a)};Math.csch=function(a){return 1/Math.sinh(a)};Math.coth=function(a){return 1/Math.tanh(a)};Math.asech=function(a){return Math.acosh(1/a)};Math.acsch=function(a){return Math.asinh(1/a)};Math.acoth=function(a){return Math.atanh(1/a)};Math.sign=function(a){return(a===0?0:(a<0?-1:1))};Math.step=function(a,c,b){return(a<0?(b?b:0):(c?c:1))};Math.root=function(a,b){return Math.pow(a,1/b)};Math.factorial=function(b){if(b===0){return 1}if(b<0){if((b%1)===0){return}if(b>-1){return Math.factorial(b+1)/(b+1)}return -Math.PI/(Math.factorial(-1-b)*Math.sin(Math.PI*b))}var a=b;if((b%1)===0){while(b>1){b=b-1;a=a*b}}else{a=Math.exp((b+0.5)*Math.log(b+1)-b-b*(0.1121105+b*0.08106103)/(1.452342+b*(2.410858+b)))}return a};Math.Gamma=function(a){return Math.factorial(a-1)};Math.Beta=function(a,b){return Math.Gamma(a)*Math.Gamma(b)/Math.Gamma(a+b)};Math.C=function(a,b){var c=1/((a+1)*Math.Beta(b+1,a-b+1));return c};Math.truncate=function(a,c){var b=c||0;return Math.floor(a*Math.pow(10,b))/Math.pow(10,b)};Math.randomString=function(a,g){var f=(g||"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").split("");var e=[],c=Math.random;var d=f.length;for(var b=0;b<a;b++){e[b]=f[0|c()*d]}return e.join("")};Math.runif=function(d,c,f){var e=f||0;return Math.truncate((c+Math.pow(10,-e)-d)*Math.random()+d,e)};Math.rnormal=function(a,b){a=a||0;b=b||1;var d=0,c=0;while(d*c===0){d=Math.random();c=Math.random()}return b*(Math.sqrt(-2*Math.log(d))*Math.cos(2*Math.PI*c))+a};(function(){var a=jQuery.fn.attr,b="http://www.w3.org/2000/svg";jQuery.fn.attr=function(m,l){var g=this.length;if(!g){return this}for(var f=0;f<g;f++){var c=this[f];if(c.namespaceURI===b){if(l!==undefined){c.setAttribute(m,l)}else{if($.isArray(m)){var d=m.length,e={};while(d--){var k=m[d];var h=c.getAttribute(k);if(h||h==="0"){h=isNaN(h)?h:h-0}e[k]=h}return e}else{if(typeof m==="object"){for(v in m){c.setAttribute(v,m[v])}}else{var h=c.getAttribute(m);if(h||h==="0"){h=isNaN(h)?h:h-0}return h}}}}else{return a.apply(this,arguments)}}return this}}());var MSVG=function($){var chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";var cal=["\uD835\uDC9C","\u212C","\uD835\uDC9E","\uD835\uDC9F","\u2130","\u2131","\uD835\uDCA2","\u210B","\u2110","\uD835\uDCA5","\uD835\uDCA6","\u2112","\u2133","\uD835\uDCA9","\uD835\uDCAA","\uD835\uDCAB","\uD835\uDCAC","\u211B","\uD835\uDCAE","\uD835\uDCAF","\uD835\uDCB0","\uD835\uDCB1","\uD835\uDCB2","\uD835\uDCB3","\uD835\uDCB4","\uD835\uDCB5","\uD835\uDCB6","\uD835\uDCB7","\uD835\uDCB8","\uD835\uDCB9","\u212F","\uD835\uDCBB","\u210A","\uD835\uDCBD","\uD835\uDCBE","\uD835\uDCBF","\uD835\uDCC0","\uD835\uDCC1","\uD835\uDCC2","\uD835\uDCC3","\u2134","\uD835\uDCC5","\uD835\uDCC6","\uD835\uDCC7","\uD835\uDCC8","\uD835\uDCC9","\uD835\uDCCA","\uD835\uDCCB","\uD835\uDCCC","\uD835\uDCCD","\uD835\uDCCE","\uD835\uDCCF"];var frk=["\uD835\uDD04","\uD835\uDD05","\u212D","\uD835\uDD07","\uD835\uDD08","\uD835\uDD09","\uD835\uDD0A","\u210C","\u2111","\uD835\uDD0D","\uD835\uDD0E","\uD835\uDD0F","\uD835\uDD10","\uD835\uDD11","\uD835\uDD12","\uD835\uDD13","\uD835\uDD14","\u211C","\uD835\uDD16","\uD835\uDD17","\uD835\uDD18","\uD835\uDD19","\uD835\uDD1A","\uD835\uDD1B","\uD835\uDD1C","\u2128","\uD835\uDD1E","\uD835\uDD1F","\uD835\uDD20","\uD835\uDD21","\uD835\uDD22","\uD835\uDD23","\uD835\uDD24","\uD835\uDD25","\uD835\uDD26","\uD835\uDD27","\uD835\uDD28","\uD835\uDD29","\uD835\uDD2A","\uD835\uDD2B","\uD835\uDD2C","\uD835\uDD2D","\uD835\uDD2E","\uD835\uDD2F","\uD835\uDD30","\uD835\uDD31","\uD835\uDD32","\uD835\uDD33","\uD835\uDD34","\uD835\uDD35","\uD835\uDD36","\uD835\uDD37"];var bbb=["\uD835\uDD38","\uD835\uDD39","\u2102","\uD835\uDD3B","\uD835\uDD3C","\uD835\uDD3D","\uD835\uDD3E","\u210D","\uD835\uDD40","\uD835\uDD41","\uD835\uDD42","\uD835\uDD43","\uD835\uDD44","\u2115","\uD835\uDD46","\u2119","\u211A","\u211D","\uD835\uDD4A","\uD835\uDD4B","\uD835\uDD4C","\uD835\uDD4D","\uD835\uDD4E","\uD835\uDD4F","\uD835\uDD50","\u2124","\uD835\uDD52","\uD835\uDD53","\uD835\uDD54","\uD835\uDD55","\uD835\uDD56","\uD835\uDD57","\uD835\uDD58","\uD835\uDD59","\uD835\uDD5A","\uD835\uDD5B","\uD835\uDD5C","\uD835\uDD5D","\uD835\uDD5E","\uD835\uDD5F","\uD835\uDD60","\uD835\uDD61","\uD835\uDD62","\uD835\uDD63","\uD835\uDD64","\uD835\uDD65","\uD835\uDD66","\uD835\uDD67","\uD835\uDD68","\uD835\uDD69","\uD835\uDD6A","\uD835\uDD6B"];var CONST=0,UNARY=1,BINARY=2,INFIX=3,LEFTBRACKET=4,RIGHTBRACKET=5,SPACE=6,UNDEROVER=7,DEFINITION=8,LEFTRIGHT=9,TEXT=10,BIG=11,STRETCHY=13,MATRIX=14;var symbols=[{input:"\\varepsilon",tag:"mi",output:"\u025B",ttype:CONST},{input:"\\varsigma",tag:"mi",output:"\u03C2",ttype:CONST},{input:"\\vartheta",tag:"mi",output:"\u03D1",ttype:CONST},{input:"\\varphi",tag:"mi",output:"\u03D5",ttype:CONST},{input:"\\varpi",tag:"mi",output:"\u03D6",ttype:CONST},{input:"\\varrho",tag:"mi",output:"\u03F1",ttype:CONST},{input:"\\alpha",tag:"mi",output:"\u03B1",ttype:CONST},{input:"\\beta",tag:"mi",output:"\u03B2",ttype:CONST},{input:"\\gamma",tag:"mi",output:"\u03B3",ttype:CONST},{input:"\\delta",tag:"mi",output:"\u03B4",ttype:CONST},{input:"\\epsilon",tag:"mi",output:"\u03B5",ttype:CONST},{input:"\\zeta",tag:"mi",output:"\u03B6",ttype:CONST},{input:"\\eta",tag:"mi",output:"\u03B7",ttype:CONST},{input:"\\theta",tag:"mi",output:"\u03B8",ttype:CONST},{input:"\\iota",tag:"mi",output:"\u03B9",ttype:CONST},{input:"\\kappa",tag:"mi",output:"\u03BA",ttype:CONST},{input:"\\lambda",tag:"mi",output:"\u03BB",ttype:CONST},{input:"\\mu",tag:"mi",output:"\u03BC",ttype:CONST},{input:"\\nu",tag:"mi",output:"\u03BD",ttype:CONST},{input:"\\xi",tag:"mi",output:"\u03BE",ttype:CONST},{input:"\\omicron",tag:"mi",output:"\u03BF",ttype:CONST},{input:"\\pi",tag:"mi",output:"\u03C0",ttype:CONST},{input:"\\rho",tag:"mi",output:"\u03C1",ttype:CONST},{input:"\\sigma",tag:"mi",output:"\u03C3",ttype:CONST},{input:"\\tau",tag:"mi",output:"\u03C4",ttype:CONST},{input:"\\upsilon",tag:"mi",output:"\u03C5",ttype:CONST},{input:"\\phi",tag:"mi",output:"\u03C6",ttype:CONST},{input:"\\chi",tag:"mi",output:"\u03C7",ttype:CONST},{input:"\\psi",tag:"mi",output:"\u03C8",ttype:CONST},{input:"\\omega",tag:"mi",output:"\u03C9",ttype:CONST},{input:"\\Alpha",tag:"mo",output:"\u0391",ttype:CONST},{input:"\\Beta",tag:"mo",output:"\u0392",ttype:CONST},{input:"\\Gamma",tag:"mo",output:"\u0393",ttype:CONST},{input:"\\Delta",tag:"mo",output:"\u0394",ttype:CONST},{input:"\\Epsilon",tag:"mo",output:"\u0395",ttype:CONST},{input:"\\Zeta",tag:"mo",output:"\u0396",ttype:CONST},{input:"\\Eta",tag:"mo",output:"\u0397",ttype:CONST},{input:"\\Theta",tag:"mo",output:"\u0398",ttype:CONST},{input:"\\Iota",tag:"mo",output:"\u0399",ttype:CONST},{input:"\\Kappa",tag:"mo",output:"\u039A",ttype:CONST},{input:"\\Lambda",tag:"mo",output:"\u039B",ttype:CONST},{input:"\\Mu",tag:"mo",output:"\u039C",ttype:CONST},{input:"\\Nu",tag:"mo",output:"\u039D",ttype:CONST},{input:"\\Xi",tag:"mo",output:"\u039E",ttype:CONST},{input:"\\Omicron",tag:"mo",output:"\u039F",ttype:CONST},{input:"\\Pi",tag:"mo",output:"\u03A0",ttype:CONST},{input:"\\Rho",tag:"mo",output:"\u03A1",ttype:CONST},{input:"\\Sigma",tag:"mo",output:"\u03A3",ttype:CONST},{input:"\\Tau",tag:"mo",output:"\u03A4",ttype:CONST},{input:"\\Upsilon",tag:"mo",output:"\u03A5",ttype:CONST},{input:"\\Phi",tag:"mo",output:"\u03A6",ttype:CONST},{input:"\\Chi",tag:"mo",output:"\u03A7",ttype:CONST},{input:"\\Psi",tag:"mo",output:"\u03A8",ttype:CONST},{input:"\\Omega",tag:"mo",output:"\u03A9",ttype:CONST},{input:"\\frac12",tag:"mo",output:"\u00BD",ttype:CONST},{input:"\\frac14",tag:"mo",output:"\u00BC",ttype:CONST},{input:"\\frac34",tag:"mo",output:"\u00BE",ttype:CONST},{input:"\\frac13",tag:"mo",output:"\u2153",ttype:CONST},{input:"\\frac23",tag:"mo",output:"\u2154",ttype:CONST},{input:"\\frac15",tag:"mo",output:"\u2155",ttype:CONST},{input:"\\frac25",tag:"mo",output:"\u2156",ttype:CONST},{input:"\\frac35",tag:"mo",output:"\u2157",ttype:CONST},{input:"\\frac45",tag:"mo",output:"\u2158",ttype:CONST},{input:"\\frac16",tag:"mo",output:"\u2159",ttype:CONST},{input:"\\frac56",tag:"mo",output:"\u215A",ttype:CONST},{input:"\\frac18",tag:"mo",output:"\u215B",ttype:CONST},{input:"\\frac38",tag:"mo",output:"\u215C",ttype:CONST},{input:"\\frac58",tag:"mo",output:"\u215D",ttype:CONST},{input:"\\frac78",tag:"mo",output:"\u215E",ttype:CONST},{input:"\\pm",tag:"mo",output:"\u00B1",ttype:CONST},{input:"\\mp",tag:"mo",output:"\u2213",ttype:CONST},{input:"\\triangleleft",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\triangleright",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\cdot",tag:"mo",output:"\u22C5",ttype:CONST},{input:"\\star",tag:"mo",output:"\u22C6",ttype:CONST},{input:"\\ast",tag:"mo",output:"\u002A",ttype:CONST},{input:"\\times",tag:"mo",output:"\u00D7",ttype:CONST},{input:"\\div",tag:"mo",output:"\u00F7",ttype:CONST},{input:"\\circ",tag:"mo",output:"\u2218",ttype:CONST},{input:"\\bullet",tag:"mo",output:"\u2022",ttype:CONST},{input:"\\oplus",tag:"mo",output:"\u2295",ttype:CONST},{input:"\\ominus",tag:"mo",output:"\u2296",ttype:CONST},{input:"\\otimes",tag:"mo",output:"\u2297",ttype:CONST},{input:"\\bigcirc",tag:"mo",output:"\u25CB",ttype:CONST},{input:"\\oslash",tag:"mo",output:"\u2298",ttype:CONST},{input:"\\odot",tag:"mo",output:"\u2299",ttype:CONST},{input:"\\land",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\wedge",tag:"mo",output:"\u2227",ttype:CONST},{input:"\\lor",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\vee",tag:"mo",output:"\u2228",ttype:CONST},{input:"\\cap",tag:"mo",output:"\u2229",ttype:CONST},{input:"\\cup",tag:"mo",output:"\u222A",ttype:CONST},{input:"\\sqcap",tag:"mo",output:"\u2293",ttype:CONST},{input:"\\sqcup",tag:"mo",output:"\u2294",ttype:CONST},{input:"\\uplus",tag:"mo",output:"\u228E",ttype:CONST},{input:"\\amalg",tag:"mo",output:"\u2210",ttype:CONST},{input:"\\bigtriangleup",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\bigtriangledown",tag:"mo",output:"\u25BD",ttype:CONST},{input:"\\dag",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\dagger",tag:"mo",output:"\u2020",ttype:CONST},{input:"\\ddag",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\ddagger",tag:"mo",output:"\u2021",ttype:CONST},{input:"\\lhd",tag:"mo",output:"\u22B2",ttype:CONST},{input:"\\rhd",tag:"mo",output:"\u22B3",ttype:CONST},{input:"\\unlhd",tag:"mo",output:"\u22B4",ttype:CONST},{input:"\\unrhd",tag:"mo",output:"\u22B5",ttype:CONST},{input:"\\sum",tag:"mo",output:"\u2211",ttype:UNDEROVER},{input:"\\prod",tag:"mo",output:"\u220F",ttype:UNDEROVER},{input:"\\bigcap",tag:"mo",output:"\u22C2",ttype:UNDEROVER},{input:"\\bigcup",tag:"mo",output:"\u22C3",ttype:UNDEROVER},{input:"\\bigwedge",tag:"mo",output:"\u22C0",ttype:UNDEROVER},{input:"\\bigvee",tag:"mo",output:"\u22C1",ttype:UNDEROVER},{input:"\\bigsqcap",tag:"mo",output:"\u2A05",ttype:UNDEROVER},{input:"\\bigsqcup",tag:"mo",output:"\u2A06",ttype:UNDEROVER},{input:"\\coprod",tag:"mo",output:"\u2210",ttype:UNDEROVER},{input:"\\bigoplus",tag:"mo",output:"\u2A01",ttype:UNDEROVER},{input:"\\bigotimes",tag:"mo",output:"\u2A02",ttype:UNDEROVER},{input:"\\bigodot",tag:"mo",output:"\u2A00",ttype:UNDEROVER},{input:"\\biguplus",tag:"mo",output:"\u2A04",ttype:UNDEROVER},{input:"\\int",tag:"mo",output:"\u222B",ttype:CONST},{input:"\\oint",tag:"mo",output:"\u222E",ttype:CONST},{input:":=",tag:"mo",output:":=",ttype:CONST},{input:"\\lt",tag:"mo",output:"<",ttype:CONST},{input:"\\gt",tag:"mo",output:">",ttype:CONST},{input:"\\ne",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\neq",tag:"mo",output:"\u2260",ttype:CONST},{input:"\\le",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leq",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\leqslant",tag:"mo",output:"\u2264",ttype:CONST},{input:"\\ge",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geq",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\geqslant",tag:"mo",output:"\u2265",ttype:CONST},{input:"\\equiv",tag:"mo",output:"\u2261",ttype:CONST},{input:"\\ll",tag:"mo",output:"\u226A",ttype:CONST},{input:"\\gg",tag:"mo",output:"\u226B",ttype:CONST},{input:"\\doteq",tag:"mo",output:"\u2250",ttype:CONST},{input:"\\prec",tag:"mo",output:"\u227A",ttype:CONST},{input:"\\succ",tag:"mo",output:"\u227B",ttype:CONST},{input:"\\preceq",tag:"mo",output:"\u227C",ttype:CONST},{input:"\\succeq",tag:"mo",output:"\u227D",ttype:CONST},{input:"\\subset",tag:"mo",output:"\u2282",ttype:CONST},{input:"\\supset",tag:"mo",output:"\u2283",ttype:CONST},{input:"\\subseteq",tag:"mo",output:"\u2286",ttype:CONST},{input:"\\supseteq",tag:"mo",output:"\u2287",ttype:CONST},{input:"\\sqsubset",tag:"mo",output:"\u228F",ttype:CONST},{input:"\\sqsupset",tag:"mo",output:"\u2290",ttype:CONST},{input:"\\sqsubseteq",tag:"mo",output:"\u2291",ttype:CONST},{input:"\\sqsupseteq",tag:"mo",output:"\u2292",ttype:CONST},{input:"\\sim",tag:"mo",output:"\u223C",ttype:CONST},{input:"\\simeq",tag:"mo",output:"\u2243",ttype:CONST},{input:"\\approx",tag:"mo",output:"\u2248",ttype:CONST},{input:"\\cong",tag:"mo",output:"\u2245",ttype:CONST},{input:"\\Join",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\bowtie",tag:"mo",output:"\u22C8",ttype:CONST},{input:"\\in",tag:"mo",output:"\u2208",ttype:CONST},{input:"\\ni",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\owns",tag:"mo",output:"\u220B",ttype:CONST},{input:"\\propto",tag:"mo",output:"\u221D",ttype:CONST},{input:"\\vdash",tag:"mo",output:"\u22A2",ttype:CONST},{input:"\\dashv",tag:"mo",output:"\u22A3",ttype:CONST},{input:"\\models",tag:"mo",output:"\u22A8",ttype:CONST},{input:"\\perp",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\smile",tag:"mo",output:"\u2323",ttype:CONST},{input:"\\frown",tag:"mo",output:"\u2322",ttype:CONST},{input:"\\asymp",tag:"mo",output:"\u224D",ttype:CONST},{input:"\\notin",tag:"mo",output:"\u2209",ttype:CONST},{input:"\\begin{eqnarray}",output:"X",ttype:MATRIX,invisible:true},{input:"\\begin{array}",output:"X",ttype:MATRIX,invisible:true},{input:"\\\\",output:"}&{",ttype:DEFINITION},{input:"\\end{eqnarray}",output:"}}",ttype:DEFINITION},{input:"\\end{array}",output:"}}",ttype:DEFINITION},{input:"\\big",tag:"mo",output:"X",atval:"1.2",ttype:BIG},{input:"\\Big",tag:"mo",output:"X",atval:"1.8",ttype:BIG},{input:"\\bigg",tag:"mo",output:"X",atval:"2.3",ttype:BIG},{input:"\\Bigg",tag:"mo",output:"X",atval:"2.9",ttype:BIG},{input:"\\left",tag:"mo",output:"X",ttype:LEFTBRACKET},{input:"\\right",tag:"mo",output:"X",ttype:RIGHTBRACKET},{input:"{",output:"{",ttype:LEFTBRACKET,invisible:true},{input:"}",output:"}",ttype:RIGHTBRACKET,invisible:true},{input:"(",tag:"mo",output:"(",atval:"1",ttype:STRETCHY},{input:"[",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\lbrack",tag:"mo",output:"[",atval:"1",ttype:STRETCHY},{input:"\\{",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\lbrace",tag:"mo",output:"{",atval:"1",ttype:STRETCHY},{input:"\\langle",tag:"mo",output:"\u2329",atval:"1",ttype:STRETCHY},{input:"\\lfloor",tag:"mo",output:"\u230A",atval:"1",ttype:STRETCHY},{input:"\\lceil",tag:"mo",output:"\u2308",atval:"1",ttype:STRETCHY},{input:")",tag:"mo",output:")",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"]",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrack",tag:"mo",output:"]",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\}",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rbrace",tag:"mo",output:"}",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rangle",tag:"mo",output:"\u232A",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rfloor",tag:"mo",output:"\u230B",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"\\rceil",tag:"mo",output:"\u2309",rtag:"mi",atval:"1",ttype:STRETCHY},{input:"|",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\|",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\vert",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\Vert",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"\\mid",tag:"mo",output:"\u2223",atval:"1",ttype:STRETCHY},{input:"\\parallel",tag:"mo",output:"\u2225",atval:"1",ttype:STRETCHY},{input:"/",tag:"mo",output:"/",atval:"1.01",ttype:STRETCHY},{input:"\\backslash",tag:"mo",output:"\u2216",atval:"1",ttype:STRETCHY},{input:"\\setminus",tag:"mo",output:"\\",ttype:CONST},{input:"\\!",tag:"mspace",atname:"width",atval:"-0.167em",ttype:SPACE},{input:"\\,",tag:"mspace",atname:"width",atval:"0.167em",ttype:SPACE},{input:"\\>",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\:",tag:"mspace",atname:"width",atval:"0.222em",ttype:SPACE},{input:"\\;",tag:"mspace",atname:"width",atval:"0.278em",ttype:SPACE},{input:"~",tag:"mspace",atname:"width",atval:"0.333em",ttype:SPACE},{input:"\\quad",tag:"mspace",atname:"width",atval:"1em",ttype:SPACE},{input:"\\qquad",tag:"mspace",atname:"width",atval:"2em",ttype:SPACE},{input:"\\prime",tag:"mo",output:"\u2032",ttype:CONST},{input:"'",tag:"mo",output:"\u02B9",ttype:CONST},{input:"''",tag:"mo",output:"\u02BA",ttype:CONST},{input:"'''",tag:"mo",output:"\u2034",ttype:CONST},{input:"''''",tag:"mo",output:"\u2057",ttype:CONST},{input:"\\ldots",tag:"mo",output:"\u2026",ttype:CONST},{input:"\\cdots",tag:"mo",output:"\u22EF",ttype:CONST},{input:"\\vdots",tag:"mo",output:"\u22EE",ttype:CONST},{input:"\\ddots",tag:"mo",output:"\u22F1",ttype:CONST},{input:"\\forall",tag:"mo",output:"\u2200",ttype:CONST},{input:"\\exists",tag:"mo",output:"\u2203",ttype:CONST},{input:"\\Re",tag:"mo",output:"\u211C",ttype:CONST},{input:"\\Im",tag:"mo",output:"\u2111",ttype:CONST},{input:"\\aleph",tag:"mo",output:"\u2135",ttype:CONST},{input:"\\hbar",tag:"mo",output:"\u210F",ttype:CONST},{input:"\\ell",tag:"mo",output:"\u2113",ttype:CONST},{input:"\\wp",tag:"mo",output:"\u2118",ttype:CONST},{input:"\\emptyset",tag:"mo",output:"\u2205",ttype:CONST},{input:"\\infty",tag:"mo",output:"\u221E",ttype:CONST},{input:"\\surd",tag:"mo",output:"\\sqrt{}",ttype:DEFINITION},{input:"\\partial",tag:"mo",output:"\u2202",ttype:CONST},{input:"\\nabla",tag:"mo",output:"\u2207",ttype:CONST},{input:"\\triangle",tag:"mo",output:"\u25B3",ttype:CONST},{input:"\\therefore",tag:"mo",output:"\u2234",ttype:CONST},{input:"\\angle",tag:"mo",output:"\u2220",ttype:CONST},{input:"\\diamond",tag:"mo",output:"\u22C4",ttype:CONST},{input:"\\Diamond",tag:"mo",output:"\u25C7",ttype:CONST},{input:"\\neg",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\lnot",tag:"mo",output:"\u00AC",ttype:CONST},{input:"\\bot",tag:"mo",output:"\u22A5",ttype:CONST},{input:"\\top",tag:"mo",output:"\u22A4",ttype:CONST},{input:"\\square",tag:"mo",output:"\u25AB",ttype:CONST},{input:"\\Box",tag:"mo",output:"\u25A1",ttype:CONST},{input:"\\wr",tag:"mo",output:"\u2240",ttype:CONST},{input:"\\arccos",tag:"mi",output:"arccos",ttype:UNARY,func:true},{input:"\\arcsin",tag:"mi",output:"arcsin",ttype:UNARY,func:true},{input:"\\arctan",tag:"mi",output:"arctan",ttype:UNARY,func:true},{input:"\\arg",tag:"mi",output:"arg",ttype:UNARY,func:true},{input:"\\cos",tag:"mi",output:"cos",ttype:UNARY,func:true},{input:"\\cosh",tag:"mi",output:"cosh",ttype:UNARY,func:true},{input:"\\cot",tag:"mi",output:"cot",ttype:UNARY,func:true},{input:"\\coth",tag:"mi",output:"coth",ttype:UNARY,func:true},{input:"\\csc",tag:"mi",output:"csc",ttype:UNARY,func:true},{input:"\\deg",tag:"mi",output:"deg",ttype:UNARY,func:true},{input:"\\det",tag:"mi",output:"det",ttype:UNARY,func:true},{input:"\\dim",tag:"mi",output:"dim",ttype:UNARY,func:true},{input:"\\exp",tag:"mi",output:"exp",ttype:UNARY,func:true},{input:"\\gcd",tag:"mi",output:"gcd",ttype:UNARY,func:true},{input:"\\hom",tag:"mi",output:"hom",ttype:UNARY,func:true},{input:"\\inf",tag:"mo",output:"inf",ttype:UNDEROVER},{input:"\\ker",tag:"mi",output:"ker",ttype:UNARY,func:true},{input:"\\lg",tag:"mi",output:"lg",ttype:UNARY,func:true},{input:"\\lim",tag:"mo",output:"lim",ttype:UNDEROVER},{input:"\\liminf",tag:"mo",output:"liminf",ttype:UNDEROVER},{input:"\\limsup",tag:"mo",output:"limsup",ttype:UNDEROVER},{input:"\\ln",tag:"mi",output:"ln",ttype:UNARY,func:true},{input:"\\log",tag:"mi",output:"log",ttype:UNARY,func:true},{input:"\\max",tag:"mo",output:"max",ttype:UNDEROVER},{input:"\\min",tag:"mo",output:"min",ttype:UNDEROVER},{input:"\\Pr",tag:"mi",output:"Pr",ttype:UNARY,func:true},{input:"\\sec",tag:"mi",output:"sec",ttype:UNARY,func:true},{input:"\\sin",tag:"mi",output:"sin",ttype:UNARY,func:true},{input:"\\sinh",tag:"mi",output:"sinh",ttype:UNARY,func:true},{input:"\\sup",tag:"mo",output:"sup",ttype:UNDEROVER},{input:"\\tan",tag:"mi",output:"tan",ttype:UNARY,func:true},{input:"\\tanh",tag:"mi",output:"tanh",ttype:UNARY,func:true},{input:"\\gets",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\leftarrow",tag:"mo",output:"\u2190",ttype:CONST},{input:"\\to",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\rightarrow",tag:"mo",output:"\u2192",ttype:CONST},{input:"\\leftrightarrow",tag:"mo",output:"\u2194",ttype:CONST},{input:"\\uparrow",tag:"mo",output:"\u2191",ttype:CONST},{input:"\\downarrow",tag:"mo",output:"\u2193",ttype:CONST},{input:"\\updownarrow",tag:"mo",output:"\u2195",ttype:CONST},{input:"\\Leftarrow",tag:"mo",output:"\u21D0",ttype:CONST},{input:"\\Rightarrow",tag:"mo",output:"\u21D2",ttype:CONST},{input:"\\Leftrightarrow",tag:"mo",output:"\u21D4",ttype:CONST},{input:"\\iff",tag:"mo",output:"~\\Longleftrightarrow~",ttype:DEFINITION},{input:"\\Uparrow",tag:"mo",output:"\u21D1",ttype:CONST},{input:"\\Downarrow",tag:"mo",output:"\u21D3",ttype:CONST},{input:"\\Updownarrow",tag:"mo",output:"\u21D5",ttype:CONST},{input:"\\mapsto",tag:"mo",output:"\u21A6",ttype:CONST},{input:"\\longleftarrow",tag:"mo",output:"\u27F5",ttype:CONST},{input:"\\longrightarrow",tag:"mo",output:"\u27F6",ttype:CONST},{input:"\\longleftrightarrow",tag:"mo",output:"\u27F7",ttype:CONST},{input:"\\Longleftarrow",tag:"mo",output:"\u27F8",ttype:CONST},{input:"\\Longrightarrow",tag:"mo",output:"\u27F9",ttype:CONST},{input:"\\Longleftrightarrow",tag:"mo",output:"\u27FA",ttype:CONST},{input:"\\longmapsto",tag:"mo",output:"\u27FC",ttype:CONST},{input:"\\sqrt",tag:"msqrt",output:"sqrt",ttype:UNARY},{input:"\\root",tag:"mroot",output:"root",ttype:BINARY},{input:"\\frac",tag:"mfrac",output:"/",ttype:BINARY},{input:"\\stackrel",tag:"mover",output:"stackrel",ttype:BINARY},{input:"\\atop",tag:"mfrac",output:"",ttype:INFIX},{input:"\\choose",tag:"mfrac",output:"",ttype:INFIX},{input:"\\over",tag:"mfrac",output:"/",ttype:INFIX},{input:"_",tag:"msub",output:"_",ttype:INFIX},{input:"^",tag:"msup",output:"^",ttype:INFIX},{input:"\\mbox",tag:"mtext",output:"mbox",ttype:TEXT},{input:"\\acute",tag:"mover",output:"\u00B4",ttype:UNARY,acc:true},{input:"\\grave",tag:"mover",output:"\u0060",ttype:UNARY,acc:true},{input:"\\breve",tag:"mover",output:"\u02D8",ttype:UNARY,acc:true},{input:"\\check",tag:"mover",output:"\u02C7",ttype:UNARY,acc:true},{input:"\\dot",tag:"mover",output:".",ttype:UNARY,acc:true},{input:"\\ddot",tag:"mover",output:"..",ttype:UNARY,acc:true},{input:"\\mathring",tag:"mover",output:"\u00B0",ttype:UNARY,acc:true},{input:"\\vec",tag:"mover",output:"\u2192",ttype:UNARY,acc:true},{input:"\\overrightarrow",tag:"mover",output:"\u2192",ttype:UNARY,acc:true},{input:"\\overleftarrow",tag:"mover",output:"\u2190",ttype:UNARY,acc:true},{input:"\\hat",tag:"mover",output:"\u005E",ttype:UNARY,acc:true},{input:"\\widehat",tag:"mover",output:"\u0302",ttype:UNARY,acc:true},{input:"\\tilde",tag:"mover",output:"~",ttype:UNARY,acc:true},{input:"\\widetilde",tag:"mover",output:"\u02DC",ttype:UNARY,acc:true},{input:"\\bar",tag:"mover",output:"\u203E",ttype:UNARY,acc:true},{input:"\\overbrace",tag:"mover",output:"\u23B4",ttype:UNARY,acc:true},{input:"\\overline",tag:"mover",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\underbrace",tag:"munder",output:"\u23B5",ttype:UNARY,acc:true},{input:"\\underline",tag:"munder",output:"\u00AF",ttype:UNARY,acc:true},{input:"\\displaystyle",tag:"mstyle",atname:"displaystyle",atval:"true",ttype:UNARY},{input:"\\textstyle",tag:"mstyle",atname:"displaystyle",atval:"false",ttype:UNARY},{input:"\\scriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"1",ttype:UNARY},{input:"\\scriptscriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"2",ttype:UNARY},{input:"\\mathrm",tag:"mtext",output:"text",ttype:TEXT},{input:"\\textrm",tag:"mtext",output:"text",ttype:TEXT},{input:"\\mathbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY,codes:chars},{input:"\\textbf",tag:"mstyle",atname:"mathvariant",atval:"bold",ttype:UNARY,codes:chars},{input:"\\mathit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\textit",tag:"mstyle",atname:"mathvariant",atval:"italic",ttype:UNARY},{input:"\\mathtt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY,codes:chars},{input:"\\texttt",tag:"mstyle",atname:"mathvariant",atval:"monospace",ttype:UNARY,codes:chars},{input:"\\mathsf",tag:"mstyle",atname:"mathvariant",atval:"sans-serif",ttype:UNARY,codes:chars},{input:"\\mathbb",tag:"mstyle",atname:"mathvariant",atval:"double-struck",ttype:UNARY,codes:bbb},{input:"\\mathcal",tag:"mstyle",atname:"mathvariant",atval:"script",ttype:UNARY,codes:cal},{input:"\\mathfrak",tag:"mstyle",atname:"mathvariant",atval:"fraktur",ttype:UNARY,codes:frk}];var names=[];if(!document.createElementNS){document.createElementNS=function(link,type){return this.createElement(type)}}function compareNames(x,y){if(x.input>y.input){return 1}else{return -1}}function refreshSymbols(){var len=symbols.length;symbols.sort(compareNames);for(var i=0;i<len;i++){names[i]=symbols[i].input}}function strim(str,n){return $.trim(str.slice(n))}function createElementXHTML(elType){return document.createElementNS("http://www.w3.org/1999/xhtml",elType)}function position(str,n){var pos=$.inArray(str,names.slice(n));if(pos<0){var narr=names.concat([str]);narr.sort();pos=$.inArray(str,narr.slice(n))}return n+pos}function getSymbol(str){var k=0;var j=0;var mk;var st;var tagst;var match="";var more=true;var sLen=str.length;for(var i=1;i<=sLen&&more;i++){st=str.slice(0,i);j=k;k=position(st,j);if(k<names.length&&str.slice(0,names[k].length)==names[k]){match=names[k];mk=k;i=match.length}more=k<names.length&&str.slice(0,names[k].length)>=names[k]}if(match!==""){return symbols[mk]}k=1;st=str.slice(0,1);if("0"<=st&&st<="9"){tagst="mn"}else{tagst=(("A">st||st>"Z")&&("a">st||st>"z")?"mo":"mi")}return{input:st,tag:tagst,output:st,ttype:CONST}}function parseSexpr(str){var symbol,node,result,result2,i,st,newFrag=document.createDocumentFragment();symbol=getSymbol(str);if(symbol===null||symbol.ttype==RIGHTBRACKET){return[null,str,null]}if(symbol.ttype==DEFINITION){str=symbol.output+strim(str,symbol.input.length);symbol=getSymbol(str);if(symbol===null||symbol.ttype==RIGHTBRACKET){return[null,str,null]}}str=strim(str,symbol.input.length);switch(symbol.ttype){case SPACE:node=createMmlNode(symbol.tag);node.setAttribute(symbol.atname,symbol.atval);return[node,str,symbol.tag];case UNDEROVER:return[createMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];case CONST:node=createMmlNode(symbol.tag,document.createTextNode(symbol.output));return[node,str,symbol.tag];case STRETCHY:node=createMmlNode(symbol.tag,document.createTextNode(symbol.output));if(symbol.input=="|"||symbol.input=="\\vert"||symbol.input=="\\|"||symbol.input=="\\Vert"){node.setAttribute("lspace","0em");node.setAttribute("rspace","0em")}node.setAttribute("maxsize",symbol.atval);if(symbol.rtag!==null){return[node,str,symbol.rtag]}else{return[node,str,symbol.tag]}break;case BIG:var atval=symbol.atval;symbol=getSymbol(str);if(symbol===null){return[null,str,null]}str=strim(str,symbol.input.length);node=createMmlNode(symbol.tag,document.createTextNode(symbol.output));node.setAttribute("minsize",atval);node.setAttribute("maxsize",atval);return[node,str,symbol.tag];case LEFTBRACKET:if(symbol.input=="\\left"){symbol=getSymbol(str);if(symbol!==null){if(symbol.input=="."){symbol.invisible=true}str=strim(str,symbol.input.length)}}result=parseExpr(str,true,false);if(symbol===null||(typeof symbol.invisible=="boolean"&&symbol.invisible)){node=createMmlNode("mrow",result[0])}else{node=createMmlNode("mo",document.createTextNode(symbol.output));node=createMmlNode("mrow",node);node.appendChild(result[0])}return[node,result[1],result[2]];case MATRIX:if(symbol.input=="\\begin{array}"){var mask="";symbol=getSymbol(str);str=$.trim(str);if(symbol===null){mask="l"}else{str=strim(str,symbol.input.length);if(symbol.input!="{"){mask="l"}else{do{symbol=getSymbol(str);if(symbol!==null){str=strim(str,symbol.input.length);if(symbol.input!="}"){mask=mask+symbol.input}}}while(symbol!==null&&symbol.input!==""&&symbol.input!="}")}}result=parseExpr("{"+str,true,true);node=createMmlNode("mtable",result[0]);mask=mask.replace(/l/g,"left ");mask=mask.replace(/r/g,"right ");mask=mask.replace(/c/g,"center ");node.setAttribute("columnalign",mask);node.setAttribute("displaystyle","false");return[node,result[1],null]}else{result=parseExpr("{"+str,true,true);node=createMmlNode("mtable",result[0]);node.setAttribute("columnspacing","0.167em");node.setAttribute("columnalign","right center left");node.setAttribute("displaystyle","true");node=createMmlNode("mrow",node);return[node,result[1],null]}break;case TEXT:if(str.charAt(0)=="{"){i=str.indexOf("}")}else{i=0}if(i==-1){i=str.length}st=str.slice(1,i);newFrag.appendChild(createMmlNode(symbol.tag,document.createTextNode(st)));str=strim(str,i+1);return[createMmlNode("mrow",newFrag),str,null];case UNARY:result=parseSexpr(str);if(result[0]===null){return[createMmlNode(symbol.tag,document.createTextNode(symbol.output)),str]}if(typeof symbol.func=="boolean"&&symbol.func){st=str.charAt(0);if(st=="^"||st=="_"||st==","){return[createMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag]}else{node=createMmlNode("mrow",createMmlNode(symbol.tag,document.createTextNode(symbol.output)));node.appendChild(result[0]);return[node,result[1],symbol.tag]}}if(symbol.input=="\\sqrt"){return[createMmlNode(symbol.tag,result[0]),result[1],symbol.tag]}else{if(typeof symbol.acc=="boolean"&&symbol.acc){node=createMmlNode(symbol.tag,result[0]);var output=symbol.output;var node1=createMmlNode("mo",document.createTextNode(output));if(symbol.input=="\\vec"||symbol.input=="\\check"){node1.setAttribute("maxsize","1.2")}if(symbol.input=="\\underbrace"||symbol.input=="\\underline"){node1.setAttribute("accentunder","true")}else{node1.setAttribute("accent","true")}node.appendChild(node1);if(symbol.input=="\\overbrace"||symbol.input=="\\underbrace"){node.ttype=UNDEROVER}return[node,result[1],symbol.tag]}else{if(typeof symbol.codes!="undefined"){for(i=0;i<result[0].childNodes.length;i++){if(result[0].childNodes[i].nodeName=="mi"||result[0].nodeName=="mi"){st=(result[0].nodeName=="mi"?result[0].firstChild.nodeValue:result[0].childNodes[i].firstChild.nodeValue);var newst=[];for(var j=0;j<st.length;j++){if(st.charCodeAt(j)>64&&st.charCodeAt(j)<91){newst=newst+symbol.codes[st.charCodeAt(j)-65]}else{if(st.charCodeAt(j)>96&&st.charCodeAt(j)<123){newst=newst+symbol.codes[st.charCodeAt(j)-71]}}}if(result[0].nodeName=="mi"){result[0]=createMmlNode("mo").appendChild(document.createTextNode(newst))}else{result[0].replaceChild(createMmlNode("mo").appendChild(document.createTextNode(newst)),result[0].childNodes[i])}}}}node=createMmlNode(symbol.tag,result[0]);node.setAttribute(symbol.atname,symbol.atval);if(symbol.input=="\\scriptstyle"||symbol.input=="\\scriptscriptstyle"){node.setAttribute("displaystyle","false")}return[node,result[1],symbol.tag]}}break;case BINARY:result=parseSexpr(str);if(result[0]===null){return[createMmlNode("mo",document.createTextNode(symbol.input)),str,null]}result2=parseSexpr(result[1]);if(result2[0]===null){return[createMmlNode("mo",document.createTextNode(symbol.input)),str,null]}if(symbol.input=="\\root"||symbol.input=="\\stackrel"){newFrag.appendChild(result2[0])}newFrag.appendChild(result[0]);if(symbol.input=="\\frac"){newFrag.appendChild(result2[0])}return[createMmlNode(symbol.tag,newFrag),result2[1],symbol.tag];case INFIX:str=strim(str,symbol.input.length);return[createMmlNode("mo",document.createTextNode(symbol.output)),str,symbol.tag];default:return[createMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag]}}function parseIexpr(str){var symbol,sym1,sym2,node,result,tag,underover;sym1=getSymbol(str);result=parseSexpr(str);node=result[0];str=result[1];tag=result[2];symbol=getSymbol(str);if(symbol.ttype==INFIX){str=strim(str,symbol.input.length);result=parseSexpr(str);if(result[0]===null){result[0]=createMmlNode("mo",document.createTextNode("\u25A1"))}str=result[1];tag=result[2];if(symbol.input=="_"||symbol.input=="^"){sym2=getSymbol(str);tag=null;underover=((sym1.ttype==UNDEROVER)||(node.ttype==UNDEROVER));if(symbol.input=="_"&&sym2.input=="^"){str=strim(str,sym2.input.length);var res2=parseSexpr(str);str=res2[1];tag=res2[2];node=createMmlNode((underover?"munderover":"msubsup"),node);node.appendChild(result[0]);node.appendChild(res2[0])}else{if(symbol.input=="_"){node=createMmlNode((underover?"munder":"msub"),node);node.appendChild(result[0])}else{node=createMmlNode((underover?"mover":"msup"),node);node.appendChild(result[0])}}node=createMmlNode("mrow",node)}else{node=createMmlNode(symbol.tag,node);if(symbol.input=="\\atop"||symbol.input=="\\choose"){node.setAttribute("linethickness","0ex")}node.appendChild(result[0]);if(symbol.input=="\\choose"){node=createMmlNode("mfenced",node)}}}return[node,str,tag]}function parseExpr(str,rightbracket,matrix){var symbol,node,result,i,tag,newFrag=document.createDocumentFragment();do{str=$.trim(str);result=parseIexpr(str);node=result[0];str=result[1];tag=result[2];symbol=getSymbol(str);if(node){if((tag=="mn"||tag=="mi")&&symbol!==null&&typeof symbol.func=="boolean"&&symbol.func){var space=createMmlNode("mspace");space.setAttribute("width","0.167em");node=createMmlNode("mrow",node);node.appendChild(space)}newFrag.appendChild(node)}}while((symbol.ttype!=RIGHTBRACKET)&&symbol!==null&&symbol.output!=="");tag=null;if(symbol.ttype==RIGHTBRACKET){if(symbol.input=="\\right"){str=strim(str,symbol.input.length);symbol=getSymbol(str);if(symbol!==null&&symbol.input=="."){symbol.invisible=true}if(symbol!==null){tag=symbol.rtag}}if(symbol!==null){str=strim(str,symbol.input.length)}var len=newFrag.childNodes.length;if(matrix&&len>0&&newFrag.childNodes[len-1].nodeName=="mrow"&&len>1&&newFrag.childNodes[len-2].nodeName=="mo"&&newFrag.childNodes[len-2].firstChild.nodeValue=="&"){var pos=[];var m=newFrag.childNodes.length;for(i=0;matrix&&i<m;i=i+2){pos[i]=[];node=newFrag.childNodes[i];for(var j=0;j<node.childNodes.length;j++){if(node.childNodes[j].firstChild&&node.childNodes[j].firstChild.nodeValue=="&"){pos[i][pos[i].length]=j}}}var row,frag,n,k,table=document.createDocumentFragment();for(i=0;i<m;i=i+2){row=document.createDocumentFragment();frag=document.createDocumentFragment();node=newFrag.firstChild;n=node.childNodes.length;k=0;for(j=0;j<n;j++){if(typeof pos[i][k]!="undefined"&&j==pos[i][k]){node.removeChild(node.firstChild);row.appendChild(createMmlNode("mtd",frag));k++}else{frag.appendChild(node.firstChild)}}row.appendChild(createMmlNode("mtd",frag));if(newFrag.childNodes.length>2){newFrag.removeChild(newFrag.firstChild);newFrag.removeChild(newFrag.firstChild)}table.appendChild(createMmlNode("mtr",row))}return[table,str]}if(typeof symbol.invisible!="boolean"||!symbol.invisible){node=createMmlNode("mo",document.createTextNode(symbol.output));newFrag.appendChild(node)}}return[newFrag,str,tag]}function createMmlNode(t,frag){var node=document.createElementNS("http://www.w3.org/1998/Math/MathML",t);if(frag){$(node).append(frag)}return node}var SVG,canvas;var collection=[];function createSVGElement(elType){return document.createElementNS("http://www.w3.org/2000/svg",elType)}function getSVGElement(id,el){var res={node:null,newEl:false};if(id){id=SVG.id+"_"+id;res.node=$("#"+id)[0]}if(!res.node){res.node=createSVGElement(el);if(id){res.node.id=id}res.newEl=true}return res}function openGroup(id,clear){var newEl=getSVGElement(id,"g");appendSVG(newEl);canvas=$("#"+SVG.id+"_"+id)[0];if(clear){$(canvas).empty()}}function closeGroup(){canvas=$("#"+SVG.id+"_Canvas")[0]}function appendSVG(elmt){if(elmt.newEl){$(canvas).append(elmt.node)}}function addButton(parent,text,title,func,id){var node=createElementXHTML("span");node.className="svgButton";node.title=title;node.onclick=func;if(id){node.id=id}$(node).append(text);$(node).css({paddingRight:"0.5em",paddingLeft:"0.5em",fontSize:"1em",fontFamily:"monospace",background:"blue",color:"yellow",cursor:"pointer"});$(node).mouseover(function(){$(this).css({background:"yellow",color:"blue"})});$(node).mouseout(function(){$(this).css({background:"blue",color:"yellow"})});$(parent).append(node);return parent}function pictureAttributes(){this.id=null;this.stroke="blue";this.strokewidth=1;this.strokeopacity=1;this.strokedasharray="none";this.fill="none";this.fillopacity=1;this.fixed=false;this.fontstyle="normal";this.fontfamily="serif";this.fontweight="normal";this.fontsize=12;this.fontstroke="none";this.fontstrokewidth=1;this.fontstrokeopacity=1;this.fontstrokedasharray="none";this.fontfill="black";this.fontfillopacity=1;this.sector=false;this.largearc=0;this.marker="o";this.orient="auto";this.size=8;this.units="userSpaceOnUse";this.markerstroke="blue";this.markerstrokewidth=1;this.markerstrokeopacity=1;this.markerstrokedasharray="none";this.markerfill="none";this.markerfillopacity=1;this.sweep=0;this.rx=0;this.ry=0;this.closed=false;this.curve="";this.direction=[1,0];this.ticklabels="";this.pos="";this.points=200;this.backgroundcolor="none";this.backgroundopacity=1}function pictureObject(){this.id=null;this.src="";this.width=320;this.height=null;this.factor=1;this.xmin=-5;this.xmax=5;this.ymin=null;this.ymax=null;this.xunitlength=null;this.yunitlength=null;this.origin=[0,0];this.mouse=[null,null];this.coords="cartesian";this.drag=null;this.pan=true;this.locked=false;this.attr=new pictureAttributes()}function drawPicture(){$(canvas).empty();$("#"+SVG.id+" .svgMarker").remove();SVG.attr=new pictureAttributes();try{this.code=function(){with(Math){eval(SVG.src)}}();this.code=null}catch(err){var errstr;if(typeof err=="object"){errstr=err.name+" "+err.message+" "+err.number+" "+err.description}else{errstr=err}alert(errstr+"\n"+SVG.src)}collection[SVG.id]=SVG}function setOptions(atr){for(var i in atr){SVG.attr[i]=atr[i]}}function getOptions(attr,options,prefix){var pref=prefix||"";if(typeof attr=="string"){return(options[pref+attr]==undefined?SVG.attr[pref+attr]:options[pref+attr])}else{var i,newAttr={},len=attr.length,item;for(i=0;i<len;i++){item=attr[i];newAttr[item]=options[pref+item]==undefined?SVG.attr[pref+item]:options[pref+item]}return newAttr}}function setAction(evt,fn,id){if(!$.isFunction(fn)){return}var node=id?$("#"+SVG.id+"_"+id):$("#"+SVG.id);$(node).bind(evt,fn)}function getAngle(p){p=p||[0,0];var res=Math.atan2(SVG.mouse[1]-p[1],SVG.mouse[0]-p[0]);res=(res<0)?res+2*Math.PI:res;return res}function getDistance(p){p=p||[0,0];return Math.sqrt(Math.pow(SVG.mouse[0]-p[0],2)+Math.pow(SVG.mouse[1]-p[1],2))}function updateButton(){var obj=$("#SVGtoolbar #SVGupdateButton");if(obj.text()=="Edit"){obj.text("Update");obj.attr("title","Update picture");$("#SVGsrc").val(SVG.src).css("display","block")}else{SVG.src=$("#SVGsrc").val();drawPicture()}}function closeEditor(){$("#SVGtoolbar").slideUp();$("#SVGsrc").val("");SVG.locked=false}function switchTo(evt){var name=evt.currentTarget.id;if(SVG.id==name||SVG.locked){return false}SVG=collection[name];canvas=$("#"+SVG.id+"_Canvas")[0];return false}function onWheel(evt){if(SVG.locked){return false}evt=evt||window.event;var factor=1;evt.preventDefault();evt.stopPropagation();if(evt.wheelDelta){factor=(evt.wheelDelta>0)?0.8:1.25}else{if(evt.detail){factor=(evt.detail<0)?0.8:1.25}}if(evt.altKey){resize(factor)}else{zoom(factor)}return false}function onClick(evt){if(SVG.locked){return false}if(evt.button===0){if(evt.shiftKey){$("#SVGtoolbar #SVGupdateButton").text("Update");$("#SVGsrc").val(SVG.src);$("#SVGtoolbar").css({top:evt.pageY,left:evt.pageX}).slideDown();SVG.locked=true;evt.stopImmediatePropagation()}else{if(SVG.pan){SVG.drag=[evt.clientX,evt.clientY];document.body.style.cursor="move"}}}return false}function onDrop(evt){if(SVG.drag==null){return false}document.body.style.cursor="default";var xlen=(SVG.drag[0]-evt.clientX)/SVG.xunitlength;var ylen=(-SVG.drag[1]+evt.clientY)/SVG.yunitlength;SVG.drag=null;if(xlen!=0||ylen!=0){setScales([SVG.xmin+xlen,SVG.xmax+xlen,SVG.ymin+ylen,SVG.ymax+ylen])}return false}function setScales(scales){if(scales){SVG.xmin=scales[0];SVG.xmax=scales[1];SVG.ymin=scales[2];SVG.ymax=scales[3]}SVG.xunitlength=SVG.width/(SVG.xmax-SVG.xmin);SVG.yunitlength=SVG.height/(SVG.ymax-SVG.ymin);SVG.origin=[-SVG.xmin*SVG.xunitlength,-SVG.ymin*SVG.yunitlength];drawPicture()}function getScales(scales){scales=scales||[];var res=[null,null,null,null,0];if(scales.length==0){res[0]=SVG.xmin;res[1]=SVG.xmax}if(scales.length>1){if(typeof scales[0]=="number"&&typeof scales[1]=="number"&&scales[1]>scales[0]){res[0]=scales[0];res[1]=scales[1];res[4]=4}else{res[0]=SVG.xmin;res[1]=SVG.xmax}}if(scales.length==4){if(typeof scales[2]=="number"&&typeof scales[3]=="number"&&scales[3]>scales[2]){res[2]=scales[2];res[3]=scales[3];res[4]+=8}}return res}function resize(factor){SVG.factor=(SVG.factor*factor).toFixed(3);SVG.width/=factor;SVG.height/=factor;var picture=$("#"+SVG.id);picture.attr("width",SVG.width);picture.attr("height",SVG.height);var parent=picture[0].parentNode;if(parent.nodeName=="DIV"){parent.style.width=SVG.width+"px";parent.style.height=SVG.height+"px"}var node=$("#"+SVG.id+"ClipPath")[0].firstChild;$(node).attr("d","M0,0 "+SVG.width+",0 "+SVG.width+","+SVG.height+" 0,"+SVG.height);setScales()}function zoom(factor,center){var px,py;if(center){px=(SVG.xmax+SVG.xmin)*0.5;py=(SVG.ymax+SVG.ymin)*0.5}else{px=SVG.mouse[0];py=SVG.mouse[1]}SVG.factor=(SVG.factor*factor).toFixed(3);var dx=(SVG.xmax-SVG.xmin)*factor;var dy=(SVG.ymax-SVG.ymin)*factor;var xmin=(1-factor)*px+factor*SVG.xmin;var ymin=(1-factor)*py+factor*SVG.ymin;setScales([xmin,xmin+dx,ymin,ymin+dy])}function updateCartesianCoord(){if(!SVG.locked){$("#"+SVG.id+"_Coords").text("("+SVG.mouse[0].toFixed(2)+", "+SVG.mouse[1].toFixed(2)+")")}return false}function updatePolarCoord(){if(!SVG.locked){$("#"+SVG.id+"_Coords").text("("+getDistance().toFixed(2)+", "+getAngle().toFixed(2)+")")}return false}function updatePosition(evt){var off=$(evt.currentTarget.parentNode).offset();SVG.mouse[0]=(evt.pageX-off.left-SVG.origin[0])/SVG.xunitlength;SVG.mouse[1]=(SVG.height-SVG.origin[1]-evt.pageY+off.top)/SVG.yunitlength;return false}function removeCoord(){$("#"+SVG.id+"_Coords").text("");return false}function tracker(pos,options){options=options||{};var coords=options.coords||SVG.coords;var func=(coords=="polar")?updatePolarCoord:updateCartesianCoord;options.id="Coords";options.fixed=true;text(pos,"",options);setAction("mousemove",func);setAction("mouseout",removeCoord)}function exportSVG(){var svg="<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n";svg+=$("#"+SVG.id).parent().html();svg=svg.replace(/&nbsp;/g,"");svg=svg.replace(/><(?!\/)/g,">\n<");$("#SVGtoolbar #SVGupdateButton").text("Edit").attr("title","Edit script");$("#SVGsrc").val(svg).css("display","block")}function toSVG(p){var x=p[0]*SVG.xunitlength+SVG.origin[0];var y=SVG.height-p[1]*SVG.yunitlength-SVG.origin[1];return[x,y]}function toSVGPair(p){var q=toSVG(p);return q[0]+" "+q[1]}function setStrokeAndFill(node,options,prefix){var attributes=["stroke","strokewidth","strokedasharray","strokeopacity","fill","fillopacity"];var attr=getOptions(attributes,options,prefix);var elem=$(node);elem.attr("stroke",attr.stroke);elem.attr("stroke-width",attr.strokewidth/SVG.factor);elem.attr("stroke-dasharray",attr.strokedasharray);elem.attr("stroke-opacity",attr.strokeopacity);elem.attr("fill",attr.fill);elem.attr("fill-opacity",attr.fillopacity)}function button(p,q,txt,action,options){options=options||{};options.id=(options.id||Math.randomString(8));rect(p,q,options);setAction("click",action,options.id);options.fill=null;options.fillopacity=1;options.id+="_t";text([(p[0]+q[0])*0.5,(p[1]+q[1])*0.5],txt,options);setAction("click",action,options.id)}function setMarkers(obj,options){var markerChars="o*sSx+<>|";var attributes=["marker","size","units","orient","markerstroke","markerstrokewidth","markerstrokeopacity"];var attr=getOptions(attributes,options);var node,node2,i,id,pos=["marker-start","marker-mid","marker-end"];var lim=attr.marker.length;for(i=0;i<lim;i++){var type=attr.marker.charAt(i);if(type=="-"||markerChars.indexOf(type)<0){continue}id=(options.id||Math.randomString(8))+"Marker_"+markerChars.indexOf(type);node=$("#"+SVG.id+"_"+id);if(node.length===0){node=$(getSVGElement(id,"marker").node);node.attr("class","svgMarker");node.attr("viewBox","0 0 10 10");node.attr("refX",5);node.attr("refY",5);node.attr("orient",attr.orient);node.attr("markerUnits",attr.units);switch(type){case"*":case"o":node2=$(createSVGElement("circle"));node2.attr("cx",5);node2.attr("cy",5);node2.attr("r",4);break;case">":node2=$(createSVGElement("path"));node2.attr("d","M0 0 L10 5 L0 10 z");node.attr("refX",10);break;case"<":node2=$(createSVGElement("path"));node2.attr("d","M10 0 L10 10 L0 5 z");node.attr("refX",0);break;case"x":node2=$(createSVGElement("path"));node2.attr("d","M0 0 L10 10 M0 10 L10 0");break;case"+":node2=$(createSVGElement("path"));node2.attr("d","M5 0 L5 10 M0 5 L10 5");break;case"|":node2=$(createSVGElement("path"));node2.attr("d","M5 0 L5 10");break;case"S":case"s":node2=$(createSVGElement("rect"));node2.attr("x",0);node2.attr("y",0);node2.attr("width",10);node2.attr("height",10)}setStrokeAndFill(node2,options,"marker");node2.attr("stroke-width",attr.markerstrokewidth);if("*<>S".indexOf(type)>-1){node2.attr("fill",attr.markerstroke);node2.attr("fill-opacity",attr.markerstrokeopacity)}node.append(node2);$("#"+SVG.id+"_Defs").append(node)}node.attr("markerWidth",attr.size/SVG.factor);node.attr("markerHeight",attr.size/SVG.factor);$(obj).attr(pos[i],"url(#"+SVG.id+"_"+id+")")}}function setLabels(p,options){var i,point=[0,0],pos;var label=(typeof options.label=="string")?[options.label]:options.label;var labelpos=getOptions("pos",options);labelpos=(typeof labelpos=="string")?[labelpos]:labelpos;var poslen=labelpos.length;var size=options.size||SVG.attr.size;var dx=(0.5*size/SVG.xunitlength)/SVG.factor;var dy=(0.5*size/SVG.yunitlength)/SVG.factor;for(i=0;i<label.length;i++){options.isLabel="_label"+i;point[0]=p[i][0];point[1]=p[i][1];pos=(poslen>i)?labelpos[i].toUpperCase():pos;if(/E/.test(pos)){point[0]+=dx}if(/W/.test(pos)){point[0]-=dx}if(/N/.test(pos)){point[1]+=dy}if(/S/.test(pos)){point[1]-=dy}options.pos=pos;text(point,label[i],options)}}function line(p,q,options){options=options||{};options.closed=false;options.curve="";path([p,q],options)}function dot(p,options){options=options||{};var direction=getOptions("direction",options);var q=[p[0]+direction[0]/SVG.xunitlength,p[1]+direction[1]/SVG.yunitlength];var st="M"+toSVGPair(p)+" "+toSVGPair(q);var elmt=getSVGElement(options.id,"path");var elem=$(elmt.node);elem.attr("d",st);elem.attr("stroke","none");setMarkers(elem,options);appendSVG(elmt);if(options.label){setLabels([p],options)}}function path(list,options,append){options=options||{};var i,elmt=getSVGElement(options.id,"path");var attr=getOptions(["curve","closed"],options);var len=list.length;if(len>0){var node=$(elmt.node);var st=(append&&!elmt.newEl)?elmt.node.getAttribute("d"):"";st+="M"+toSVGPair(list[0])+" "+attr.curve;for(i=1;i<len;i++){st+=toSVGPair(list[i])+" "}if(attr.closed){st+="Z"}node.attr("d",st);setStrokeAndFill(node,options);if(options.marker){setMarkers(node,options)}appendSVG(elmt);if(options.label){setLabels(list,options)}}}function rotate(id,angle,options){if(!id||!angle){return}var node=$("#"+SVG.id+"_"+id)[0];if(node){options=options||{};var center=options.center?toSVG(options.center):SVG.origin;angle=-angle*180/Math.PI;var transform=node.getAttribute("transform")||"";transform="rotate("+angle+" "+center+") "+(options.replace?"":transform);$(node).attr("transform",transform)}}function translate(id,delta,options){if(!id||!delta){return}var node=$("#"+SVG.id+"_"+id)[0];if(node){options=options||{};delta=toSVG(delta);var transform=node.getAttribute("transform")||"";transform="translate("+(delta[0]-SVG.origin[0])+"  "+(SVG.origin[1]+delta[1]-SVG.height)+") "+(options.replace?"":transform);$(node).attr("transform",transform)}}function curve(list,options){options=options||{};options.curve=options.curve||"T";path(list,options)}function circle(center,radius,options){ellipse(center,radius,radius,options)}function loop(p,options){options=options||{};var d=options.direction||[1,0];options.curve="C";options.closed=false;path([p,[p[0]+d[0],p[1]+d[1]],[p[0]-d[1],p[1]+d[0]],p],options)}function arc(options){options=options||{};var start=options.start;var end=options.end;var center=options.center;var startangle=options.startangle;var endangle=options.endangle;var st="M",elmt=getSVGElement(options.id,"path");var attr=getOptions(["largearc","sweep","closed","sector"],options);var radius=options.radius;if(center!=null&&startangle!=null&&endangle!=null&&radius!=null){start=[radius*Math.cos(startangle)+center[0],radius*Math.sin(startangle)+center[1]];end=[radius*Math.cos(endangle)+center[0],radius*Math.sin(endangle)+center[1]]}if(start==null||end==null){return}if(!radius){var v=[end[0]-start[0],end[1]-start[1]];radius=Math.sqrt(v[0]*v[0]+v[1]*v[1])}if(attr.sector){st+=toSVGPair(center)+" "}st+=toSVGPair(start)+" A"+radius*SVG.xunitlength+","+radius*SVG.yunitlength+" 0 "+attr.largearc+","+attr.sweep+" "+toSVGPair(end);if(attr.sector||attr.closed){st+=" z"}var node=$(elmt.node);node.attr("d",st);setStrokeAndFill(node,options);if(options.marker){setMarkers(node,options)}appendSVG(elmt);if(options.label){setLabels([start,end],options)}}function sector(options){if(!options.center||!options.startangle||!options.endangle||!options.radius){return}options.sector=true;arc(options)}function ellipse(center,rx,ry,options){options=options||{};var elmt=getSVGElement(options.id,"ellipse");center=toSVG(center);var node=$(elmt.node);node.attr("cx",center[0]);node.attr("cy",center[1]);node.attr("rx",rx*SVG.xunitlength);node.attr("ry",ry*SVG.yunitlength);setStrokeAndFill(node,options);appendSVG(elmt)}function polygon(list,options){options=options||{};options.closed=true;path(list,options)}function rect(p,q,options){options=options||{};var elmt=getSVGElement(options.id,"rect");var attr=getOptions(["rx","ry"],options);var node=$(elmt.node);node.attr("x",toSVG(p)[0]);node.attr("y",toSVG(q)[1]);node.attr("width",(q[0]-p[0])*SVG.xunitlength);node.attr("height",(q[1]-p[1])*SVG.yunitlength);node.attr("rx",attr.rx*SVG.xunitlength);node.attr("ry",attr.ry*SVG.yunitlength);setStrokeAndFill(node,options);appendSVG(elmt)}function text(p,st,options){options=options||{};var id=options.id;var attr=getOptions(["fontstyle","fontfamily","fontweight","fontfill","fontsize","fixed","pos"],options);if(id&&options.isLabel){id+=options.isLabel}var pos=attr.pos.toUpperCase();if(!attr.fixed){attr.fontsize/=SVG.factor}var elem,node,dx,dy,latex=false,str=$.trim(st.toString()),q=toSVG(p);if(str.charAt(0)=="$"){str=str.substr(1,str.length-2);latex=true}if(latex){if(p[0]>SVG.xmax||p[0]<SVG.xmin||p[1]>SVG.ymax||p[1]<SVG.ymin){return}node=createElementXHTML("div");node.style.position="absolute";node.style.left="-1000px";node.style.top="-1000px";$("body").append(node);var math=MSVG.parseMath(str,true,attr.fontsize+"px",attr.fontfill);var mathNode=$(node);mathNode.append($(math).clone());dx=-node.offsetWidth/2;dy=-node.offsetHeight/2;if(/N/.test(pos)){dy=-node.offsetHeight}if(/S/.test(pos)){dy=0}if(/E/.test(pos)){dx=0}if(/W/.test(pos)){dx=-node.offsetWidth}var width=mathNode.width(),height=mathNode.height();mathNode.remove();q[0]+=dx;q[1]+=dy;var elmt=getSVGElement(id,"foreignObject");elem=$(elmt.node);elem.empty().append(math);elem.attr("width",width);elem.attr("height",height)}else{var baseline="middle",textanchor="middle";if(/E/.test(pos)){textanchor="start"}if(/W/.test(pos)){textanchor="end"}if(/N/.test(pos)){baseline="text-after-edge"}if(/S/.test(pos)){baseline="text-before-edge"}var elmt=getSVGElement(id,"text");elem=$(elmt.node);elem.empty().text(str);elem.attr("font-style",attr.fontstyle);elem.attr("font-family",attr.fontfamily);elem.attr("font-weight",attr.fontweight);elem.attr("font-size",attr.fontsize);elem.attr("text-anchor",textanchor);elem.attr("dominant-baseline",baseline);setStrokeAndFill(elem,options,"font")}elem.attr("x",q[0]);elem.attr("y",q[1]);appendSVG(elmt)}function image(url,options){options=options||{};var elmt=getSVGElement(options.id,"image");var elem=$(elmt.node);var height=options.height?options.height/SVG.factor:SVG.height;var width=options.width?options.width/SVG.factor:SVG.width;var origin=toSVG(options.origin||[SVG.xmin,SVG.ymin]);var pos=(options.pos||"").toUpperCase();var x=origin[0]-width*0.5;var y=origin[1]-height*0.5;if(/N/.test(pos)){y-=height*0.5}if(/S/.test(pos)){y+=height*0.5}if(/E/.test(pos)){x+=width*0.5}if(/W/.test(pos)){x-=width*0.5}elem.attr("x",x);elem.attr("y",y);elem.attr("width",width);elem.attr("height",height);elem.attr("preserveAspectRatio","none");elmt.node.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",url);appendSVG(elmt)}function grid(options){options=options||{};var dx,dy,x,y,k;var orig=options.origin||[0,0];var id=options.id||"Grid";options.stroke=options.stroke||"grey";options.strokewidth=(options.strokewidth||SVG.attr.strokewidth*0.5);var coords=options.coords||SVG.coords;var lim=getScales(options.scales);openGroup(id,true);lim[2]=(typeof lim[2]=="number")?lim[2]:SVG.ymin;lim[3]=(typeof lim[3]=="number")?lim[3]:SVG.ymax;if(coords=="polar"){dx=options.dx||1;dy=options.dy||3;var limit=Math.max(Math.abs(lim[0]),Math.abs(lim[1]),Math.abs(lim[2]),Math.abs(lim[3]));for(x=dx;x<limit;x+=dx){circle(orig,x,options)}if(dy>1){for(y=1;y<dy;y++){k=Math.tan(y*Math.PI/(2*dy));line([lim[0],(lim[0]-orig[0])*k+orig[1]],[SVG.xmax,(lim[1]-orig[0])*k+orig[1]],options);line([lim[0],-(lim[0]-orig[0])*k+orig[1]],[SVG.xmax,-(lim[1]-orig[0])*k+orig[1]],options)}}}else{dx=options.dx||1;dy=options.dy||dx;for(x=orig[0];x<SVG.xmax;x+=dx){if(x>lim[0]&&x<lim[1]){line([x,lim[2]],[x,lim[3]],options)}}for(x=orig[0]-dx;x>SVG.xmin;x-=dx){if(x>lim[0]&&x<lim[1]){line([x,lim[2]],[x,lim[3]],options)}}for(y=orig[1];y<SVG.ymax;y+=dy){if(y>lim[2]&&y<lim[3]){line([lim[0],y],[lim[1],y],options)}}for(y=orig[1]-dy;y>SVG.ymin;y-=dy){if(y>lim[2]&&y<lim[3]){line([lim[0],y],[lim[1],y],options)}}}closeGroup()}function axes(options){options=options||{};options.marker="-|"+(options.marker?options.marker.charAt(0):"-");var i,x,y,start,stop,label;var dx=options.dx||1;var dy=options.dy||dx;var id=options.id||"Axes";var fontsize=getOptions("fontsize",options);var coords=options.coords||SVG.coords;var orig=(coords=="polar")?[0,0]:(options.origin||[0,0]);var ddx=options.decx||Math.max(0,-Math.floor(Math.log(dx)/Math.log(10)));var ddy=options.decy||Math.max(0,-Math.floor(Math.log(dy)/Math.log(10)));options.stroke=options.stroke||"black";options.strokewidth=(options.strokewidth||SVG.attr.strokewidth*0.5);options.markerstroke=options.stroke;options.markerstrokewidth=options.strokewidth;openGroup(id,true);var lim=getScales(options.scales);lim[2]=lim[2]||SVG.ymin;lim[3]=lim[3]||SVG.ymax;if($.isArray(options.xticks)){var xticks=options.xticks.sort();var list2=[[lim[0],orig[1]]];label=[""];for(i=0;i<xticks.length;i++){list2.push([xticks[i],orig[1]]);label.push(String(xticks[i].toFixed(ddx)))}list2.push([lim[1],orig[1]]);label.push("")}else{var list1=[],label1=[];var list2=[],label2=[];start=SVG.xmin+0.25*dx;stop=SVG.xmax-0.25*dx;i=1;var cand,leftExit=0,rightExit=0;while(leftExit*rightExit==0){cand=orig[0]+i*dx;if(cand>start){if(cand<stop){list1.push([cand,orig[1]]);label1.push(String(cand.toFixed(ddx)))}else{rightExit=1}}cand=orig[0]-i*dx;if(cand<stop){if(cand>start){list2.push([cand,orig[1]]);label=(coords=="polar")?"":cand.toFixed(ddx);label2.push(String(label))}else{leftExit=1}}i++}list1.push([lim[1],orig[1]]);label1.push("");list2.push([lim[0],orig[1]]);label2.push("");list2.reverse();list2=list2.concat(list1);label2.reverse();label=label2.concat(label1)}if(options.ticklabels!=false){options.label=label;options.pos="S"}path(list2,options);if($.isArray(options.yticks)){var yticks=options.yticks.sort();var list2=[[orig[0],lim[2]]];label=[""];for(i=0;i<yticks.length;i++){list2.push([orig[0],yticks[i]]);label.push(String(yticks[i].toFixed(ddy)))}list2.push([orig[0],lim[3]]);label.push("")}else{list1=[],label1=[];list2=[];label2=[];start=SVG.ymin+0.25*dy;stop=SVG.ymax-0.25*dy;i=1;leftExit=0;rightExit=0;while(leftExit*rightExit==0){cand=orig[1]+i*dy;if(cand>start){if(cand<stop){list1.push([orig[0],cand]);label1.push(String(cand.toFixed(ddy)))}else{rightExit=1}}cand=orig[1]-i*dy;if(cand<stop){if(cand>start){list2.push([orig[0],cand]);label=(coords=="polar")?"":cand.toFixed(ddy);label2.push(String(label))}else{leftExit=1}}i++}list1.push([orig[0],lim[3]]);label1.push("");list2.push([orig[0],lim[2]]);label2.push("");list2.reverse();list2=list2.concat(list1);label2.reverse();label=label2.concat(label1)}if(options.ticklabels!=false){options.label=label;options.pos="W"}options.stroke=options.markerstroke;path(list2,options);closeGroup()}function list(fun,tmin,tmax,options){var inc=(tmax-tmin)/getOptions("points",options);if(inc<=0||fun.length==0){return}var t,pth,g=[],xt,yt;for(t=1;t>=0;t--){if($.isFunction(fun[t])){g[t]=fun[t]}else{if(typeof fun[t]=="string"){with(Math){eval("g["+t+"] = function(x){return "+fun[t]+"}")}}else{return}}}if(g.length<2){return}pth=[];for(t=tmin;t<=tmax;t+=inc){xt=g[0](t);yt=g[1](t);if(isFinite(xt)&&isFinite(yt)){pth[pth.length]=[xt,yt]}}return pth}function plot(fun,options){options=options||{};var append,pth,steps=options.steps||[];var n_steps=steps.length;options.closed=false;options.curve="";var xmin=(options.min==null)?SVG.xmin:Math.max(SVG.xmin,options.min);var xmax=(options.max==null)?SVG.xmax:Math.min(SVG.xmax,options.max);if(n_steps===0){pth=list(["x",fun],xmin,xmax,options);if(pth){path(pth,options)}}else{options.id=options.id||Math.randomString(6);steps.sort();var steps_a=[];steps_a.push(xmin);for(i=0;i<n_steps;i++){if(steps[i]>xmin&&steps[i]<xmax){steps_a.push(steps[i])}}steps_a.push(xmax);n_steps=steps_a.length-1;for(i=0;i<n_steps;i++){xmax=steps_a[i+1];xmin=steps_a[i];pth=list(["x",fun],xmin,xmax,options);append=(i>0);if(pth){path(pth,options,append)}}}}function area(fun1,fun2,options){options=options||{};options.curve="";options.closed=true;var xmin=(options.min==null)?SVG.xmin:options.min;var xmax=(options.max==null)?SVG.xmax:options.max;var pth1=list(["x",fun1],xmin,xmax,options);var pth2=list(["x",fun2],xmin,xmax,options);if(pth1&&pth2){pth1=pth1.concat(pth2.reverse());path(pth1,options)}}function polarPlot(fun,options){var g1,g2;if(typeof fun=="string"){with(Math){eval("g1 = function(x){return ("+fun+")*cos(x)}");eval("g2 = function(x){return ("+fun+")*sin(x)}")}}else{if($.isFunction(fun)){with(Math){eval("g1 = function(x){return fun(x)*cos(x)}");eval("g2 = function(x){return fun(x)*sin(x)}")}}}parametricPlot(g1,g2,options)}function parametricPlot(fun1,fun2,options){options=options||{};options.closed=false;options.curve="";var xmin=(options.min==null)?0:options.min;var xmax=(options.max==null)?2*Math.PI:options.max;var pth=list([fun1,fun2],xmin,xmax,options);if(pth){path(pth,options)}}function slopeField(fun,options){options=options||{};var g=fun;if(typeof fun=="string"){with(Math){eval("g = function(x,y){return "+fun+"}")}}var gxy,x,y,u,v,dz;var dx=(options.dx==null)?1:options.dx;var dy=(options.dy==null)?1:options.dy;dz=Math.sqrt(dx*dx+dy*dy)/6;var xmin=Math.ceil(SVG.xmin/dx);var ymin=Math.ceil(SVG.ymin/dy);for(x=xmin;x<=SVG.xmax;x+=dx){for(y=ymin;y<=SVG.ymax;y+=dy){gxy=g(x,y);if(!isNaN(gxy)){if(Math.abs(gxy)=="Infinity"){u=0;v=dz}else{u=dz/Math.sqrt(1+gxy*gxy);v=gxy*u}line([x-u,y-v],[x+u,y+v],options)}}}}return{showFormulaOnMouseOver:false,latexImages:false,latexConverter:"http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=",mathColor:"",mathFontSize:"",mathFontFamily:"",define:function(oldstr,newstr){if(MSVG.latexImages){return}if((typeof oldstr)=="string"){oldstr=[oldstr];newstr=[newstr]}var i,len=oldstr.length;if(len!=newstr.length){return}for(i=0;i<len;i++){symbols=symbols.concat([{input:"\\"+oldstr[i],tag:"mo",output:newstr[i],ttype:DEFINITION}])}refreshSymbols()},parseMath:function(str,displaystyle,size,color){if(str===null){return null}var frag=parseExpr(str.replace(/^\s+/g,""),false,false)[0];var node=createMmlNode("mstyle",frag);if(displaystyle){$(node).attr({displaystyle:"true"})}$(node).attr({mathcolor:color||MSVG.mathColor,fontsize:size||MSVG.mathFontSize,fontfamily:MSVG.mathFontFamily});node=createMmlNode("math",node);if(MSVG.showFormulaOnMouseOver){$(node).attr({title:str.replace(/\s+/g," ")})}return node},parseMathExternal:function(str,displaystyle,size,color){if(str===null){return null}var node=createElementXHTML("img");var snip=MSVG.latexConverter+str;$(node).attr({src:snip});if(MSVG.showFormulaOnMouseOver){$(node).attr({title:str.replace(/\s+/g," ")})}return node},generic:function(){if(!$.browser.mozilla){MSVG.latexImages=true}if(MSVG.latexImages){MSVG.parseMath=MSVG.parseMathExternal}else{refreshSymbols()}if(!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")){MSVG.initPictures=MSVG.removePictures}},removePictures:function(obj){var pictures=obj?$(obj):$(".SVGgraph");$(pictures).each(function(){var that=$(this);this.id=null;that.empty();that.css({color:"red",background:"yellow"});that.text("Missing picture: your  browser does not support inline SVG");window.setTimeout(function(){that.remove()},10000)})},initPictures:function(obj){var options,scales,qnode,node,node2,status,offline,elem;var pictures=obj?$(obj):$(".SVGgraph");$(pictures).each(function(){var that=$(this);offline=!(this.nodeName=="SPAN");status=0;SVG=new pictureObject();options=$(this).attr("options");that.removeAttr("id");if(options){with(Math){eval("options={"+options+"}")}setOptions(options)}else{options={}}if(options.pan==false){SVG.pan=false}SVG.coords=options.coords||SVG.coords;SVG.src=$.trim($(this).text());that.empty();if(typeof options.width=="number"&&options.width>0){SVG.width=options.width;status+=1}if(typeof options.height=="number"&&options.height>0){SVG.height=options.height;status+=2}var scales=getScales(options.scales);SVG.xmin=scales[0];SVG.xmax=scales[1];SVG.ymin=scales[2];SVG.ymax=scales[3];status+=scales[4];SVG.height=options.height;if(status%4!=0){SVG.width=options.width}if(!SVG.width){SVG.width=1.6*SVG.height}else{if(!SVG.height){SVG.height=0.625*SVG.width}}if(status<8){SVG.ymax=0.5*SVG.height*(SVG.xmax-SVG.xmin)/SVG.width;SVG.ymin=-SVG.ymax}else{if(status<12){SVG.xmax=0.5*SVG.width*(SVG.ymax-SVG.ymin)/SVG.height;SVG.xmin=-SVG.xmax}}if(status==12||status==13){SVG.height=SVG.width*(SVG.ymax-SVG.ymin)/(SVG.xmax-SVG.xmin)}else{if(status==14){SVG.width=SVG.height*(SVG.xmax-SVG.xmin)/(SVG.ymax-SVG.ymin)}}SVG.id=Math.randomString(16);qnode=createSVGElement("svg");elem=$(qnode);qnode.id=SVG.id;elem.attr("xmlns","http://www.w3.org/2000/svg");elem.attr("xmlns:ev","http://www.w3.org/2001/xml-events");elem.attr("xmlns:xlink","http://www.w3.org/1999/xlink");elem.attr("version","1.1");elem.attr("baseProfile","full");if(options.border){elem.attr("style","border:"+options.border)}node=createSVGElement("clipPath");node.id=SVG.id+"ClipPath";node2=createSVGElement("path");$(node).append(node2);elem.attr("clip-path","url(#"+SVG.id+"ClipPath)");node2=createSVGElement("defs");node2.id=SVG.id+"_Defs";$(node2).append(node);$(qnode).append(node2);node=createSVGElement("rect");elem=$(node);elem.attr("x","0");elem.attr("y","0");elem.attr("width","100%");elem.attr("height","100%");elem.attr("fill","none");elem.attr("pointer-events","all");$(qnode).append(node);node2=createSVGElement("g");node2.id=SVG.id+"_Canvas";$(qnode).append(node2);that.append(qnode);this.style.position="relative";if(offline){setAction("mousemove",updatePosition);if(SVG.pan){setAction("mouseup",onDrop)}if(window.addEventListener){var evt=$.browser.mozilla?"DOMMouseScroll":"mousewheel";qnode.addEventListener(evt,onWheel,false)}}setAction("mousedown",onClick);setAction("mouseover",switchTo);canvas=$("#"+SVG.id+"_Canvas")[0];resize(1)});if(pictures.length>0&&$("#SVGtoolbar").length===0){node=createElementXHTML("span");node.id="SVGtoolbar";node.style.position="absolute";node.style.textAlign="left";node.style.zIndex=10;node=addButton(node,"X","Close editor",closeEditor);node=addButton(node,"Update","Update picture",updateButton,"SVGupdateButton");node=addButton(node,"SVG","View SVG code",exportSVG);node=addButton(node,"-","Zoom out",function(){zoom(1.25,true)});node=addButton(node,"+","Zoom in",function(){zoom(0.8,true)});node=addButton(node,"\u2191","Enlarge picture",function(){resize(0.8)});node=addButton(node,"\u2193","Reduce picture",function(){resize(1.25)});$(node).append("<br />");node2=createElementXHTML("textarea");$(node2).attr({id:"SVGsrc",rows:8,cols:60});$(node).append(node2);$(node).hide();$("body").append(node)}}}}(jQuery);
//}}}
/***
!~TiddlyWiki formatters
***/
//{{{
if(!version.extensions.MathSVGPlugin) { //# ensure that the plugin is only installed once
version.extensions.MathSVGPlugin = {installed: true};
MSVG.generic();

config.formatterHelpers.MathSVGHelper = function(w) {
  if(MSVG.noMathTag && jQuery.inArray(MSVG.noMathTag,w.tiddler.tags)>-1) return;
  this.lookaheadRegExp.lastIndex = w.matchStart;
  var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
  if(lookaheadMatch){
    var eq = MSVG.parseMath(lookaheadMatch[1],this.displaystyle);
    if(this.displaystyle){
      var node = createTiddlyElement(w.output,"div");
      node.style.textAlign='center';
      node.appendChild(eq);
      w.output.appendChild(node);
    } else {w.output.appendChild(eq);}
    w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
  }
}

/* I'm using jsMath LaTeX plugin, so disable LaTeX handling by SVGMath:

config.formatters.push( {
  name: "clatex",
  match: "\\$\\$",
  lookaheadRegExp: /\$\$((?:.|\n)*?)\$\$/mg,
  displaystyle: true,
  handler: config.formatterHelpers.MathSVGHelper
})

config.formatters.push( {
  name: "clatex2",
  match: "\\\\\\\[",
  lookaheadRegExp: /\\\[((?:.|\n)*?)\\\]/mg,
  displaystyle: true,
  handler: config.formatterHelpers.MathSVGHelper
})

config.formatters.push( {
  name: "latex",
  match: "\\$",
  lookaheadRegExp: /\$((?:.|\n)*?)\$/mg,
  displaystyle: false,
  handler: config.formatterHelpers.MathSVGHelper
})

config.formatters.push( {
  name: "latex2",
  match: "\\\\\\\(",
  lookaheadRegExp: /\\\(((?:.|\n)*?)\\\)/mg,
  displaystyle: false,
  handler: config.formatterHelpers.MathSVGHelper
})

*/

config.formatters.push( {
  name: "graph",
  match: "<div",
  lookaheadRegExp: /<div.+SVGgraph.+?>((?:.|\n)*?)<\/div>/mg,
  handler: function(w){
    if(MSVG.noSvgTag && jQuery.inArray(MSVG.noSvgTag,w.tiddler.tags)>-1) return;
    this.lookaheadRegExp.lastIndex = w.matchStart;
    var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
    if(lookaheadMatch){
      var text = lookaheadMatch[0].replace('<div','<div id="currentGraph"');
      jQuery(w.output).append(text);
      MSVG.initPictures("#currentGraph");
      w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
    }
  }
})

config.formatters.push( {
  name: "inlineGraph",
  match: "<span",
  lookaheadRegExp: /<span.+SVGgraph.+?>((?:.|\n)*?)<\/span>/mg,
  handler: function(w){
    if(MSVG.noSvgTag && jQuery.inArray(MSVG.noSvgTag,w.tiddler.tags)>-1) return;
    this.lookaheadRegExp.lastIndex = w.matchStart;
    var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
    if(lookaheadMatch){
      var text = lookaheadMatch[0].replace('<span','<span id="currentGraph"');
      jQuery(w.output).append(text);
      MSVG.initPictures("#currentGraph");
      w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
    }
  }
})

}
//}}}
/***
The script should not be edited. All available options can be set by the following variables:
***/
//{{{
//MSVG.showFormulaOnMouseOver = false; //show LaTeX code on mouse over the equation
//MSVG.latexImages = false; //set to true to force the use of an external converter
//MSVG.latexConverter = "http://www.yourequations.com/eq.latex?"; //link to external converter
//MSVG.mathColor = "green"; //font color
//MSVG.mathFontSize = ""; //font size
//MSVG.mathFontFamily = ""; //font family
MSVG.noMathTag = null;
MSVG.noSvgTag = 'noSVG';
//}}}
/***
New symbols or commands can be defined here:
***/
//{{{
 var commands = ["nle","R","diagup","varnothing","ind","DD"];
 var symbols = ["\u2270","\u211D","\u2571","\u2205","\u2AEB","\\frac{d}{dr}"];
 MSVG.define(commands,symbols);
//}}}
/***
External javascript code can be loaded here:
***/
//{{{
 jQuery.getScript("demo.js");
//}}}
!! Session 1: 2010-05-22
* [[Rényi Entropy]]
* Jaynes: Stat Mech and Theory of Information
* Tactical Asset Allocation (TAA)
* Leland 1985
* Merton Model of Risky Debt
! Types of Derivatives
!! Buy side:
# Bond future
# Currency FX forward
# Fixed-income call/put
# Equity call/put
# Index Future
# Interest Rate (IR) Future
# Asset swap
# Credit Default Swap (CDS)
# Cross-currency swap
# Index Swap
# Warrant

!!Energy Derivatives
# Spread Option
# Volumetric Option
# Average Options (asian): see Phenim Boyle, D. Emmanuel
# Path-dependent instrument
# Tolling Agreement  / Variable Annuity / Lease Agreement. MBS = Mortgage-Backed Security
# Swaption

!! Hedge Funds
# Digital Option
# Barrier Option
# Future/Forward
# Credit Derivatives
# Structure Products, CDOs

!Indexes
S&P 500
Russel 2000
DJIA
CPI
VIX (volatility index)
MSCI Morgan-Stanley: ACWI, Emergent Markets, EAFE

butterfly spread
Barclays ishares
information ratio

!Spread Options
* widely used in Energy markets, some fixed-income instruments depend on spread options
* also called real options
René Carmona, Valdo Durrleman "Pricing and Hedging Spread Options"

!Random Stuff

Let $Z=A\,W_t$ be a 2-dimensional stochastic process with $A := \pmatrix {\sqrt{ \frac{1+\rho}{2} } &\sqrt{ \frac{1-\rho}{2} } \\ \sqrt{ \frac{1+\rho}{2} } & -\sqrt{ \frac{1-\rho}{2} }  }$, where $\rho$ incremental coefficient. $A^TA=\pmatrix{1 & \rho \\ \rho & 1}$.

$Z_1(t)-Z_1(s), Z_2(t)-Z_2(s)$ variance $t-s$, covariance $\rho(t-s)$.
!! Question 2

Solve \[ y'+y=e^{-x}, \ y(0)=1. \] Use Euler's method on the interval $[0,1]$ with mesh size $h=\frac{1}{n}$ to obtain a recurrence relation for the numerical approximation to $y$. Solve this relation and obtain a numerical approximation to $y(1)$. Show that this approximation converges to the exact solution as $n\to\infty.$

!! Solution

Recall that \[ (1+h)^\frac{1}{h} = \frac{1}{e}(1+\frac{h}{2} + O(h^2)) \]

$ y=A e^{-x} $ is clearly the general form of a solution to the homogeneous problem $y'+y=0$, and $y=xe^{-x}$ is clearly a 'particular integral', hence the general solution is \[ 
 y = (x+A) e^{-x}, \] and the one satisfying the given initial condition corresponds to $A=1,$ i.e., $y=(x+1)e^{-x}.$

The Euler's approximation is
\[ y_{k+1} = y_k + y'_k h = y_k + h(e^{-kh}-y_k)=(1-h)y_k+he^{-kh} \]
!! Syllabus
Define $\mathcal{F}_{t^+} := \cap_{s\geq t} \mathcal{F}_s$ to be the field of events in the 'immediate future of $t$',
and $\mathcal{F}_{t^-} := \sigma(\cup_{s\leq t} \mathcal{F}_s)$ that of the 'immediate past of $t$'.
A filtration is right-continuous if $\mathcal{F}_t=\mathcal{F}_{t^+}$ and left-continuous if $\mathcal{F}_t=\mathcal{F}_{t^-}$.

In discrete time case $t\in\mathbb{N}$, we clearly have $\mathcal{F}_{t^+} = \mathcal{F}_{t+1}$, $\mathcal{F}_{t^-} = \mathcal{F}_{t-1}$
!Society of Actuaries' Financial Economics Segment Exam

!!! ~Put-Call Parity

$C-P=(F-K)^*$
!! LEARNING OUTCOMES – FINANCIAL ECONOMICS SEGMENT   
A. Interest rate models  
1. Evaluate features of the Vasicek and Cox-Ingersoll-Ross bond price models.  
2. Explain why the time-zero yield curve in the Vasicek and Cox-Ingersoll-Ross bond price 
models cannot be exogenously prescribed.  
3. Construct a Black-Derman-Toy binomial model matching a given time-zero yield curve and a 
set of volatilities.   
 
B. Rational valuation of derivative securities  
1. Use put-call parity to determine the relationship between prices of European put and call 
options and to identify arbitrage opportunities.  
2. Calculate the value of European and American options using the binomial model.  
3. Calculate the value of European options using the Black-Scholes option-pricing model.  
4.  Identify the situations where the values of European and American options are the same. 
5. Interpret the option Greeks.  
6. Explain the cash flow characteristics of the following exotic options: Asian, barrier, compound, 
gap, and exchange.  
7. Explain the properties of a lognormal distribution and explain the Black-Scholes formula as an 
expectation with respect to a lognormal distribution.  
8. Explain what it means to say that stock prices follow a diffusion process.  
9. Apply Itô’s lemma in the one-dimensional case.  
 
C. Simulation  
1. Simulate lognormal stock prices.  
2. Use variance reduction techniques to accelerate convergence.   
 
D. Risk management techniques  
1. Explain and demonstrate how to control risk using the method of delta-hedging.  
 
Note:   Concepts, principles and techniques needed for Exam MFE are covered in the             
reference listed below. Candidates and professional educators may use other             
references, but candidates should be very familiar with the notation and terminology             
used in the listed references.    
 
 
!! Texts – Financial Economics Segment
Derivatives Markets (Second Edition), 2006, by McDonald, R.L.,   
Chapter 9,   
Chapter 10, (excluding “Options on Commodities” on page 334),   
Chapter 11, Sections 11.1 – 11.4, Appendices 11.A and 11.B,   
Chapter 12, Sections 12.1–12.5, Appendix 12.A,   
Chapter 13, including Appendix 13.B,  
Chapter 14,   
Chapter 18,  
Chapter 19, Sections 19.1–19.5  
Chapter 20, Sections 20.1–20.6 (up to but excluding “Multivariate Itô’s Lemma” on 
pages 665-666) and  20.7 (up to but excluding “Valuing a Claim on S 
a 
Q 
b 
Chapter 21, Sections 21.1 – 21.2 (excluding “What If the Underlying Asset Is Not an 
Investment Asset” on pages 688-690) and 21.3 ( excluding “The Backward Equation” on 
pages 691-692, and excluding the paragraph on page 692 that begins “If a probability…” 
and through the end of the section),   
on pages 
670-672 and excluding “Finding the lease rate” on top one-half of page 669),   
Chapter 22, Section 22.1 (but with only those definitions in Tables 22.1 and 22.2 that are 
relevant to Section 22.1),   
Chapter 23, Sections 23.1 – 23.2 (pp.744 thru the middle of p.746 only),   
Chapter 24, Sections 24.1–24.5 (up to but excluding “Forward rate agreements” on 
pages 806-808),   
Appendix B.1, Appendix C and including relevant Errata (see below).   
Unless otherwise stated chapter appendices are not included in the required readings from this 
text.  
Taken from Khuri, ## 7:5,9,13,16,17,21,24,25,26
!! 7.1 - limits
The function $f(x,y):=\frac{|x|}{y^2}\exp(-\frac{|x|}{y^2})\,\bar{1}_{\{0\}}$ has limit zero as $(x,y)\to0$ along any straight line through $0$; but does not have a limit as $(x,y)\to0$.
!!! Solution
Indeed, take a sequence $z_n:=(x,y)_n:=(\frac{\al}{n},\frac{1}{n})$ along $\al y= x$: \[ f(z_n) = |\al| e^{-|\al|} \times \frac{1}{|y|}\exp(\frac{1}{|y|}) \to 0 \]
On the other hand, taking a sequence along e.g. $x^2 = y$ will yield $f(z'_n)=e^{-1}$ which clearly does not converge to 0.

!! 7.5 - continuity and partial derivatives
The function $f(x,y):=\frac{xy}{x^2+y^2} \, \bar{1}_{\{0\}}$ is not continuous at the origin, but possesses both partial derivatives there.
!!! Solution
We can see that $f$ is not continuous from reparametrizaton $x=r\cos\th, y=r\sin\th$: $f=\frac{\sin2\th}{2}$, so if we approach zero along the line $x=y$ the limit is $+\frac{1}{2}\neq0$, and along the line $x=-y$ the limit is $-\frac{1}{2}$. Thus the function has a non-removable discontinuity at 0.
On the other hand, $\partial_x f|_0 = \lim_{x\to0} \frac{f(x,0)}{x} = 0$, and similarly for $\partial_y f|_0$.

!! 7.7 - continuity and directional derivatives
The function $f(x,y):=\frac{x^2y}{x^4+y^2}\,\bar{1}_{\{0\}}$ is not continuous at zero, but possesses directional derivative in any direction
!!! Solution
A sequence $f(z_n):=f()\to$, whereas $f(w_n):=f()$, so $f(x)$ is not continuous. On the other hand, along \[
\lim_{x\to0} \frac{1}{x}\frac{\al x^3}{x^4+\al^2 x^2} = \lim_{x\to0}\frac{1}{\al^2+x^2} = \al^{-2}
\]

!! 7.6 - Euler's theorem for homogeneous functions.
A function $f(x_1,\ldots,x_n)$ is called homogenous of defree $n$ if $f(tx_1,\ldots,tx_n)=t^n f(x_1,\ldots,x_n)$. If $f$ is differentiable, then \[
\sum_{i=1}^n\!x_i \partial_i f = nf \].
!!! Solution
Note that an example of a homogenous function in $\real^2$ which is not differentiable is $r^2 D(\theta)$, where $D$ is the Dirichlet function on $[0,2\pi)$
!! Problem 1
Show that the mgf of a normal variable $Z$ is $\psi(t)=\exp(\mu t+\frac{\sigma^2 t^2}{2})$, and use it to show that $aZ+b\sim N(a\mu+b,a^2\sigma^2)$. Also show that for $\mu=0,\sigma=1$, the odd moments vanish and the even moments are $\mu_{2j}=\frac{(2j)!}{j!2^j}$
!!! Solution
Complete the square: \[ \psi(t) = \int_\real\!\frac{\exp(xt -\frac{(x-\mu)^2}{2\sigma^2})}{\sqrt{2\pi\sigma^2}}\,dx 
=  \int_\real\!\frac{\exp(-\frac{- 2xt\sigma^2 + (x-\mu)^2}{2\sigma^2})}{\sqrt{2\pi\sigma^2}}\,dx 
=  \int_\real\!\frac{\exp(-\frac{(x-(\mu+t\sigma^2))^2 + \mu^2 - (\mu+t\sigma^2)^2)}{2\sigma^2})}{\sqrt{2\pi\sigma^2}}\,dx 
\]
From which, immediately:
\[ \psi(t) = \exp(-\frac{\mu^2-(\mu+t\sigma^2)^2}{2\sigma^2}) \int_\real\!\frac{\exp(-\frac{(x-(\mu+t\sigma^2))^2}{2\sigma^2})}{\sqrt{2\pi\sigma^2}}\,dx
= \exp(\mu t +\frac{\sigma^2 t^2}{2}) \times 1
\]
Now, recall that a constant random variable is independent of every other r.v., and $\psi_b=e^{bt}$, so that \[ 
\psi_{aZ+b} = \psi_Z(at)\psi_b(t) = \exp((\mu a+b)t + \frac{a^2\sigma^2t^2}{2})
\] which we recognize as the mgf for a normal r.v. with mean $\mu a+b$ and variance $(a\sigma)^2.$

Expanding $\psi_Z=\exp(t^2/2)=\sum_j\!\frac{(t^2/2)^j}{j!} = \sum_j\! \frac{t^{2j}}{2^j j!} $ and equating it to the power series representation in terms of the moments $\psi_Z=\sum_k\frac{m_k}{k!}t^k$, we immediately obtain the claimed result.

!! Problem 2 - ~Riemann-Stieltjes Integration by Parts
Show that, for $F,G:[a,b]\to\real$ bounded nondecreasing functions, \[
\int_a^b\!F\,dG + \int_a^b\!G\,dF = F(b)G(b) - F(a)G(a)
\]
NB: ask - didn't understand hint.
!!! Solution
Choose a partition $P:=\{a=x_0<x_1<\ldots<x_n=b\}$ of $[a,b]$, together with 'tags' $t_i\in(x_{i-1},x_i)$. Write $\Delta := F(b)G(b) - F(a)G(a) $ as a 'telescopic sum' \[ F(b)G(b) - F(a)G(a) = \sum_k F(x_k)G(x_k) -F(x_{k-1})G(x_{k-1}) 
= \sum_k F(x_k)G(x_k) - \sum_k F(x_{k-1})G(x_{k-1})
\]
Now approximate $\int_a^b\!G\,dF$ as a RS sum $S(P,t,G,F)$ wrt to the tagged partition $(P,t)$ above:
\[ S(P,t,G,F) = \sum_k\! G(x_k)\Delta F(x_k) = \sum_k\! G(x_k)F(x_k) - \sum_k\! G(x_k)F(x_{k-1}),
\] and consider the convergence of $\Delta - S(P,t,G,F)$: \[
\Delta - S(P,t,G,F) = \sum_k\!F(x_k)(G(x_k)-G(t_k)) + \sum_k\!F(x_{k-1})(G(t_k)-G(x_{k-1})).
\] We recognize the latter as the RS sum for $\int_a^b\!F\,dG$ wrt a refinement of $P$ by adding the tags $t_k$ as partition points.
Because $F$ is bounded and non-decreasing, it is of bounded variation, so that $S(P,t,G,F)\to\int_a^b\!G\,dF$, and 
thus $\Delta-S(P,t,G,F) \to \int_a^b\!F\,dG$ as the partition $P$ is refined.

!! Problem 3
Let $X$ be a non-negative r.v. with distribution function $F(x)$ and mean $\mu_F=\int_{\real^+}\!x\,dF$. Show that \[
\mu_F=\int_{\real^+}\!\bar{F}\,dx,\] where $\bar{F}(x):=1-F(x)$
!!! Solution
Integrating by parts, we have \[ 
\int_0^a\!x\,dF + \int_0^a\!F\,dx = aF(a)
\] after simple manipulations, we write it as \[ 
\int_0^a\!x\,dF = \int_0^a\!1-1-F \,dx + aF(a) = \int_0^a\!\bar{F}\,dx - a\bar{F}(a).
\] We now have two options: if $a\bar{F}(a)\to0$, we immediately have $\mu_F=\int_{\real^+}\!\bar{F}\,dx$. If not, we must have $a\bar{F}(a)>y$ for some $y>0$, on some infinite interval $(b,\infty)$ (recall that $\bar{F},a>0$). But this forces $\mu_F=+\infty$, and therefore $\int_0^a\!\bar{F}\,dx > \int_0^a\!x\,dF \to +\infty$.

!! Problem 5
Let $f:\real^2\to\real^2$ be given by \[ f(x,y)^T = (e^{x^2-y},e^{2xy}\cos(xy))^T \]

!!! Solution

Jacobian: \[ 
J_f = \left(
\begin{array}{cc}
2xe^{x^2-y} & -e^{x^2-y} \\
2ye^{2xy}\cos(xy) - ye^{2xy}\sin(xy) & 2xe^{2xy}\cos(xy) - xe^{2xy}\sin(xy)
\end{array}
\right)
\]
At $v=(1,0)^T$, $J_f|_v =  \left(
\begin{array}{cc}
2e & -e \\
0 & 2
\end{array}
\right),$ $det(J_f|_v)=4e\neq0$. Moreover, $J_f$ is continuous on $\real^2$, thus we can apply the inverse function theorem: $
J_{f^{-1}}(f(v))=J_f^{-1}(v)=\frac{1}{4e}\left(
\begin{array}{cc}
2 & e \\
0 & 2e
\end{array}
\right)$
Thus, \[ 
z = f^{-1}(w) = f^{-1}(w_0) + J_f^{-1}(v) (w-w_0) + O(||w-w_0||^2) = (1,0)^T + \frac{1}{4e}\left(
\begin{array}{cc}
2 & e \\
0 & 2e
\end{array}
\right) (u,v)^T + O(||w-w_0||^2)
\]

!! Problem 6
Let $g:\real^2\to\real$ be $g(x,y) = \frac{x}{1+r^2}$, where $r^2:=x^2+y^2$. Find and classify stationary points.
!!! Solution
Note that $\partial_x (r^2)=\frac{x}{r}$. The gradient is $\nabla g(x,y) = \frac{1}{(1+r^2)^2}(1+r^2-2x^2, -2xy)^T $ so the critical points $\nabla g=0$ must satisfy  $1+r^2-2x^2 = 0$ and ($x=0$ or $y=0$). $x=0$ is clearly impossible since $1+y^2\geq1>0$, so we have $1+y^2-x^2=0$ and $y=0$.
The critical points are thus \[ (\pm1,0)^T. \] It is clear that $(+1,0)$ is the local maximum and $(-1,0)$ the local minimum, but let us show it by considering the Hessian: \[ 
H = \frac{1}{(1+r^2)^3} \left(
\begin{array}{cc}
-2x(3+3y^2-x^2) & 2y(3x^2-1-y^2) \\
-2y(1+y^2+3x^2) & -2x(1+x^2+3y^2)
\end{array}
\right),
\] which at the critical points becomes $H=-\frac{1}{2}\left(
\begin{array}{cc}
x & 0 \\
0 & x
\end{array}
\right).$ When $x=+1$, the Hessian has both negative eigendirections, and both positive ones at $x=-1$; $g$ is odd in $x$.
! Assignment 1

!! Problem 1
Determine the rank of the matrix
\[ A = \left( 
\begin{array}{cccc} 
11 & 12 & 13 & 14 \\ 
21 & 22 & 23 & 24 \\ 
31 & 32 & 33 & 34 \\ 
41 & 42 & 43 & 44 \\ 
\end{array} 
\right) \]
!!!Solution
Let us consider the row rank of $A$: Clearly $rk(A)\leq 2$, since $A$ can be obtained from 
\[ \hat A = \left( 
\begin{array}{cccc} 
1 & 1 & 1 & 1 \\
1 & 2 & 3 & 4 \\ 
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
\end{array} 
\right) \]
by elementary row operations: e.g. $(21,22,23,24) = 10\times (1,1,1,1) + (1,2,3,4)$.

On the other hand, the first two rows of $\hat A$ are clearly linearly independent, so $$rk(A)=2$$


!!Problem 2
Let $e_1,e_2,e_3,e_4$ be four l.i. vectors in a vector space $V$. Find the dimension of $\left< f_1,\ldots,f_4 \right> := \left< e_1-e_2, e_2 - e_3, e_3 - e_4, e_4-e_1\right>$.
!!! Solution

We will find a maximal l.i. subset of $\{f_i\}$ - this is a basis of $\left<f_i\right>$, and the dimension of this subspace is the cardinality of such a basis.

Note that $-f_4 = e_1-e_4 = f_1+f_2+f_3 $, so $dim\left<f_i\right>\leq3$.

On the other hand, it is easy to see that e.g. $\{f_1,f_2,f_3\}$ ''is'' a l.i. set: suppose
$$ \alpha_1 (e_1-e_2) + \alpha_2 (e_2-e_3) + \alpha_3 (e_3-e_4) 
 = \alpha_1e_1 + (\alpha_2-\alpha_1)e_2 + (\alpha_3-\alpha_2)e_3 -\alpha_3e_4 = 0  $$

Since $\{e_i\}$ are l.i., we must have $\alpha_1 = \alpha_3=0$. But then $\alpha_2e_2 - \alpha_2 e_3 =0$, so - again, by l.i. of $\{e_i\}$, $\alpha_2=0$.

Thus $3\leq dim\left<f_i\right>\leq 3$, i.e. 
$$ dim  \left< e_1-e_2, e_2 - e_3, e_3 - e_4, e_4-e_1\right> = 3$$ 

!!Problem 3
Show that the matrix 
\[ A = \left( 
\begin{array}{cccc} 
a & b & c & d \\ 
b & a & c & d \\ 
b & c & a & d \\ 
b & c & d & a \\ 
\end{array} 
\right) \]
has the eigenvalues $a-b, a-c, a-d$. Find the fourth eigenvalue of $A$.

!!! Solution
Recall that $\lambda$ is an eigenvalue of $A$ if for some $x\neq0$, $Ax=\lambda x$.

We immediately see the fourth eigenvalue by inspection:
$$ A\,(1,1,1,1)^T = (a+b+c+d)\,(1,1,1,1)^T$$

On the other hand, we see that e.g. $A-(a-b)1$ is singular:

\[ A-(a-b)1 = 
\left( 
\begin{array}{cccc} 
b & b & c & d \\ 
b & b & c & d \\ 
b & c & b & d \\ 
b & c & d & b \\ 
\end{array} 
\right) \]

The first two rows are identical, which means that the row-rank is not full, therefore $|A-(a-b)1|=0$. Similarly for $a-c$ and $a-d$.
This means that $a-b,a-c,a-d$ are roots of the characteristics equation, i.e. eigenvalues. 

!! Problem 4
Recall that $A$ is called '''idempotent''' if $A^2=A$. Show:
!!! 4a
If $A$ idempotent, then so is $1-A$.
!!!! Solution
Indeed, $ (1-A)^2 = (1-A)(1-A) = 1-2A+A^2 = 1-A $
!!! 4b
If $A$ idempotent and invertible, then $A=1$.
!!!! Solution
Let $A^{-1}$ be the inverse of $A$, i.e. $A^{-1}A=1$. Then 
$$ 1 = A^{-1}A = A^{-1}A^2 = (A^{-1}A)A = A $$  
!!! 4c
An example of $2\times2$ idempotent matrix which is neither zero nor identity:
!!!! Solution
Consider 
\[ s = \left(
\begin{array}{cc}
1 & 0 \\ 0 & 0 \\
\end{array}
\right)
\]
Clearly $s^2=s, 1\neq s\neq0$.
!!! 4d
If $A$ is idempotent, is $1-2A$ invertible?
!!!! Solution
Yes, $1-2A$ is in fact self-inverse: 
$(1-2A)^2=1-4A+4A^2 = 1$

!! Problem 5

Let $m\leq n$, $A=A_{m\times n}$ be an $m\times n$ matrix, $B=B_{n\times m}$ an $n\times m$ matrix. Then the eigenvalues of $BA$ are those of $AB$ together with $n-m$ zeros. 
Hint: ''Provided'' $P,S$ are invertible, $\left| \begin{array}{c|c} P & Q \\  R & S \end{array}\right| = |P| \times |S-RP^{-1}Q| = |S|\times |P-QS^{-1}R|$
Let us consider the determinant of the following block matrix, for $\lambda\neq0$:

$$
\left| \begin{array}{cc} \lambda 1_n & B_{n\times m} \\  A_{m\times n} & 1_m \end{array}\right| 
   = |\lambda1_n|\cdot|1_m-\lambda^{-1}AB| 
     = \lambda^n |1_m-\lambda^{-1} BA| \times\frac{|\lambda1_m|}{|\lambda1_m|}
     = \lambda^{n-m} |\lambda 1_m- BA|
   = |1_m|\cdot|\lambda1_n - BA|
$$

Which shows that all non-zero roots of the characteristic equations for $AB$ and $BA$ coincide. By the fundamental theorem of algebra, the characteristic equation for $BA$ has $n\geq m$ roots, at least $n-m$ of which have to be zeros, since it has at most $m$ non-zero roots, and all of them it shares with $\chi_{AB}$.

!! Problem 6
Show $tr(AB)=tr(BA)$. Give an example of $tr(ABC)\neq tr(BAC)$
!!! Solution
In component form, the proof of $tr(AB)=tr(BA)$ is unenlightening and is essentially the commutativity of addition: if $A=A^i_j$, $B=B^k_l$, we have $AB=(AB)^i_k = A^i_j B^j_k$ (using Einstein's summation convention), and
$$
   tr(AB) = A^i_j B^j_i = B^j_i A^i_j = tr(BA)
$$
Take $A= \left(
\begin{array}{cc}
1 & 0 \\ 1 & 0 \\
\end{array}
\right)
$, $B =  \left(
\begin{array}{cc}
1 & 0 \\ 0 & 0 \\
\end{array}
\right)
$, $ C =  \left(
\begin{array}{cc}
1 & 1 \\ 0 & 0 \\
\end{array}
\right)
$: $ABC =  \left(
\begin{array}{cc}
1 & 1 \\ 1 & 1 \\
\end{array}
\right)
$, and $ BAC =   \left(
\begin{array}{cc}
1 & 1 \\ 0 & 0 \\
\end{array}
\right)
$

Clearly $tr(BAC) = 1 \neq 2 = tc(ABC)$.

!! Problem 7
Prove that a matrix $M$ is symmetric positive-semidefinite ''iff'' $M=A^TA$ for some matrix $A$.
!!! Solution
The 'if' part is trivial: $M=A^TA \ \implies x^TMx = x^TA^TAx = ||Ax||^2 \geq 0$. Moreover, $(A^TA)^T=A^T(A^T)^T=A^TA$
Now consider a symmetric positive-definite matrix $M$. we know that $M=V^TD_\lambda V$ for an orthogonal 'change-of-basis' $V$
and a diagonal matrix $D=diag(\lambda_1,\lambda_2,\ldots,\lambda_n)$ of eigenvalues of $M$. Furthermore, 
$$ 0 \leq u^TMu=u^TV^TD_\lambda Vu = (Vu)^T D_\lambda (Vu) $$ 
from which we see that $D_\lambda$ is also positive-semidefinite (image of $V$ is the entire space). In case of a diagonal matrix $D_\lambda$ this means that every $\lambda_i\geq0$, and we can write $$M=V^TD_{\sqrt\lambda}D_{\sqrt\lambda}V = A^TA $$
Where $A=D_{\sqrt\lambda}V$

!! Problem 8
Let $M$ be a symmetric $n\times n$ matrix with eigenvalues $\lambda_1,\ldots,\lambda_n$. Show that, $\forall k\in\mathbb{N}$,
 $$\sum_1^n\!\lambda_i^k=tr(M^k)$$
!!! Solution
Since $M$ has $n$ real eigenvalues, it is diagonalizable: there exists an invertible change-of-basis operator $V$ such that
$M=V^{-1}DV$, where $D=diag(\lambda_1,\ldots,\lambda_n)$. But trace is independent of basis: 
$$ tr(M) = tr(V^{-1}DV) = tr(VV^{-1}D) = tr D = \sum_i\lambda_i$$
Furthermore, it is easily seen by induction that $M^k$ = $V^{-1}D^kV$, and 
$$tr(M^k) = tr(D^k) = tr(diag(\lambda_1^k,\ldots,\lambda_n^k)) = \sum_i\lambda_i^k$$
!! Problem 1

Let \[
A = \left( 
\begin{array}{rrr} 
1 & 2 & 1 \\ 
-1 & -5 & -3  \\ 
1 & 5 & 8  \\ 
\end{array} 
\right)
=:(a_1,a_2,a_3)\]
and \[
b = \left( 
\begin{array}{r} 
0 \\ -1 \\ 1 
\end{array} 
\right)
\]

* Determine $QR$-decomposition of $A$
* Solve $Ax=b$

!!! Solution

* Let us find the QR factorization using the ~Gram-Schmidt process: We are going to generate an orthonormal basis $(q_1,q_2,q_3)$ from $(a_1,a_2,a_3)$.
** $||a_1|| = \sqrt{3}$, so $q_1=\frac{1}{\sqrt{3}}(1,-1,1)^T$
** $a_1\cdot a_2 = 12$, so $u_2=a_2-(q_1\cdot a_2)q_1 = (-2,-1,1)$, and $q_2=\frac{1}{\sqrt{6}}(-2,-1,1)^T$
** $u_3=a_3-(q_2\cdot a_3)q_2 - (q_1\cdot a_3)q_1 = \frac{5}{2}(0,1,1)^T$, so that $q_3=\frac{1}{\sqrt{2}}(0,1,1)^T$
* The orthogonal matrix \[Q=(q_1,q_2,q_3)
= \frac{1}{\sqrt{6}} \left( 
\begin{array}{rrr} 
\sqrt{2} & -2 & 0 \\ 
-\sqrt{2} & -1 & \sqrt{3}  \\ 
\sqrt{2} & 1 & \sqrt{3}  \\ 
\end{array} 
\right),
\] and the upper-triangular matrix $R$ is given by \[ 
R = \left( 
\begin{array}{ccr} 
q_1\cdot a_1 & q_1\cdot a_2 & q_1\cdot a_3 \\ 
0 & q_2\cdot a_2 & q_2\cdot a_3  \\ 
0 & 0 & q_3\cdot a_3  \\ 
\end{array} 
\right)
=
\left( 
\begin{array}{ccr} 
\sqrt{3} & 4\sqrt{3} & 4\sqrt{3} \\ 
0 & \sqrt{6} & \frac{9}{\sqrt{6}}  \\ 
0 & 0 & \frac{5}{\sqrt{2}}  \\ 
\end{array} 
\right)
\]
* We thus have $Q^TQRx=Q^TAx=Q^Tb=:c=\frac{1}{\sqrt{6}}(2\sqrt{2},2,0)^T$, and so \[ Rx =
\left( 
\begin{array}{ccr} 
\sqrt{3} & 4\sqrt{3} & 4\sqrt{3} \\ 
0 & \sqrt{6} & \frac{9}{\sqrt{6}}  \\ 
0 & 0 & \frac{5}{\sqrt{2}}  \\ 
\end{array} 
\right)
 \left( \begin{array}{r}  x\\ y \\ z  \end{array}  \right) 
     = \frac{1}{\sqrt{6}} \left( \begin{array}{r}  2\sqrt{2}\\2  \\ 0  \end{array}  \right)
\]

Finally, \[ x = \frac{1}{3} \left( \begin{array}{r}  -2\\ 1 \\ 0  \end{array}  \right), \] which can be directly verified.

!! Problem 2

|!-- |!Calgary|!Edmonton|!Jasper|!Saskatoon|h
|!Calgary | -- | 310 | 700 |  |
|!Edmonton | | -- | 360 |  |
|!Jasper |  |  | -- | 900 |
|!Saskatoon | 810 |  |  | -- |

Given that ~J-S, ~S-C, and ~C-J distances are via Edmonton, estimate the distances $EC=:\th_1$, $EJ=:\th_2$, $ES=:\th_3$ from the above data.

!!! Solution

This is a 'linear regression through the origin' problem: \[ 
T:=\left( \begin{array}{r}  310 \\ 360 \\ 900 \\ 810 \\ 700 \end{array}  \right)  
= A \th  + \ep
= \left( \begin{array}{rrr}  
   1 & 0 & 0 \\
   0 & 1 & 0 \\
  0 & 1 & 1 \\
  1 & 0 & 1 \\
  1 & 1 & 0 
\end{array}  \right)  
  \left( \begin{array}{r}  \th_1\\ \th_2 \\ \th_3  \end{array}  \right) + \ep
\]

Our task is to find $\theta$ that minimizes $||\ep||^2=||y-A\theta||^2$.

!! Problem 3
* ''Prove'' that for any index set $\Lambda$ (countable or uncountable), $ A := \cup_\Lambda A_{\lambda\in\Lambda}^o $ is open; and 
* ''give an example'' of a collection of $(A_i^o)_{i\in\mathbb{N}}$ such that $\cap_iA_i^o$ is not open.

!!! Solution

* If all sets in the collection are empty, there is nothing to prove. If otherwise, take a point $x\in A$, which must belong to some $A_\lambda^o\neq\emptyset$ in the collection, and fit an open $\epsilon$-ball around $x$: 
** Since $A_\lambda^o$ is open, there is $\epsilon>0$ be such that $U_{\epsilon}^o(x)\subseteq A_\lambda$
** But every point in $U_{\epsilon}^o(x)$ also belongs to the union: $U_{\epsilon}^o(x)\subseteq A_\lambda\subseteq \cup_\Lambda A_{\lambda\in\Lambda}^o =:A $
** Which is the definition of `open' in the metric topology.
* Take $A_n^o := (-\frac{1}{2^n},+\frac{1}{2^n})$, so that $\cap_{i\in\mathbb{N}}A_i^o=\{0\}$, which is manifestly not open.

!! Problem 4

''Prove'' that: 
* if $\emptyset\neq A\subseteq\mathbb{R}$ is closed and bounded ''from below'', then $a:=\inf A\in A$, and that 
* if $B^o\subseteq\mathbb{R}$ is open and bounded, then $\inf B \notin B$

!!! Solution

* First of all, $a:=\inf A$ exists, since $A\neq\emptyset$. Moreover, 
** $a\leq A$ ($a$ is a lower bound) and 
** $\forall \epsilon>0$, $a+\epsilon$ is ''not'' a lower bound. But this means that every $\epsilon$-open ball $U_\epsilon(a)$ (in $A$) contains a point other than $a$: $\exists x\in A: a<x<a+\epsilon$. Thus $a$ is an accumulation point of a closed set $A$, and therefore $a\in A$.
* By the above result, $\sup A\in A$ for a closed set $A$ bounded from above, since $\sup -X = -\inf X$ 
* If $B^o$ is empty, there is nothing to prove. If $B^o\neq\emptyset$ is bounded, it is in particular bounded from below, so let $b:=\inf B$. 
** The set $\tilde B:=(-\infty,b]\cap B^c$ is closed and bounded from above by $b$: $b\geq\real_{\leq b}\geq \tilde B$
** Moreover, no $z<b$ can be an upper bound of $\tilde B$, since this would mean $\frac{z+b}{2}<b$ is a lower bound of $B$
** Thus, $b=\sup \tilde B$; by the above results, $b \in \tilde B\subset B^c$, i.e. $b\notin B$

!! Problem 5

Let $A_{n\times n}$ be a symmetric positive-definite matrix. ''Show'' that, for any $a$ such that $||a||=1$, \[ Q(a):=(a^TAa)(a^TA^{-1}a)\geq1 \]

!!! Solution

First, let us consider a diagonal positive-definite matrix $D=diag(\lambda_1,\ldots,\lambda_n)$, where $\lambda_j>0$. Then \[
Q(a)=Q((a_1,\ldots,a_n)^T)=(\sum_{j=1}^n\lambda_ja_j^2)(\sum_{i=1}^n\!\frac{1}{\lambda_i}a_i^2) 
\] Now, let us define the random variable $X$ which takes value $\lambda_i$ with probability $a_i^2$ (we are assuming $\lambda_i$ unique here, but merely for convenience):  \[\prob[X^{-1}(\lambda_i)]=a_i^2.\] Our expression then becomes \[ Q(a) = \xpct[X] \xpct[\frac{1}{X}] = \xpct\left[X\xpct[\frac{1}{X}] \right]. \] 
Since $\lambda_i>0$, $\xpct[X]>0$. Moreover, since $\frac{1}{x}$ is convex, the Jensen's inequality for it reads $
\xpct[\frac{1}{X}]\geq\frac{1}{\xpct[X]}$, and thus \[ Q(a) \geq \frac{\xpct[X]}{\xpct[X]} = 1 \]

But any symmetric positive-definite matrix $A$ can be written as $V^TDV$, where  $V$ is an orthogonal change-of-basis matrix. Thus $A^{-1}=V^{-1}D^{-1}(V^T)^{-1}=V^TD^{-1}V$, and \[
Q(a) = (a^TAa)(a^TA^{-1}a) = (a^T V^TDVa) (a^TV^TD^{-1}Va) = (b^TDb)(b^TD^{-1}b) \geq1,
\]
where we defined $b:=Va.$


!! Problem 6!! Problem 6

Suppose that $X_n\to^{\prob}c$, and that $a_n\to a\in \real$. ''Show'' that $a_nX_n\to^\prob ac$.

!!! Solution

Recall that the convergence in measure means that $ \prob [ |Xn-c|\geq \ep ] \to 0 $ as $n\to\infty$. We also see that $[|X_n-c|\geq \ep] \supset  [|X_n| \geq |c| +\ep ].$

* First suppose $a=0$: 
** For any $\ep>0$, there is $N\in\natural$ s.th. $|a_n|<\delta:=\frac{\ep}{|c|+\ep} \ \forall n\geq N$
** We have, for large enough n, \[ [|a_n X_n|\geq\ep]  \subseteq [ \delta |X_n| \geq\ep ] = [|X_n| \geq |c| + \ep ] \subseteq [|X_n-c|\geq \ep] \] 
** Since $\prob(A\subseteq B) \leq \prob(B)$, we have $a_nX_n \to^\prob 0 = ac$
* If $a\neq0$, consider the sequence $\frac{a_n}{a}X_n$:
** Take $\ep>0$. We have $|\frac{a_n}{a}-1|<\gamma:=\frac{\ep}{|c|+\ep/2} \ \forall n>N$. Then, for large enough $n$, \[ 
 \left[ |\frac{a_n}{a}X_n-c|\geq\ep \right] \subseteq [  |\frac{a_n}{a}X_n|  \geq |c|+\ep ] \cup [  |\frac{a_n}{a}X_n|  \leq |c|-\ep ] 
\subseteq [|X_n|\geq\frac{|c|+\ep}{1+\ga} ] \cup [ |X_n|\leq\frac{|c|+\ep}{1-\ga} ] \subseteq [X_n|\leq|c|+\ep/2] \cup [X_n|\geq|c|-\ep/2]= [|X_n-c|\geq\ep/2] 
\] 
** Once again, this forces $\frac{a_n}{n}X_n\to^\prob c$, and the claim follows immediately.
I would still like to copy the problems; this way I don't have to keep the handout separately.

!! Problem 1a
\[ \lim_{x\to\infty}\frac{x^n}{e^x} = 0 \]
!!! Solution
By induction: Clearly for $n=0$, $e^{-x}\to0$ as $x\to\infty$. Now for the induction step, use L'Hopital's rule: \[ 
\lim_{x\to\infty} \frac{x^{n+1}}{e^x} = (n+1) \lim_{x\to\infty} \frac{x^n}{e^x} = 0 \] when we use the induction hypothesis.

!! Problem 1b
\[ \lim_{x\to0^+}\frac{\sin x}{1-\cos x} = +\infty \]
!!! Solution
Again, using L'Hopital's rule: \[ \lim_{x\to0^+}\frac{\sin x}{1-\cos x} = \lim_{x\to0^+}\frac{\cos x}{\sin x} = +\infty \]

!! Problem 1c

\[\lim_{x\to1} \frac{x\log x -x +1}{(x-1)\log x}  = \frac{1}{2} \]

!!! Solution
Yet again, L'Hopital's rule to the rescue: \[ 
\lim_{x\to1} \frac{x\log x -x +1}{(x-1)\log x}  
     = \lim_{x\to1} \frac{\log x - 1  +1 }{\frac{x-1}{x} + \log x}  
     = \lim_{x\to1}\frac{1}{1+\frac{x-1}{x\log x}}
     = \frac{1}{1+\lim_{x\to1}\frac{x-1}{x\log x}}
\] provided the latter limits exist. But, by L'Hopital's rule again, \[ 
\lim_{x\to1} \frac{x-1}{x\log x} = \lim_{x\to1}\frac{1}{1+\log x} = 1,
\]
From which the statement follows
!! Problem 2a

Find an example of a function $f(x):\real\to\real$ for which $\lim_{x\to x_0}f'(x)$ exists but $f'$ does not exist at $x=x_0$.

!! Solution
The Heaviside function $H(x) := 1_{\real^+}(x) $ is differentiable with derivative $H'(x)=0$ everywhere but at $x=0$. $\lim_{x\to0}H'(x)=0$, but the $H$ is not continuous and therefore
decidedly not differentiable at $x=0$.

!! Problem 2b

Show that $g(x):=0+1_{x\neq0}x^2\sin\frac{1}{x}$ is differentiable at $x=0$, but the derivative is not continuous at $x=0$.

!!! Solution

The only potentially problematic point where $g(x)$ is not differentiable is $x=0$; we have \[ \lim_{h\to0}\frac{1}{h}(h^2\sin\frac{1}{h}-0)=\lim_{h\to0}h\sin\frac{1}{h}=0=g'(x)|_{x=0} \] by the 'squeeze' theorem. On the other hand \[ g'|_{x\neq0}=2x\sin\frac{1}{x}-\cos\frac{1}{x} \] which does not have a limit as $x\to0$ since the sequence $a_n := (\frac{1}{n\pi})\to0$, yet  $b_n := (\cos\frac{1}{a_n})$ has both $+1$ and $-1$ as accumulation points and therefore cannot converge to a limit.

!! Problem 3
Investigate convergence of  \[ f_n(x) := \frac{n^\al}{1+n^2x^2} \]

!!! Solution 

Clearly, the sequence does not converge for $\al>2$ since $f_n(x) > n^{\al-2} \to \infty$.
When $\al=2$, $f_n\to\frac{1}{x^2}$ pointwise ($f_n = \frac{1}{n^{-\al}+x^2})$ but not uniformly since $f_n$ is continuous on $[0,1)$ whereas $\frac{1}{x^2}$ isn't.
For $0\leq \al<2$, $f_n(x)=\frac{1}{n^{-\al}+n^{2-\al}x^2} \to 0$ pointwise but not uniformly: 
For $\al<0$, $f_n\to0$ uniformly: the pointwise convergence is clear; moreover $ |f'_n| = 2n^{2-\al}\frac{x}{(1+n^2x^2)^2} $ is uniformly bounded.

!! Problem 4

Customers enter store according to a Poisson distribution with parameter $\la$, and each customer makes a purchase independently and with probability $p$. Find the distribution of the number of purchases $S$ during the day.

!!! Solution

The probability generating function of $N$ is $\phi_N(z) = e^{\la(z-1)} $, and the pgf of the individual purchase decision (a Bernoulli r.v. with parameter $p$) is $\phi_B(z)=(1-p)+zp$. The pgf. of the sum of $N$ iid. Bernoulli r.v.'s is thus  \[ 
\phi_{\sum_0^N\!B} = (\phi_N \circ \phi_B)(z) = e^{\la((1-p)+zp-1)} = e^{p\la (z-1) }
\]
as required. This is the pgf. of a Poisson r.v. with parameter $p\la$, and the probabilities are thus \[ \prob(\sum = n) = e^{-p\la} \frac{(p\la)^n}{n!}\]

!! Problem 5

Let $M(t)=\sum_{j=0}^\infty\!m_j\frac{t^j}{j!}$ be the mgf. of a r.v. $X$, and $K=\log(M(T)) = \sum_{j=0}^\infty\!\ka_j\frac{t^j}{j!}$ be its cumulant generating function. Derive the relationship
between $\ka_k$ and $m_j$: \[ \ka_{k} = m{k} - \sum_{j=1}^k {k-1 \choose j} \ka_{k-j}m_j \]

!!! Solution
We have $ M'(t) = M(t)K'(t).$ Differentiating term-by term, we have $M'(t) = \sum_{j=0}^\infty\! m_{j+1} \frac{t^j}{j!}$ and $K(t) = \sum_{j=0}^\infty \ka_{j+1} \frac{t^j}{j!}$. Multiplying the series term-by term and comparing the coefficients of $t^j$, we immediately obtain the claimed relation:

\[ m_{k+1} = \ka_{k+1} + \sum_{j=1}^k {k \choose j} \ka_{k+1-j}m_j
\]

!! Problem 6

Survival model for right whales: a female in female at time $n$ produces no offspring if she dies before time $n+1$; she produces one offspring (herself) if she survives but does not produce a female calf, and two offspring if she begets a female calf. Assume that the events of survival and giving birth are independent and constant for all $n$. Denote by $p$ the survival probability, and by $\mu$ the probability of procreating in the same period.

!!! Solution
Let us model the survival and procreation process during a period as a random variable $Y$ given by the pgf. \[ \phi_Y(s) := s^0 (1-p) + s^1 p(1-\mu) + s^2 p\mu. \] If the expectation of $Y\leq1$, eventual extinction is certain; this is the case if \[ p(\mu+1)\leq1.\] On the other hand, if the $\xpct(Y)>1$, the extinction probability is the root of $\phi(s)=s$ in the interval $(0,1)$:

\[ s^2 -s(1+\frac{1-p}{p\mu}) +\frac{1-p}{p\mu} = (s-1)(s-\frac{1-p}{p\mu}) = 0  \]

We see that if the survival probability in any given period is independent of that of giving birth in that period (and ander the assumption of independence), $T$ follows a Geometric distribution with parameter $p$: $\prob(T=n)=p^{n-1}(1-p)$, with expected value of $\xpct(T)=\frac{1}{p}$. Moreover, we have that the expectation of the population size - under the above independence conditions - is given by $\xpct(\sum\!Y_j)=(\xpct(Y))^n$. The population remains constant on average iff \[ \xpct(Y) = 2p\mu +p(1-\mu) = p(1+\mu) = 1. \]


! Additional Problems - for fun
5.2, 5.6, 5.11, 5.21, 5.23, 5.31
!~STAT512 class at ~UofA

!! Linear Algebra

* $rk(AB)\leq rk(A)$, in fact $rk(AB)\leq\min(rk(A),rk(B))$
* $rk(A)=rk(A^T)=rk(A^TA)$

!!Metric Topology

* $A$ closed $\iff$ $A^c$ open $\iff$ $A^c$ contains all its limit points
* sequence convergence
* net convergence
* filters and ultrafilters

!! Convex Analysis
* convex -> cts
* Jensen's theorem

!! Convergence of random variables

* convergence in probability
* Weak Law of Large Numbers
* Taylor's theorem
* transformation of random variables: if $Y=\psi(X)$, then its d.f. $G(y) = F(\psi^{-1}(y))$, and density $g(y)=\frac{f(\psi^{-1}(y))}{\psi'(\psi^{-1}(y))}$
* variance stabilization

!! Problem 3b
''Prove'' that if $A$, $B$ symmetric positive definite matrices, then $max_{x\neq0}\frac{x^TAx}{x^TBx}$ is the largest eigenvalue of $AB^{-1}$

!! Problem 5b
''Show'' that for $p_i>0$ with $\sum_ip_i=1$ and $q_i>0$ with $\sum_iq_i$, one has \[ -\sum_ip_i\log p_i \leq -\sum_i p_i\log q_i\]

!! Problem 6
* Define a variance-stabilizing transformation
* Show that $h(x)=2\arcsin(\sqrt{x})$ is a variance-stabilizing transformation for data related to independent random variables $Z_i$ with $Z\sim$Bernoulli$(p)$. 


! Sample Midterm
!! Problem 3
Consider the linear regression model for $y=X\theta+\epsilon$, where $X_{n\times p}$ has full column rank. Derive the least squares estimator $\hat\theta$ as the solution of a certain optimization problem.
! Statistical Inference - lecture course at ~UofA

!! Prerequisite Facts

* Sample mean and variance $S:=\frac{\sum_i{X_i-\bar X}}{n-1}$
* For any r.v. for which the first two moments are finite, $\xpct \bar X = \mu$, $\xpct S^2=\sigma^2$, $\var \bar X = \frac{\sigma^2}{n}$
* For a normal r.v., $\var S^2 = \frac{2\si^4}{n-1}$

!! Sufficient Statistics

!!! Definition
A statistic $T(X)$ is ''sufficient'' for $\theta$ if the conditional distribution of the sample $X$, $f(X|T(X))$, is independent of $\theta$; if $Y$ is another sample such that $\prob_\th(Y=y|T(X)=T(x)=:t)=\prob_th(X=y|T(x)=t)$, then the unconditional probabilities are equal $\prob_th(Y=y)=\prob_th(X=x)$

!!! Theorem
If $p(x|th)$ is the joint pdf/pmf of $X_i$ and $q(t|\th)$ is the pdm/pmf of $T(x_i)$ then $T(X_i)$ is sufficient for $\th$ if $\forall x\in\Omega, 
\frac{p(x_i|\th)}{q(t|\th)}=\frac{p(x_i|\th)}{q(T(x_i)|\th)}$ is independent of $\th$.
!!!! Proof


* Statistic
* Sufficient
* Minimal Sufficient

!!! Halmos-Savage Factorization Theorem
Let the joint distribution function of $X_i$ be $f(x_i|\theta)$. A statistic $T(X_i)$ is sufficient for $\theta$ ''iff'' \[ f(x_i|\theta) = g(T(x_i)|\theta) h(x_i) \] for some functions $g(t|\theta), h(x)$.

!!! Theorem - Sufficient Statistics for exponential family

!!! Sufficient Statistics - Examples
* $Bin(n,\theta)$: Let $X_i \iid B(\theta)$. Then $T:=\sum\!X_i$ is a ''SS'' for $\theta$
* $X_i\iid N(\mu,\sigma^2)$ with $\sigma$ known: $T:=\bar X:=\frac{\sum\!X_i}{n}$ is ''SS'' for $\mu$
* $X_i\iid U(\{1,2,\ldots,\theta\})$: $T:=X_{(n)}=\max_iX_i$ is ''SS'' for $\theta$
* $X_i\iid U(0,\theta)$: $T:=X_{(n)}$ is once again ''SS'' for $\theta$. Note that $2\bar X$ is an unbiased, but not sufficient for $\theta$.
* $X_i\iid N(\mu,\sigma^2)$: $T:=(\bar X, S^2)$ is ''SS'' for $(\mu,\sigma^2)$, where $S^2:=\frac{\sum\!(x_i-\bar x)^2}{n-1}$ is the sample variance. 

* $X_i\sim^{indep}exp\{i\theta-x\}1_{x\geq i\theta}$: $min_i(X_i/i)$ is ''SS'' for $\theta$
* $X_i\iid U(\theta-\frac{1}{2},\theta+\frac{1}{2})$: $T:=(X_{(1)},X_{(n)})$ is ''SS'' for $\theta$

!! Minimal Sufficient Stat

!!! Examples
* $X_i\iid N(\mu,\sigma^2)$: $T:=(\sum X_i, \sum X_i^2)$ is ''MSS'' for $(\mu,\sigma^2)$
* $X_i\iid \frac{1}{\sigma} exp\{-\frac{x-\mu}{\sigma}\} 1_{x>\mu}$: $(X_{(1)},\sum X_i)$ is ''MSS'' for $(\mu,\sigma)$


!! Ancilllary Statistics; Complete Statistics
* $T(X|\th)$ with pdf/pmf family $f(t|\th)$ is ''complete'' if \[ 
  \forall \th \quad \xpct_\th g(T)=0  \iff \prob_\th[g(T)^{-1}(0)]=1
\]

!!! Basu's Theorem

!!! Examples

* sample drawn from a location family: $X_i\iid f(x-\theta)$; Range $R:=X_{(n)}-X_{(1)}$ is ancillary for $\theta$
* sample drawn from scale family: $X_i\iid \frac{f(\sigma x)}{\sigma}$; Any statistic that depends only on $\frac{X_1}{X_n},\ldots\frac{X_{n-1}}{X_n}$ is ancillary
* $X_i\iid U(\theta-1,\theta+1)$: Range $R$ is ancillary, but $(X_{(1)}, R)$ is ''MSS'' for $\theta$
* $X_i\iid U(0,\theta>0)$: $X_{(n)}$ is ''complete'' for $\theta$. $\frac{n+1}{n}X_{(n)}$ ''CSS''.
* $x_i\iid exp\{ -(x-\theta) \} 1_{x\geq\theta}$: $X_{(1)}$ is ''complete & sufficient'' for $\theta$
* $X_i \iid B(\theta)$. Then $T:=\sum\!X_i$ is ''complete'' for $\theta$
* $X_i\iid \frac{e^{-\theta}\theta^x}{x!} 1_{\mathbb{N}}$: $\sum X_i$ is ''complete''
* $X_i\iid N(\mu,\sigma^2)$: $T:=(\sum X_i, \sum X_i^2)$ is ''complete'' for $(\mu,\sigma^2)$
* $X_i\iid Bin(n,p)$: $\sum X_i$ is ''complete'' for $p$
* $X_i\iid U(\theta,2\theta)$: $(X_{(1)},X_{(n)})$ is ''complete, MSS'' for $\theta$


!! Point Estimation
!!! Method of Moments 
* Binomial method of moments
* Satterthwaite approximation: want to find $\nu$ such that $\sum_1^n\!a_iY_i \sim \frac{\chi^2_\nu}{\nu}$ in wide sense (i.e. first moments coincide):
** \[ \hat\nu=\frac{(\sum\!a_iY_i)^2}{\sum\frac{a_i}{r_i}Y_i^2} \]

!!! Maximum Likelihood Estimators
* Normal likelihood for $X_i\iid n(\th,1)$: $\hat\th=\bar X$
* Bernoulli MLE: $X_i\iid B(p)$: $\hat p=\bar X$
* Binomial MLE; unknown number of trials (p.318) -aside
* Invariance property of the MLE: For any $f$, MLE of $f(\th)$ is $f(\hat\th)$.
** Relies on defining the induced likelihood function $L_f(\eta|x)=\sup_{\{f(\th)=\eta\}}\!L(\th|x)$
* Normal MLE, unknown $\mu$ and $\sigma$: $(\bar X,\frac{\sum\!X_i-\bar X}{n})$

!!! ~Mean-Square Error (MSE)
* $W$ an estimator of $\th$, its MSE is $\xpct_\th(W-\th)^2 = \var_\th W + \xpct^2(W-\th) =: \var_\th W + {\rm bias}_\th W$
* $W$ is ''unbiased'' if $\forall\th\ \xpct_\th W =\th$ 
* Best Unbiased estimators (UMVUE): an unbiased $W^*$ is best if for any unbiased $W$ of $\th$, $\var_\th W^*\leq\var_\th W$
* UMVUE is in fact unique:
!!!! ~Cramer-Rao Inequality
* Let $X_1,\ldots,X_n$ be a sample with joint pdf $f(X)$ ''If'' $\frac{d}{d\th}\xpct_\th W(X) = \int_\Om\!\partial_\th[W(X)f(x|\th)]\,dx$ and $\var_\th W(X)<\th$, then \[
\var_\th W(X) \geq \frac{(\frac{d}{d\th}\xpct_\th W(X))^2}{\xpct_\th((\partial_\th\log f(X|\th))^2)}
\] 
** If the sample above is iid with every r.v.'s pdf $f$, we have furthermore \[ 
    \var_\th W(X) \geq \frac{(\frac{d}{d\th}\xpct_\th W(X))^2}{n\xpct_\th((\partial_\th\log f(X|\th))^2)}
\] 
** moreover, if $f(x|\th)$ satisfies \[
  \frac{d}{d\th}\left( \partial_\th\log f(X|\th)\right) = \int\!\partial_\th[\partial_\th\log f(x|\th)]f(x|\th)]\,dx
\] (e.g.) exp. family, then \[
\xpct_\th\left(\partial_\th\log f(X|\th)^2\right) = -\xpct_\th(\partial^2_{\th\th}\log f(X|\th))
\]
 
!! Tests

!!! Likelihood Ratio Tests
Recall that the likelihood function for an iid sample $X_1,\ldots,X_n$ is $L(\th|x) = \prod_1^n f(x_i|\th)$, where $f$ is the pmf.
LRT Statistic: \[ \la(x) = \frac{\sup_{\Th_0}L(\th|x)}{\sup_\Th L(\th|x)}, \]
LRT rejection region $\{0 \leq \lambda(x)\leq c \leq 1\}$
!! Linear Algebra & Distribution Theory

* Class correlation Matrix. Eigenvectors and eigenvalues
* Spectral Decomposition Theorem. Proof.
* Positive-(semi)-definite matrices.
** Square roots. 
*** Symmetric sq.roots.
*** Lower-diagonal sq. root. Cholesky decomposition
* Mahalanobis distance.

!! Linear Models with Multivariate Response

!! Classification and Grouping

!! Analysis of Covariance Structure
! Regression Analysis - Lecture Course at ~UofA

Text: 

[ ] Normal Equations  $X^Ty=X^TX\beta$
[ ] QR decomposition
[ ] Projection operator: $im(1-H) = im(H)^\perp = ker(H)$

http://www.stat.ualberta.ca/~mizera/578/

Text: Generalized Additive Models: An Introduction in R, by Simon Wood, Chapman & Hall/CRC, 2006.
Midterm: Oct-25-2010; Final: Dec-15 2010
! Sixth Term Examination Papers
I have the following past papers: 
* 1987A, 1987B
* 1988A, 1988A, 
* [[STEP FM1989A]], [[STEP FM1989B]], 
* 1992-A, 
* [[STEP FM1993A]], [[STEP FM1993B]], 
* 1994-II, 1994-III, 
* 1995-II, 1995-III

There is also a number of Oxford admission papers in my possession, as well as Siklos' 'Advanced Problems in Core Mathematics' book.
Cambridge University has a number of recent STEP papers on its website, too.
Show that the center of mass of a spherical segment obtained by slicing by planes through a fixed axis, of angle $2\th$, is a distance \[
\frac{3\pi a\sin\th}{16\th}
\] from the axis. Also show that if a uniform chocolate orange of mass $M$ split into such segments is held together by a light inextensible narrow ribbon, the tension in the ribbon is at least \[ 
\frac{3}{32}Mg
\]
!!! Solution
Taking moments about the point of contact of the orange with the supporting plane, We have \[ 
2T\sin\th\times a = \frac{Mg}{n}\times \frac{3\pi a\sin\th}{16\th}
\] where $n:=\frac{2\pi}{2\th}$ is the number of slices, each of angle $2\th$. Simple algebra gives the claimed result.
For a square matrix $A$ such that $1-A$ is invertible, define $$B:=(1+A)(1-A)^{-1}$$ Show that $B^TB=1$ ''iff'' $A^T+A=0$.

Recalling that $(XY)^T=Y^TX^T$, $(X^T)^{-1}=(X^{-1})^T$, and that $(1+A)^T=(1^T+A^T)=(1+A^T)$;  we have 
$$
B^TB = [(1-A)^{-1}]^T(1+A)^T(1+A)(1-A)^{-1} = (1-A^T)^{-1}(1+A^T)(1+A)(1-A)^{-1}
$$

So that, ''if'' $A^T+A=0$, then $A^TA=-A^2$, and 
$$B^TB = (1-A^T)^{-1}(1+A^T+A+A^TA)(1-A)^{-1} = (1+A)^{-1}(1-A^2)(1-A)^{-1}=(1+A)^{-1}(1+A)(1-A)(1-A)^{-1} = 1$$

''Conversely'', if  $B^TB = 1$, then $ (1-A^T)(1-A) = (1+A^T)(1+A)$, and $$1-A^T-A+A^TA=1+A^T+A+A^TA$$ so that
$$
  2(A^T+A) = 0
$$
And - over field of characteristic not 2 - $A$ is skew-symmetric.
Let $S:=\{ a_1,\ldots,a_N\}$, $N>2$. Investigate which of the group axioms hold for the following operations on $S^2$:
* $a_j\circ a_k=a_{\max(j,k)}$
* $a_j\star a_k=a_{|j-k|+1}$

!!! Solution
* $\circ$: 
## Clearly $\max\{i,\max\{j,k\}\} = \max\{\max\{i,j\},k\}$, i.e., $\circ$ is associative
## $a_N$ is clearly the identity under $\circ$, 
## but $a_N$ is the only element which has an inverse under $\circ$.
* $\star$:
## $a_1$ is the identity: $a_1\star a_k = a_k$
## $a_k$ is self-inverse
## is not associative: Take $(i,j,k)=(2,3,5)$: $a_2\star a_3=a_2$, $a_3\star a_5=a_3$, $a_2\star a_5=a_4$; thus \[
(a_2\star a_3) \star a_5 = a_2\star a_5 = a_4 \neq a_2 = a_2\star a_3  = a_2\star(a_3\star a_5)
\]
Note that $\star$ is an example of a commutative yet non-associative operation.
A train of length $l_1$ and a lorry of length $l_2$ are heading for a level crossing at speeds $u_1$ and $u_2$, respectively. Initially the front of the train and that of the lorry are at distances $d_1$ and $d_2$ from the crossing. ''Find'' conditions on $u_1$ and $u_2$ under which a collision will occur. On a diagram with $u_1$ and $u_2$ as axes, shade the region which represents collision.

Hence ''show'' that if $u_1$ and $u_2$ are two independent random variables, both uniformly distributed on $(0,V)$, then the probability of a collision in the case when initially the back of the train is nearer to the crossing than the front of the lorry is $$ \frac{l_1l_2 + l_2d_1+l_1d_2}{2d_2(l_2+d_2)}$$
''Find'' the probability of a collision in each of the other two possible cases.
My two friends, $P$ and $Q$, both told me this afternoon that there is a body in my fridge. I am not sure what to make of this, because $P$ tells the truth with probability of only $p$, while $Q$ -- independently -- tells the truth with probability of  $q$. This morning, I would have said there was just as likely to be a body in my fridge as not. In view of what $P$ and $Q$ told me, I must revise this estimate. Explain why the estimate of the probability of there being a body in my fridge should be $$\frac{pq}{1-p-q+2pq}$$
I have now been to look in the fridge, and there is indeed a body in it; perhaps more than one. It seems that only my enemy $A$, or my enemy $B$, or -- with a bit of luck -- both $A$ and $B$ could be in the fridge, and this evening I would have judged the three possibilities equally likely. But tonight I asked $P$ and $Q$ separately whether or not $A$ was in the fridge, and they each said that he was. What should be my new estimate of the probability that both $A$ and $B$ are in the fridge?
Of course, I tell the truth always.
!!! Solution
Define $\Omega=\{0,1\}$ to be the set of possible states of the fridge. We have that $\prob(P=1|1)=p, \prob(Q=1|1)=q, \prob(PQ=1|1)=pq$, and that the prior is $\prob(1)=z=\frac{1}{2}$. Bayes' theorem gives us \[ 
\prob (1|PQ=1) = \prob(PQ=1|1) \frac{\prob(1)}{\prob(PQ=1)} = \frac{pqz}{\prob(PQ=1|1)\prob(1)+\prob(PQ=1|0)\prob(0)}
=\frac{pqz}{pqz+(1-p)(1-q)(1-z)}.
\] In our case, $z=1-z$, and the claim follows immediately.
Once again, by Bayes' theorem: \[
\prob(B|PQ=A) = \frac{\frac{1}{3}pq}{\prob(B\cap A\cap PQ) + \prob(B\cap(-A)\cap PQ))} 
=\frac{pq}{1-p-q+3pq}
\]
* Write down necessary and sufficient conditions for the distinct complex numbers $\al,\be,\ga$ to represent the vertices of an equilateral triangle, taken in anticlockwise order.
* Show that $\al,\be,\ga$ represent the vertices of an equilateral triangle (taken in any order) ''iff'' \[\al^2+\be^2+\ga^2 = \al\be+\be\ga+\ga\al \] 
* Find necessary and sufficient conditions on the coefficients $a,b,c\in\complex$ for the roots of \[x^3+ax^2+bx+c=0\] to lie at the vertices of an equilateral triangle in the Argand diagram.
!!! Solution
* Let $d$ be the centre of the triangle. Then \[ 
\begin{align} (\al-d)e^{2i\pi/3} &= \be-d  \\ (\be-d)e^{2i\pi/3} &= \ga-d \end{align} 
\] which is equivalent to \[
\begin{align} (\al-\be)e^{2i\pi/3} &= \be-\ga  \\ (\be-\ga)e^{2i\pi/3} &= \ga-\al \end{align} 
\] which is in fact the same condition written twice, and is clearly necessary and sufficient.
* Thus $ \frac{\al-d}{\be-d}=\frac{\be-d}{\ga-d},$ so that $\al\ga+d^2-(\al+\ga)d = \be^2+d^2 - 2\be d$ and therefore \[ \al\ga-\be^2=d(\al+\ga-2\be),\] along with the cyclic permutations $
\al\be-\ga^2=d(\be+\al-2\ga) $ and $ \be\ga-\be^2=d(\be+\ga-2\al)$. Adding these identities, we get \[\al^2+\be^2+\ga^2 = \al\be+\be\ga+\ga\al \] as required. We can also argue that 'taken in either order' means either clockwise or anticlockwise, so \[ 
((\al-\be)e^{2i\pi/3}-(\be-\ga))((\al-\be)e^{-i\pi/3}-(\be-\ga)) = 0 
\]
** ''only if'?''
** ''show also'': $3d=\al+\be+\ga$
* We have \[x^3+ax^2+bx+c=(x-\al)(x-\be)(x-\ga),\] so that $ -a=\al+\be+\ga $, $b=\al\be+\be\ga+\ga\al$, and $-c=\al\be\ga$. From the above, we also have $b=\al^2+\be^2+\ga^2$, and $a^2 = \al^2+\be^2+\ga^2+ 2(\al\be+\be\ga+\ga\al) = 3b $.
* As an aside, let us explore the following quantities:
** $a^2 = \al^2+\be^2+\ga^2+ 2(\al\be+\be\ga+\ga\al) = 3b $
** $-ab = (\al+\be+\ga)(\al\be+\be\ga+\ga\al) = -3c+\al^2(\be+\ga)+\be^2(\al+\ga)+\ga^2(\al+\be)$
** $-a^3=(\al+\be+\ga)^3 = \al^3+\be^3+\ga^3 + 6\al\be\ga + 3[\al^2(\be+\ga)+\be^2(\al+\ga)+\ga^2(\al+\be)]$
** Eliminate $Q:=\al^2(\be+\ga)+\be^2(\al+\ga)+\ga^2(\al+\be)$:
*** $-a^3=-3ab$
*** $3[-3c+Q]=\al^3+\be^3+\ga^3 -6c +3Q$
*** so that $\al^3+\be^3+\ga^3 = -3c $
** On the other hand,
** $-(\al^3+\be^3+\ga^3)=a(\al^2+\be^2+\ga^2)+b(\al+\be+\ga)+3c=ab-ba+3c=3c$
Recall that a definite integral can be approximated by the trapezium rule
$$
  \int_{x_0}^{x_n}\!f(x)\,dx \approx \frac{h}{2} \left\{ f(x_0) + 2f(x_1) + \ldots + 2f(x_{n-1}) + f(x_n) \right\} = h\sum_{k=0}^n\,f(x_k) - \frac{h}{2}[f(x_0) + f(x_n)]
$$

Use trapezium rule to ''estimate'' $\int_1^n\!x\,dx$, for $\mathbb{N}\ni n>2$:
$$\int_1^n\!ln(x)\,dx \approx ln(2) + ln(3) + \ldots + ln(n) - \frac{1}{2}ln(n) $$
''Deduce'' that $n! \approx g(n) := n^{n+\frac{1}{2}} e^{1-n} $.
We have $$ e^{\int_1^n\!ln(x)\,dx} \approx e^{\sum_{k=2}^{n}\!ln(n) - \frac{1}{2}ln(n)} = n! \times n^{-1/2}$$
And, integrating by parts: $$\int_1^n\!ln(x)\,dx = \int_1^n\!\frac{dx}{dx}\,\int_1^x\!\frac{1}{s}\,ds\,dx = (x-1) ln(x) $$  (Remember that $\int (u'\int\!v) = u\int\!v - \int\!uv$)
Thus, $${\left(e^{ln(n)}\right)}^{n-1} = n^{n-1} \approx n! \times  n^{-1/2}$$

By using the trapezium rule with intervals of length $k^{-1}$ for $k\in\mathbb{N}$, ''show'' that
$$
   (kn)! = k!\,n^{kn+\frac{1}{2}} \left( \frac{e}{k} \right)^{k(1-n)}
$$

''Determine'' if this approximation or $g(kn)$ is closer to $(kn)!$
For fixed vectors $a\neq b$, describe the locus in 3D given by each of the following 4 equations:
# $(a-b)\cdot r = \frac{|a|^2-|b|^2}{2}$
# $(a-r)\cdot(b-r) = 0$
# $|r-a|^2 = \frac{1}{2}|a-b|^2$
# $|r-b|^2 = \frac{1}{2}|a-b|^2$
Prove algebraically that the equations (1) and (2) together are equivalent to (3) and (4) together. Explain carefully the geometric meaning of this equivalence.
!! Solution
(1) is the equation the perpendicular bisector of the segment (a-b): it is the plane with normal $a-b$ which clearly passes through $Z:=\frac{a+b}{2}$.
(2) is the equation of a sphere with the centre at $\frac{a+b}{2}$, and radius $R:=\frac{|a-b|}{2}$. This can be seen geometrically from $(a-r)\perp(b-r)$, or algebraically by completing the square:  \[ 
|r-\frac{a+b}{2}|^2 =  \frac{a^2}{4} + \frac{b^2}{4} + \frac{a\cdot b}{2} + ( r^2 + a\cdot b  - (a+b)\cdot r) - a\cdot b = R^2 + 0
\]
(3) is the sphere centered at $a$ with radius $R\sqrt{2}$
(4) ditto, centered at $b$

The intersection of the spheres in (3) and (4) is clearly a circle in the perpendicular bisector. Subtracting (3) and (4), we immediately obtain (1); and summing them we get \[ 
 r^2 - r\cdot(a+b) + a^2/4 + b^2/4 + \frac{a\cdot b}{2} = |r-Z|^2 = \frac{a^2}{4}+\frac{b^2}{4}-\frac{a\cdot b}{2} = R^2
\] Which we know is equivalent to (2). Conversely, expanding the dot product in (2) and adding to (1) we get \[
 r^2 - 2a\cdot r + a^2 = |r-a|^2 = \frac{b^2}{2}-a\cdot b + \frac{a^2}{2} = \frac{1}{2}|a-b|^2.
\] Similarly, subtracting (2) and (1) we obtain (4).
Let $a,b\in\mathbb{N}^{+}$ such that $b<2a-1$. For any integer $n\geq1$, the integers $N_n, M_n$ are defined as
\[
  [a+\sqrt{a^2-b}]^n = N_n - r_n
\]
and
\[
  [a-\sqrt{a^2-b}]^n = M_n + s_n
\]
where $0\leq r,s<1$. ''Prove'' that:
# $ M=0 $
# $ r=s $
# $ r_n^2-N_nr_n+b^n = 0 $
''Show'' that for large $n$, $(8+3\sqrt{7})^n$ only differs from an integer by about $2^{-4n}$.

!! Solution

From the condition on $b$, $b<2a-1$, we have $a-\sqrt{a^2-b} < a-\sqrt{a^2-2a+1} = a-\sqrt{(a-1)^2} = 1$. Thus by induction,
$M_n + s_n = s_{n-1} (a-\sqrt{a^2-b}) < s_{n-1} < 1$, i.e. $M_n=0 \ \forall n$.

Finally, take $a=8$, $b=1$, so that $a^2-b=63=7\cdot 3^2$; consequently $r_n = \frac{N_n}{2} \left\{ 1- \sqrt{1-(\frac{2}{N_n})^2}\right\}$
Given crude model of population dynamics, with A and B representing the numbers of aardvarks and buffaloes, respectively:
$$
\pmatrix{ A_{n+1} \\ B_{n+1} } =:v_{n+1} = L\,v_n := \pmatrix {\frac{3}{4} & \frac{1}{4} \\ -\frac{1}{2} & \frac{3}{2}  } v_n 
$$
It is assumed that if either $A_n$ or $B_n$ becomes non-positive for some $n$, the population becomes extinct.

* ''Show'' that the ratio of the number of buffaloes to the number of aardvarks can remain the same every year, provided it takes one of two possible values.

Suppose $\frac{A_n}{B_n} = a \neq 0$ for some $n \geq 1$. If this ratio is preserved in the next step, we must have

$$
  \lambda \pmatrix{ a \\ 1 } = \pmatrix{ \frac{3}{4} & \frac{1}{4} \\  -\frac{1}{2} & \frac{3}{2}  } \pmatrix{ a \\ 1 }
$$

which is an eigenvalue problem:
$$
   (\frac{3}{4} - \lambda)(\frac{3}{2}-\lambda) + \frac{1}{8} = 0
$$

with solutions $\lambda_{\pm} = \frac{5}{4}, 1$, corresponding to eigenvectors $v_\mp = (1,1)^T, (\frac{1}{2},1)^T$.

* If the numbers of aardvarks and buffaloes in a particular year are $a$ and $b$, respectively, ''find'' their numbers in the subsequent years.

Note that the eigenvectors $v_\pm$ span the configuration space: $ (a,b)^T = \alpha\,v_- + \beta\,v_+$, with $\alpha = 2a-b, \beta = 2(b-a) $; so that
$$
 v_{n+s} = L^s \pmatrix{a \\ b } = (2a-b)\times1^s\times\pmatrix{1 \\ 1}+ 2(b-a)\times(\frac{5}{4})^s\times\pmatrix {1/2 \\ 1 }
$$

In the $a-b$ plane, ''mark'' the regions which correspond to the following situations:
# an equilibrium is reached in the limit $t\to\infty$
# buffaloes become extinct after a finite time
# buffaloes approach extinction as $t\to\infty$

<div class='SVGgraph' style='float:right' options="scales:[-1,5,-1,5]">
axes();
var j, a = [];
for(j=0;j<50;j++){
  a.push([j/10,j/10]);
  path(a,{stroke:"none",marker:"-o-",size:3});
}
plot("1.2*x",{steps:[0]});
slopeField("2*(y-x)/(y-4*x)",{dx:0.5, dy:0.5, marker:"-->",size:4, markerstroke:"pink",stroke:"pink"});
</div>
In how many ways can the sum $s$ of two integers be expressed, if each integer is between 0 and $m$?
How about the sum of three integers, with the same restriction?
!!! Solution
If $0\leq s\leq m$, we can write $s=k+(s-k)$, where $0\leq k\leq s$, and hence there are $s+1$ ways of doing so. On the other hand, if $m\leq s\leq 2m$, we can express $s=2m-S$, where $0\leq S\leq m$, and by the above there are $2m-s+1$ possible ways. In summary, \[
N_2 = 1+ s \times 1_{0\leq s\leq m} (s) + (2m-s) \times 1_{m<s\leq 2m} (s)
\]
For a sum of three integers, if $0\leq <m$, we have $s=s_1+(s_2+s_3)$, and, for every value of $s_2+s_3$ there is only one way of obtaining $s$. Thus the total number of combinations in this case is $\sum_{k=0}^{s}(k+1)=\frac{(s+1)s}{2}$.
Similarly, if $2m<s\leq 3m$, we have $s=3m-S$ where $0\geq S=3m-s<m$, and the number of possibilities is $\frac{(3m-s+1)(3m-s)}{2}$.
If $m<s\leq2m$, the total number is $\frac{6ms-3m^2-2s^2+3m+2}{2}$
Suppose $B$ is a standard normal variable: $B \sim N(0,1)$. ''Find'' the probability that the roots of $$X^2+2BX+1=0$$ are real.
''Given'' that the two roots $X_\pm$ are real, ''find'' the probability that both of them are greater than $\frac{1}{5}$, and ''calculate'' the expected value of $|X_++X_-|$.
!!Solution
We have $$X^2+2BX+1 = (X+B)^2 - (B^2-1) = 0$$ which clearly only has real roots if $B^2 \geq 1$, i.e. $|B|\geq1$. Thus $\prob(A)=2(1-\Phi(1))=:a.$ $A$ is the event that the given equation has real roots. 
The sum if the roots is equal to the linear coefficient: $|X_-+X_+|=2|B|,$ hence \[ 
\xpct(|X_-+X_+|\,{\Large|}A)=2\times\frac{2\times\int_1^\infty\!xe^{-x^2/2}\,dx}{\sqrt{2\pi}a} =
   \frac{2e^{-\frac{1}{2}}}{\sqrt{2\pi}(1-\Phi(1))}
 \]
Finally, let us consider the probability that the smaller root (and hence both roots) is greater than 1/5: \[ 
a\times\prob[X_->\frac{1}{5}|A] = \prob[-B-\sqrt{B^2-1}>\frac{1}{5}] 
  =\prob[-\sqrt{B^2-1}>B+\frac{1}{5} \wedge B>1 ] +  \prob[-\sqrt{B^2-1}>B+\frac{1}{5} \wedge B\leq-1]  
\]
If $B>1$, there are clearly no solutions; $-\sqrt{B^2-1}\leq0$ but $B+\frac{1}{5}>0$. Thus we must have $0>-\sqrt{B^2-1}>B+\frac{1}{5}$, so that \[
a\times\prob[X_\pm>\frac{1}{5}|A] = \prob[B^2-1<B^2+\frac{2B}{5}+\frac{1}{25}] = \prob[-1>B>-\frac{13}{5}]=\Phi(\frac{13}{5})-\Phi(1)
\] and finally \[ \prob[X_\pm>\frac{1}{5} | A ]= \frac{\Phi(\frac{13}{5})-\Phi(1)}{2(1-\Phi(1))}\]
Prove that $\cos 3\th = 4\cos^3\th - 3\cos \th$, and use it to solve the cubic equation \[ 24x^3 - 72x^2 +66x -19 = 0. \]
!!! Solution
In general, let us start with a monic cubic $x^3+\al x^2 + \be x + \ga = 0.$ We can eliminate the quadratic term by translation $y = x-a$: 
\[ 0 = y^3 + y^2 (\al-3a) + y(3a^2-2a\al + \be) + \hat\ga, \] so choosing $\al = 3a$ we reduce the cubic to \[ y^3 - \frac{D}{12}y  + \hat\ga = 0.\]
Note that the condition for the cubic to have a critical point $3x^2+2\al x + \be = 0$ is $D=4(\al^2-3\be)\geq0$. 
If $D>0$, we can rescale $z=\frac{\sqrt{D}}{3}y$ to obtain \[ \frac{D^{3/2}}{4\times3^3} (4z^3 - 3z +k ) =0 \]
In our example, $\al=3a=-3,\be=\frac{33}{12}, D=3$, so that $-k=\frac{\sqrt{3}}{2}$, so that the solutions are \[ 
x = 1 + \frac{\cos\al\frac{\pi}{18}}{\sqrt{3}}
\] where $\al\in\{1,11,13\}$
Evaluate the integrals:
!! $\int_0^{2\pi}\!\cos(mx)\cos(nx)\,dx$, where $m,n\in\integer$
We have $\cos((m\pm n)x) = \cos(mx)\cos(nx)\mp\sin(mx)\sin(nx)$, so that \[ 
2\cos(mx)\cos(nx) = \cos((m+n)x)+\cos((m-n)x) \] and thus \[
\int_0^{2\pi}\!\cos(mx)\cos(nx)\,dx = \frac{1}{2}\int_0^{2\pi}\!\cos((m+n)x)\,dx+\frac{1}{2}\int_0^{2\pi}\!\cos((m-n)x)\,dx = \begin{cases}0 & m\neq n \ {\rm and}\  m\neq -n \\ \pi & {\rm otherwise}\end{cases}
\]
!! $\int\!\sqrt{1+\frac{1}{x}}\,dx$
Solve the ~ODEs by making the suggested substitutions:

!!! $y'-y-3y^2=-2$ by substituting $y=-\frac{u'}{3u}$
We have $y'=\frac{(u')^2}{3u^2}-\frac{u''}{3u}$, from which $-\frac{u''}{3u}+\frac{u'}{3u}=-2$, $u''-u'-6u=0$. Characteristic equation $k^2-k-6=(k-3)(k+2)=0$,
so that $u=Ae^{3x}+Be^{-2x}$, and finally \[
y=\frac{1}{3}\times\frac{2Be^{-2x}-3Ae^{3x}}{Ae^{3x}+Be^{-2x}}
.\]

!!! $x^2y'+xy+x^2y^2$ by substituting $y=\frac{1}{x}+\frac{1}{v}$, where $v=v(x)$
We have $y'=-\left(\frac{1}{x^2}+\frac{v'}{v^2}\right)$, $y^2=\frac{1}{x^2}+\frac{1}{v^2}+\frac{2}{xv}$, so that \[
-x^2(\frac{1}{x^2}+\frac{v'}{v^2}) + x(\frac{1}{x}+\frac{1}{v}) + x^2 (\frac{1}{x^2}+\frac{1}{v^2}+\frac{2}{xv}) = 1
\] and thus $v'+\frac{3}{x}v=-1$. The integrating factor is $x^3$, therefore $v=\frac{C}{x^3}-\frac{x}{4}$
Let $P=(x_P,y_P)$ be a point in $\real^2$. Define the transformation $T$ of $\real^2$ as follows: lines are drawn through $P$ parallel to the lines $y=mx$ and $y=-mx$ to cut the line $y=kx$ at points $Q$ and $R$ respectively. $T(P)=:Z$ is the fourth vertex of the parallelogram $PQZR$. Find the matrix of the transformation $T$, and show that $T$ preserves area.
!!! Solution
Let us find the coordinates of point $Q=(x_Q,y_Q)$ first: solve the system \[
\begin{eqnarray}
y_Q &= k x_Q \\
\frac{y_Q-y_P}{x_Q-x_P} &= m
\end{eqnarray}
\] to give $x_Q = \frac{mx_P-y_P}{m-k}$, $y_Q=k\frac{mx_P-y_P}{m-k}$. 
Similarly for $R$: $x_R=\frac{mx_P+y_P}{m+k}$, $y_Q=k\frac{mx_P+y_P}{m+k}$
To find $Z$, we solve the system \[
\begin{eqnarray}
\frac{k x_R-y_Z}{x_R-x_Z} &= +m \\
\frac{k x_Q-y_Z}{x_Q-x_Z} &= -m
\end{eqnarray}
\] to give \[
\left( \begin{array}{c} x_Z \\ y_Z \\ \end{array} \right) = 
 \left( \begin{array}{cc} 1 & 1 \\ 1 & 1 \\ \end{array} \right)
\left( \begin{array}{c} x_P \\ y_P \\ \end{array} \right) 
\]
Sum the following series:
!!! $1+\frac{1}{3}(\frac{1}{2})^2 + \ldots + \frac{1}{2n+1}\left(\frac{1}{2}\right)^{2n} + \ldots $
Start with the power series $S_n = \sum_{n=0}^\infty x^{2n} = \frac{1}{1-x^2}$, with radius of convergence 1, within which it can be integrated term-by term: \[ \int_0^x\!\frac{ds}{1-s^2} = x\sum_{n=0}^\infty\frac{x^{2n}}{2n+1} - 0 \] Evaluating the integral e.g. by partial fraction decomposition; \[
\log \left| \frac{1+x}{1-x}\right| = 2x \sum_{n=0}^\infty\frac{x^{2n}}{2n+1}. \] Substituting $x=\frac{1}{2}$ yields the required sum, which evaluates to $\log3$

!!! $2-x-x^3+2x^4-\ldots+2x^{4k}-x^{4k+1}-x^{4k+3}+\ldots $ for $|x|<1$
$\sum_{j=0}^\infty\! 2x^{4k}-x^{4k+1}-x^{4k+3}=\sum_{j=0}^\infty\! x^{4k}-x^{4k+1}+ x^{4k}-x^{4k+3}$

!!! $\sum_{r=2}^\infty\!\frac{r2^{r-2}}{3^{r-1}} $
Let us consider $ v(x) := \sum_{r=2}^\infty\!x^r = \frac{1}{1-x} - (x+1)$, so that $v'(x) = \sum_{r=2}^\infty\!r x^{r-1} = \frac{1}{(1-x)^2} - 1$. But \[ 
\sum_{r=2}^\infty\!\frac{r2^{r-2}}{3^{r-1}} = \frac{1}{2}\sum_{r=2}^\infty\!\frac{r2^{r-1}}{3^{r-1}} = \frac{1}{2}v'(x)|_{x=\frac{2}{3}} = 4
\]

!!! $\sum_{r=2}^\infty\!\frac{2}{r(r^2-1)} $
We have \[ 
\sum_{r=2}^\infty\!\frac{2}{r(r^2-1)} = \sum_{r=2}^\infty\!\frac{1}{r}\left(\frac{1}{r-1}-\frac{1}{r+1}\right)
\]
Now $\sum_{r=2}^\infty\!\frac{1}{r}\frac{1}{r-1}=\frac{1}{2}\sum_{r=2}^\infty\!\left(\frac{1}{r-1}-\frac{1}{r}\right) = \frac{1}{2}(1-\frac{1}{2}+\frac{1}{2}-\frac{1}{3}+\ldots)=\frac{1}{2}$, and similarly $\sum_{r=2}^\infty\!\frac{1}{r}\frac{1}{r+1}=\frac{1}{4}$, so that $\sum_{r=2}^\infty\!\frac{2}{r(r^2-1)}=\frac{1}{2}$
The point in the Argand diagram representing the complex number $z$ lies on the circle with centre $k$ and radius $r$.
''Claim'': $zz^* - zk^* -z^*k + kk^* -r^2 = 0$.
It is trivial to see this statement if we recall the equation of the circle: 
$$ r^2 = |z-k|^2 = (z-k)(z-k)^* = (z-k)(z^*-k^*) = zz^* - zk^* -z^*k + kk^* $$

Let $L$ be the locus of points $z$ be the circle with centre at $i$ and radius 1. Find the locus $M$ of the points obtained from $L$ by transformation $\omega_1 = \frac{z}{z-1}$.
''Claim'': $M$ is also a circle, with centre at $-i$ and radius 1. We can verify it as follows:
The equation that $z$ satisfies is $zz^* + i\,z - i\,z^* = 0$. Now, for $\omega_1$:
$$(\omega_1 + i)(\omega^* - i) = (\frac{z}{z-1} + i) (\frac{z^*}{z^*-1} - i) = 1 + \frac{zz^*-iz+iz^*}{(z-1)(z^*-1)} = 1 $$

''Show'' that the locus $N$ of points obtained from $L$ by the transformation $\omega_2 := z^*$ coincides with $M$. ''Determine'' the values of $z$ for which $\omega_1 = \omega_2$.
That $L=M$ can be seen either from 1) the transformation $z\to z^*$ is the reflection in the real axis; or 2) symbolically from the equation for $z$, by substituting $z^*=\omega_2$: $$\omega_2\omega_2^* -i\omega_2 + i\omega_2^* + ii^* - 1^2 = 0$$

From the condition $\omega_1 = \omega_2$, we have $\frac{z}{z-1} = z^*$, which leads us to the equation of a circle of radius 1 centered at 1:
$$ zz^* - 1z^* - 1^*z + 1\times1^* - 1^2 = 0 $$
This circle intersects $L$ at $z=0$ and $z=1+i$.
Show: \[ (n-1)\sum_1^n\!a_i^2\geq\sum_{i\neq j}\!a_ia_j 
\] and \[
\left(\sum_1^n\!a_i\right)^2 \geq \frac{n}{n-1}\sum_{i\neq j}\!a_ia_j
\]
!!! Solution
Start with $0\leq\sum_{i<j}\!(a_i-a_j)^2 = (n-1)\sum\!a_j^2 - \sum_{i\neq j}\!a_ia_j$, which gives the first inequality, and note that
\[ (n-1)(\sum\!a_i)^2 - n\sum\!a_ia_j = n\left[\left(\sum\!a_i\right)^2 - \sum_{i\neq j}\!a_ia_j\right] - \left(\sum\!a_i\right)^2 = (n-1)\sum\!a_i^2 - \sum_{i\neq j}\!a_ia_j \geq 0
\] which gives the second inequality immediately, since $n-1>0$.
Define operation $\circ$ on $\complex^2$ by \[ (z_1,z_2)\circ(\om_1,\om_2) = (z_1\om_1-z_2\om_2^*,z_1\om_2+z\om_1^*)
\] Evaluate: $(z,0)\circ(\om,0)=(z\om,0)$, $(z,0)\circ(0,\om)=(0,z\om)$, $(0,z)\circ(\om,0)=(0,z\om^*)$, $(0,z)\circ(0,\om)=(-z\om^*,0)$. 

$\circ$ is associative: \[
[(a,b)\circ(c,d)]\circ(e,f) = ((ac-bd^*)e-(ad+bc^*)f^*,(ac-bd^*)f+(ad+bc^*)e^*) = (a,b)\circ[(c,d)\circ(e,f)]
\]
$\circ$ is not commutative: \[
(1,i)\circ(i,1) = (0,2) \neq (2i,0) = (i,1)\circ(1,i)
\]

Let $S:=\{A,B,C,D,E,F,G,H\}\subset\complex^2$, where $A:=(1,0),B:=(0,1),C:=(i,0),D=(0,i),E=-A,F=-B,G=-C,H=-D$
From calculations in the first section, we see that $S$ is closed under $\circ$. Moreover, $A$ is the identity.
We can directly verify: $B^{-1}=F$, $C^{-1}=G$, $D^{-1}=H$, $E^{-1}=E$, $F^{-1}=B$, $G^{-1}=C$, $H^{-1}=D$.

Find the order of each element of $S$: $o(A)=1, o(E)=2$, $B^2=C^2=D^2=F^2=G^2=H^2=E$, so that $o(B)=o(C)=o(D)=o(F)=o(G)=o(H)=4$. In fact, we have $<B>=<F>=\{A,B,E,F\}$, $<C>=<G>=\{A,C,E,G\}$, $<D>=<H>=\{A,D,E,H\}$

Finally, consider the group $P:=<x>:=\left<\left(\begin{array}{cc}0 & 1 \\ -1 & 0 \\\end{array}\right)\right>$ under matrix multiplication. It is easy to see that $\phi:S\to P$, $\phi(B)=x$ is a group isomorphism.
# Show that the set of matrices of the form $\left(\begin{array}{cc} a & a \\ a & a \\ \end{array}\right) $ for $a\neq0$ is a group under matrix multiplication.
# Suppose $S$ is a set of $n\times n$ matrices which is a group under matrix multiplication. Show that if any element $a\in S$ is singular (i.e.) $\det a=0$ then all elements of $S$ are singular. Give an example of such a group for $n=3$.
!! Solution
If we write $M(a):=a\left(\begin{array}{cc} 1 & 1 \\ 1 & 1 \\ \end{array}\right)$ and $I:=M(1)$ we see that $M(a)M(b)=2abM(1),$ from which the group axioms are clear. Note that the unit element is $M(1/2)$, and the inverse to $M(a)$ is $M(\frac{1}{4a})$.
Since $S$ is a group, every element $x$ can be expressed as $x=aa^{-1}x$, so that $\det x = \det a \det (a^{-1}x) = 0$. An example is the group of matrices of the form $\left(\begin{array}{ccc} a & a & a \\ a & a & a \\ a & a & a \\ \end{array}\right)$ for $a\neq0$.
Game of Cambridge Whispers: Albert flips a fair coin and whispers to Bertha the result 'heads' or 'tails'. Bertha then whispers to her neighbor, and so on, until the last player, Zebedee, whispers the result back to Albert. What is the probability that Albert hears the correct result, given that the probability of hearing what is said is $2/3$, independently for all  for all players. If Albert does not hear the correct result, the game continues until he does. Find the expected number of 'rounds' until the game stops.

!! Solution
Let the probability of correct transmission at each stage be $p$, probability of a 'flip' $q:=1-p$. For an even number of steps $n=2m$, probability of 'win' = probability (number of 'flips' is even) = \[ \sum_{k=0}^{m}\!{n \choose 2k} p^{n-2k}(1-p)^{2k} = \frac{1+(2p-1)^n}{2} =: r. \] (from the binomial expansion $
(p+q)^n+(p-q)^n = 2\sum_{k=0}^n\!{n \choose 2k}p^{n-2k}q^{2k}
$)
Now the probability of 'loosing' a round is $s:=1-r=\frac{1-(2p-1)^n}{2},$ and the probability of winning the game on the $a^{th}$ round is given by the Geometric r.v. $\prob(X=a)=s^{a-1}r$ with the expectation equal to \[ 
\xpct X = r\sum_a^\infty\!a s^{a-1} = \frac{r}{r^2} = \frac{1}{r} = \frac{2}{1+(2p-1)^n}
\]
Traffic enters a tunnel 9600m long, in which overtaking is impossible. The number of vehicles entering is governed by the Poisson distribution with mean 6 cars per minute. All vehicles travel at constant speed until forced to slow down on catching up a slower vehicle ahead. I enter the tunnel travelling at 30 m/s and all other traffic is travelling at 32 m/s. What is the expected number of vehicles queuing behind me when I leave the tunnel?

Now suppose I travel at 30 m/s, but all the other vehicles are independently equally likely to travel at either 30m/s or 32 m/s. Find the probability that exactly 2 vehicles enter the tunnel and catch me up before I leave it. Also find the probability that there are exactly 2 vehicles queuing behind be when I leave the tunnel.

!! Solution
First, we determine the time window $\de$ in which the entering faster car will catch up with me: $9600 \geq 32(t-\delta) \geq 30t$ and  $\geq 32(t-\delta)$, i.e. $t\leq320$sec, and $\delta\leq\frac{t}{16}\leq20$ seconds. The probability of a car entering in (1/3) of a minute is once again a Poisson random variable $X_\la$, with parameter $\la=\frac{6}{3}=2$, which is also the expected value of this distribution.
Now, if there is other slower traffic entering the tunnel, denote by $p$ the fraction ($=\frac{1}{2}$ in this example) of the slower vehicles and let $q:=1-p$. The probability that exactly 2 vehicles enter the tunnel and catch me up before I leave it is $\prob(X_\la=2)\times q^2=\frac{1}{2e^2}$. The situation where exactly 2 cars are queuing behind be can be achieved either if no additional cars enter within the same 20 seconds, or if exactly the third car entering is the 'slower' car, which gives the combined probability of \[ q^2\prob(X_\la=2) + q^2 p\prob(X_\la\geq3) =\frac{e^2-1}{8}  \]
One definition of the Bernoulli polynomials is $B_0=1$, and - for $n\geq1$, \[\frac{d}{dx}B_n=nB_{n-1}\] and \[ \int_0^1B_n\,dx=0 \]
''Calculate'' $B_4$, show that $B_n(1)-B_n(0)=0$, that \[B_n(x+1)-B_n(x) = nx^{n-1}, \] and that $\sum_{m=0}^{1000}\!m^3=(500500)^2$.
!! Solution
We have, trivially, $B_0=1,B_1=x-\frac{1}{2}, B_2=x^2-x+\frac{1}{6}, B_3=x^3-x^2+\frac{1}{2}, B_4 = x^4-2x^3+x^2-\frac{1}{30}=x^2(x-1)^2-\frac{1}{30}$. Also, \[ 0=n\int_0^1\!B_{n-1\,dx}=\int_0^1\!\frac{d}{dx}B_n\,dx = B_n(1)-B_n(0). \] Now \[
\frac{d}{dx}(B_{n+1}(x+1)-B_{n+1}(x) - (n+1)x^n) = (n+1) (B_n(x+1) + B_n(x) - nx^{n-1}) = 0
 \] by induction. Since $B_n(0+1)-B_n(0)=0$, the claim follows immediately. Finally, writing the telescopic sum \[\sum_{m=0}^k\!m^{n-1} = B_n(k+1)-B_n(0) \] for $k=1000$, we obtain $\sum_{m=0}^{1000}\!m^3=\frac{B_4(1001)-B_4(0)}{2^2} = (500\times1001)^2 = (500500)^2$
Two identical snowploughs plough the same stretch of road. The first starts at time $t_1$ after it starts snowing, and the second starts in the same direction time $t_2-t_1$ thereafter. The depth of the falling snow increases at a constant rate $k$. The speed of each snowplough is $k\frac{a}{z}$, where $z$ is the depth of snow on the road and $a$ is a constant. Each plough clears all the snow. Show that the time $t$ at which the second snowplough has travelled distance $x$ satisfies the equation \[ a\frac{d\,t}{d\,x}=t-t_1e^{x/a}\] and show that the ploughs will collide after travelling the distance $a(\frac{t_2}{t_1}-1)$.
!! Solution
For the first snowplough, the equation of motion is \[ \frac{d\,t}{d\,x_1} = 1/\frac{d\,x_1}{d\,t} = \frac{z_1}{ka} = \frac{t}{a} \] From which \[ 
t=t_1\exp(x/a) \]
For the second plough, $z_2=k(t-\tau)$ where $\tau$ is the time at which the first plough has passed the same $x$ position. From the above, \[
z_2 = k(t-t_1\exp(x/a)) \] and therefore \[ \frac{d\,t}{d\,x_2} = \frac{z_2}{ka} = \frac{t-t_1\exp(x/a)}{a}\]
The integrating factor for this equation is $f=\exp(-x/a)$: \[ 
ft-aft'=a\frac{\exp(-x/a)}{a}t-a\exp(-x/a)t'=-a(\exp(-x/a)t)' =t_1
\] Which integrates to \[
t\exp(-x/a) = -\frac{x}{a}t_1+c
\] and the initial condition $t(x=0)=t_2$: $ t_2=c$
For the collision, we have \[ 
t_1\exp(x/a)\exp(-x/a)=t_2-\frac{x}{a}t_1
\] From which the claim follows trivially.

!!! Generalization to $n$ identical snowploughs
Define the indefinite integrals $I_1:=\int\!\frac{\cos x}{\cos x+\sin x}\,dx$ and $I_2:=\int\!\frac{\sin x}{\cos x+\sin x}\,dx$. By considering $I_1\pm I_2$, determine $I_{1,2}$. Also determine \[J_1:=\int\!\frac{\cos x}{a\cos x+b\sin x}\,dx.\]
!! Solution
Omitting the integration constants, we have $I_1+I_2=x,$ and $I_1-I_2=\int\!\frac{f'}{f}\,dx=\log|\cos x+\sin x|$, where $f:=\cos x+\sin x$. Thus \[ 
I_{1,2} = \frac{x\pm\log|\cos x+\sin x|}{2}. \]
Similarly, define $J_2:=\int\!\frac{\sin x}{a\cos x+b\sin x}\,dx$, and consider $aJ_1+bJ_2=x$; $bJ_1-aJ_2=\log|a\cos x+b\sin x|$, from which \[
J_{1,2} = \frac{ax\pm b\log|a\cos x+b\sin x|}{a^2+b^2}
\]
It is also instructive to use the same method for $e^{\pm x}sech(x)=\frac{2e^{\pm x}}{e^x+e^{-x}}$, and also to rederive $J_{1,2}$ by writing $a\cos x+b\sin x =: R\cos(x-\al)$.
* Show, by means of the substitution $x=\al \cos^2\th +\be \sin^2\th$, that \[ \int_\al^\be\!\frac{dx}{\sqrt{(x-\al)(\be-x)}} = \pi \] when $\al<\be$.
* Using the substitution $t=x^{-1}$, show that \[ \int_a^b\frac{dt}{t\sqrt{(t-a)(b-t)}} =\frac{\pi}{\sqrt{ab}}\] when $0<a<b$
* Evaluate, for $d>c>0$, the integral \[ \int_c^d\!\frac{du}{u\sqrt{(u^2-c^2)(d^2-u^2)}}\]
!!! Solution
First, $dx=(\be-\al)\times2\sin\th\cos\th\,d\th$, and $\sqrt{(x-\al)(\be-x)}=\sqrt{((\be-\al)\sin\th\cos\th\times(\be-\al)\sin\th\cos\th}$, so that \[ 
\int_\al^\be\!\frac{dx}{\sqrt{(x-\al)(\be-x)}} = \int_{\th=0}^{\th=\pi/2}\!2\th\,d\th = \pi \] Note that for $\be<\al$, we have $\int_\al^\be\!I\,dx=-\int_\be^\al\!I\,dx=-\pi$
Now $dt=-\frac{dx}{x^2}=-t^2\,dx$, so that \[ \int_a^b\frac{dt}{t\sqrt{(t-a)(b-t)}} = 
\int_\frac{1}{b}^\frac{1}{a}\!\frac{dx}{\sqrt{(1-ax)(bx-1)}}
= \frac{1}{\sqrt{ab}}\int_\frac{1}{b}^\frac{1}{a}\!\frac{dx}{\sqrt{(\frac{1}{a}-x)(x-\frac{1}{b})}}
= \frac{\pi}{\sqrt{ab}}\]
For the last integral, make substitution $u^2=:v$, so that $dv=2u\,du$, and \[ 
 \int_c^d\!\frac{du}{u\sqrt{(u^2-c^2)(d^2-u^2)}} = \frac{\pi}{2cd}
\] 
Define $F:=1+\sum_1^\infty\!\frac{t^n}{n!}A^n$, where $A:=\left(\begin{array}{rr} -3 & -1 \\ 8 & 3 \end{array}\right)$, and $t\in\real$.
Calculate $A^2$, and show that \[ F = 1\cosh t + A\sinh t. \] Verify that $F^{-1}=1\cosh t - A\sinh t =:G $, and that $\dot F =FA$.
Now suppose that $r\in\real^2$ satisfies $\dot r + Ar = 0$, with initial condition $r(0)=r_0=(a,b)^T$. Show that \[ 
r(t) = Gr_0 
\]
!! Solution
We have $A^2=1$, and therefore $F = 1 \sum_{n=0}^\infty\!\frac{t^{2n}}{(2n)!} + A\sum_{n=0}^\infty\!\frac{t^{2n+1}}{(2n+1)!} = 1\cosh t + A\sinh t $. Simple multiplication shows $FG=1$,and that $\dot F = \sinh t + A\cosh t = FA$. Pre-multiplying the ODE by $F$, we get \[
F \dot r + FA r = F\dot r + \dot F r = \frac{d}{dt}\!(Fr)=0
\] Thus $Fr = F|_{t=0}r_0=r_0$, and $r=Gr_0$.
1) Find all sets of positive integers $a,b,c$ that satisfy the equation \[ \frac{1}{a} + \frac{1}{b} + \frac{1}{c} = 1\]
2) Determine the sets of positive integers $a,b,c$ that satisfy the inequality \[ \frac{1}{a} + \frac{1}{b} + \frac{1}{c} \geq 1 \]
!! Solution
Wlog $a\geq b\geq c$, so that $\frac{1}{a}\leq\frac{1}{b}\leq\frac{1}{c}\leq1$. Clearly we must have $a,b,c\geq2$.
Take $c=2$: then $\frac{1}{a}+\frac{1}{b}=\frac{1}{2}$. $b=2$ is not an option, but $b=3$ gives $a=6$. $b=4$ also gives a solution, $a=4$. However, for $b\geq5$ we have $\frac{1}{a}\geq\frac{1}{2}-\frac{1}{5}=\frac{3}{10}$, so $5\leq b\leq a<4$, which is impossible.
Now for $c=3$: $a=b=3$ is clearly a solution, but $b\geq4$ yields $4\leq a\leq[\frac{2}{3}-\frac{1}{4}]^{-1}=\frac{12}{5}<3$ which once again is impossible.
Finally, $c\geq4$ gives $\frac{2}{b}\geq\frac{1}{a}+\frac{1}{b}\geq\frac{3}{4}$, so that $4\leq c\leq b\leq{8}{3}<3$, and once again we have no solutions.
Thus, the possibilities are $\{2,3,6\},\{2,4,4\}$ and $\{3,3,3\}$.

For the inequality, the additional possibilities are clearly $(a\in\natural^+,b\in\natural^+,1),(a\in\natural^+,2,2),(3,3,2),(4,3,2),(5,3,2)$.
# Write down the average of the integers $n_1,n_1+1,\ldots,n_2$, and show that $\sum_{n_1}^{n_2}\!j=\frac{(n_1+n_2)(n_2-n_1+1)}{2}.$
# Prove that \[ \sum_{n^2+1}^{(n+1)^2}\!j = n^3 + (n+1)^3 \] and hence that \[\sum_0^n\!j^3 = \frac{(n+1)^2}{4}n^2 \]
!! Solution
The average is $\frac{n_1+n_2}{2}$, and the sum of integers between $n_1$ and $n_2$ is the average times the number of points in between, which is what is claimed.
Now by the first part, \[ \scriptsize  \sum_{n^2+1}^{(n+1)^2}\!j = \frac{((n+1)^2+n^2+1)((n+1)^2-(n^2+1)+1)}{2}  = (n^2+n+1)(n+(n+1)) =(n+(n+1))((n+1)^2-(n+1)n+n^2) = (n+1)^3+n^3 \normalsize \]  and summing this last identity from $0$ to $n^3$, we get \[
2\sum_0^n\!j^3 + (n+1)^3 = \sum_0^{(n+1)^2}\!j = \frac{(n+1)^2((n+1)^2+1)}{2}
\] from which the claim follows trivially.
!!! Aside note
To find the formula for the sum of general integer powers, either start with a guess that $\sum\!j^n$ is a polynomial of degree $n+1$, and fix the coefficients by matching the first $n+1$ values (and then proving the formula by induction); or try to find a polynomial  $f(k)$ of degree $n+1$ such that $f(r+1)-f(r)$ is of degree $n$, and use the telescopic sum $\sum_0^n\!f(k+1)-f(k) = f(n+1)-f(0)$.
E.g, for $n=1$, take $f(k) = (k-1)k/2$, so that $f(k+1)-f(k)=k$. 
For $n=2$, take $f(k)=(k+1)k(k-1)/3$, $f(k+1)-f(k)=k(k+1)$, so that $\sum\!k^2+\sum\!k = (n+1)n(n-1)$. 
For $n=3$, try $f(k)=r^2(r-1)^2/2$: $f(k+1)-f(k)=r^2(r+1)$, so \[ \sum\!k^3+\sum\!k^2 = n^2(n-1)^2/2 \]
# The equation $x^2+bx+c=0$ has the property that if $k$ is a root, then $k^{-1}$ is a root. Determine the restrictions this places on $b$ and $c$.
# Instead of the above property, the equation $x^2+bx+c$ has the property that if $m$ is a root, then $1-m$ is a root. Determine the restrictions on $b$ and $c$.
# The equation $x^2+bx+c=0$ has both the above properties. ''Show'' that $b=-1$ and $c=1$.
# The equation $x^3+px^2+qx+r=0$ has both the properties above. Determine the possible values of $p,q,$ and $r$.

!!! Solution
* qn 1 [[STEP 1989A qn 1 - solutions of a cubic]] done

[[STEP 1993A qn 2 - integrals]] - finish second part
[[STEP 1993A qn 3 - ODEs]] - needs checking
* [[STEP 1993B qn 4 - summing series]] - finish part (iii)
* [[STEP 1993B qn 10 - linear transformations]] needs to be finished
A $\sigma$-algebra is an algebra closed under complement and countable union operations:

$ A\in\mathbf{F} -> A^c \in \mathbf{F} $
everything I should remember but probably don't
Ze Brain
* Joint pmf $f_{XY}(x,y)=\prob(X=x,Y=y)$
* Joint cdf $F_{XY}(x,y)=\prob(X\leq x,Y\leq y)$. $\partial^2_{xy}F=f_{XY}(x,y)$
* Marginal pmf $f_X(x)=\sum_y\!f_{XY}(x,y)$
* Conditional pmf/pdf: $f(Y|X) = \frac{f_{XY}(x,y)}{f_X(x)}$
**  Radon-Nykodim derivative
* Conditional expectation: $\xpct[g(Y)|X]=\int_\real\!g(y)f_{XY}(Y|X)\,dx $
* 
!~Doleans-Dode Exponential

For a semimartingale $H$,

$ \mathcal{E}_t(H) := exp \left\{  H_t-H_0-\frac{1}{2}\langle H^c \rangle_t \right\}\prod_{0\leq s\leq t}(1+\Delta H_s)e^{-\Delta H_s}$

!!!! Properties of Stochastic Exponential
For $H$ semimartingale:
* $\mathcal{E}_t^{-1}(H) := \frac{1}{\mathcal{E}_t(H)} = \mathcal{E}_t(-H^*)$, where
$H_t^* = H_t - \langle H^c \rangle_t - \sum_{s\leq t}(1+\Delta\!H_s)^{-1}(\Delta\!H_s)^2 $
* The solution of a inhomogenous equation
$$
  X_t = G_t + \int_0^t\!X_{s^-}\,dH_s
$$
is
$$
X_t = \mathcal{E}_t(H) (G_0 + \int_0^t\!\mathcal{E}_{s^-}^{-1}(H)\,dG_s^o)
$$
where $G_t^o = G_t - \langle G^c, H^c \rangle_t - \sum_{s\leq t}(1+\Delta\!H_s)^{-1}\Delta\!G_s\Delta\!H_s $
@@Remark:@@ if $V_t \leq G_t + \int_0^t\!V_{s^-}\,dH_s$ then $V_t\leq X_t\ \forall t$ (@@cf. Gromov's theorem@@)
* Multiplication rule: for $U,V$ semimartingale,
$$
  \mathcal{E}_t(U)\mathcal{E}_t(V) = \mathcal{E}_t(U+V+[U,V])
$$
.viewer {
  line-height: 125%;
  font-family: serif;
  font-size: 12pt;
}
.viewer pre {
  font-size: 10pt;
}
#mainMenu {
  width: 11em;
}
Definition: Haushalt: eine Wirtschaftseinheit, die keine Güter für den Markt, sondern nur für den eigenen Konsum produziert.

!!! Autonome entscheidungen unter Sicherheit

* Minimalforderung an Rationalverhalten: Konsistenz: die gleiche Auswahlsregel zwischen Alternativen. Erzeugt Präferenzordnung.
* Instrumentelle Rationalität: mit der Entscheidung ist ein bestimmtes Ziel vervolgt, welches unabhängig von der Entscheidung definiert ist.
* Substantieller Rationalität: 
* perfekte Rationalität:

!!!! Präferenzordunung:
Ausstattungseffekt (Endownment effect)
* Vollständigkeit: $A\preceq B$ für jedes Paar von Alternativen $(A,B)$
* Transitivität: $A\preceq B\preceq C \implies A\preceq C$
** Transitivität + Unersättlichkeit $\implies$ Indifferenzkurven schneiden sich nicht
* Reflexivität: $A\preceq A$
** Framing-effekt
<div class='SVGgraph' style='float:right' options="scales:[0,5,-.01,5]">
axes();
plot("1/x",{steps:[0]});
text([4.8,0.2],"$X_1$");
text([0.2,4.8],"$X_2$");
plot("4-4*x",{stroke:"red"});
plot("2-x",{stroke:"red"});
path([[0,0],[1,1]],{stroke:"green"});
arc({start:[.3,0],end:[0.3/sqrt(2),0.3/sqrt(2)],radius:.3});
arc({start:[.5,0],end:[0.5/sqrt(65),0.5*8/sqrt(65)],radius:.5});
path([[0,0],[.5,2]],{stroke:"green"});
</div>
!!!! Indifferenzkurven
* ''Stetigkeitsanname'': $\forall A\succeq B\succeq C \ \exists \al :\  \al A+(1-\al)C \sim B $ 
* Anname der ''Konvexität''
** Gemischte Güterbündel werden den "einseitigen" bevozugt
* Grenzrate der Substituzion (GRS)
** ${\rm GRS(1,2)} := - \frac{dX_1}{d X_2} $
* Substitutionselastizität
** $\ep_{2,1} = \ $

!!!! Beispiele:
* Lexikografische Präferenzordnung
** Indifferenzkurven entarteten zu einzelnen Punkten: $(X_1,X_2)\sim(Y_1,Y_2)\implies X_1=Y_1,X_2=Y_2$
** Anname der Nichtsättingung ist erfüllt.
** Anname der Transitivität ist erfüllt


!!!! Nutzenfunktion
* 1. Gossen'sche Gesetz: der Grenznutzen nimmt bei Konsum ab.
* 2. Gossen'sche Gesetz: Ausgleich der Grenznutzen
* Nutzenfunktion: $U(X)>U(Y) \iff X\succ Y$  ''und''  $U(X)=U(Y) \iff X\sim Y$
** Nutzen ist nicht kardinal messbar; Nutzenfunktion nicht eindeutig: $V(U)$ erzeugt dieselbe Präferenzordnung wie $U$ solange $V$ streng monoton steigend ist.
** Jede Präferenzordnung, welche den Rationalitätsaxiomen und der Stetigkeitsanname genügt, läßt sich durch eine Nutzenfunktion darstellen.
** Indifferenzkurven sind Konturen der Nutzenfunktion
* $dU=\partial_1U\,dX_1 \ + \ \partial_2 U\,dX_2$
** $\partial_j U > 0$ wegen der Nichtsättigungsannahme
* Auf einer Indifferenzkurve gilt $\partial_1U\,dX_1 + \partial_2U\,dX_2 =0$, also \[
{\rm GRS(1,2)} := -\frac{dX_1}{d X_2} = \frac{\partial_2 U}{\partial_1 U}
\]
* Unter einer streng monoton steigenden Transformation $\partial_j V(U) = \partial_j U \times \frac{dV}{dU} > 0$
** also ${\rm GRS(1,2)} = \frac{\partial_2 U}{\partial_1 U} = \frac{\partial_2 V}{\partial_1 V} $
** jedoch $\partial_{jj}^2 V = \partial_{jj}^2 U + (\partial_j U)^2 V''$ kann ein anderes Vorzeichen haben von $\partial_{jj}^2U$.
*** 1. Gossen'sche Gesetz lässt sich aus der Definition der Nutzenfunktion nicht ableiten!

!!!! Beispiele
* ~Cobb-Douglas utility: $U(X,Y)=X^\al Y^\be$. ${\rm GRS(1,2)} = \frac{\be}{\al} \frac{X}{Y}$
* $U=3X_1 + X_2$. ${\rm GRS(2,1)} = 3$
* $U=(X_1X_2)^2$. Das ist (2,2)-~Cobb-Douglas Nutzenfunktion. ${\rm GRS(1,2)} = \frac{X_2}{X_1}$
* $U=\sqrt{X_1^2+X_2^2}$. ${\rm GRS(1,2)} = \frac{X_1}{X_2}$
* $U=\log X_1 + \log X_2 = \log(X_1X_2)$. ${\rm GRS(1,2)} = \frac{X_2}{X_1}$

!!!! Nutzenmaximierung
* Budgetbeschränkung: $\sum_i\!P_iX_i=B=const$
* Unsättlichkeitsanname $\implies$ optimale Güterbündel wird durch Tangente zur Indifferenzkurve durch die Budgetgerade gegeben
* Strikte konvexität der Indifferenzkurven $\implies$ eindeutigkeit des optimalen Güterbündels
* Aufgrund der Konvexität gibt das Lagrange-Verfahren eine hinreichende Bedingung für ein Optimum: $
    \La(X_1,X_2,\ldots,X_n,B) := U(X_1,X_2,\ldots,X_n) + \la (B-\sum_i X_i P_i)$
** $\partial_i \La = \partial_i U - \la P_i = 0 $
** $\partial_\la \La = B-\sum_i X_i P_i = 0$
*** Grenzrate der Substitution des Gutes i durch das Gut j ist ${\rm GRS(i,j)} = \frac{P_j}{P_i} $
*** der Nutzen einer marginalen Ausgabeeinheit ist in allen Verwendungen gleich: $\frac{\partial_i U}{P_i} = \frac{\partial_j U}{P_j} = \la$
**** vgl. das 2. Gossen'sche Gesetz
*** $\la$ is der Schattenpreis des Nutzens: $\la=\frac{dU}{dB}$
*** der Preis eines Gutes ist proportional zu dem Grenznutzen dieses Gutes: $P_i=\frac{\partial_i U}{\la}$

!!!!! Beispiele
* Cobb-Douglas NF: $U(X,Y)=X^\al Y^\be$, $B=PX+QY$
** $\frac{X}{Y}=\frac{\al}{\be}\frac{Q}{P}$, $X=\frac{B/P}{1+\frac{\be}{\al}}$, $Y=\frac{B/Q}{1+\frac{\al}{\be}}$
 * Lo estimate paper
 * [[UW prelim exam risk management|http://www.stats.uwaterloo.ca/stats_navigation/Comprehensive.shtml]]
 * [[UC Berkeley prelims|http://math.berkeley.edu/~desouza/Prelims]]
!! Lab Session Scripts, Past Quizzes and Solutions

The latest writeup should open in the frame below. If your browser seems to have difficulty, click [[here|http://artefacts.build.semyon.org/~sema/labs.pdf]]. The quizzes (with solutions) are made available after the end of the corresponding week. The write-up is arranged in reverse order; scroll down for earlier labs.

<html><div align="center"> 
<iframe width='100%' height="800" frameborder='0' 
src='http://artefacts.build.semyon.org/~sema/labs.pdf'
</iframe>
</div></html>
| !date | !user | !location | !storeUrl | !uploadDir | !toFilename | !backupdir | !origin |
| 05/04/2011 17:42:00 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  | ok |
| 05/04/2011 18:12:52 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  |
| 08/04/2011 14:00:19 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  |
| 11/04/2011 17:06:13 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  | ok |
| 11/04/2011 17:07:21 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  |
| 12/04/2011 16:48:35 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  | ok |
| 12/04/2011 16:54:14 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  |
| 13/04/2011 13:39:58 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  | ok |
| 13/04/2011 13:41:04 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  |
| 16/05/2011 22:05:06 | SemyonChaichenets | [[/|http://tiddly.semyon.org/]] | [[store.php|http://tiddly.semyon.org/store.php]] | . | [[index.html | http://tiddly.semyon.org/index.html]] |  |
The 'usual conditions' imposed on a filtration are [[right-continuity|Right- and Left-continuous Filtrations]] and completeness of the probability space $(\Omega, \mathcal{F},\mathbb{P})$.
!! Recall 
the Cartesian, Polar, and intrinsic equations,
!! Calculate the arc lengths, areas, CMs, moments of inertia, and volumes of surfaces of revolution
!! for:
* folium of Descartes
Jaynes, "Sur les fonctions convexes et les inegalites entre les valeurs moyennes"
Shakura "(Chap. 6) Statistical Inference with Fractional Brownian Motion"
Shakura "The Elements of Fractional Calculus"
Partition Function in Maths - wikipedia article
Jaynes "Information Theory and Statistical Mechanics p.2"
Nested Sampling Algorithm
Crank & Nicolson, A practical Method for numerical evaluation of solutions of partial differential equations of the heat-conduction type"
Courant, Friederichs, Lewy "On the partial difference equtaions of mathematical physics"
Pilar Grau-Carles "Empirical Evidence of long-range correlations in stock returns"
J Galbraith, Zinde-Walsh "Autoregression-Based Estimators for ARFIMA Models"
Huillet "Renewal processes and the Hurst Effect"
Koutsoyannis "Hurst phenomenon and fractional Gaussian noise made easy"
Pitcher "Parameter estimation for stochastic processes"
Davies, Harte "Tests for Hurst Effect"
Oksendal, Sulem "Maximum principle for optimal control of stoch systems with delay, with applications to finance"
Ferrante, Rovira "Stochastic Delay equations driven by fractional Brownian motion with H>1/2"

Kac "A stochastic model related to the telegrapher's equation"
Orsinger, "Probability Law, flow function, maximum distribution of wave-governed random motions and their connections with kirchoff's laws"

Numerical Methods for Inverse Problems (SIAM)
Numerical Lin Alg (SIAM)
/***
|Name|Plugin: jsMath|
|Created by|BobMcElrath|
|Email|my first name at my last name dot org|
|Location|http://bob.mcelrath.org/tiddlyjsmath.html|
|Version|1.5.1|
|Requires|[[TiddlyWiki|http://www.tiddlywiki.com]] &ge; 2.0.3, [[jsMath|http://www.math.union.edu/~dpvc/jsMath/]] &ge; 3.0|
!Description
LaTeX is the world standard for specifying, typesetting, and communicating mathematics among scientists, engineers, and mathematicians.  For more information about LaTeX itself, visit the [[LaTeX Project|http://www.latex-project.org/]].  This plugin typesets math using [[jsMath|http://www.math.union.edu/~dpvc/jsMath/]], which is an implementation of the TeX math rules and typesetting in javascript, for your browser.  Notice the small button in the lower right corner which opens its control panel.
!Installation
In addition to this plugin, you must also [[install jsMath|http://www.math.union.edu/~dpvc/jsMath/download/jsMath.html]] on the same server as your TiddlyWiki html file.  If you're using TiddlyWiki without a web server, then the jsMath directory must be placed in the same location as the TiddlyWiki html file.

I also recommend modifying your StyleSheet use serif fonts that are slightly larger than normal, so that the math matches surrounding text, and \\small fonts are not unreadable (as in exponents and subscripts).
{{{
.viewer {
  line-height: 125%;
  font-family: serif;
  font-size: 12pt;
}
}}}

If you had used a previous version of [[Plugin: jsMath]], it is no longer necessary to edit the main tiddlywiki.html file to add the jsMath <script> tag.  [[Plugin: jsMath]] now uses ajax to load jsMath.
!History
* 11-Nov-05, version 1.0, Initial release
* 22-Jan-06, version 1.1, updated for ~TW2.0, tested with jsMath 3.1, editing tiddlywiki.html by hand is no longer necessary.
* 24-Jan-06, version 1.2, fixes for Safari, Konqueror
* 27-Jan-06, version 1.3, improved error handling, detect if ajax was already defined (used by ZiddlyWiki)
* 12-Jul-06, version 1.4, fixed problem with not finding image fonts
* 26-Feb-07, version 1.5, fixed problem with Mozilla "unterminated character class".
* 27-Feb-07, version 1.5.1, Runs compatibly with TW 2.1.0+, by Bram Chen
!Examples
|!Source|!Output|h
|{{{The variable $x$ is real.}}}|The variable $x$ is real.|
|{{{The variable \(y\) is complex.}}}|The variable \(y\) is complex.|
|{{{This \[\int_a^b x = \frac{1}{2}(b^2-a^2)\] is an easy integral.}}}|This \[\int_a^b x = \frac{1}{2}(b^2-a^2)\] is an easy integral.|
|{{{This $$\int_a^b \sin x = -(\cos b - \cos a)$$ is another easy integral.}}}|This $$\int_a^b \sin x = -(\cos b - \cos a)$$ is another easy integral.|
|{{{Block formatted equations may also use the 'equation' environment \begin{equation}  \int \tan x = -\ln \cos x \end{equation} }}}|Block formatted equations may also use the 'equation' environment \begin{equation}  \int \tan x = -\ln \cos x \end{equation}|
|{{{Equation arrays are also supported \begin{eqnarray} a &=& b \\ c &=& d \end{eqnarray} }}}|Equation arrays are also supported \begin{eqnarray} a &=& b \\ c &=& d \end{eqnarray} |
|{{{I spent \$7.38 on lunch.}}}|I spent \$7.38 on lunch.|
|{{{I had to insert a backslash (\\) into my document}}}|I had to insert a backslash (\\) into my document|
!Code
***/
//{{{

// AJAX code adapted from http://timmorgan.org/mini
// This is already loaded by ziddlywiki...
if(typeof(window["ajax"]) == "undefined") {
  ajax = {
      x: function(){try{return new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){return new XMLHttpRequest()}}},
      gets: function(url){var x=ajax.x();x.open('GET',url,false);x.send(null);return x.responseText}
  }
}

// Load jsMath
jsMath = {
  Setup: {inited: 1},          // don't run jsMath.Setup.Body() yet
  Autoload: {root: new String(document.location).replace(/[^\/]*$/,'jsMath/')}  // URL to jsMath directory, change if necessary
};
var jsMathstr;
try {
  jsMathstr = ajax.gets(jsMath.Autoload.root+"jsMath.js");
} catch(e) {
  alert("jsMath was not found: you must place the 'jsMath' directory in the same place as this file.  "
       +"The error was:\n"+e.name+": "+e.message);
  throw(e);  // abort eval
}
try {
  window.eval(jsMathstr);
} catch(e) {
  alert("jsMath failed to load.  The error was:\n"+e.name + ": " + e.message + " on line " + e.lineNumber);
}
jsMath.Setup.inited=0;  //  allow jsMath.Setup.Body() to run again

// Define wikifers for latex
config.formatterHelpers.mathFormatHelper = function(w) {
    var e = document.createElement(this.element);
    e.className = this.className;
    var endRegExp = new RegExp(this.terminator, "mg");
    endRegExp.lastIndex = w.matchStart+w.matchLength;
    var matched = endRegExp.exec(w.source);
    if(matched) {
        var txt = w.source.substr(w.matchStart+w.matchLength, 
            matched.index-w.matchStart-w.matchLength);
        if(this.keepdelim) {
          txt = w.source.substr(w.matchStart, matched.index+matched[0].length-w.matchStart);
        }
        e.appendChild(document.createTextNode(txt));
        w.output.appendChild(e);
        w.nextMatch = endRegExp.lastIndex;
    }
}

config.formatters.push({
  name: "displayMath1",
  match: "\\\$\\\$",
  terminator: "\\\$\\\$\\n?", // 2.0 compatability
  termRegExp: "\\\$\\\$\\n?",
  element: "div",
  className: "math",
  handler: config.formatterHelpers.mathFormatHelper
});

config.formatters.push({
  name: "inlineMath1",
  match: "\\\$", 
  terminator: "\\\$", // 2.0 compatability
  termRegExp: "\\\$",
  element: "span",
  className: "math",
  handler: config.formatterHelpers.mathFormatHelper
});

var backslashformatters = new Array(0);

backslashformatters.push({
  name: "inlineMath2",
  match: "\\\\\\\(",
  terminator: "\\\\\\\)", // 2.0 compatability
  termRegExp: "\\\\\\\)",
  element: "span",
  className: "math",
  handler: config.formatterHelpers.mathFormatHelper
});

backslashformatters.push({
  name: "displayMath2",
  match: "\\\\\\\[",
  terminator: "\\\\\\\]\\n?", // 2.0 compatability
  termRegExp: "\\\\\\\]\\n?",
  element: "div",
  className: "math",
  handler: config.formatterHelpers.mathFormatHelper
});

backslashformatters.push({
  name: "displayMath3",
  match: "\\\\begin\\{equation\\}",
  terminator: "\\\\end\\{equation\\}\\n?", // 2.0 compatability
  termRegExp: "\\\\end\\{equation\\}\\n?",
  element: "div",
  className: "math",
  handler: config.formatterHelpers.mathFormatHelper
});

// These can be nested.  e.g. \begin{equation} \begin{array}{ccc} \begin{array}{ccc} ...
backslashformatters.push({
  name: "displayMath4",
  match: "\\\\begin\\{eqnarray\\}",
  terminator: "\\\\end\\{eqnarray\\}\\n?", // 2.0 compatability
  termRegExp: "\\\\end\\{eqnarray\\}\\n?",
  element: "div",
  className: "math",
  keepdelim: true,
  handler: config.formatterHelpers.mathFormatHelper
});

// The escape must come between backslash formatters and regular ones.
// So any latex-like \commands must be added to the beginning of
// backslashformatters here.
backslashformatters.push({
    name: "escape",
    match: "\\\\.",
    handler: function(w) {
        w.output.appendChild(document.createTextNode(w.source.substr(w.matchStart+1,1)));
        w.nextMatch = w.matchStart+2;
    }
});

config.formatters=backslashformatters.concat(config.formatters);

window.wikify = function(source,output,highlightRegExp,tiddler)
{
    if(source && source != "") {
        if(version.major == 2 && version.minor > 0) {
            var wikifier = new Wikifier(source,getParser(tiddler),highlightRegExp,tiddler);
            wikifier.subWikifyUnterm(output);
        } else {
            var wikifier = new Wikifier(source,formatter,highlightRegExp,tiddler);
            wikifier.subWikify(output,null);
        }
        jsMath.ProcessBeforeShowing();
    }
}


/* insert jsMath LaTeX macros here */

/* jsMath.Extension.Require("AMSmath"); */
/* jsMath.Extension.Require("AMSsymbols"); */
/* jsMath.Extension.Require('underset-overset'); */

/* Greek */
jsMath.Macro('al','\\alpha');
jsMath.Macro('be','\\beta');
jsMath.Macro('ga','\\gamma');
jsMath.Macro('de','\\delta');
jsMath.Macro('ep','\\epsilon');
jsMath.Macro('va','\\varepsilon');
jsMath.Macro('ze','\\zeta	');
jsMath.Macro('et','\\eta');
jsMath.Macro('th','\\theta');
jsMath.Macro('io','\\iota');
jsMath.Macro('ka','\\kappa');
jsMath.Macro('la','\\lambda');
jsMath.Macro('rh','\\rho');
jsMath.Macro('si','\\sigma');
jsMath.Macro('ta','\\tau');
jsMath.Macro('up','\\upsilon');
jsMath.Macro('ph','\\phi');
jsMath.Macro('ch','\\chi');
jsMath.Macro('ps','\\psi');
jsMath.Macro('om','\\omega');
jsMath.Macro('Ga','\\Gamma');
jsMath.Macro('De','\\Delta');
jsMath.Macro('Th','\\Theta');
jsMath.Macro('La','\\Lambda');
jsMath.Macro('Si','\\Sigma');
jsMath.Macro('Up','\\Upsilon');
jsMath.Macro('Ph','\\Phi');
jsMath.Macro('Ps','\\Psi');
jsMath.Macro('Om','\\Omega');

/* misc */
jsMath.Macro('pa','\\partial');
jsMath.Macro('na','\\nabla');
jsMath.Macro('ti','\\times');
jsMath.Macro('lb','\\left[');
jsMath.Macro('rb','\\right]');
jsMath.Macro('lp','\\left(');
jsMath.Macro('rp','\\right)');
jsMath.Macro('li','\\left<');
jsMath.Macro('ri','\\right>');
jsMath.Macro('ll','\\left|');
jsMath.Macro('rl','\\right|');
jsMath.Macro('lc','\\left\\{');
jsMath.Macro('rc','\\right\\}');
jsMath.Macro('ld','\\left.');
jsMath.Macro('rd','\\right.');
jsMath.Macro('ha','{\\small \\frac{1}{2}}');
jsMath.Macro('fr','{\\small \\frac{#1}{#2}}',2);
jsMath.Macro('p','\\phantom{#1}',1);
jsMath.Macro('vp','\\vphantom{#1}',1);
jsMath.Macro('label','{\\mathrm{#1}:\\;\\;\\;}',1);

/* accents */
jsMath.Macro('f','{\\underset{\\raise4mu{\\smash{-}}}{{#1}}}',1);
jsMath.Macro('ff','{\\underset{\\raise3mu{\\smash{=}}}{{#1}}}',1);
jsMath.Macro('fff','{\\underset{\\raise3mu{\\smash{\\equiv}}}{{#1}}}',1);
jsMath.Macro('nf','{\\underset{\\raise4mu{\\smash{\\sim}}}{{#1}}}',1);
jsMath.Macro('ud','{\\underset{\\raise4mu{\\smash{\\cdot}}}{{#1}}}',1);
jsMath.Macro('od','{\\overset{\\lower4mu{.}}{{#1}}}',1);
jsMath.Macro('udf','{\\underset{\\raise4mu{\\smash{- \\cdot}}}{{#1}}}',1);
jsMath.Macro('udff','{\\underset{\\raise3mu{\\smash{= \\cdot}}}{{#1}}}',1);
jsMath.Macro('ve','{\\overset{\\lower4mu{\\moveright1mu{\\rightharpoonup}}}{{#1}}}',1);
jsMath.Macro('vv','{\\overset{\\lower4mu{\\overset{\\moveleft.1mu{\\lower4mu{\\Large \\rightharpoonup}}}{\\rightharpoonup}}}{{#1}}}',1);

/* logic */

jsMath.Macro('implies','\\Rightarrow');

/* common sets */

jsMath.Macro('natural','\\mathbb{N}');
jsMath.Macro('integer','\\mathbb{Z}');
jsMath.Macro('rational','\\mathbb{Q}');
jsMath.Macro('real','\\mathbb{R}');
jsMath.Macro('bool','\\mathbb{B}');
jsMath.Macro('complex','\\mathbb{C}');

/* stochastic calculus */

jsMath.Macro('prob','\\mathbb{P}');
jsMath.Macro('iid','\\sim^{iid}');
jsMath.Macro('var','{\\rm var}');
jsMath.Macro('filt','\\mathbb{F}');
jsMath.Macro('xpct','\\mathbb{E}');
jsMath.Macro('stexp','\\mathcal{E}');
jsMath.Macro('sfld','\\mathcal{F}');
jsMath.Macro('borel','\\mathcal{B}');
jsMath.Macro('Mart','\\mathcal{M}');
jsMath.Macro('Mloc','\\Mart_{loc}');


/* end of jsMath macros */

//}}}
Express the usual logical connectives $\neg,\wedge,\vee,\implies,\iff$ in terms of the Sheffer's stroke (NAND) $A|B := \neg(A\wedge B)$. Also express XOR and $P(A,B,C)$, where the latter evaluates to T iff exactly one of $A,B,C$ is T.
!!! Solution
Clearly, $\neg A = A|A, A\vee B = (\neg A)|(\neg B) = (A|A)|(B|B)$, $A\wedge B = \neg (A|B) = (A|B)|(A|B)$. 
For the implication connective, use the following tautology: $A\implies B = \neg A \vee B = (A|A) \vee B = A|\neg B = A|(B|B) $.
For the iff connective, use \[ 
A\iff B = A\wedge B \vee (\neg A \wedge \neg B) = A\wedge B \vee \neg (A\vee B) = \neg((A\vee B)\wedge\neg(A\wedge B))
  = (A\vee B)|(A|B) = [(A|A)|(B|B)]|(A|B)
\]
XOR: \[
\begin{split}
A\oplus B=(A\vee B)\wedge\neg(A\wedge B) &= (A\wedge\neg(A\wedge B))\vee(B\wedge\neg(A\wedge B)) =
\neg[(\neg A\vee(A\wedge B))\wedge(\neg B\vee(A\wedge B) ) ] \\
&= \neg (A\wedge(\neg(A\wedge B)) | \neg (B\wedge(\neg(A\wedge B)) \\ 
&= [A|\neg(A\wedge B)] | [B|\neg(A\wedge B)] = [(A|B)|A] | [(A|B)|B]
\end{split}
\]
Here is a circuit diagram for a XOR gate from NAND gates:
<html><div align="center"> 
<img src='http://upload.wikimedia.org/wikipedia/commons/f/fa/XOR_from_NAND.svg'></img>
</div></html>
Finally, $P(A,B,C)=A\wedge\neg(B\vee C) \vee B\wedge\neg(A\vee C) \vee C\wedge\neg(B\vee A)$
!! ~Pre-Calculus

* Functions, composition of functions, inverses
* Graphs
* lines. Conic sections
* Roots of Polynomials
* Logs and Hyperbolic functions
* Trig Functions

!! Calculus 1

* Arc length
* Area in polar coordinates

!! Calculus 2

!! ~ODEs

* Homogenous equations: $M,N$ homogenous of degree $n$ ($M(tx,ty)=t^nM(x,y)$), \[ M\,dx+N\,dy =0 \] is solved by $y=vx$, $dy=x\,dv+v\,dx$
* Exact equations: $M\,dx+N\,dy=0$ is exact if $\partial_y\!M=\partial_x\!N$, with the solution $f(x,y)=c$, where $\partial_x\!f=M, \partial_y\!f=N$
* Integrating factors: if $M_y-N_x\neq0$, and $\frac{M_y-N_x}{N}=\xi(x)$, then $\mu(x):=\exp(\int\!\xi(x)\,dx)$ is the integrating factor.
** Similarly, if $\frac{M_y-N_x}{M}=-\eta(y)$, then $\mu(y):=\exp(\int\!\eta(y)\,dy)$ is the integrating factor.

!! Linear Algebra

* Gaussian elimination
* determinants
* rank-nullity theorem
* ~Cayley-Hamilton Theorem

!! Algebra

* Euclidian algoithm
** $gcd(a,b)\times lcm(a,b) = a\times b$
* linear Diophantine equations $ax+by=c$
** Let $d:=gcd(a,b)$. If $d|c$, then there is an infinite set of solutions, $x=x_1+t\times\frac{b}{d}$, $y=y_1-t\times\frac{a}{d}$
** $x_1,y_1$ determined from Euclid's algorithm:

!! Complex Variables
* $z=r(\cos\th + i\,\sin\th) = r\exp(i\,\th)$
* roots of unity, primitive root
* logarithms: ${\rm Log} z = \log |z| + i\,{\rm Arg} z$, where $-\pi \leq {\rm Arg} z \leq \pi$
! Mathematical Finance 1: Lecture Course at UofA

* $\exists$ martingale (risk-neutral) probability measure $\iff$  no arbitrage $\implies$ no dominant trading strategies $\implies$ law of one price
* separating hyperplane theorem

!!! Definition: Dominant Trading Strategy
A DTS is a self-financing portfolio $\hat\pi$ with the greatest terminal wealth, a.s.: $$X^{\hat\pi}_T \geq X^{\pi}_T \quad {\rm a.s.} \quad \forall \pi\in SF$$

!!! Definition: Law of One Price
Law of One Price is said to hold for a market if for any two trading strategies $\pi_1,\pi_2\in SF$ such that $X^{\pi_1}_T = X^{\pi_2}_T$ a.s., $ X^{\pi_1}_0 = X^{\pi_2}_0 \quad {\rm a.s.} $

!!! Definition: Arbitrage Opportunity
An arbitrage is a trading strategy $\pi\in SF$ satisfying the following: 
* $X^\pi_0 = 0$
* $X^\pi_T \geq 0 \quad {\rm a.s.}$
* $\xpct(X^\pi_T) > 0$

----
!! Literature Used
* [[Pliska, "Intro to Math Finance"|http://books.google.com/books?id=Ye6TPptCUvYC&source=gbs_navlinks_s]]
!Mathematical Finance 2: lecture course at [[UofA|http://www.ualberta.ca]], Winter 2011

!! Stochastic Processes

# $X, Y$ have the same finite-dim distributions
# $X_t$ modification of $Y_t$
# $X,Y$ indistinguishable
* $(3)\implies(2)\implies(1)$
* example of (2) but not (3)
* example of (1) but not (2)?
* $X,Y$ modifications and both have r-cts sample paths $\implies$ (3)
** use separability to show both that $[X_t\neq Y_t]$ mble and has measure zero
* mble process
* completed $\sfld$, immediate future and past $\sfld_{t\pm}$. $(\sfld_{t+})$ right-cts. usual conditions
* Fubini: 
* Fatou lemma

* conditional expectations, independent sigma-fields, independent r.v.s
* sub-martingale, martingale
* If $X\in L^1(\filt)$ with indep. increments then $Y_t:=X_t-\xpct X_t$ is a martingale. Hint: $X_t=X_t -X_s+X_s$
** e.g. $S_n:=\sum_{k=1}^n\!X_k$ iid. sample sums.

* Brownian Motion: stationary, Normally-distributed, independent increments.
* Brownian filtration. Right+left-cts

* Jensen's inequality. Proof
** Jensen's inequality for martingales: $X_t$ mtgle, $\phi$ convex $\implies$ $\phi(X)$ sub-matgle

* uniformly integrable sets
* Dominated Convergence Theorem
* $L^2[0,T] = \{ X | \xpct\int_0^T\!X^2_s\,ds =: ||X|| _{L^2_T}^2 < \infty \} $
* {simple processes} dense in $L^2[0,1]$
!! Problem 0 (bonus)
Let $\sigma:\Omega\to\real^+$ be a $\sfld$-random variable. Then $X_t:=1_{[\sigma,+\infty)}(t)$ is adapted to a filtration $\filt$ ''iff'' $\si$ is a s.t. wrt $\filt$. Moreover, $X_t$ is cadlag if it is adapted.
!!! Proof
Recall the definition of stopping time

!! Problem 0.3 (bonus)
Let $\tau$ be s.t. Claim: $\tau_n:=\sum_0^\infty\!\frac{k+1}{2}1_{\{\frac{k}{2^n}\leq\tau<\frac{1+k}{2^n}\}}$ is a s.t. for any $n\geq1$, and $\tau_n\to\tau$ a.s.

!! Problem 0.5 (bonus)
If $\sigma$ is a s.t., $\sigma+\epsilon$ is a s.t. $\forall\epsilon>0$

!! Problem 1
Let a monotonic sequence $(\sigma_n)$ of stopping times converge to $\sigma$ in probability. Then $\sigma$ is also a stopping time.
!!! Proof
We have that, for any sequence of s.t. $\si_n$, $\si:=\sup_n \si_n$ is a stopping time: \[
[\si\leq t] = \cap_n[\si_n\leq t] \in \sfld_t.
\] And, if $\si_n$ is monotonically increasing, $\lim_n\si_n = \sup_n\si_n$

!!Problem 2
If $M_t$ is a martingale, $(t_i)_{i=0,\ldots,n}$ a finite partition of the time domain, and $H_i$ are bounded $\sfld_{t_i}$-measurable random variables, then the process \[X_i:=\sum_0^{n-1}H_i(M_{t\wedge t_{i+1}}-M_{t\wedge t_i}) \] is a martingale with respect to the natural filtration of $M_t$.

!! Problem 3
A 'real' time $\rho:\Omega\to\real^+;\omega\to s\in\real^+\ \forall \omega\in\Omega$ is a stopping time.
!!! Proof
$\rho$ is clearly $\sfld$-measurable: $\sfld\ni\rho^{-1}(B\in\borel(\real))=\begin{cases}\emptyset&s\notin B\\\Omega&s\in B\end{cases}$, and $
[\rho\leq t] = \begin{cases}\emptyset&s>t\\ \Omega&s\leq t\end{cases}$ is clearly $\sfld_t$-measurable.

!! Problem 4
Let $\tau$ be a stopping time.
* $\sfld_\tau:=\{A\in\sfld | A\cap[\tau\leq t]\in\sfld_t \forall t>0 \}$ is a sigma-field.
* Any $\sfld_\tau$-measurable random variable $T\geq\tau$ (a.s.) is a stopping time.
!!! Proof
Take a countable collection of sets $A_i$ in $\sfld_\tau$. Then, for any $t$, \[
(\cup_i A_i)\cap[\tau\leq t]=\cup (A_i\cap[\tau\leq t]) \in \sfld_t \] since each $
A_i\cap[\tau\leq t]\in\sfld_t$ by definition, and $\sfld_t$ is a sigma-field. It is also clear that, for $A\in\sfld_\tau
$, $(A\cap[\tau\leq t])^c=A^c\cup[\tau\leq t]^c\in\sfld_t$ Now because $\tau$ is a s.t., $[\tau\leq t]\in\sfld_t$. Therefore \[
A^c\cap[\tau\leq t] = A^c\cap[\tau\leq t] \cup \emptyset = A^c\cap[\tau\leq t] \cup ( [\tau\leq t] \cap [\tau\leq t]^c ) = (A\cap[\tau\leq t])^c \cap [\tau\leq t] \in\sfld_t
\]
Now let $T$ be such that $\prob[T\geq\tau]=1; [T\leq t]\in\sfld_\tau.$ We need to show that $[T\leq t]\in\sfld_t$.

!! Problem 5
Let $W$ be a 1D Brownian motion and $\filt$ be its natural filtration
* Find a process $a_t$ such that \[ Y_t:=W_t^3 -\int_0^t\!a_s\,ds \] is a martingale (wrt $\filt$).
* prove that $\forall \la\in\real$, the process \[ U:=\exp\{ \la W_t-\frac{\la^2}{2}t \} \] is a martingale (again, wrt $\filt$)
!! Problem 1
* Ex. 2.9
!! Problem 2
* Ex 2.11
!! Problem 3
Consider a stock price $P_1$ modeled by \[
dP_1(t) = b(t) P_1(t)  + \si(t) P_1(t) \, dW(t) 
\] with $P_1(0) = p_1 $.
The mean rate of return $b(t)$ and the volatility $\si$ satisfy $b(t) = 2\times 1_{[0,3)} + 3\times 1_{[3,6]}$ and $\si(t)=3\times1_{[0,3)} + 4\times1_{[3,6]} $. Set $p_1=5$. Find the probability that $P_1(t=6)>4$.

!! Problem 4
Let $X$ be the price of a stock expressed in USD satisfying \[ 
dX_t = \al X_t\,dt + \si X_t\,dW_t \]. Let $Y$ be the exchange rate CAD/USD, satisfying \[ 
dY_t = \be Y_t\,dt + \rho Y_t\,dV_t
\] where $\al,\be,\rho,\si>0$ are constants, and $W_t, V_t$ are independent Brownian motions. Find the governing equation for $Z:=XY$, the price of the stock in CAD.

!! Problem 5
Suppose the price of a stock follows a geometric Brownian motion with mean return $\mu:=16\%$ per year and volatility $\si:=30\%$ per year. Suppose that at $t=0$, $P(t=0) = 50$. Calculate:
* $\xpct P|_{t=1{\rm day}}$
* the variance of the stock price at the end of the next day.
* The 90\% confidence interval of the stock price at the end of the next day.
!Advanced Mathematical Finance: lecture course at [[UofA|http://www.ualberta.ca]], Winter 2010


!!!Lectures 1 & 2: 2010-01-{08,11}

* probability space, stochastic process, filtration, [['usual conditions'|Usual Conditions]]
* example: different behaviour of stochastic processes in discrete and continuous time:
** in discrete time, $\prob(X_n = Y_n) = 1$ implies $\prob(\{\om | X_n(\om) = Y_n(\om)\}) = 1$
** in continuous time, consider $X_t = 0$, $Y_{t\neq T} = 0, Y_{t=T} = 1$. 
*** The set $\{t=T\}$ has Borel measure 0, so that $\forall s\neq T \ \prob(X_s = Y_s) = 1$
* Definition: $X$ is a modification of $Y$ if $\prob(X_t=Y_t)=1 \forall t$
* Definition: $X$ and $Y$ are indistinguishable if $\prob(\{\om\in\Om | \forall t\geq0 \ X(t,\om) = Y(t,\om)\}) = 1$
* Claim: $X$ and its modification $Y$ are indistinguishable if $X$ has right-continuous paths, $Y$ continuous.
* Definition: Finite-dimensional distributions of $X$: $\prob^X_{t_1,\ldots,t_n} (A\in\borel(R^n)) = \prob(X_1,X_2,\ldots,X_n\in A)$
* Definition: Wiener Process
* Properties of $W$

----

!!!Lectures 3,4,5: 2010-01-{13,15,18}

* Kolmogorov Consistency Theorem
* Kolmogorov Test: If for some positive constants $C,\epsilon,\beta$, $\mathbb{E}(|X_t-X_s|^\beta) \leq C |t-s|^{1+\epsilon}$, then X admits a continuous modification
* Properties of Sample Paths of $W$

* Standard Stochastic Basis
* random sets, stochastic interval
* $\sigma$-algebras on $R^+\!\times\Omega$
** measurable process, progressively measurable process, $\Pi$
** optional $\sigma$-algebra, $\mathcal{O}$
** predictable $\sigma$-algebra, $\mathcal{P}$
* If $(\sfld_t)$-adapted process $X$ admits a right-continuous modification, it is progressively measurable.
* $\borel(R^+)\otimes\sfld \supseteq \Pi \supseteq \mathcal(O) \supseteq \mathcal{P}$
* debut of $D\in\mathcal{O}$

* "{stopping times} = { predictable s.t.} $\cup$ {non-predictable s.t.}"
* Definition: stopping time $Z$ is predictable if there exists an announcing sequence
* Martingales


!!! Lectures 6,7,8: 2010-01-{20,22,23}
@@ Notes! @@
!!! Lectures 9,10,11: 2010-01-{25,27,29}
@@ Notes! @@
!!! Lectures 12,13,15: 2010-02-{01,03,05}
@@ Notes! @@
!!! Lectures 16,17,18: 2010-02-{08,10,12}
@@ Notes! @@

----

!!! Lectures 19,20,21: 2010-02-{22,24,26}

!!!! Martingale Characterization of Strategies (Portfolios)

Assume the martingale measure is unique $\mathcal{M}(X,\prob)=\{\prob^*\}$. Then for a process $Y\geq0$ we have:
* $Y$ is a discounted wealth of self-financing $\pi\in SF$ iff $Y\in\mathcal{M}_{loc}(\prob^*)$
* $Y$ is a discounted wealth of self-financing strategy with consumption iff $Y$ is a supermartingale wrt $\prob^*$

!!!!! Proof
@@use@@
# Martingale representation
# Optional decomposition

!!!! Definition: Contingent claim
any $\mathcal{F}_T$-mble random variable $f$ is a 'European-type' contingent claim. An 'American-style' c.c. is an adapted process which can be stopped (claim exercised) at any time $0\leq t\leq T$.

!!!! Definition: Hedge
A hedge of c.c. $f$ is a strategy $\pi\in SF$ s.th. $X_T^\pi\geq f$ (a.s.)
!!!! Definition: Minimal Hedge
A minimal hedge $\pi^*\in SF$ is one that requires least amount of capital: $X_t^{\pi^*}\leq X_t^\pi \ \forall \pi\in SF$ -- @@ $X_t$ or $X_T$ ?@@

!!!! Theorem: existence of minimal hedge in a complete market
Suppose $\mathcal{M}(X,\prob)=\{\prob^*\}$, and let c.c. $g:=f/B_T$ be integrable: $\mathbb{E}^*[g]<\infty$. Then there is a minimal hedge $\pi^*$ s.th.:
$
\begin{align}
   \frac{X_t^{\pi^*}}{B_t} &= \mathbb{E}^*[g|\mathcal{F}_t] \quad \forall t\leq T \\
   \frac{X_t^{\pi^*}}{B_t} - \frac{X_0^{\pi^*}}{B_0} &= \int_0^t\!\gamma_u^*\,dX_u \quad X_u = S_u/B_u \\
   \pi_t^* &= (\beta_t^*,\gamma_t^*)
\end{align}
$
!!!!! Proof

$\xpct[g|\mathcal{F}_t] =: Y_t^* \in \mathcal{M}_{loc}(\prob^*)$ since it is the discounted wealth of a self-financing strategy.
$Y^*_T$ is $g/\mathcal{F}_T$-mble, so identify $Y_T^* =: g$. 
Now show $Y^*_t$ is minimal:
Suppose $\pi$ is another hedge: 
$\frac{X_t^\pi}{B_t} = \xpct^*[\frac{X_T^*}{B_T}|\mathcal{F}_t] \geq \xpct^*[\frac{f}{B_T}|\mathcal{F}_t] = Y_t^* = \frac{X_t^{\pi^*}}{B_t}$
Where the first equality is due to $\frac{X_t^\pi}{B_t}$ martingale.

!!!! Definition: complete market
A market is complete if for any bounded contingent claim $g$ there exists a replicating portfolio $\pi^*\in SF$: $X_T^{\pi^*}/B_T = g$.
In other words, any c.c. $g$ is attainable.

!!!! Theorem: complete markets and martingale measures

A market is complete iff $\mathcal{M}(X,\prob) = \{ \prob^* \}$.

!!!!! Proof

'if': just shown in previous theorem.
'only if': Suppose there  exist two martingale measures, $\prob_1^*, \prob_2^*$, and take an event $A\in\mathcal{F}_T$. Let $g=1_A$, and
$\pi^*\in SF$ be such that $Y^*:=\frac{X_T^*}{B_T} = g (=1_A)$, a.s.
Then 
$$
   \prob_1^*(A) = \xpct_1^* 1_A = \xpct_1^* Y_T = \xpct_2^* Y_T = \xpct_2^* g = \prob_2^*(A)  
$$

!!! [[Black-Scholes semimartingale model|Black-Scholes Model]]

assets $B,S$, $B$ predictable, $S$ semimartingale.
$
\begin{align}
   dB_t &= B_t -dh_t \quad & B_0=1 \\
   dS_t &= S_t - dH_t \quad & S_0 > 0 \\
\end{align}
$

!!! [[Solutions of the Semimartingale Black-Scholes Model|Black-Scholes Model]]

!!!! [[Properties of Stochastic Exponential|Stochastic Exponential]]

!!!! Finding Martingale Measures
Reminder: in [[Black-Scholes Model]], they came from [[Girsanov's Theorem]].

$$
\prob^*\in\mathcal{M}(X,\prob) \iff X=\frac{S}{B}\in\Mloc(\prob^*)
$$

$$
  X_t = \frac{S_t}{B_t} = X_0 \frac{E}{E}
$$

----

!!! Lectures 22,23,24: 2010-03-{01,03,05}

* [[Generalization of Girsanov's Theorem|Girsanov's Theorem]]
Use this methodology for particular examples:

!!!! [[Black-Scholes Model]]
Recall that
\begin{eqnarray}
dB_t &= B_tr\,dt                             & B_0=1 \\
dS_t &= S_t (\mu\,dt+\sigma\,dW_t) & 
\end{eqnarray}

@@ FINISH!! @@

----
!!! March 5: Incomplete Markets: Super-hedging Methodology


! Midterm Preparation: [[math625|math525]]

# Standard Stochastic Basis $(\Omega,\sfld,\filt,\prob) $ with [[usual conditions|Usual Conditions]]
# Stopping Times and [[Sigma-Algebras|SigmaAlgebra]] Associated with them
!! Empirical Study of Markets Based on Fractional Brownian Motion
* процессы с долгой памятью
* Patrick Cheridito: thesis
* Hurst Parameter > 3/4
* Yulia Mishura [["Stochastic Calculus for Fractional Brownian Motion"|http://books.google.ca/books?id=a0g6wHrDy-YC&client=firefox-a&source=gbs_navlinks_s]], in particular Ch. 3.2
* max likelihood estimation; should be the same as least squares
$\mu^*$ is an outer measure if
$\mu(\emptyset)=0,\mu^*(A\subseteq B) \leq \mu^*(B), \mu^*(\cup_n A_n)\leq\sum_n\mu^*(A_n)$
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"
	});
*/
[[GNS construction in finance|http://www.google.ca/patents?id=S60SAAAAEBAJ&zoom=4&pg=PA40#v=onepage&q&f=false]]
A measure $\mu$ on $\Omega$ is $\sigma$-finite if there exists a cover $(\Omega_n)$ of $\Omega=\cup_n\Omega_n$ by sets of finite measure: $\mu(\Omega_n)<\infty$
!! Tangents
Find the angle between the tangents to the curves $y=\sin 2x$ and $y=\cos 3x$ at the point of their intersection.
!!! Solution:
$\cos\xi = \frac{1+f'g'}{\sqrt{(1+f'^2)(1+g'^2)}}$

!! Series
 * Find \[ \lim_{n\to\infty}\sum_{k=1}^n\!\frac{k}{k^2+n^2} \]
 * The product of absolutely convergent series converges absolutely

!! Topology
A set of discontinuities of a function $f:\real\to\real$ cannot be:
* $\rational$
* $\real$
* $\real^{>0}$
* $\real\backslash\rational$
!Applied Measure Theory: lecture course at [[UofA|http://www.ualberta.ca]], Winter 2010

[_] schorack chapter 1 (Measures)
[_] schorack chapter 2 (Mble functions and convergence)
[ ] schorack chapter 3 (Integration)
[ ] script pp. 15-25 (Mble functions and convergence)
[ ] script pp. 26-38 (Integration)
----
[ ] Counter-Examples in Probability
[ ] Doob "Measure Theory"

!! Concepts
* convergence a.s.
* convergence in probability
* convergence in distribution
* MCT
* DCT
* Slutsky's theorem
* portmanteau theorem
* Borel-Cantelli Lemmas
* Radon-Nikodym Theorem
* Fundamental Theorem of Calculus
* Caratheodory's Extension Theorem
Show that \[ \ze(2) = \sum_1^\infty\frac{1}{n^2}=\frac{\pi^2}{6} \]
!!! Euler's method
start with the power series for $\sin x=x-x^3/3!+x^5/5!-\ldots$, and treat it as polynomial in $x$. We know what the roots are: $x=0,\pi,2\pi,\ldots$.
So we have, ignoring the first root, $0 = 1-x^2/3!+x^4/5!-\ldots$. The product of the roots is the constant term, and the sum of reciprocals is therefore the linear coefficient: $\frac{1}{3!}=\frac{1}{\pi^2}+\frac{1}{2^2\pi^2}+\ldots$.
!!! Using Fubini's Theorem:
version.extensions.UploadPlugin = {
	major: 4, minor: 1, revision: 4,
	date: new Date("2008-08-11"),
	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 == 404)
			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");