C++ is a hack

Posted in code with tags , , , , , on September 12, 2010 by maxpower3141

If you are reading this, you probably knew it already.

Basically C++ is just a set of semi-clever preprocessor hacks on top of C – I seem to remember that actually the first C++ compilers were just an extra preprocessing pass on top of a C-compiler!

In themselves, hacks are not evil, but they do normally always cause some undesired side-effects that limits usability. In this case as C++ is basically just a hack on top of C, it means that it actually works by doing a lot of odd name-mangling in the preprocessing steps in order to get the names correct and here in lies the problem.

I recently began using thrust and with it some template programming on C++ and while thrust is great, C++ itself is not so much.

Firstly the template syntax is kind of awkward, but that’s not so much of an issue – the issue is the following:

Using function-objects (types that just overload the “function-call”-operator ()), I can abstract my CUDA-algorithms, by making them template-based on the different function-object types.

For example the SAXPY-call using thrust (this computes result = a X + Y, for vectors X,Y and scalar a) is as I had earlier written:

struct saxpy_functor
{
const float a;

saxpy_functor(float _a) : a(_a) {}

__host__ __device__
float operator()(const float& x, const float& y) const {
return a * x + y;
}
};

void saxpy_fast(float A, thrust::device_vector& X, thrust::device_vector& Y)
{
// Y <- A * X + Y
thrust::transform(X.begin(), X.end(), Y.begin(), Y.begin(), saxpy_functor(A));
}

This is ok, but I have started to like the idea of keeping the code close to where it is executed (guess I’m getting old or something) so I though that I would like to create a small macro that creates me a transformation-functor type on the fly so I could actually semi-transparently embed CUDA-code with my host code! That Would just rock! Something like:


void saxpy_fast(float A, thrust::device_vector& X, thrust::device_vector& Y)
{
struct saxpy_functor
{
const float a;
saxpy_functor(float _a) : a(_a) {}
__host__ __device__
float operator()(const float& x, const float& y) const {
return a * x + y;
}
};
// Y <- A * X + Y
thrust::transform(X.begin(), X.end(), Y.begin(), Y.begin(), saxpy_functor(A));
}

and hopefully wrap the silly stuff inside some macro to get:


{
DEFINE_XFORM_CALL(saxpy, data, input1, input2)
{
return data.a * x + y;
};
CALL_XFORM(saxpy, data, in1, in2);
}

Sweet no? Local types are supported by C++, except not in template parameters! And this causes:

“error: a template argument may not reference a local type” – compilation error!

Nice – what’s the freaking problem now? Can’t deduce the name of the type? Oh dear… SW sucks.

There has been a proposition to fix this in the standard itself, but of course this will never be fixed there – I guess MS supports this as compiler extension, but NVCC does not – I’ll request this feature and hope that NVIDIA listens – they do need all the user-friendliness they can get and this would be really friendly for me!

I’ll keep you posted if I ever hear from my request again πŸ™‚ (not filed yet, sorry – TBD tomorrow)

Also I really think it is starting to be high time to switch to D Programming Language – as soon as NVCC supports it, I’m there!

Here’s a sneak-peek for a reduction:

import std.algorithm, std.range, std.stdio;

int main()
{
int[] a1 = [0,1,2,3,4,5,6,7,8,9];
int[] a2 = [6,7,8,9];
int sentinel = 5;

int mysum(int a, int b) {
if (b <= sentinel) // access outside variable
return a + b;
else
return a;
}

auto result = reduce!(mysum)( chain(a1, a2) ); // pass in a delegate (closure)
writeln("Result: ", result);

return 0;
}

Kristofer Columbus in Barcelona pointing

Linux Sucks!

Posted in code with tags , , , on September 12, 2010 by maxpower3141

Just trying to get a snappy title.

A short post, no rant, about some Linux silliness I run into constantly. Recently I ranted about Eclipse.

Now a couple of observations with KDE4 – the Vista of Linux. πŸ™‚

a) When I have another user logged on, I’m logged on to my account and I want to let the other user use his session for some reason clicking “switch user” on the launcher, it doesn’t display at all the existing sessions – how convenient is that? I have to lock screen and then select switch user to do it – end result: 2-4 sessions open by each user – go KDE4!

b) When another user-session is going on, it is actively hogging computer resources! Like 20% of one CPU – hello? The worst offender is the plasma-desktop so my question is, why on earth aren’t the processes sleeping?? I could forgive something like firefox offending this, but plasma is a system service! Surely the system knows nobody’s using it!

These two are quite minor rants, but running into this kind of silly problems all the time seems depressing – I mean, it’s 2010? Shouldn’t the sw start working some day soon? πŸ™‚

Zoom to Alligator

It’s not your program!

Posted in politics with tags , , , on September 12, 2010 by maxpower3141

I’ve been busy lately – all work and no posts make Max a dull boy.

Oh well, anyways I just bumped into this case on one of my favorite websites; To put the story short for you the idea is that a guy was selling autodesk CAD (tm, C, R whatnot) sw he found in some garage-sale of a bankrupt company on ebay (or something equivalent). The sw had never been used and autodesk sued the guy for “selling something that wasn’t his”.

So, what’s going on here? Once you buy something shouldn’t you be able to resell it always? Especially if you didn’t use the product yourself? For example if you buy a cd with music you can sell it later, provided you didn’t make copies of it for yourself. Is there a difference here? Well, the SW company will say that you did not buy the product, but merely a license to use it – therefore they could have a different price for those who want to license over to those who want to resell it – retail anyone? Makes sense?

How about concert tickets? You buy a “license” to listen to the musical performance once, but you are always allowed to sell this license to somebody else in case you can’t make it. On the other hand the cheapest levels of airline tickets are such that you must use the ticket yourself – why? I guess any changes to airline tickets cause some costs to airlines (the name, well the identity, of the user is important here, so they have to do something actively if it changes), but on the other hand this should be a minor cost (that could be put on the licensee). On the other hand airliners say that this way they can differentiate themselves on pricing, but again everybody knows that airline ticket-pricing algorithms are just CRAZY, with some tickets actually ending up costing to the airline, where other tickets then compensate the difference – this means that if you are buying your ticket on the last minute you get high price fighting for the last seats of the airplane and end up paying part of the trip of your fellow travelers that did buy their tickets on time – nice no?

So what’s the end-result? Consumer benefit? Uh, maybe not exactly. One of the issues here is that big companies have way too much money compared to their employees and hence big companies should pay more for the same sw (/other stuff as well) than the employees as individual consumers. This is because the companies themselves know this (of course – they are not dumb). The field is littered with examples.

So the verdict you are waiting for? Uh, the thing is that this situation sucks – basically I think that this is a variation of the issue of durable products I touched on my post about why Capitalism Sucks. It is in the best interest of the sw-company to get into a situation where the client has to pay a tax-like small license fee preferably as often as possible and buying this service on discount on ebay constitutes cheating this system. Putting aside utopian fixes to problem of capitalism (and human happiness) I think this problem would be solvable inside a capitalistic system as well – just make the rules clear: if your company sells products as services then make the customer go to your website to get the license – selling this kind of license in a box is equivalent to entrapment and should not be allowed – you sell a box means you give rights to the client to resell the box. I mean, should people really start reading the EULAs? πŸ™‚ Come on.. πŸ™‚

Ok, back to sleep – I leave you with this photo:

Odd CG-scene by me a looong time ago

How to fix politics – ie. save the World

Posted in politics with tags , on August 21, 2010 by maxpower3141

Today a group of armed assailants invaded a luxury hotel in Rio de Janeiro, Braliz.

These are the kind of news that wake us up – why? Because it could affect us; Things like the Monsoon floods of Pakistan do not shock us, as we do not go there. So we shake it off with a “how terrible” – comment.

But things like this attack on our turf really make us think – What’s going on? How did we get here? And how can we fix the situation?

Well, in order to cut the story short, I will summarize the two news-items (and many more) into a single thought: We are screwed and the problem is poverty. Fix poverty and both of the problems above are avoided. Simple, eh? Of course this would solve a host of other problems as well.

Of course fixing poverty is not easy, but I’m afraid it is our only sane way out of a nasty deadlock – we still have some time to fix this, but of course we should keep in mind that the more we wait, the more severe the problems will get. Surely you can see problems caused by both local and worldwide poverty in your neighborhood?

No? And if you really try hard?

Another picture here:

One-fifth scale replica of the Statue of Liberty at Île des Cygnes

Eclipse: Too many files open problem – possible solution!

Posted in code on August 19, 2010 by maxpower3141

In my previous post I did a quick rant on how sucky open-source code is – well – I implied it in the context.

Just today I ran again into the problem (I now have ulimit -n and ulimit -Hn to 19000) so I started going through web trying to find real solution. The loveliest thing about this problem is that it doesn’t allow you to save your changes! So what do you do? Yes – copy the changes to clipboard, close the program open the file(s) in text-editor and apply the recent changes manually (and pray that there isn’t so many of them) – BRRRRRRR!!!! WRONG! In Linux, not even copy-paste works... Of course this most probably is not the fault of the lovely kernel but the problem lies most probably somewhere in the wonderful world of gnus, gnomes and so-forth, but damn.. πŸ™‚ I miss KDE 3.5.9.. πŸ™‚ Or maybe I should just get a mac – Ok, I’m not that desperate yet..

This Eclipse.org forum-post shows the most promise – yet again you get stability by switching to code produced by people who are paid to do it. πŸ™‚ oh well.. πŸ™‚ Let’s see if it works – I plan to code now for a week with Eclipse open and lets see. Oh yes – the proposed solution is to switch from OpenJDK to Sun’s Java implementation – it figures… πŸ™‚

Btw. Have I ever mentioned to you that gnome sucks? It’s unfortunate that so does KDE4 now, but at least they are trying.

I will put a picture of Big Ben I took, in a vague effort to make my blog more graphical – enjoy!

Why Capitalism sucks ?

Posted in politics with tags , , on August 17, 2010 by maxpower3141

Simple question, with some nice bias built into it.

The answer is this: It does not lead to the best products in most product categories. It does work exceptionally well for products that are still being developed and improved, but a lot of the products are not this way.

It fails especially in producing durable products. I remember hearing from a friend, who had been talking to a local retailer in a small town, that they had to stop selling a particular brand of shoes in the store, because the customer wouldn’t come back for a looooong time to buy new shoes after buying a pair of that particular brand.

Therefore capitalism actually favors those kind of products that have shorter lifetime and keep sending the customer back for more. This ultimately leads to products with somewhat sloppy design and a lot of cut corners, that want to impose a certain type of tax for us. Just think about print cartridges – you know, the ink stuff? Ends up costing you tons of money if you print at home! With most computer equipment this is alleviated by the fact that the new computers are faster than the old ones, and therefore it is a smaller risk for computer manufacturers to build something that actually lasts – the optimal solution is one, where the computer usage starts to get more cumbersome and slow after a long time, making you long for that upgrade. Sounds familiar yet?

The thing is, that this list could go on and on, but I guess I have made my point already. So what can we do? Nothing? Well – that’s my first thought, since sadly capitalism is the only system we know that even remotely works. Of course in these sort of problem scenarios, we should step back, look at the big picture, identify path to solution and then go work on the details that one day will lead us there, but unfortunately political sciences – being the worst failed science of all – is somehow utterly incapable of employing this sort of thinking.

I think it might be due to capitalism – it seems very much, that in our modern western society, capitalism has employed politics as one of its tools in self-optimization, not the other way around.
Which is why Capitalism sucks.

About Coulombic Friction models

Posted in code, physics with tags , , on August 16, 2010 by maxpower3141

So I have been lately somewhat involved in modeling Coulombic friction in my (perhaps game-) physics simulations project, as you can see from my post on writing test code and the first O’Caml rant.

Just today I spent some time in augmenting the test-case for the static friction case, and it occurred to me, that you, my loyal reader and supporter, might be interested in what is involved with the math and code when implementing these kind of models, so here we go again:

First of all, let us set the background: We are interested in this case friction between two bodies connected with some kind of constraint – let this constraint be realized by the equation: \phi(x_i) = 0. The function \phi(x_i) could be almost anything involving the coordinates x_i, i = 1, 2, 3, \ldots – for example in my test-case has \phi(x, y) = \sin x + y = 0, which just tells that whatever the rest of the dynamics are, the point-body described by the coordinates (x, y) should always lie on the negative sine-curve.

Then basic Lagrangian mechanics tells us that there exists a quantity \lambda, which ensures that when one applies the force(s) F_i = \lambda \frac{\partial \phi}{\partial x_i} to the body (bodies), then the constraint can be satisfied. This force is the contact or normal force of the constraint and it has the special property that it doesn’t perform any physical work, because it is always orthogonal to the movement-vector of the body.

Then the typical, and quite accurate model, for friction force caused by the constraint \phi is that the movement of the body (/ the relative movement of the bodies) is slowed down by a force that is linearly proportional in magnitude to the normal force of the constraint F_i = \lambda \frac{\partial \phi}{\partial x_i}. Then of course the magnitude of the constraint force is \| F_i \| = | \lambda | \sqrt{\sum_i \left(\frac{\partial \phi}{\partial x_i}\right)^2} and the proportionality constant of the friction force is slightly higher in case the body is not (bodies are not) moving.

Until now, I have mostly concentrating on the dynamical friction, where the friction force is completely opposite to the velocity vector of the bodies v_i:
F^{fric}_i = - \xi \frac{v_i}{\|v\|} \| F_i \| = - \xi \frac{v_i}{\|v\|} | \lambda | \sqrt{\sum_i \left(\frac{\partial \phi}{\partial x_i}\right)^2}, where \xi is the coefficient of the friction.

Now we get to the actual predicament: How to do this in practice? The force is proportional to another force, but alas, it is the absolute value that it is proportional to! We would get perfect model for linear dependence – meaning something like F^{fric}_i = \lambda \ldots, but we do have linear dependency on the velocity – almost: it is linearly dependent on the direction of the velocity.

In order to study this, I devised three models how to numerically solve them:

1) Make the linear dependency on the velocity linear and use other values from previous known state – this results effectively in:
F^{fric}_i = - \xi \frac{v_i}{\|v_0\|} | \lambda_0 | \sqrt{\sum_i \left(\frac{\partial \phi}{\partial x_i^0}\right)^2}, where v_0 is the previous velocity, \lambda_0 is the previous Lagrange multiplier and x_i^0 are the coordinates from previous state. The nice thing about this model is that it is really simple and computationally inexpensive to implement, but it has the weird property that the velocity used comes from two different points in time, but according to my tests the model is quite ok (except for really smally velocities).

2) Make the force linearly dependent on the Lagrange multiplier \lambda, \rightarrow
F^{fric}_i = - \xi \frac{v_i^0}{\|v_0\|} \lambda \  sign (\lambda_0)\  \sqrt{\sum_i \left(\frac{\partial \phi}{\partial x_i^0}\right)^2}
Here of course |\lambda| = \lambda \  sign (\lambda_0) is always true, except when the constraint force changes directions between two time-steps, but in these situations normally anyways the bodies can drift apart (in case we have a normal contact-constraint \phi(x_i) \ge 0) and the model works nicely as it is completely up-to-date with the constraint force, but alas it is somewhat more complex to compute.

The third option, that I haven’t tried out yet, is to just throw away all quantities of current step and just throw the entire force on the right-hand-side of the dynamics equation, making it basically a constant force over each time-step and this just might be completely sufficient for my purposes but all this still requires some work and testing, as the dynamics model I’m using is somewhat novel. Hopefully I can share more about that later on. For now, I bid you good night.

Btw, I’m planning on modeling the rest-friction case as just conditional constraint in the tangent-space of the original constraint. More on that to come. πŸ™‚