Lithium – Day 13

by Martin on December 7, 2011

Short update on the lithium…

Today I doubled my dose from 300 mg to 600 mg (12 mmol Li+). After two weeks at 300 mg, I can’t really say, that I have felt anything. My mood was good for the first week, and I thought, that I might be starting to feel an effect. However, these last three nights, I have sleept about 6 hours in total – one night I did not sleep at all. This is despite the fact that I took 25 mg of Seroquel before going to bed. I does not seem to have any significant effect on me, apart from making me a little bit groggy in the morning. I’ve thought about upping the dosage to 50 mg before bedtime, but given quetiapine’s half-life of 6 hours, I will probably feel a lot more groggy in the morning – who knows, maybe it’s worthwhile, assuming I get some sleep.

To summarize, no discernible effect of lithium as of yet. Hopefully, I will feel the famous “letterbox” in the coming weeks.

The letterbox refers to a description given by Richard Dreyfuss in Stephen Fry‘s decent BBC documentary The Secret Life of the Manic Depressive:

With Lithium, I remember driving down Mulholland Drive one night, when all of a sudden, I was aware, that I had letterbox. And it was an absolutely non-claustrophobic experience, that took the top and bottom off, and said “You can live here.”. And I was very happy to do so. I married with it, had children by it, reclaimed a career, if you want to put it that way.

(This quote is from memory, but it is fairly accurate, I believe.)

Stay sleepy!

{ 0 comments }

Lithium – Day 1

by Martin on November 24, 2011

Remember my last post about feeling well? Yeah, well, it turns out that I was feeling well, because I was going through hypomania (leading up to full-blown mania). Needless to say, that really sucks. I am home from work today, as I am recovering from risperidone withdrawal symptoms. (I was given risperidone as an acute mania treatment – horrible drug for me!)

So… I decided, that I want to give lithium a try. As you may recall from an earlier post, this was the medication, I was initially suggested to take. At that time I convinced my psychiatrist to try the milder lamotrigine first, and while it has managed my depressive symptoms very well, it has failed to rectify the highs. Yesterday, I went to see my (new) psychiatrist about it, and we decided to give lithium a shot. I will keep taking my lamotrigine as well, but, if at all possible, I would like to remove that in the future. I like to keep my medication simple, so that I know what works and what doesn’t.

After our little “chat”, I drove to a nearby pharmacy to pick up these lithium citrate pills:

Apart from the fact that taking a new medication is a big step, at least for me, the container smelled REALLY bad. Think of stuff you paint the bottom your boat with. Luckily, though, once I took one of the pills out of the container it was pretty much odor-free. Probably some kind of interaction of the lithium with the oxygen or nitrogen in the container.

Anyway, today I took my first 300mg dose (6 mmol) of lithium. I don’t really know, what to expect from this low dose, these first few weeks, but I am hoping that it will begin to slow me down to the point, where I no longer think so fast, that my thoughts turn into a whirlpool, that is pretty hard to make out. I’ve been given a fairly conservative titration schedule, in which, I take 300mg for two weeks, then 600mg for one week, before my first screening blood tests. Lithium is very toxic, if the blood level becomes too high, so I have to have regular blood tests as long as I take lithium. Small price to pay, if it works!

So I will keep writing a bit about my experiences with lithium. Probably not every day, but whenever something changes. Wish me luck!

{ 2 comments }

Poul Glargaards gyserhistorier [danish]

by Martin on October 18, 2011

Poul Glargaard er død. De fleste husker ham nok bedst fra mindre roller på film og tv, men nogle af os husker bestemt også hans fantastiske gyserbånd, der skræmte livet af os, da vi var børn!

Derfor disse mp3-versioner af de kassettebånd, der aldrig kom med på CD’en Gys med Poul Glargaard:

  • Det mystiske spejl [mp3, 26MB]
  • Dracula [mp3, 16MB]
  • Gravkammerets hemmelighed [mp3, 24MB]
  • Mænd af sten [mp3, 12MB]
  • Vampyrjagten [mp3, 8MB]

Det kan godt være, at I lige selv skal høre dem igennem, inden I giver dem videre til jeres børn. :-)

UPDATE: Her er en pakket fil med alle historierne.

UPDATE 2: Efter anmodning fra familien, har jeg fjernet historierne. Det skal naturligvis respekteres.

{ 13 comments }

Bipolar update

by Martin on October 17, 2011

Hi guys. It’s been a while, since I last posted anything about my bipolar disorder.

As you may remember, I have been slowly increasing my lamotrigine dose to 200 mg/day. I have been at that dose for about three months, and, I am happy to say, that things are going great! And not in any manic way! ;-)

The lamotrigine seems to be doing its job, and I have felt stable and relaxed for the last two months or so. I still have lots of ideas and trouble sleeping, but it does not seem to get out of hand. When I work hard on one of my small projects, it is because I find it interesting, and not just some frantic, feverish I-need-to-be-productive mess of simultaneous tasks and ideas.

It’s been a long time since I found myself to be (extremely) irritable for no reason.

I do have one (small?) side-effect, though: My short-term memory sucks! I have never been very good at remembering appointments, what I did a few days ago, etc., but that has definitely gotten even worse! Luckily, I am still able to remember stuff, that is interesting to me, allowing me to stay focused at work, for instance. All in all, it’s a trade-off, that I am very happy about.

{ 0 comments }

Thought I would post a piece of code, that I was unable to find any examples of online.

Suppose you want to traverse a tree, that can possibly be quite deep. In that situation, you often want to create a custom stack, that you can scale as needed, rather than use the system call stack. Such iterative algorithms are easy to find code examples for around the internet. Preorder traversal is very simple, postorder traversal less so.

However, if you are in a situation, where you need to do both preorder and postorder. What then?

Of course, you can just do both, but it turns out, that it is fairly easy to adapt the postorder traversal to do preorder as well:

void combined_iterative_traversal(node_t *node)
{
  my_stack_t  *stack;
  node_t      *prev;

  // Create stack.
  stack = stack_create();

  // Initialize previous node.
  prev = node;

  // Push root node.
  stack_push(stack, node);

  // Do preorder stuff with root node.
  preorder(node);

  // Push left or right node, if any.
  if      (node->left)  stack_push(stack, node->left);
  else if (node->right) stack_push(stack, node->right);

  // While elements left in stack.
  while (stack->count > 0) {

    // Get node from top of stack.
    node = stack_top(stack);

    // Are we moving down the tree?
    if (prev->left == node || prev->right == node) {

      // Yes. Do preorder stuff with node.
      preorder(node);

      // Push left or right node, if any.
      if      (node->left)  stack_push(stack, node->left);
      else if (node->right) stack_push(stack, node->right);

    } else if (node->left == prev) {

      // No. We are moving up from the left. Push right subtree, if any.
      if (node->right) stack_push(stack, node->right);

    } else {

      // No. We are either moving up from the right or at a leaf node.
      // Do postorder stuff.
      postorder(node);

      // Pop node.
      stack_pop(stack);
    }

    // Update previous node.
    prev = node;
  }
}

The above algorithm has been complicated slightly, to get rid of a special case within the loop. In particular, I have “peeled” the handling of the root node from the while loop. Whether this is worthwhile, compared to the slightly prettier algorithm, depends on your application, I guess.

{ 0 comments }

Ok, I am a lazy bastard…

I have never really spent the time to create myself a good, simple gcc Makefile template. I always end up hacking something together at the last minute. So… yesterday I took some time to do a simple, reusable, cross-platform Makefile to be used with my small C projects:

# Executable, object names and library/linker flags
EXECUTABLE  = program
OBJECTS     = program.o other.o stuff.o

# Common compiler and linker flags
CFLAGS  = -Wall -Werror -m64
LDFLAGS = -lpthread

# OS-specific stuff
OS = $(shell uname -s)
ifeq ($(OS), Darwin)
	STRIP_OPTIONS = -u -r -arch all
endif
ifeq ($(OS), Linux)
	STRIP_OPTIONS = -s
endif

# release/all: Set additional flags, build and strip executable
all: CFLAGS += -O3 -fomit-frame-pointer -funroll-loops
all: $(EXECUTABLE)
	strip $(EXECUTABLE) $(STRIP_OPTIONS)

# debug: Set additional flags and build executable
debug: CFLAGS += -O0 -g -DGX_DEBUG
debug: $(EXECUTABLE)

# clean: Remove executable and object files (rarely needs to be changed)
clean:
	rm -f $(EXECUTABLE) $(OBJECTS)

# Complete compiler string
CC = gcc $(CFLAGS)

# Link objects into executable (rarely needs to be changed)
$(EXECUTABLE): $(OBJECTS)
	$(CC) -o $@ $^ $(LDFLAGS)

# Compile all files to objects (rarely needs to be changed)
%.o: %.c
	$(CC) -c $<

This will allow you to use “make” to do a release build, “make debug” to build a debug build, and finally “make clean” to remove all produced files. Suggestions are welcome!

{ 6 comments }

Unrolled binary search

by Martin on September 12, 2011

Thought I would share another little code gem. This one is really cool. :-)

Suppose you have a sorted array of integers, and you want to find the index of a particular element, if it’s in there, or the closest match.

The naïve way of doing it is by linear search, which may be the fastest thing for very small arrays (less than 10 elements). For larger arrays you are much better off using binary search. To those of you, who are unfamiliar with binary search methods, the idea is very simple.

Compare your needle (number you are looking for) to the central element of the haystack (the array you are searching). If the needle is smaller than the central element, you continue your search by repeating the procedure on the left part of the array (and vice versa).

This allows you to find the element you are looking for in O(log n) time, meaning that for n elements, you only need to do about log n comparisons, eg. if n is 1024, you only need to do 10 comparisons. This is of course much better than doing a simple, linear search, which, for random array and needle, would need 512 comparisons on average!

What I want to show you is a very elegant way of doing a binary search of an array of fixed size – in this case 256 integers.

int unrolled_binary_search(int *haystack, int needle)
{
  int i = 0;

  if (haystack[    128] <= needle) i += 128;
  if (haystack[i +  64] <= needle) i +=  64;
  if (haystack[i +  32] <= needle) i +=  32;
  if (haystack[i +  16] <= needle) i +=  16;
  if (haystack[i +   8] <= needle) i +=   8;
  if (haystack[i +   4] <= needle) i +=   4;
  if (haystack[i +   2] <= needle) i +=   2;
  if (haystack[i +   1] <= needle) i +=   1;

  return i;
}

This little piece of code is not only beautiful. It is also very, very fast. Instead of having a loop, such as a “for” statement, we have unrolled the loop, which eliminates some CPU instructions when it… comes out the other end. There are a few other optimizations, that can be done, but that would spoil the simplicity of the code. Enjoy.

{ 0 comments }

Ternary quicksort

by Martin on September 12, 2011

As a follow-up to my last post, I thought, I would provide you with an unsigned version of the same algorithm. The last algorithm, that I provided you with, will underflow, if you plug in unsigned variables.

Here is a more robust version.

void ternary_quicksort(unsigned int *a, unsigned int begin, unsigned int end)
{
  unsigned int i, j, k, p, x;

  if (begin < end) {

    i = j = begin;
    k = end;

    // Calculate median pivot
    p = median(a[i], a[k], a[(i + k) >> 1]);

    // Partition
    do {
      if      (a[j] < p) swap(a, i++, j++);
      else if (a[j] > p) swap(a, j, --k);
      else j++;
    } while (j < k);

    // Recurse
    ternary_quicksort(a, begin, i);
    ternary_quicksort(a, k, end);
  }
}

Note, that I have changed “end” to mean, not the last element, but the first element not in the array. This is more compatible with other range specifications and leads to less confusing code.

{ 0 comments }

Fast ternary quicksort code in C

by Martin on September 6, 2011

Hi guys, it’s code sharing time!

This weekend, I started a new pet project. I produced a lot of code, and thought I would share a tiny bit, that turned out surprisingly fast, clean and simple.

The code is a ternary, or three-way, quicksort. It is an extension of Hoare’s original quicksort, that is both faster and more useful, i.e. we have a win-win situation on our hands.

In the original quicksort algorithm, you sort a set by going through the following three steps:

  1. Pick a pivot value from the set. This can be done in several ways.
  2. Partition the set into two subsets – one containing elements smaller and one containing elements larger than the pivot.
  3. Recurse on these two smaller subsets, i.e. invoke this function successively on the two subsets.

A ternary quicksort splits each set into three subsets instead – one smaller, one larger and one with values equal to the pivot. Sounds like more work, right? Wrong!

Let us sum up the algorithm to compare it with the standard quicksort:

  1. Pick a pivot value from the set.
  2. Partition the set into the three subsets.
  3. Recurse on the smaller and the larger one.

At this point, you can begin to see the performance benefit. We are no longer recursing over two half sets (excluding the pivot). Instead, we fix the elements that equal the pivot in the center. This way, we avoid shuffling these “equal” elements around in subsequent calls/rounds. Another benefit is, that should be apparent from the code below is, that we keep track of the middle part as well, which is quite useful if you are doing string (or similar multikey) sorting – maybe I will write more on this in a later post.

Here is the code:

void ternary_quicksort(int *a, int begin, int end)
{
  int i, j, k, p;

  if (begin < end) {

    i = begin;
    k = end;

    // Calculate median pivot
    p = median(a[i], a[k], a[(i + k) >> 1]);

    // Partition
    j = i;
    while (j <= k) {
      if      (a[j] < p) swap(a, i++, j++);
      else if (a[j] > p) swap(a, j, k--);
      else j++;
    }

    // Recurse
    ternary_quicksort(a, begin, i - 1);
    ternary_quicksort(a, k + 1, end);
  }
}

Note, that we are using the median of the first, last and central element as our pivot. The median is simply the element, that has the “middle value” of the set, eg. median(3, 7, 2) = median(2, 3, 7) = 3.

inline int median(int vi, int vj, int vk)
{
  if (vi <= vj) {
    if (vj <= vk) return vj;
    else if (vi <= vk) return vk;
    else return vi;
  } else {
    if (vi <= vk) return vi;
    else if (vk <= vj) return vj;
    else return vk;
  }
}

The swap method is just a trivial swap of the elements in the array:

inline void swap(int *a, int i, int j)
{
  register int k;
  register int l;

  k     = a[i];
  l     = a[j];
  a[i]  = l;
  a[j]  = k;
}

Here be dragons! Note, that this is not a classic implementation of the algorithm. I have done away with the pivot element, as the only thing, we really need, is a pivot value to group around. Hopefully, it still works. :-)

{ 0 comments }

Ok, this has REALLY been bugging me – and I mean big time!

I really like OS X Lion, but one utterly ridiculous bug is this: Key repeat does not work even though it is enabled in System Preferences!

Apparently, this has something to do with a new feature called “Press and hold”. Here is a quick fix:

defaults write -g ApplePressAndHoldEnabled -bool false

Have a much nicer day! ;-)

UPDATE:

This may have something to do with my editor, TextMate, as I hear that others do not experience this problem.

{ 0 comments }