text:
# Finding the Optimal Parameter Order

When I first started programming I tought the order of function parameters was essentially arbitrary; just the order the author decided to structure it. But after dabbling with a number of functional programming languages I came to the conclusion that the order is in fact important.

Let me try to convince you.

When programming Clojure, you often end up chaining function calls, like (baz (bar (foo x))), since after all, we all work on data and that data is processed by functions. This has been totally normal, at least until the threading/thrush operator came along, -> (a really long time ago). So you can replace the code with (-> x foo bar baz) and it looks much cleaner and obvious. It’s fantastic!

This only works for functions with the arity of 1 (single argument functions) and by extension, for functions which take the element to be “threaded in” as their first argument. Therefore, Clojure also has also its sibling, ->> (called “thread-last”, analogous to -> being “thread-first”), which unsurprisingly threads the value in as last argument to the specified functions.

Working with code, we often have a seq that we want to operate on, so that’s what we usually thread. Unfortunately, the standard library is not very consistent about this, since common seq operations take the collection as first argument, like update, assoc, dissoc, conj. So we could use them with ->. But then when we want to use some combinators like map, filter, reduce, the collection has to be provided last, which would require ->> instead.

The reason why e.g. assoc has the collection first is that is a multi-arity function and can associate multiple values at once, so the order of arguments of (assoc coll :arg1 val1 :arg2 val2 :arg-n val-n) is logical. Generally, most clojure.core functions which take collections and an unspecified amount of arguments seem to be this way, which is understandable considering how & arguments are handled in Clojure.

To avoid the awkward mess of mixing code that uses -> and ->>, Clojure 1.5 introduced as->, which allows naming the argument to be threaded (I usually go naming the argument <>, aka “diamond”), so it can be put in the proper place to be resolved, but this feels very much like a clumsy (albeit effective) compromise to get around the argument order mess.

So, which “side” of the ->/->> split is right? Personally, I subscribe to the thread-last school of argument order. This means that I order the arguments in functions according to their specificity: from the most general to the least general. Consider (map f coll), which takes the function first (since it might work on any coll element) and then only the specific values to be applied on. Similarly reduce. Working this way also has the advantage that partial can be used to pre-populate some arguments with known values and then just operate on a function of lesser arity.

This approach is not without precedent. For languages with implicit currying like OCaml or Haskell this order is completely normal. Currying creates out of a function like

a function like

So when calling (foo bar) a function is returned which takes baz and returns the result. So basically it’s like using partial for every argument. This of course means that arguments can only be supplied left to right. The OCaml way of threading is then coll |> map inc so the argument is threaded in at the end, just like our friend ->> does. The actual reason for this is of course a bit different, since map f returns a single-arity function so it doesn’t really matter whether threading first or last element, since they are identical in that case.

A more accurate translation to Clojure would be

Which is silly, since we can just use the less awkward ->> in this case:

So, I definitely recommend preferring ->> as it leads to more reasonable argument order that can better be composed with other functions. Unfortunately, we can’t just be all happy using ->> as we’ll have to keep using -> for functions like assoc/dissoc. Maybe having them with multiple arity was not such a great idea to start with.

# Destructuring Order in Or-clauses

Lately I was wondering how to set variables in a specific order in a :or clause in Clojure’s destructuring mini language. I needed to set a key b to the return value of a function f that is dependant on a key a.

My first thought was that the :or {} syntax wouldn’t obey the order (since it is a map), so I’ve used :or []. But that doesn’t work at all, it does not do anything, both get bound to nil, as if no :or was specified.

When using :or {} it magically worked, but how can you trust that the order is always correct, since maps are inherently unordered?

Turns out, the order in which keys are taken from the :or map depends on the :keys vector! Compare specifying a before b, which works as expected:

with specifying b before a which fails since a is not yet known.

This behaviour works well but it was rather unexpected. It kinda does explain why the :keys takes a vector as a value and not a set, because the order is important.

Thanks to Jan Stępień for getting to the bottom of this.

# Disabling Mouse in Spacemacs

Those of you following me on Twitter already heard that I’ve been trying out Spacemacs lately — a GNU Emacs configuration to emulate Vim. The reason behind it is, I want to check out whether writing Clojure in Emacs works better than in Vim (which is pretty decent, actually).

Now there is one thing that bothered me the most, coming from console vim: every time I switch focus to Emacs by clicking in a random place on the window, the cursor moves to this place. Incredibly inconvenient, since I don’t want to move my cursor accidentally. Since I never use the mouse for anything in my editor anyway, I decided to disable it.

Turn’s out, it is not that easy, since it is not a global key binding, but one that is local to the Evil mode. Frustrating to figure out, so here’s how to do it:

Hope that helps and watch this space for more adventures/rants in Space(macs)!

# Lenovo X1 Carbon 2015 on Linux

In 2015, Lenovo managed to create a new ThinkPad that was again usable, namely the X1 Carbon (aka 3rd gen). After the last iteration of the Carbon was pretty terrible they went back to a more proven formula, for the better.

I needed a laptop for work, so I decided I give this device a spin. I got a BTO model with an i7-5500U (Broadwell, 2.4 GHz), the 256 GB PCIe SSD and the WQHD screen (2560x1440) along with the US keyboard with Euro key.

## The device

Generally, I am quite satisfied. Compared with my T41 and T42p it is much faster, compared to my T420 it is much thinner. The keyboard is, unlike on the T420 an island-style keyboard but works pretty well in general. The layout is pretty sensible. I never use the keyboard backlight, just like I never used the ThinkLight, so whatever. The screen is pretty good, the frame is much thinner than my other devices. The touchpad is quite nice, although it is sometimes tricky to right-click — but I’ve always been a TrackPoint kind of guy. This is where the device has the biggest flaw: the trackpoint is set slightly below the keyboard and requires surprisingly much force to use. I’ve ended up getting an external mouse.

The SSD is ridiculously fast, but my workflows are rarely disk-bound.

If there is one word to describe the hardware it would be “slick”.

## Linux

Having read some pretty sobering experiences I can now offer a counterpoint: the hardware support in Fedora 22 (Kernel 4.0.4) is pretty solid. The installer of the Workstation edition works without issues, no problems with graphics whatsoever, did not encounter any problems with WiFi (using it since two weeks). Suspend works, the cursor works and sound is no problem.

I’ve also tried DisplayPort to HDMI which worked only with a 1080p resolution (which is supposedly the fault of the Dell 27” screen I’ve been using), but when using DisplayPort to DisplayPort natively, the external screen lights up with 2560x1440 just fine. I’ve also tried the VGA adapter, this also worked out of the box. I did not try Bluetooth (my mouse uses Logitech Unifying dongle) or mobile data (since I haven’t ordered any mobile data cards).

Battery time seems quite decent, six hours or so. I’ve never discharged the device that much, since most of the time I’m sitting at my desk with the charger plugged it. Unfortunately, they changed the charger again, so now I have a third generation of chargers for ThinkPads. Honestly, I liked the round plug of the T420 the most.

In normal use, the device is absolutely silent. Whee. When I start some more complicated processes, it gets a bit louder, but it still isn’t anywhere bad.

Overall: pretty good! Fedora also did a good job packaging it together.

## The bad parts

This is something that I cannot blame on Lenovo. The HiDPI mode on Linux sucks. GTK+ only supports integer scaling factors, so I can choose between 2560x1440 or 1280x720. The latter is of course completely ridiculous on such a pretty device, the former is ok but quite small. Coupling a HiDPI device (X1 Carbon) with a non-HiDPI device (external screen) isn’t supported, so either you use both HiDPI or both unscaled. A 27” screen in 1280x720 is just hilariously terrible. Maybe Wayland will solve this issue, since i don’t think this is an overly exotic problem.

Firefox fortunately does support scaling by any factor, which is nice. So when working I have my terminals on my external screen and Firefox on the laptop. I’ve set the scaling manually to something like 1.6x, which does not make everything look huge but is still legible. While this sounds awesome, I of course ran into another bug, where context menus are displayed on the wrong screen when using a scaling factor that is not 1 or 2. So, everytime I open the context menu, it just opens on my other screen :-(

## tl;dr

Hardware works really well with Linux, Linux software has issues with HiDPI, maybe solvable through Wayland in the next couple of decades. Would recommend the device.

# Go 1.4.2 for Raspberry Pi

I was notified by multiple mails that my package signing key expired. Thanks. I’ve changed the expiration date. So in case you are affected, run the first line (wget …) below and you can access the packages again. Took me some time because I moved and didn’t plug the Raspberry Pi back in.

While I was updating, Debian jessie came out and the Debian release freeze ended, so I decided that I might as well update to the newest Go release available from Debian, 1.4.2.

So if you just stumbled onto this blog, looking for Go packages for your Raspberry Pi (I’ve tried with the Raspberry Pi Model B), here are the instructions that you should run to get a working Go compiler on your mini-computer.

# Cycling in Munich

Inspired by a similar post by Julius, let’s contrast cycling in London with cycling in Munich. Especially as now the weather has been pretty good, so I started cycling to work almost every day.

Munich calls itself the “Radlhauptstadt”, which means the cycling capital. As Julius points out, there are not many capitals in Bavaria, so the competition for the title is rather easy. Am I hinting on what is coming? You bet.

Let’s start with the good things: Munich is contrary to the fact that it is reasonably close to the Alps, pretty flat, which makes overall pretty easy cycling. The second thing that is good in Munich is that pedestrians usually say clear from cycleways (if you see people there it’s 95% chance they are Asian, who don’t care about cycleways, something I’ve experienced in Japan as well).

But cycling to work in Munich is an exercise in frustration and the city doesn’t take this seriously at all. Let me illustrate this with a couple of points.

## Cycleways end abruptly

Munich has a number of roads reserved for cyclists. This is all well and good, but unfortunately, you can’t get anywhere using them. They mostly start at some random place and end at some other random place and in between you have to switch to the street.

I can get to the main station in Munich on cycleways but then they completely drop the ball and you have to either take a detour or take the road. The road shared with light trams, huge long distance busses and rush hour traffic.

After surviving the main station, there is some cycleway until you get to the old city, which is also horrible to traverse by bike, due to mixing cyclist traffic with pedestrians, light trains (and especially their tracks, which are deadly to road bike wheels) and paving.

## Crappy cycleways

Even if there are cycleways, they are often of bad quality: very bumpy, narrow, badly maintained. In this regard I’ll disagree with Julius, the cycleways on the streets are above and beyond much better quality-wise than the cycleways. Because roads for cars are built with quality in mind so that space to the right reserved for bikes is fine. Usually, they are also wide enough and in Germany, cars tend to leave you alone there. But these are rare, on the 8km I cycle to work, its two stretches, 1km tops.

## Mandatory cycleways

There is a certain sign, pretty commonly used in Germany which forces cyclist to take the cycleway. It is incredibly infuriating when you see a really nice, wide street and you’re forced on the sidewalk with some white line drawn on it. You’re losing so much time and comfort, by being, effectively, sidelined.

It gets even better, since the cycleways tend to be directional, so you can’t just return the way you came, you’d have to cross the road. Which on bigger streets would mean that you have to drive around the block to the next crossing. All the downsides of cars, with none of the upsides.

## Cars

Even if you are on a cycleway and are going in the right direction (congratulations!), cars like to park on the side and block at least part of it. Also, while german drivers tend to be pretty good, I often get shouted at by some know-it-alls for not obeying some fictional traffic rules. The atmosphere is sometimes quite hostile.

Part of this is surely caused by cyclist breezing through red lights, but some lights are adjusted horribly, cyclists would need to stop every 20m for the next red light. No wonder they often breeze through shortly after it switches to red.

## Locking, oh gosh, the locks

So, there are bike locking stands on many places, great. You lock your bike, you come back after a day and what is left is your front wheel.

German locking stands have (for the most part) stagnated since 1927 with the invention of the Quick release skewer. It allows taking of your wheels with no tools required, and conversely also taking of your bike from a bike locking stand which only locks your front wheel to the stand.

I used to think, that these kinds of locking stands were standard, but I have seen exacly none of them visiting London. All locking stands had a way to lock your frame to it, which makes sense if you like to keep your bike. So it is pure ignorance that locking is so bad.

I usually lock my bike to handrails of stairs or similar because proper locking stands are still rare. At least, this is getting better.

## Concluding

I don’t see any serious effort of the city to make cycling more appealing. The current traffic rules for bikes are out of touch with reality and to create better infrastructure for cyclists would require rethinking how bicycles, cars and pedestrians interact in a modern city. Maybe cities like Amsterdam or Copenhagen can lead us the way.

# Go 1.3.3 for Raspberry Pi

As I had some time, I decided to update the Go(lang) package to the newest version available in Debian testing/unstable. Go 1.4.1 is only in experimental yet, so I’ve been holding off for now.

These packages were built on an Raspberry Pi Model B, and should be able to run on every Raspberry Pi (also Raspberry Pi 2) with Raspbian. They include support for all kinds of crosscompilers for Linux on x86 and x86_64 as well as FreeBSD, NetBSD, OS X and Windows.

If you have installed my backport already, then Go 1.3.3 is just a aptitude upgrade away. If you haven’t, here’s the steps:

# Avoiding Action at a Distance Is the Fast Track to Functional Programming

That’s an odd title, for sure. What is “action at a distance”? Well, how about an example? Let’s take Python 3.x, but it would work very much the same with JavaScript. Or Lua. Or most other languages.

A perfectly fine program, right? It adds some elements to a list, nothing unusual (yes, I know extend exists, but extend is only a shortcut for exactly this functionality), you might see that in every Python program ever.

Now, how about we wrap that in a function?

That’s something most semi-knowledgeable Pythoneers would object, since you can call that function anywhere and the value of lat magically changes. This is what I was calling “action at a distance”. You can call that also “nonlocal modification/assignment”, and Python 3 even has a nonlocal keyword to allow such nonlocal assignments.

So, looking at the function, it takes no arguments and returns None. Python-programmers will say: ok, then, make lat an argument and return the new list instead.

Great, now the function is not able to magically change lat any time it wants. When we look into this code, we have basically run into a circle: the for loop “takes” no input data and “returns” no output data, it just magically changes lst. This is a small toy function, so it is easy to see, but conceptually we can think about it again as a function that does action on a distance.

The usual way is to do so is to write functions that take arguments and return some new values. Unfortunately, append does not return a value, it, again, does action at a distance in some way, “magically” adding an element to the list. That’s easy to fix, let’s make our own append operator:

With this in order, we would need to call append(lst, 4) and then append(that_result, 5) and append(previous_result, 6) on it, thus constructing append(append(append(lst, 4), 5, 6). Fortunately, Python ships with a function that does exactly that, in 2.x it is called reduce and in 3.x it is still called reduce but moved into the functools module.

The whole code looks like this now:

This time we eliminated all action-at-a-distance operations. Every operation takes an input and returns a result, there is no more things changing in the background without an assignment. Interestingly enough, we have just invented functional programming, a paradigm that avoids action-at-a-distance as much as possible, which makes reasoning about code easier. This is, by the way called “referential transparency”, a fancy-pants name for “nothing happens at a distance”.

Would you think, that there are people who made programming languages which only do functional programming?

# Secure Secure Shell on Debian Wheezy

If you have passingly paid attention to the internet at all lately, you probably ran across the Secure Secure Shell article, which advises on how to better secure your SSH sessions. This is nice and all, but it doesn’t apply to Debian 7, Wheezy, too much: “Warning: You will need a recent OpenSSH version. It should work with 6.5 but I have only tested 6.7 […]”.

Yeah, I’ve tested it on the version shipped with Debian Wheezy, 6.0 and guess what, many of the secure algorithms are unavailable. You could try installing backports of newer OpenSSH versions, but then you have to hope that these get maintained as well as the regular Debian security updates. And if you have many machines installing the backport might be tedious. So now that the next version of Debian, Jessie/8 is in freeze state which will ship with OpenSSH 6.7, I don’t feel like updating.

So what exactly is missing? As I saw everything using Curve25519 is not yet implemented in OpenSSH 6.0, so forget about the key exchange and Ed25519 public keys, but the Encrypt-then-MAC modes aren’t here either. ChaCha20? Nope, sorry.

Stripping out the algorithms that are missing, left me with these settings in /etc/ssh/sshd_config:

On the positive side: you can upgrade your RSA keys to 4096 bits (if they aren’t already) and you can delete your DSA and ECDSA keys. You can edit the module to only have larger values, as described in the article.

Overall, I’d say it is decent. I haven’t seen any incompatibility so far with the clients I used (OpenSSH and JuiceSSH, the latter only recently implemented diffie-hellman-group-exchange-sha256 and support for higher DH moduli), so that’s good.

# Reinventing the Semicolon Operator

Lately I was writing some semi-imperative code in OCaml and thinking to myself “man, these ; everywhere sure look ugly”. As I am quite a fan of the |> operator, which threads the execution of multiple functions into a chain: every function gets the result of the application of the previous function, so a |> b |> c corresponds to c (b a).

What I wanted was an operator like |> which throws away the result of the previous function and calls the next function in a normal way. So I named it |-, which coult be used like fun1 |- fun2, which would evaluate to the value of fun2. We could even enforce that the value that fun1 is evaluated to is to be () (unit), so we don’t throw away any important data.

So, let’s implement it:

Then it dawned on me: The operator I was looking for existed all along, it is just ;, I can replace all occurences of |- by ;!

This might look like a trivial epiphany, but it has indeed deepened my understanding of the semicolon operator in the language. What I have previously thought of as an purely syntactic element of the language turned out to be an operator in disguise1 and rather unlike how for example Python uses ; (to concatenate multiple expressions into one expression).

1. Actually, this is not quite true, since ; is indeed syntax, but can be thought as just syntactic sugar for an operator that drops the result of the evaluation of its first argument.


text:
The Behavioural Impossibility Theorem

It’s been a few years since I’ve posted here but here goes…

Many non-economists (and economists alike) seem to think that behavioural economics is the new and important big thing in economics. I’m writing this blog post for myself as a quick reference I can send to people on why I think behavioural economics is fundamentally limited, but it might be interesting to others. The fundamental limitation I will describe is what I call `The Behavioural Impossibility Theorem’. David K. Levine has a great and accessible discussion here too.

The Impossibility Theorem of Behavioural Economics is the simple insight that a behavioural theory of beliefs cannot simultaneously be believed and true. Or, more strictly, a behavioural economic theory cannot be acted upon and be true. The only theories that can be both acted upon and true at the same time are those that satisfy rational expectations (RE).

Why is this the case? Consider an example of forecasting a stock-market crash. Suppose there were a theory that could accurately predict that the stock market was mis-priced and that there would be a crash in a week. This theory can only be true if it is not widely believed or acted upon. If it were believed, then everyone would short the stock market and asset prices would fall today rather than in a week. Thus the theory now becomes false.

Such a theory would be predicated on a systematic flaw in agents’ reasoning. When agents correct the reasoning by adopting the theory they then disprove the theory they now believe. By contrast, in a rational expectations theory, agents necessarily reason as best they can. They do not have perfect foresight or anything like that, but rather, they agree on on an underlying probability distribution for events which is optimal. In this world, the only possible shocks to the stock market that can occur are those which are essentially unpredictable (or predictable only at great cost of things like information acquisition or skill).

Mathematically this idea can be described as follows (ignore this italic text if you don’t want the math). Consider a mathematical space, $X$, where theories describing the world are objects of the space and agents’ beliefs are functions on the space, $f$. Since the economy is composed of peoples’ actions following their beliefs, the belief functions map to real world outcomes, $Y$, i.e

$f:X \to Y$.

In particular, $f$ is a bijection from beliefs, $X$, to outcomes, $Y$. Formally you might have to appropriately condense the belief space into equivalence classes blah blah but that’s by-the-by. Since the bijection exists, beliefs and outcomes can be considered isomorphic spaces, so $X=Y$. In this space, behavioural theories are never fixed points i.e $f(a) \neq a \in X$. Only rational expectations theories are fixed points, i.e $f(a^*)=a^*$. Fixed points are the theories which can be both true and believed.

This is why I, and many others, think that RE theories are the most beautiful and likely to endure. They embrace the intrinsic randomness of human civilization. Much commentary focuses on Economists’ inability to forecast the financial crisis of 2008, but that’s the whole point! If Economists could forecast such a thing then it would signal a much deeper disfunction in our economy and our theories. Rational expectations is the truest embrace of randomness. It is our abyss in which to float, as Professor Mark Fabian would perhaps phrase it.

Note that Rational Expectations is also not efficiency. Perhaps the stock market is mis-priced, and that everyone knows it is but that there are short-sale constraints.* Then the stock market is mispriced, everyone knows that, but the mispricing persists for a while due to frictions. This is why economists like frictional explanations for things (including informational frictions).

David K. Levine nicely analogises economists’ RE theory to the Heisenberg uncertainty principle in physics. The Heisenberg uncertainty principle arises because the physicists’ very act of measuring a quantum system disturbs the quantum system in an unpredictable way. The same thing happens to economists. The act of generating a theory which is acted upon changes people’s behaviour and potentially disturbs the theory. Luckily, economists have Rational Expectations where physicists don’t!

*Actually, short-sale constraints cannot keep the price elevated in a world of pure RE, so the example is technically wrong (you need belief dispersion). I think the example is instructive nonetheless so I’ll keep it.

The Strength of Strong Form

The Efficient-market hypothesis, developed by Eugene Fama, is probably one of the most contested topics in the history of financial economics. Both on an empiric and theoretical basis economists, traders and media pundits often claim to have the truth that either supports or undermines the observations of Fama dating back to the 1960s. The EMH states that asset market prices reflect all available information and hence obey a ‘random walk’ on a ‘fat-tailed’ distribution.

But when financial economists say ‘reflect all available information’ what exactly do they mean? There are 3 possible interpretations:

Weak form- traded assets reflect all past public information.
Semi-strong form- traded assets reflect all past information but also adjust instantaneously to reflect all present public information.
Strong form- traded assets, in addition to having the properties of semi-strong form also reflect current and past ‘insider information’.
To most people, if one of the above forms is the most plausible it is either the weak or the semi-strong. By my intuition at least, it seems implausible that markets are able to completely price information that cannot even be acted on by most agents. Eugene Fama himself describes access to information on a continuum, where at first the cost is quite flat before quickly skewing off to infinity as more information is obtained on the margin. Hence, by his own admissions it may seem that ‘insider information’ is too costly to attain for most agents.

Nevertheless, Fama and others in favour of the EMH insist that more statistical evidence was found in favour of the strong strand of EMH than for the weaker forms. How can this be? I am by no means well-trained enough to devour the reams of statistical evidence on both sides of the debate and hence will refrain from offering a general opinion on whether the EMH is inherently flawed or a beautiful prophecy; but I will attempt to explain how the Strong-Form of the EMH has more going for it than is commonly assumed. In fact, it seems that Strong-Form is to be expected from some classic financial economics theorems which expose the vulnerabilities of using ‘economic intuitions’ alone. Contrary to popular belief, in this vein a “strong-form” of the EMH is probably more consistent with highly volatile markets than the weaker versions.

The clue to understanding why the ‘strong-form’ may be empirically sound comes from an unlikely source. Nothing really needs to be said about investors obtaining fundamental information for themselves. Rather, it has something to do with the effect that asset trading itself has on the dispersion of information.

A formal and somewhat abstract way of thinking about price information dispersal throughout a market comes from the No-trade theorem. Informally, this theorem states that under conditions whereby the market is composed completely of rational traders (no-noise) and operating at an efficient equilibrium there is no scope to profit off of private information. This is because given that all traders are rational with acknowledgement of collective rationality, any attempt to initiate a trade will reveal the private agent’s informational advantage and hence change market expectations in line with that. Consequently, all insider information is automatically reflected in prices as if it were public information.

Note that the assumptions behind the No-trade theorem are obviously not met by reality, and that theorems themselves are only strictly true when their assumptions are met. However, when thinking about information diffusion in an economy notice the game theoretic nature of asset trading in the hyper-rational world of the No-trade theorem.

Implicitly there is some strategic interaction, where each agent attempts to anticipate the motives of the others, and due to strict rationality ends up concluding that their own information is less accurate. If any forms of the EMH are to be taken seriously then there is the inevitable recognition roughly speaking the market will be at some kind of ‘perceived’ efficient equilibrium with noise traders not having the financial capital to issue the largest trades.

Hence, whilst the assumptions of the No-trade theorem are not completely met even when the EMH holds, the No-trade theorem still provides a context for understanding how Strong-Form may actually be more plausible than expected.

The idea is that using Fama’s model of an information-cost continuum, only agents with access to substantial capital have the capacity or incentive to actually obtain that information and then trade on it. Following this, the trade using insider information is likely to be quite large, often issued by a known Hedge Fund which can ‘lever’ the information up to the hilt. The fact that the private information holder is only likely to exist if they are agents with an ability to trade large volumes implies that they are often sophisticated agents whose valuations are more likely to be perceived as fundamental rather than noise by the rest of the market. Thus, using the game theoretic analysis from the No-trade theorem it would be quite rational for other agents to reprice their own valuations in line with the offer/bid by the private information holder.

It can be expected that in a world of fast paced traders trailing behemoth funds there is little to be gained from trading on insider information which serves as a signal more than anything else. Practically, it may even be in the public’s interest to permit insider trading where there is scope to maintain the information-cost continuum (via an excise tax perhaps); seeing as it can signal an efficient pricing mechanism.

Furthermore, the existence of these ‘game theoretic’ patterns whereby smaller traders attempt to piggy-back off the information of more sophisticated ones in a world of Strong-Form EMH could also be more prone to volatility of the sort first identified by Mandelbrot. In this context, the ‘fat tails’ of financial markets can represent the cascading of less sophisticated agents attempting to bid immediately after large sophisticated ‘shock trades’. In turn, quick readjustments may be the realisations that high-frequency ‘trailing’ is often misplaced since large trades may simply reflect internal dynamics of the leading firm. This fits the observable facts that shocks are often random, and readjustments follow seemingly unimportant information.

Note, that none of the above discussion is bullet-proof financial theory, nor is it an exposition of the strength of the EMH. Rather, I have attempted to explain practically how insider information can be priced effectively in markets, and how it is linked to seemingly unexplainable volatility that may otherwise be used as evidence for irrationality.

Formalising ‘Trickle Down’ Economics

Note I am not an advocate of trickle down, I just want to make the definition meaningful. I apologise for the slap dash structure.

Looking at the Wikipedia definition of trickle down economics one can get a broad sense of the kind of policies that it might imply. My contention is that the term is just a euphemism used by left-wing audiences, with little actual substance in its current popular usage. I propose an alternative interpretation here which is more in line with the original conception.

When people normally think of trickle down they think of things like tax cuts on the rich, financial deregulation and union busting. Tracing back to 1896 the term was popularised by a Presidential candidate as being “you just legislate to make the well-to-do prosperous, that their prosperity will leak through on those below.”

This is a purely rhetorical point, but it is possible to think about how this framework can work from a technical economic perspective. There are a few ways. From a supply-side point of view we might just think of deregulation. But this is not really ‘trickle down’. It already has a term- deregulation.

The notion of ‘trickle down’ that I would understand from the 1896 definition is one where we conceptualise that by funding the business and wealthy interests we can boost economic growth for all. Deregulation may or may not be in the interests of businesses, so it’s not a useful way of thinking of it.

So let’s think about this formally. Why would helping rich people boost economic growth? Milton Friedman in a famous video described the argument as being “When you give money to a rich entrepreneur, they’ll put it back into the business and create investment and jobs for all. By contrast if you give it to a poor person, they will tend to consume rather than invest”.
This idea can be made more rigorous as follows. Rich people and businesses have a lower marginal propensity to consume. Therefore they have a higher propensity to save. Under standard macro assumptions, these savings in turn go through the financial sector to create investment. Thus by allowing the rich to retain more income you can grow the economy faster for long term benefit to everyone, at the cost of short term consumption. The point is that you try and take from agents that spend, and give to agents that save to boost the pool of savings. In turn you boost the pool of investment.

The precise mechanisms which lead to this can be found in an intro macroeconomics textbook if the reader is interested.

I contend that this is the most meaningful way to approach the definition of trickle down. Don’t think of it as a bunch of policies with uncertain impacts on the rich. That is just pure political rhetoric with no meaning. Think of it as a framework to grow the economy by affording businesses and the rich more opportunities.
Now that we are thinking of trickle down in a more formal and precise framework, what are some examples.

Let’s look at Reaganism. Is that trickle down? I contend that it is NOT. Reagan’s economic reforms involved large scale financial deregulation. One impact of this was to allow the US economy to borrow more from international capital markets. This in turn via some technical trade theory forced a current account deficit on the US economy. This borrowing surge overall probably lowered the total pool of investment in the US and dramatically lowered savings rates. (Interest rates would have stayed roughly the same though.). Hence yes while in some ways the rich benefited from these policies, the impact on US business profits is uncertain. We can look at this some more, but I think I have illustrated my point.

Now let’s look at China and Germany. In a certain sense these two economies have similar structure, but China would be the one to focus on here. Both via a large swathe of economic policies give huge implicit subsidies to business. Things like energy subsidies, infrastructure spending and currency devaluation take money from consumers and give money to businesses. The result is a strong pool of savings that have created highly industrial economies. Consequently we get faster (though distorted) growth, and a widening of income inequality. Note that both these economies are very different from Reagan’s conceptualisation of the ideal US economy. They both have high regulation. But it is this regulation that captures the ‘trickle down’ effect at its most potent.

If we look at trickle down this way, then in a sense it definitely does lead to fast growth. Japan, China, Germany, the UK, Taiwan, South Korea all used a form of high regulation trickle down to reach record levels of growth, though with large negative consequences. This is not to say that ‘trickle down’ is good in any normative sense. I don’t really have a view on that, as the morality is extremely complex. But it certainly seems like it works from a ‘boosting growth’ perspective if we have a formal definition.

The point of this rant is to give a shitty rhetorical tactic some substance, and address a pet peeve of mine. Helping business interests actually does boost growth in developing nations, and the left cannot simply ignore this inconvenience.

Explaining Slow Growth: Turning Away from the Stale “Lessons from Japan”

For the past 3 years, macroeconomists and central bankers have grappled fiercely over the topic of developed market economic stagnation, pending a true recovery from the financial implosions of 2008. Many influential “macro guys” and financial analysts now see stark similarities with the Japanese post 1990 experience and the current forecasts given for much of the developed world. Paul Krugman in a recent Op—Ed piece in his New York Times Blog for example stated emphatically that “Nowadays, we are all Japan”, whilst Richard Koo’s (highly informative) “The Holy Grail of Macroeconomics: Lessons from Japan” attempted to empirically relate the current financial position of the US to that of Japan during the lost decade. Nevertheless, I see a number of structural differences between the Japanese economy leading up to 1990 and the other indebted developed markets of today.

Essentially, if China’s economic model is a mirror of Japan’s, and thus awaits an equally daunting “Long Landing” as is expected (See Pettis, China Financial Markets), then surely the U.S and Europe who run a functionally obverse economic model shouldn’t intuitively be in the midst of a Japanese styled slump. To my mind, much of the debate amongst the macroeconomists misses this point and is therefore muddled and wonky. To my mind, a viable opponent to the Japanese analysis, is one based upon the international Balance of Payments (BoP).

I have long found it curious and odd, that even at the height of sub-prime lending in the U.S combined with excessively low interest rates after 2001, that the U.S economy remained on its long term average growth path. Surely the asset bubble and leveraging cycle should have propelled growth. Similarly, the 3 rounds of QE in the post-crisis era should have also stimulated growth and investment. (I share the opinion of Richard Koo in the idea that the US financial sector, contrary to popular sentiment is indeed healthy) One explanation for lacklustre growth is that the US economy has lost much of its comparative advantage, and that without constant monetary pump priming growth would be even slower. Another idea is that of Richard Koo and those of the Japan school, who now believe that the U.S economy is caught in a fierce deleveraging cycle that may take decades to resolve. And yet both of these theories, as intuitive as they may be, are muddled by inconsistent empirical evidence and strange contradictions.

What if however, the U.S and European economies were plagued by a very different type of problem? One which monetary pump-priming and asset bubbles could not solve. What if, the U.S and peripheral European demand over the past 20 years had simply been bled out by distortions in the external account? In this case, the US crisis was driven by external trade policies, and not, by a statist investment orgy as in Japan.

This situation at first glance seems to be supported by simple facts and intuition. The persistent current account deficits of developed markets, specifically the US, to my mind have caused both the inflated asset prices leading up to 2008, and also the below trend equilibrium (rather than actual) growth rates experienced since roughly 1997.

The late nineties were indeed a tumultuous period, and can be seen hence, as crucial to the development of instability within the US financial system. In 1997-8 a few things happened:

1. East-Asian financial markets, stunned by a sequence of currency devaluations, began to run targeted trade surpluses.
2. The US capital inflows soared (functionally the equivalent of a rising trade deficit that balanced the East-Asian surpluses)
3. Lending and credit within the US expanded, funnelled largely into real estate.
4. Housing prices and volumes began their ominous ascent.

The East-Asian surpluses then, can be seen to have (either directly or indirectly) penetrated the American trade account. Consequently, East-Asian markets served to change the composition of the American economy. The U.S tradable sector, due to financial repression and increasing savings in East-Asia, was beaten to a pulp and workers quickly made redundant. With a contracting tradable sector, the only possible way to redeploy labour is through a surge in foreign-financed debt which expands domestic consumption and investment. In addition, when the economy is balancing away from the tradeable sector most investment becomes speculative and in this case was inevitably funnelled towards the increasingly liquid real estate sector.

Therefore, the capital inflows (functionally current account deficits) can be seen to have both slowed equilibrium growth, as productive workers were redeployed and fired, and simultaneously fuelling a speculative binge. (The impending crisis’ magnitude was of course also amplified by the irresponsible lending techniques rampant within US financial markets which increased the probability of insolvency).

Even to this day, East-Asian capital exports have continued to increase, with China probably consuming a mere 35% of production (GDP) in comparison to the US’ 72% and Europe’s 65% (Rough estimates). The effect of such Underconsumption on the national savings rate is immense and if the US is to bear the brunt of the resultant capital inflows and Chinese production overload (As the PBoC reserve account holdings of USD implies it does) then it means the U .S is being bled white through the gaping hole in the external account.

With the financial crisis having largely capped the private sector’s willingness to further leverage-up and accumulate debt, there thus remains only one natural way for the U.S economy to absorb foreign excess capacity- unemployment and slower growth. Of course also there are a few politically unlikely ways too though. The US could become competitive through devaluation, higher VAT tax or equivalent, labour market reforms, tariffs etc. But the point is that China and East-Asia have purposely pushed their surplus savings onto the US. The US must absorb this excess by either more consumption, more investment (both imply less savings) or by intervening in trade and stopping the central bank purchases of so many treasuries (remember for every net $1 of Treasuries that are bought by foreigners, that is by economic law$1 added to the trade deficit). Since debt financed consumption and investment is not really an option without significant fiscal stimulus from the public sector (the private sector seems unwilling to leverage up further) and intervening in trade is politically unlikely the only other way to reduce savings is to reduce production by an amount more than the reduction in consumption. ie unemployment. This is basically an accounting necessity

Spain is an exaggerated version and perhaps a better example to see why. Spain can’t devalue due to it’s Eurozone membership. It also has a very limited capacity to load up on leverage (Look at sovereign bond risk premiums and the imploding banking sector) and so if Germany’s surplus continues to be pushed onto it, what can the Spanish administration do? All it can do is lower domestic savings by jacking up unemployment or try to become competitive and push it’s own savings out onto the rest of the world. (Like a Vampire state, sucking away at foreign demand to keep employment high). Coincidentally, the quickest way to regain competitiveness without intervening in trade is to grind down wages via unemployment. This is referred to the “internal devaluation” mode of recovery.

It is in this context that the anomalous predicament of the U.S and other developed markets is neither surprising nor complex. Unemployment will remain high until the trade interventions in surplus nations are eliminated, and the deficit ones are allowed to compete on an equal basis. In a situation where demand is being haemorrhaged to foreigners, fiscal stimulus will also need to be focused on innovative investments and cannot be allowed to stimulate consumption as is optimal Japan. In this world we must draw very different conclusions from those of the 90s.

The Redundancy of Supply-Side Economics in Abe’s Japan

Great expectations surrounded the announcement of Shinzo Abe’s economic revolution in Japan to pull the economy out of its 20 year slump. The revolution involved a huge overhaul of public policy, with a three-pronged attack on the macroeconomic conditions beleaguering the nation.

The first prong, a tsunami of monetary stimulus and cheap credit released by the Bank of Japan’s new governor Haruhiko Kuroda was designed to end the deflationary spiral. The second was a similarly immense fiscal stimulus package worth $116 billion designed to offset lacklustre investment from the private sector. But it was the third arrow, a series of supply-side reforms, that was perceived to be key to improving the competitiveness of Japanese firms and bolster long-term growth. At best, these supply-side measures will prove to be only mildly stimulative to the Japanese economy if it begins to recover from its 20 year slump. By contrast, if the economy falls into another recession and the continued deregulation of Japanese labour markets is pursued aggressively, the result could be damaging. So let’s star our analysis by looking at the channels through which labour market reforms increase productivity. The first channel allows low-productivity sectors and unprofitable enterprises to shed labour more easily. The second channel is then designed to allow firms to hire workers more easily, and consequently pick up the previously fired workers. Therefore, in a healthy economy, structural reform redistributes labour from unproductive employment towards productive employment. In conditions of economic malaise however, the second channel operates rather weakly. It is easy to see why. When aggregate demand is depressed even productive firms may be saturating the market with unsellable produce and as a result, they are hardly likely to increase employment until aggregate demand recovers. Thus, only the first channel operates at full capacity, and labour is fired at increasing rates. Synthesising these two channels in dampened economic conditions therefore results in heightened levels of unemployment, whilst aggregate demand is depressed even further. If Abe’s supply-side plan is to recognise any success in this case it will have to hope that the effects of monetary and fiscal stimulus hit the economy before the labour market deregulations do. But even in this event (which admittedly is the more likely one), the third arrow of growth will inevitably fail to boost growth substantially. The fact of the matter is that Japan’s crisis is one of a huge debt-deflation overhang, and one of depressed demand. That is; it is cyclical in nature, not structural. The huge time-frame and multitude of bogus recoveries would seem to imply that the recession is not a normal one, and the implication is correct; the problems are odd. But the peculiarity of the problems does not make them structural. In an economy suffering from supply-side malaise, firms are unable to compete internationally and produce anything of meaningful values. In this situation, the current account deficit will rise due to domestic inefficiencies (since domestic production will be unable to compete with imports, and exports will falter).When the current account deficit rises, the currency devalues by the natural mechanisms. When the currency devalues imported inflation will rise. And when inflation rises the central bank will attempt to remedy the problem via contractionary monetary policy. Thus an economy suffering from supply-side inefficiencies should be characterised by having: • A deficit on the current account. • A weak currency • High levels of inflation • Contractionary monetary policy These symptoms validate the experience of the USA in the 1970s, when it suffered from stagflation. Indeed, the problems in that situation were supply-side, and the required response was microeconomic in nature. But 1970s America is very different to 2000s Japan. The Japanese economy for the past 20 years has shared none of the symptoms of stagflation. It has enjoyed persistent current account surpluses, a strong currency (the government has had to step in on numerous occasions to weaken the Yen in the past 20 years), persistent deflation and the most expansive monetary policy seen in history. This should all point to the fact that Japanese firms are highly competitive on an international-scale. Whilst many academic economists may not realise this reality, one merely has to look in their own home to validate the reality. Japan’s firms are at the forefront of global innovation, and export their products vigorously to western households and businesses. If Japan’s economy thus does not suffer from supply-side ails, and an economy stifled by over regulation then Shinzo Abe’s measures will be largely fruitless. If the demand-side stimulus measures hit the economy fast, the microeconomic reforms will be redundant. If however, implementation of the fiscal and monetary attacks wavers, the microeconomic reforms could cripple the situation and prolong the pain even further. The reality stabs policymakers in the face every day. Japan’s problems are demand-side, failing to recognise this jeopardises the livelihood of millions of people. A Quick Note on Quantitative Easing- The Portfolio Composition is More Important than the Reserve Levels. So I was recently engaged in a debate with a close friend of mine over what the repercussions of continued Quantitative Easing (QE) would be, and what the inflationary effects of QE would be. The debate began with agreement, with both of us acknowledging that the current program was largely ineffectual due to the huge amount of excess reserves in the US financial system. Differences did soon become apparent however when my friend expressed his concern over the inflationary effects of the program if it went on indefinitely. This was because of the difficulties of retracting the program if it were allowed to go on for too long. Retracting$2 trillion dollars is easier than retracting \$20 trillion. With the reserves just sitting there in huge excess, surely Bernanke could taper the constant injections, but leave the money already there as is. Money at the moment is just sitting in the system floating about, so what’s the point of putting more in if it just makes the retraction harder? Surely the huge monetary base would keep liquidity high and interest rates low across the board. There is so much excess, why do we need more? Stop the program, leave the reserves there, and lending growth should be unchanged. The analogy is “If the shops can’t sell 10 apples, giving them 100 isn’t going to help them sell any more if the price doesn’t change”. And in other words again, people seem to think that as the money multiplier declines banks ‘park’ their money with the Fed, and do not ‘Lend it out’

This line of thinking however overlooks the actual mechanisms that drive the operations behind QE, and its theoretical framework. The fact is that QE works to drive specifically Long-term interest rates down with the purchase of Long-term assets. The answer lies in the fact that banks have strict portfolio norms that they follow, and that reserves don’t simply get “lent out”.

So let’s briefly address the “Lending-Out Misconception” first. This common misconception holds that when commercial banks hold too much cash in their reserve accounts with the central bank, they can expand their lending operations. They simply lend out this extra cash to the private sector and real economy. This is simply not true. The commercial bank has no actual control over reserve levels, and the link is indirect. (see for more http://www.standardandpoors.com/spf/upload/Ratings_US/Repeat_After_Me_8_14_13.pdf)

So, on to the more substantial point. If it’s reserves that matter and if there are excess reserves, what is the point of pushing even more into the system? The money is not being used as it is!

The point however is that it’s not the reserves nor the liquidity that expand lending. Rather, lending comes from individual banks changing their portfolio composition. In reality, when the Fed implements QE, what it does is buy long-term securities (henceforth simplified to be mortgages). Buying these mortgages helps to increase lending activity, not because the banks now have money in their checking accounts that they can lend out, but rather because banks strive to have a consistent level of long-term assets and liabilities relative to short term ones. When the Fed buys mortgages off of a bank. The bank will find itself with a more cash assets, and less mortgage assets. It’s portfolio’s composition will have changed. In order to address this the bank will strive to correct the portfolio and buy up mortgage contracts and assets off of the private sector. It will then credit the private sector with cash. Hence, when the Fed buys mortgages off of the banks, portfolio corrections means that it is really accumulating them off of the private sector. The private sector will then find itself with excess cash and the money should theoretically be invested or used.

Where the ‘flow’ of QE becomes important is in distorting the banking sector’s portfolio. As it stands, the banks are not inclined to correct their portfolios, and lending rates are not rising. But corrections back to normality DO nevertheless happen slowly, and the more balance sheets become liquid with cash exceeding mortgages, the more the banks will strive to correct their balance sheets, buying up mortgages off of the private sector.

Thus, QE works through the norms of the financial sector, and no matter how redundant inflating the monetary base through reserves may seem, it incentivises lending expansion regardless. Why are banks not so keen to rebalance their distorted portfolios? Is this situation permanent? The answer is a resounding no to the latter. Banks simply do not want to rebalance their portfolios because the returns on long-term assets have not been deemed valuable enough relative to those of highly liquid assets at the moment. In addition, the 0.25% interest rate payment that the Fed gives the sector for excess reserves provides an incentive to keep the asset compositions highly liquid. This means keeping the portfolios at above equilibrium levels of liquidity. That doesn’t mean that banks will completely disregard the portfolio norms however. Indeed, the more the Fed increases the liquidity of the balance sheets, the more the banks will strive to accumulate mortgages off of the private sector. Thus the private sector’s holdings of loanable funds increases, and interest rates fall.

*Disclaimer: I think I’m wrong

Understanding Sovereign Bonds- Foreign Financing of Fiscal Deficits

The rise of Neo-Mercantilism’s export-led growth in countries such as China and Japan has brought a host of Balance of Payments (BoP) and Sovereign Debt problems to the fore. These problems are paramount to the international economy, but experts and policymakers alike demonstrate ignorance of the mechanisms behind the BoP through counterproductive proposals.

Sovereign Debt Markets and the Balance of Payments are one of the most counterintuitive and complex themes that policymakers face, fallacies are therefore riddled throughout the public debate. Not even the US Secretary of State Hillary Clinton is immune to frequent blunders when engaging in the sphere of international macroeconomics. In February, 2009 for example she made a famous imploration to China that they continue their purchases of US treasuries. This simple (and fallacious) request to the Jintao administration received almost no academic criticism; despite the detrimental effect that the Secretary of State’s policy goals would have on the US economy. An analysis of Chinese purchases of US dollar-assets is therefore required in order to address the unforeseen issues associated with foreign financing of sovereign bonds.

There are two main problems with Clinton’s imploration to the Chinese- namely the nondiscretionary nature the Bank of China’s treasury purchases, and the manner in which these purchases fail to alleviate fiscal deficit serviceability.

Firstly, the Bank of China (BoC), and Chinese Sovereign Wealth Funds do not simply decide to purchase huge quantities of US dollar-assets (in the form of bonds for now) based on whimsical choices of investment hubs. The decisions are not arbitrary; they are natural. The Bank of China’s decision to keep the RMB devalued means that they acquire huge foreign exchange reserves primarily in the form of US dollars. These dollars must be invested somewhere, and the only two markets large enough to absorb this influx of liquidity are the Eurozone and the US. Of these two options the US financial sector’s development and reputation of a safer investment location makes it the obvious choice.

Even if the Chinese decided to shift their exchange reserves to the Eurozone, they would have to undergo huge and costly transactions changing their accumulated dollars to Euros, in the process making huge losses in arbitrage as the dollars were devalued. It is clear with this in mind that Clinton’s beggary to the Chinese was completely ineffectual. The only way the Secretary of State could get her wish of increased foreign purchases of dollar-assets would be through the BoC devaluing the RMB even more, acquiring more reserves, before shoving them back into the bloated US treasuries market.

This leads us to the second (and far more important) fallacy underlying the Secretary of State’s understanding of foreign financing. The only way for China to unilaterally increase its purchase of US bonds would be to increase the volume of its capital exports to the US, thereby forcing a larger current account surplus as well (By definition the quantity of capital that is imported or exported is equal to the quantity of goods that are imported or exported respectively). The influx of demand for dollars would inflate the value of the currency, increasing the trade deficit by an even larger amount, and consumption on imports would boom leading to an even more indebted household sector.

In addition, interest rates on bonds would be largely unaffected and the government’s debt would become no more serviceable than before. This is due to the fact that with an appreciation of the dollar, many tradable sector firms would be adversely affected, and workers would be made redundant quite quickly. As a consequence, the US fiscal deficit would rise in a quantity roughly equal to the initial influx of Chinese bond purchases which caused the appreciation or by contrast the US would have endure higher levels of unemployment (The change in the capital deficit will be exactly equal to the trade deficit).

The point is that the Obama administration would have to issue an amount of bonds roughly equal to or in excess (A few economists have tried to calculate the exact relationship with little success) of the amount purchased by the Chinese. The influx of supply would equal the influx of demand, and the price (in the form of interest) would have no net effect. The difference for the American economy would be that both the current account deficit and the fiscal deficit would have grown. Americans, in essence, would be forced into an even larger imbalance between consumption and production.

Hillary Clinton’s imploration to the Chinese in this light is clearly opposed to American interests, and yet the entire economics profession remained largely apathetic to her announcements. Today, the profession continues to be mute when confronted by similar policies that flout textbook macroeconomics.

format: plain


text:
Mutable and Ref

Let's go over the high level view of what's going on. Conceptually, the entire library revolves around the Mutable typeclass and the Ref associated type.

class Mutable s a where
type Ref s a = v     | v -> a s

thawRef   :: (PrimMonad m, PrimState m ~ s) => a -> m (Ref s a)
freezeRef :: (PrimMonad m, PrimState m ~ s) => Ref s a -> m a
copyRef   :: (PrimMonad m, PrimState m ~ s) => Ref s a -> a -> m ()

-- ... plus some more methods that can be implemented using
-- the others in most cases

An instance of Mutable s a is an a that has a "mutable version" that can be updated/mutated in a "mutable PrimMonad m" (like IO or ST) that has a state token s.

The (injective) type family Ref associates every type a with its "mutable version".

(A quick note on PrimMonad --- it comes from the primitive library and is used across the ecosystem; it's a typeclass that abstracts over all "impure" monads like IO, ST s, ReaderT r IO, etc. You can think of it as an expanded version of MonadIO to also include monads that use ST s. PrimState is what you give to MutVar and MVector to make things "work properly")

For example, for Vector, the "mutable version" is an MVector:

class Mutable s (Vector a) where
type Ref s (Vector a) = MVector s a

thawRef   = V.thaw
freezeRef = V.freeze
copyRef   = V.copy

For simple non-composite data types like Int, you can just use a MutVar (a polymorphic version of IORef/STRef):

class Mutable s Int where
type Ref s Int = MutVar s Int

thawRef   = newMutVar
copyRef   = writeMutVar

class Mutable s Double where
type Ref s Int = MutVar s Double

thawRef   = newMutVar
copyRef   = writeMutVar

All we are doing so far is associating a type with its "mutable" version. But, what happens if we had some composite type?

data MyType = MT
{ mtInt    :: Int
, mtDouble :: Double
, mtVec    :: V.Vector Double
}
deriving (Show, Generic)

We might imagine making a piecewise-mutable version of it, where each field is its own mutable reference:

data MyTypeRef s = MTR
{ mtrInt    :: MutVar s Int
, mtrDouble :: MutVar s Double
, mtrVec    :: MV.MVector s Double
}

instance Mutable s MyType where
type Ref s MyType = MyTypeRef s

thawRef (MT x y z) = MTR <$> newMutVar x <*> newMutVar y <*> V.thaw z freezeRef (MTR x y z) = MT <$> readMutVar x
<*> V.freeze   z

copyRef (MTR a b c) (MT x y z) = do
writeMutVar a x
writeMutVar b y
V.copy c z

But, this is pretty tedious to write for every single data type we have. What if we could instead automatically derive a reference type?

Well, we're in luck. If MyType is an instance of Generic, then we can just write:

instance Mutable s MyType where
type Ref MyType = GRef s MyType

We can now leave the rest of the typeclass body blank...and the mutable library will do the rest for us!

• GRef s MyType is an automatically derived type that is equivalent to the MyTypeRef that we wrote earlier. It leverages the power of GHC generics and typeclasses. Every field of type X turns into a field of type Ref s X. This "does the right thing" as long as all your fields are instances of Mutable.
• The mechanisms in DefaultMutable will automatically fill in the rest of the typeclass for you.


text:
Flow around a NACA 0012 airfoil

Available data

Each case is stored in a folder that contains sub-folders for each of the 6 grids sets available.

Folder of each case contains 15 files:

 File Contents README.txt Description of the contents of the other 15 files conv_data_cd.dat Friction () and pressure () drag coefficients and friction () and pressure () lift coefficients of the airfoils for the 6 grids available. conv_surface_cflo.dat Skin friction coefficient  at the 19 selected locations of the lower surface of the airfoil for the 6 grids available. conv_surface_cplo.dat Pressure coefficient  at the 19 selected locations of the lower surface of the airfoil for the 6 grids available. conv_surface_cfup.dat Skin friction coefficient  at the 19 selected locations of the upper surface of the airfoil for the 6 grids available. conv_surface_cplo.dat Pressure coefficient  at the 19 selected locations of the upper surface of the airfoil for the 6 grids available. field_points_r---.dat Horizontal  and vertical  velocity components and the eddy-viscosity  at the 130 selected field locations for each grid. r--- corresponds to the grid refinement ratio  as defined in the test case description. Reynolds number Turbulence Model Zipped Files Rar Files Spalart & Allmaras SST k-w Spalart & Allmaras SST k-w Spalart & Allmaras SST k-w


text:
## sheaangel Calculate the number the possibility of drawing 5 red cards in a row with no replacement one year ago one year ago

1. jygebs

how many total card are there?

2. robtobey

52 cards in a standard deck. 13 Diamonds and 13 Hearts, all RED.$\frac{26}{52}\frac{25}{51}\frac{24}{50}\frac{23}{49}\frac{22}{48}=\frac{253}{9996}=0.0253$

3. jygebs

that's right


text:
The arrow of time (4): entropy and reversibility, pictured in designs

So…I do not see any convincing answers in physics to the basic question of `what is time?’. To wrap up this complicated subject for now, I will show some half-designs for the IMAPP symposium (which I did not elaborate on since the Francesco del Cossa design that I showed earlier clearly was superior), and reformulate earlier questions on time and entropy.

The first question already is hard to formulate without falling into much inaccuracy as well as absurdity. But here goes anyway: suppose we have two situations / configurations S1 and S2 of a closed system U [for Universe] such that S1 is exactly the same as S2 in every conceivable non-time-related way (particles, waves, constellations,…down to every last photon). Then I would say that

A: Within U there is no time difference between S1 and S2, in other words they are also time identical.
B: Therefore time in U corresponds to (some measure of) the difference between configurations of U.

Hence my earlier `formula’ ΔTime $\approx$ ΔEntropy.

Thus the question of (ir)reversibility, known as `arrow of time’, in my eyes could well be a tautology. To see this, consider the statement: `we cannot lower the entropy of the system U when going forward in time’. When ΔTime `equals’ ΔEntropy this more or less becomes equivalent to: `we cannot lower the entropy of the system U when the entropy is increasing’…

Also, it raises the question whether time is a `local’ phenomenon (non-uniform). One half-design that I made for the IMAPP symposium centered around this entropy idea:

(click for enlargement, you might notice different `reversal arrows’ which I added pictorially, to express the questions surrounding this subject)

Next, in my eyes the question of causality and reversibility is intimately connected to our own consciousness. We seem to experience things exclusively in the present, but! we do not even know what `experience’ and `the present’ mean. Anything we experience stems from neurons firing in our brain; anything we see/hear/sense in this way has a time lag as compared to the stimulus which provoked our senses…

Somehow we retain memories (unreliable!) from past events, and we experience time as moving forward, probably because our consciousness is hardwired that way. See Immanuel Kant‘s Kritik der Reinen Vernunft, we quote from wikipedia:

Kant proposed a “Copernican Revolution” in philosophy. Kant argued that our experiences are structured by necessary features of our minds. In his view, the mind shapes and structures experience so that, on an abstract level, all human experience shares certain essential structural features. Among other things, Kant believed that the concepts of space and time are integral to all human experience, as are our concepts of cause and effect.[3] One important consequence of this view is that one never has direct experience of things, the so-called noumenal world, and that what we do experience is the phenomenal world as conveyed by our senses. These claims summarize Kant’s views upon the subject–object problem.

In my humble and ignorant opinion, Kantian philosophy is not eclipsed by Einstein’s relativity and its concomitant spacetime. A real discussion of relativistic spacetime is beyond both me and the scope of this series of blog posts, but perhaps it is relevant to notice that causality in relativistic spacetime hinges on `light cones’ (image by Stib):

When it comes to reversibility and the arrow of time, the Kantian crux seems to me: what do we mean with the word causality?

If our consciousness were hardwired `the other way round’, could we not perceive reality as follows: a billiard ball rolling `kauses’ a billiard cue to hit the ball which in turn `kauses’ a billiard player to appear at the billiard table etc. etc.

With this in mind I made the following Escherian half-design:

(click for enlargement)

and since I found this half-design to be too sterile, I also made another one based more on entropy and human experience (which is approximate, vague, sketchy):

(click for enlargement)

This last design was a close contender (but lost to the Del Cossa design, see the first posts in this series), however it lacked the depiction of a human interaction, intervention, … I also tried yet another half-design, before finally picking the Del Cossa design:

(click for enlargement, the arrow shooter comes from a centaur sculpture in the Basilique Sainte-Marie-Madeleine of Vézelay, the original photo was taken by Vassil)

In the end , the Del Cossa design, apart from its visual strength, had another interesting feature which proved decisive: the golden circle held by its arrow-bearing protagonist. To me this circle symbolized both mathematics, and two other conundrums of time: can there be a first moment in time? is time circular (another way of looking at reversibility)?:

(click for enlargement, almost final design, just the sponsors omitted)

Hope you enjoyed this cross-over between science, philosophy and graphical design!

Postscript: if you’ve come this far, then the following very recent article should interest you: new quantum theory could explain the flow of time. It seems that every few years or so, a new insight in `the arrow of time’ is claimed…which in a way illustrates how hard the problems surrounding time really are.

Entropy, entanglement, energy dispersal… they all start with an E so perhaps I could just pimp up my `formula’ thus: ΔT = H(ΔE), where H is some appropriate function (multiplication with constant would be nice but is probably far too simplistic).

Isn’t cosmology just the most marvelous religion? The really amazing part of physics to me is that we actually succeed in increasing our capabilities to manipulate Nature, even when (in my eyes) we remain largely ignorant of the real mechanisms at work. On the other hand, I’m highly pessimistic about whether this increase in manipulative activities will be beneficial to humanity, and life on earth in general.

[End of series]


text:
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
This post explains how to calculate the key rate durations (KRD). Ho (1992) introduces KRD to measure non-parallel movements of the yield curve that the existing duration measures can not describe as these are defined under the assumption of a parallel shift of the yield curve.

# Key Rate Duration using R code

Ho (1992) introduced the concept of the key rate duration (hereafter KRD), which is a new measure of interest rate risk exposure. KRD is a vector of the price sensitivity of a bond to each key rate change. The sum of the key rate durations is identical to the effective duration. The sum of the product of key rate durations and each yield changes in key rates (with negative sign) is the bond price change due to the non-parallel shift of the yield curve.

### Key Rate Shifts

Unlike the traditional effective duration, KRD is calculated not from a par yield curve but from a zero curve (spot rate) so that the bump and reprice are performed on selected spot rates (key rates). In other words, individual effective durations are calculated by shift of each spot rate at each key maturity and the sum of them is the KRD.

Formally, ith key rate shift is defined to be zero shift for maturities shorter than (i-1)th key rate and longer than (i+1)th key rate. Interestingly, the shift between these two adjacent key rates is defined by the linear interpolation with the peak at the ith key rate.

As can be seen in the above figure, yellow colored maturity is assumed to be the selected maturities of key rates. Ho (1992) suggests the size of shift as 10 bp but we use 1%(=100bp) simply for illustration purpose. A shift of one key rate by 1% affects its neighborhood of that key rate with linear interpolation. Rates outside the range of selected key maturities are set simply by the nearest key rate.

In particular, the light blue colored line (bottom) illustrates the shifts at all maturities, which resulted from 60M key rate’s change. In this case, all the key rates except 60M are not affected but two adjacent rates at 54M and 66M are affected linearly.

The ith shifted yield curve is the sum of the initial yield curve (blue colored solid line) and its shifts at all maturities, which resulted from the change of ith key rate. When we add up all shifted changes together on the initial yield curve, we can get the parallel shifted curve (red colored solid line).

### Key Rate Durations

By shifting each key rates, we can get N shifted zero curves (N is the number of key rates). Using these N shifted zero curves, each effective duration ($$KRD_i, i=1,…,N$$) is calculated with the initial zero curve.

\begin{align} KRD_i = \frac{P_{up} – P_{down}}{2 \times P_0 \times \Delta s(t_i)} \end{align}
Here, $$s(t_i)$$ is a spot rate at time $$t_i$$

\begin{align} \frac{\Delta P_i}{P} = -KRD_i \times \Delta s(t_i) \end{align}
By definition, the sum of KRDs is the effective duration of a bond.

\begin{align} D = \sum_{i=1}^N KRD_i \end{align}
The shift of the yield curve can be approximated by the sum of all the key rate shifts.

\begin{align} \frac{\Delta P}{P} = – \sum_{i=1}^N KRD_i \times \Delta s(t_i) \end{align}

### Key Rate Shifts in R code

As will be shown in R code, it is worth noting that a vector of shifts due to a key rate movement is appended horizontally with the name of its key rates as follows.

Therefore, each shifted zero curve can be calculated by simply summing the initial zero curve and the corresponding shift vector.

### R code

R code below implements the above explanations. After calculating we compare the sum of key rate durations with the traditional effective duration. When we use not 0.01 (1%) but 0.0001 (1bp) as a small change in a key rate, two duration measures are nearly the same in the perspective of numerical calculation.

 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 #========================================================## Quantitative ALM, Financial Econometrics & Derivatives # ML/DL using R, Python, Tensorflow by Sang-Heon Lee ## https://kiandlee.blogspot.com#——————————————————–## Key Rate Durations#========================================================# graphics.off(); rm(list = ls()) #=======================================================# read data#=======================================================str.zero <– “matm zero             12    0.022             24    0.030             36    0.040             48    0.046             60    0.050             72    0.052             84    0.053             96    0.053            108    0.053            120    0.054″ df <– read.table(text = str.zero, header = TRUE) v.key_matm <– df$matm # maturities for key ratesnkey <– length(v.key_matm) # linear interpolation of zero ratesf_interpol <– approxfun(df$matm, df$zero, rule = 2) # fill rates between key rates by 6M tenormatm = seq(6,120,6)df.sa <– data.frame(matm = matm)nobs <– length(matm) df.sa$zero <– f_interpol(matm) # 10Y YTMYTM10 <– 0.0527780789520333CPN10 <– YTM10 # 10Y coupon = par yield rate  #=======================================================# read data#======================================================= # rate shift : 0.0001 is preferabledr = 0.0001 # make a table of dr for each key ratesfor(n in 1:nkey) {    df.sa <– cbind(df.sa, NA)    colnames(df.sa)[2+n] <– as.character(v.key_matm[n])        key_matm <– v.key_matm[n]        # set dr to the same key maturity    # set  0 to other key rates    # set NA to rates between key rates    for(i in 1:nobs) {                matmi <– df.sa$matm[i] if(matmi == key_matm) { df.sa[i,2+n] <– dr } else if (matmi %in% v.key_matm){ df.sa[i,2+n] <– 0 } } # rates between key rates is linearly interpolated f_interpol <– approxfun(matm, df.sa[,2+n], rule = 2, na.rm = TRUE) df.sa[,2+n] <– f_interpol(matm)} # p0zero <– df.sa$zeroP0 <– sum((YTM10/2)/(1+zero/2)^(matm/6)) +            1/(1+zero[nobs]/2)^(matm[nobs]/6) # all the key rate shiftszerou <– zero + rowSums(df.sa[,1:nkey+2])zerod <– zero – rowSums(df.sa[,1:nkey+2]) # effective duration : traditionalPu <– sum((YTM10/2)/(1+zerou/2)^(matm/6)) +       1/(1+zerou[nobs]/2)^(matm[nobs]/6)Pd <– sum((YTM10/2)/(1+zerod/2)^(matm/6)) +       1/(1+zerod[nobs]/2)^(matm[nobs]/6)ED <– (Pd – Pu)/(2*P0*dr) # Key rate duationsdf.KRD <– data.frame(matm = df$matm, ED = NA)for(n in 1:nkey) { # key rate shifts zerou <– zero + df.sa[,2+n] zerod <– zero – df.sa[,2+n] # effective duration : KRD Pu <– sum((YTM10/2)/(1+zerou/2)^(matm/6)) + 1/(1+zerou[nobs]/2)^(matm[nobs]/6) Pd <– sum((YTM10/2)/(1+zerod/2)^(matm/6)) + 1/(1+zerod[nobs]/2)^(matm[nobs]/6) df.KRD[n,2] <– (Pd – Pu)/(2*P0*dr)}df.KRD # check if sum of KRDs is equal to effective durationdrsum(df.KRD$ED)ED Colored by Color Scripter cs

Running this R code, we can get the following results which show that calculation of key rate durations is proper when we use 1bp as the size of shift. Of course, it depends on which problem is investigated.

### Concluding Remarks

In this post we implemented the key rate durations which is invented by Ho (1992). This can be used in the case of the non-parallel shifts of yield curve and has broad application: replicating portfolio of option embedded bonds, managing fixed-income portfolio, analyzing complex interest rate contingent claims, and so on.

### Reference

Ho, T.S.Y. (1992), “Key Rate Durations: Measures of Interest Rate Risks,” The Journal of Fixed Income 2-2, pp.29-44. $$\blacksquare$$


text:
Jan Stary

# Jan Stary: Coherent ultrafilters

Tuesday, January 12, 2016 17:15

Room: D1-215

Speaker:
Jan Stary

Title: Coherent ultrafilters

Abstract. The notion of a P-ultrafilter on $$\omega$$can be stranghtened in a natural way to the notion of a coherent P-ultrafilter on a complete ccc Boolean algebra. These ultrafilters exist generically under the condition isolated by Ketonen, namely $$\mathfrak c = d$$. Similarly, under the Canjar condition $${\mathfrak c }= cov(Meager)$$, coherently Ramsey ultrafilters can be shown to exist. Existence of "coherent" versions of other traditional objects is an ongoing programme. The coherent ultrafilters are relevant in an old topological question: a coherent P-ultrafilter on an algebra B is an untouchable point in the Stone space of B, witnessing its non homogeneity.


text:
ON GENERALIZED JORDAN LEFT DERIVATIONS IN RINGS

Title & Authors
ON GENERALIZED JORDAN LEFT DERIVATIONS IN RINGS

Abstract
In this paper, we introduce the notion of generalized left derivation on a ring R and prow that every generalized Jordan left derivation on a 2-torsion free primp ring is a generalized left derivation on R. Some related results are also obtained.
Keywords
prime rings;generalized left derivation;generalized Jordan left derivation;
Language
English
Cited by
1.
LEFT JORDAN DERIVATIONS ON BANACH ALGEBRAS AND RELATED MAPPINGS,;;

대한수학회보, 2010. vol.47. 1, pp.151-157
1.
On generalized left derivations in rings and Banach algebras, Aequationes mathematicae, 2011, 81, 3, 209
2.
LEFT JORDAN DERIVATIONS ON BANACH ALGEBRAS AND RELATED MAPPINGS, Bulletin of the Korean Mathematical Society, 2010, 47, 1, 151
3.
On Lie Ideals and Generalized Jordan Left Derivations of Prime Rings, Ukrainian Mathematical Journal, 2014, 65, 8, 1247
4.
Generalized Jordan left derivations on semiprime algebras, Monatshefte für Mathematik, 2010, 161, 1, 77
5.
Generalized Jordan left derivations in rings with involution, Demonstratio Mathematica, 2012, 45, 4
6.
Generalized left derivations acting as homomorphisms and anti-homomorphisms on Lie ideal of rings, Journal of the Egyptian Mathematical Society, 2014, 22, 3, 327
7.
Left Derivations Characterized by Acting on Multilinear Polynomials, Communications in Algebra, 2011, 39, 6, 1979
8.
Additive mappings satisfying algebraic conditions in rings, Rendiconti del Circolo Matematico di Palermo (1952 -), 2014, 63, 2, 211
9.
Some Theorems for Sigma Prime Rings with Differential Identities on Sigma Ideals, ISRN Algebra, 2013, 2013, 1
10.
CHARACTERIZATIONS OF REAL HYPERSURFACES OF TYPE A IN A COMPLEX SPACE FORM, Bulletin of the Korean Mathematical Society, 2010, 47, 1, 1
References
1.
M. Ashraf, On left $({\theta},{\phi})$-derivations of prime rings, Arch. Math. (Brno) 41 (2005), no. 2, 157-166

2.
M. Ashraf, A. Ali, and S. Ali, On Lie ideals and generalized $({\theta},{\phi})$-derivations in prime rings, Comm. Algebra 32 (2004), no. 8, 2977-2985

3.
M. Ashraf and N. Rehman, On Jordan generalized derivations in rings, Math. J. Okayama Univ. 42 (2000), 7-9

4.
M. Ashraf and N. Rehman, On Lie ideals and Jordan left derivations of prime rings, Arch. Math. (Brno) 36 (2000), no. 3, 201-206

5.
M. Ashraf, N. Rehman, and S. Ali, On Jordan left derivations of Lie ideals in prime rings, Southeast Asian Bull. Math. 25 (2001), no. 3, 379-382

6.
M. Ashraf, N. Rehman, and S. Ali, On Lie ideals and Jordan generalized derivations of prime rings, Indian J. Pure Appl. Math. 34 (2003), no. 2, 291-294

7.
M. Bresar and J. Vukman, On left derivations and related mappings, Proc. Amer. Math. Soc. 110 (1990), no. 1, 7-16

8.
W. Cortes and C. Haetinger, On Jordan generalized higher derivations in rings, Turkish J. Math. 29 (2005), no. 1, 1-10

9.
Q. Deng, On Jordan left derivations, Math. J. Okayama Univ. 34 (1992), 145-147

10.
I. N. Herstein, Jordan derivations of prime rings, Proc. Amer. Math. Soc. 8 (1957), 1104-1110

11.
I. N. Herstein, Topics in Ring Theory, Univ. of Chicago Press, Chicago, 1969

12.
B. Hvala, Generalized derivations in rings, Comm. Algebra 26 (1998), no. 4, 1147-1166

13.
W. Jing and S. Lu, Generalized Jordan derivations on prime rings and standard operator algebras, Taiwanese J. Math. 7 (2003), no. 4, 605-613

14.
K. W. Jun and B. D. Kim, A note on Jordan left derivations, Bull. Korean Math. Soc. 33 (1996), no. 2, 221-228

15.
Y. S. Jung, Generalized Jordan triple higher derivations on prime rings, Indian J. Pure Appl. Math. 36 (2005), no. 9, 513-524

16.
E. C. Posner, Derivations in prime rings, Proc. Amer. Math. Soc. 8 (1957), 1093-1100

17.
J. Vukman, Jordan left derivations on semiprime rings, Math. J. Okayama Univ. 39 (1997), 1-6

18.
S. M. A. Zaidi, M. Ashraf, and S. Ali, On Jordan ideals and left $({\theta},{\theta})$-derivations in prime rings, Int. J. Math. Math. Sci. 2004 (2004), no. 37-40, 1957-1964

19.
B. Zalar, On centralizers of semiprime rings, Comment. Math. Univ. Carolin. 32 (1991), no. 4, 609-614


text:
# [Grammar]choose

Status
Not open for further replies.

##### Member
.I.......... three letters this afternoon.

wrote____ have written____ have been writing

I would choose' wrote' because the action is finished

#### emsr2d2

##### Moderator
Staff member
.I.......... three letters this afternoon.

wrote____ have written____ have been writing

I would choose' wrote' because the action is finished

I would say that, depending on context, all three are possible. If you have been told specifically that the action is finished, then "wrote" would be my first choice too, but "have written" would also be OK.

Status
Not open for further replies.


text:
## Related Articles

• CBSE Class 12 Syllabus
• CBSE Class 12 Maths Notes
• CBSE Class 12 Physics Notes
• CBSE Class 12 Chemistry Notes
• CBSE Class 12 Accountancy Notes
• CBSE Class 12 Computer Science (Self-Paced Course)

# Evaluating Definite Integrals

• Last Updated : 20 May, 2021

Integration, as the name suggests is used to integrate something. In mathematics, integration is the method used to integrate functions. The other word for integration can be summation as it is used, to sum up, the entire function or in a graphical way, used to find the area under the curve function. Integration is known to be the opposite of differentiation which is the process of breaking down a function into smaller functions whereas integration is summing the smaller bits to obtain the entire area under the curve.

### Definite Integrals

There are two ways of integration possible- definite integration and indefinite integration. Definite integration is done for the area given with limits or boundaries, that is, the curve is finite and hence, the area under the curve shall also be finite whereas indefinite integration is used for the function having no upper or lower limits, the functions are infinite in nature and therefore, the upper and lower limits for indefinite functions are +∞ and -∞.

Definite integrals of a function f(x) from a to b when the function f is continuous in the closed interval [a, b].

Where, a and b are the lower and upper limits.

F(x) is the integral of f(x), and if f(x) is differentiated, F(x) is obtained. Hence, it can be said F is the anti-derivative of f. Definite integrals are also known as Riemann Integrals.

### Evaluation of Definite Integrals — Properties

In Mathematics, simple summation and addition are easy but when it comes to evaluating complex integrals, simple calculations and additions are not enough, therefore, Integration is required. While evaluating definite integrals, sometimes calculations become too cumbersome and complex, so some empirically proven properties are made in order to make the calculations comparatively easy.

Property 1:

This property can be proved by simply substituting the value of “t” in place of “x”.

Property 2:

Proof: Let F(x) be anti-derivative of the integral

So, we know

Comparing these two equations, we can deduce that

Hence, Proved.

Property 3:

Proof:

Adding the above two equations will give us the first equation,

Property 4:

Proof: Let’s assume t = a + b -x. Then dt = -dx, When x = a, t = b and wh

en x = b, t = a.

Therefore,

Property 5:

Proof: This property is a particular case property 4, so it can also be proved that way.

Property 6:

Proof: Using Property 3, we can write this as,

Let t = 2a  x in the second integral on the right-hand side. Then dt = – dx. When x = a, t = a and when x = 2a, t = 0. Also, x = 2a – t. Therefore, the second integral becomes

Hence, \

Property 7:

Proof: Using property 6, we have

Now, if f(2a – x) = f(x) then this equation becomes,

And if f(2a – x) = – f (x), then that equation becomes

Property 8:  if it’s an even function, i.e, if f(-x) = f(x).

Property 9: , if it’s an odd function, i.e f(-x) = -f(x).

Proof: Using Property 3, we have,

Let t = – x in the first integral on the right-hand side.

dt = – dx. When x = – a, t = a and when x = 0, t = 0. Also, x = – t.

So, we can rewrite the above expression as,

1. Now, if f is an even function i.e f(-x) = f(x),

2. If f is an odd function i.e f (–x) = – f(x).

### Sample Problems

Question 1: Evaluate,

Solution:

Integrating,

Question 2: Evaluate,

Solution:

Integrating the above given function,

Question 3: Evaluate,

Solution:

Integrating the function,

Question 4: Given, . Find the value of  .

Solution:

For solving this question, we will be using Property 3.

Now, we just have to plug in the value of the given definite integrals.

Question 5: Given f(x) = x3. Find the value of .

Solution:

Now this answer can be calculated through usual integration method, it is fairly easy. But we can think of a property which can be used here to completely save your calculation and time.

Property 8 and Property 9 can be used depending upon which kind of function f(x) = x3 is, even or odd. Let’s check whether f(x) is even or odd.

For an even function, f(-x) = f(x) and for an odd function f(-x) = -f(x).

Here in our case, f(-x) = (-x)3 = -x3 = -f(x). So it is an odd function.

Thus, Property 9 is applicable here, and through property 9 we can say that.

Question 6: Given, . Find the value of

Solution:

This question is similar to what we solved a little while ago, It also requires application of Property 3. But we need to do something about

This problem can be solved by the application of Property 2.

Using property 2,

So, now plugging the values,

Question 7: Evaluate,

Solution:

In previous questions we checked for an even or odd function. By a similar check, we can say that sin2x is an even function.

So by the use property 8, we can rewrite it as,

Question 8: Evaluate,

Solution:

This expression contains two terms. We know,

Sin(x) is an odd function and x4 is an even function.

So,

My Personal Notes arrow_drop_up


text:
Step by step instructions to phase with Eagle?
2
2
Entering edit mode
5.8 years ago
moxu ▴ 500

It’s a little bit convoluted.

I just want to impute SNPs in 23andme format like the following:

# rsid chromosome position genotype
rs3094315  1 752566 AA
rs12562034 1 768448 AA
rs3934834  1 1005806  CC
rs9442372  1 1018704  GG
rs3737728  1 1021415  GG
rs11260588 1 1021658  GG
rs6687776  1 1030565  CT

I was told Minimac3 is the best tool to impute for 1 sample at a time (I am not looking to impute multiple samples at one time, but 1 sample by 1 sample for some reason). Minimac3 is easy to use and fast, and I made it work. However, it requires phased input file, so I need to phase the file described above.

Eagle from Broad Institute was recommended to do phasing, and it seems that eagle only takes a genomic profile in .VCF format, so I converted the above file into .VCF as the following:

##fileformat=VCFv4.2
##filedate=Fri Aug 26 23:11:37 EDT 2016
##source=csv2vcf.pl
##reference=
##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">
#CHROM POS ID REF ALT QUAL FILTER INFO  FORMAT  GENOTYPE
1 752566 rs3094315  G A . . .  GT 1/1
1 768448 rs12562034 G A . . .  GT 1/1
1 1005806  rs3934834  C T . .  .  GT 0/0
1 1018704  rs9442372  A G . .  .  GT 1/1
1 1021415  rs3737728  A G . .  .  GT 1/1
1 1021658  rs11260588 G A . .  .  GT 0/0

and named it “myprofile.vcf”. Then I ran eagle using the following:

eagle --vcf myprofile.vcf  --geneticMapFile Eagle/tables/genetic_map_hg19_withX.txt.gz --outPrefix /tmp/myprofile.beagleImputed

“Eagle/tables/genetic_map_hg19_withX.txt.gz” was provided by eagle.

It didn’t go through. The error I got was:

[W::vcf_parse] contig '1' is not defined in the header. (Quick workaround: index the file with tabix.)
ERROR: Multi-allelic site found (i.e., ALT contains multiple alleles)
Either drop or split (bcftools norm -m) multi-allelic variants

Not sure what it exactly means. “index the file with tabix”, index which file? It cannot be the “genetic_map_hg19_withX.txt.gz” file right? So I tried to “tabix myprofile.vcf”, then I got the following error:

Not a BGZF file: data/genome_3j.vcf
tbx_index_build failed: data/genome_3j.vcf

Up to this point, I think the error is reckless. Probably I’ve done something terribly wrong.

I just want to impute some SNPs in this very popular and easy format, can’t someone write a program to just take such a file as input and a couple of options to point to needed reference SNP database and/or genome sequences? Actually, someone has already done that – Michigan Imputation Server, but you need to register an account, upload your data to their server, and download results there. This is awesome and the way to go in terms of the simplicity to use, but you cannot pipeline in the server.

The “manuals” or “READMEs” or “instructions” are not good enough for me.

Thanks for any instructions.

snp genome software error • 4.8k views
0
Entering edit mode
5.8 years ago

You need to bgzip your VCF file and then index it using tabix.

bgzip myprofile.vcf
tabix myprofile.vcf.gz

##contig=<ID=1,length=249250621>
##contig=<ID=2,length=243199373>
...
...
...

Regarding multi alleles, as said, either remove them ( using vcftools etc ) or split them using bcftools. This should be done before you index your VCF.

0
Entering edit mode

Great! After doing the bgzip on the .vcf, it went much further. I ran

eagle --vcf myprofile.vcf.gz  --geneticMapFile genetic_map_hg19_withX.txt.gz --outPrefix /tmp/t --chrom 21

and got the following error:

Phasing samples 1-1
WARNING: Sample 1 (1-indexed) has a het count of 0
ERROR: Failed to allocate 18446744073709551596 bytes

Not sure why eagle requires this much -- I guess -- memory.

It didn't complain about multi alleles this time, although I have not taken care of the multi allele problem yet because I don't know how. Could you please give me the bcftools command line to run the splitting? I don't see a split command/option or something that might be related.

Thanks much!

0
Entering edit mode

This may have been answered, but may I please check if there's a solution to the memory issue? I am having the same problem whilst trying to run Eagle2. Thanks so much.

0
Entering edit mode

Dear I am also facing the exact same error. May I know how you fixed this issue.

0
Entering edit mode

Did anyone figure out a solution to this error? ERROR: Failed to allocate 18446744073709551596 bytes

I keep getting it and I can't find an answer anywhere online.

0
Entering edit mode

I have the same problem, did anybody find a solution?

0
Entering edit mode

sorry, I found the problem!

0
Entering edit mode
3.8 years ago

Any solution/suggestion to the memory problem? Thanks.


text:
# Synopsis: Free falling

An optical cavity can track the trajectory of atoms with submicron resolution.

The technology for studying the interaction of an atom with a high-finesse optical cavity has reached such a high level of sensitivity that detecting quantum fields from a single photon and a single atom has become reasonably routine.

The same system can, in principle, track an atom’s trajectory: As the atom traverses the cavity, it disturbs the allowed optical modes in the cavity in a way that can be detected. So far, however, attempts to do this weren’t able to narrow down the atom’s path with high resolution.

Now, researchers in China have proposed and demonstrated a method to unambiguously determine the trajectory of an atom using a high-finesse cavity. In a Rapid Communication appearing in Physical Review A, Pengfei Zhang and colleagues at Shanxi University, China, describe experiments where they tracked an atom’s path with a spatial resolution of $100$ nanometers and in a measurement time of $10$ microseconds.

The group releases a small sample of laser-cooled atoms from a trap located several millimeters above the center of the cavity. They then detect the strong coupling between the falling atoms and a tilted cavity mode—a mode that breaks the spatial symmetry and is therefore sensitive to the details of an atom’s path.

Zhang et al. are also able to extract an independent measurement of the atom cloud’s temperature by averaging over many single-atom measurements. Their technique could ultimately be applied to optomechanical cooling and time-resolved single atom-cavity microscopy. – Frank Narducci

### Announcements

More Announcements »

## Subject Areas

Atomic and Molecular Physics

## Previous Synopsis

Quantum Information

## Next Synopsis

Interdisciplinary Physics

## Related Articles

Atomic and Molecular Physics

### Viewpoint: Casting New Light on Atomic Interactions

Optical pulses—tuned to a magic wavelength—provide both spatial and temporal control over the interactions between atoms in an ultracold gas. Read More »

Atomic and Molecular Physics

### Synopsis: Gyroscopic Molecules

Fast-rotating molecules spun up by a laser pulse maintain their alignment despite collisions. Read More »

Atomic and Molecular Physics

### Synopsis: Atoms in a Photonic Trap Exhibit Superradiance

Trapping atoms near a photonic crystal waveguide produces strong atom-photon coupling that results in enhanced atomic emission of light. Read More »