Seasons Generation from Orbital Parameters

Welcome back to part 3 of the Procedural Calendar Generation series. In the first part we looked on how to compute celestial body position in a simple two-body system. The second part, instead is crash course on ellipse geometry.

In this part, instead, we will tackle a fascinating consequence of the cosmic dance of our planet around its sun: seasons. Seasons are a strange beast because their behavior depends on a huge amount of factors. We are used to our four seasons with mild springs and autumns, hot summers and cold winters. But these four season are just the consequence of our planet ecosystem, atmosphere, the peculiar axial tilt, if the orbit is particularly eccentric, distance from the sun in different period of the year can be a strong modifier too! In multi-star system, we can have more than 4 seasons, in planets with strange mechanics we can not have seasons at all (or better, the “season” depends on where are you on the planet).

Continue reading “Seasons Generation from Orbital Parameters”

Not every classification error is the same

In this article, I would like to talk about a common mistake new people approaching Machine Learning and classification algorithm often do. In particular, when we evaluate (and thus train) a classification algorithm, people tend to consider every misclassification equally important and equally bad. We are so deep into our mathematical version of the world that we forget about the consequences of classification errors in the real world.

Continue reading “Not every classification error is the same”

A Dwarf Fortress calendar in PureScript + Halogen

My last week project involves PureScript and Halogen and the Dwarf Fortress calendar. I wanted to give a first-hand experience with some pure functional language for web front-end and, after discarding Elm, I ended with PureScript. I will not go on a comparison between PureScript and the rest of the world. If you want a comparison among the other candidates, you can look at this very detailed article. (There is ClojureScript too, if Clojure will ever came back from the graveyard).

To test PureScript I decided to implement a very simple project: a page showing today’s date according the calendar used in Dwarf Fortress. It is easy enough to be tackled without me knowing nothing about PureScript and Halogen in a week: you take today’s date, you apply some math, and you print your result on an HTML widget. At the same time, I think it is complex enough to have a grasp of PureScript potential (at least, in the allocated time).

You can find the result here. (Github Repository) Now, we can go on.

Continue reading “A Dwarf Fortress calendar in PureScript + Halogen”

Crash course on basic ellipse geometry

Because I started a small series about astronomical algorithms and the magic of math in space, I think we need to cover an important prerequisite. In the series, I will talk a lot about ellipses (duh), I will move from the semi-axis majors, to the periapsis, to eccentricity, to ellipse’s center and ellipse’s foci. I am concerned that things can get more complicated than expected if the readers does not know many of the geometric properties of the ellipse. For this reason, I put here this vade mecum on the ellipse geometry. A summary with all the basic points and lengths. A place that I can link everywhere I need to refresh a definition.

Continue reading “Crash course on basic ellipse geometry”

WordPress abandoning React: a Facebook horror story

Today, during my daily web crawling, I found this article by Matt Mullenweg. I will not dwell in details, you can read the full story in the linked post. But I try to give you the core of the announcement: WordPress just decided to abandon React. This is a big news, with many implications and a few lessons to learn. Let’s go by steps.

Continue reading “WordPress abandoning React: a Facebook horror story”

Computing planetary orbits between two celestial objects

As you probably know, I am working (slowly) on an astronomically accurate calendar generator. All the orbital calculations involved are quite challenging, and I am discovering a lot. It is a lot of fun (except for the all the times I need to do some trigonometric magic to make some formula work).

Anyway, during this process, I am reshaping and producing many many formulas. I am sure that in six months I will forget all the motivations behind them. For this reason, I want to try to save some of them here. In this way, I will have a good place where to look back at my notes and, moreover, I can be useful to other people trying to do some low-accuracy orbital calculations.

I want to start from the beginning: orbital period and orbital trajectory.

Position of the planet on the orbit

Orbital Diagram for an earth-like object by XKCD.

First of all, we need to have a clear idea of what are the orbital elements. If we consider a true three-object system (e.g., sun-earth-moon) things get very, very messy. A complete orbital diagram for such system involves an impossible number of angles, axises and intersections between imaginary lines.

For this reason, for simplicity, we want to start from a very basic two-objects system: a point object orbiting around another (more massive) point object. In this situation, there are no rotation axises, there are no orbital inclination. There is only one object orbiting the other.

A diagram showing the basic measures for an object P on an elliptic orbit around another object in F [source].
We also assume that the mass of the star is much greater than the planet mass. In this way we can consider the star “fixed” and put there our system origin. As we know, an orbiting system like this obeys to the Kepler’s laws of planetary motion:

  1. The orbit of a planet is an ellipse with the star is at one of the two foci (F in the above diagram).
  2. A line segment joining a planet and the star sweeps out equal areas during equal intervals of time.
  3. The square of the orbital period of a planet is proportional to the cube of the semi-major axis of its orbit.

We will look at Law 2 and 3 later, for now the first law is enough.  Orbits are elliptical. This seems easy but keeping track of non-uniform movement along an ellipse is more complicated than you think. Assuming that you know how an ellipse is defined (eccentricity, major axis, minor axis, and so on) we are interested in one measure: the true anomaly. This is the angle between the planet P and the star in F. In the diagram, this is the angle f.

As you can see, if we know this angle, and we know the orbit dimensions, we know where the planet is on the orbit.  Because orbit dimensions are usually given (there are many sets of equivalent dimensions, for the moment, we don’t care), the only thing we need to determine the planet position over time is the true anomaly over time.

Computing the True Anomaly

Computing the true anomaly over time is not a trivial task. Before we can compute the true anomaly, we need some intermediate steps. The first stop is computing the mean anomaly. Imagine a circle with radius a (the semi-axis major of the ellipse, in other words, half the “width” of an ellipse). Imagine now a body orbiting this circular orbit with constant speed (because circle) with the same period (P) of the real planet. The angle of this imaginary body at time t is the mean anomaly.

Computing the mean anomaly over time is very easy, after all, it is moving with constant speed. Therefore:

M(t) = \frac{2\pi}{P}

Now, we introduce a new angular measure, the eccentric anomaly. This is the angle E shown in the above diagram. It represents the angle between the circular orbit center C and the kind of projection of the real planet position on the elliptic orbit on the imaginary circular orbit we defined before. To compute this value we use the Kepler’s Equation:

M(t) = E(t) - \epsilon \sin(E(t))

Note that \epsilon is just the ellipse eccentricity. This is a wonderful relation between the mean anomaly and the eccentric anomaly. However, give this formula, it is impossible to express E(t) in closed form. For this reason, there are a thousand of methods for approximating this value.

The one I prefer is the recursive one. In short, we rewrite the formula as

E(t) = M(t) + \epsilon \sin(E(t))

You can note that we have expressed a kind of recursive function. Thus, we can replace E(t) on the right with the same formula again

E(t) = M(t) + \epsilon \sin(M(t) + \epsilon \sin(E(T))

And we can continue the process over and over, every time obtaining a closer approximation. I usually do this process 3 times, and, with some trigonometric magic trick, I get the following formula

E = M + \epsilon \sin(M) + \epsilon^2 \sin(M)\cos(M) + \frac{1}{2} \epsilon^3 \sin(M) \left( 3 \cos^2(M) - 1) \right)

Finally, we can rewrite this formula in a way that it is easier for the computer (it is faster, it performs less sin and cos, and reduce the floating-point errors):

E = M + \epsilon \sin(M) \left(1 - \epsilon \left( \frac{\epsilon}{2} + \cos(M) \left(1 + \frac{3 \epsilon}{2} \cos(M) \right) \right) \right) 

Cool. Now it is time for the last step of our process. We have seen that the eccentric anomaly is just the “angle between the center of the circular orbit and the projection of the real planet on it” (this is a very loose definition, but I think it is the most intuitive approximation). Therefore, to find the real angle we just to “project the planet back” to the elliptical orbit. Fortunately, this is much less painful problem. The relation between the two angles is given by the following formula (where \theta is the true anomaly).

(1 - \epsilon) \tan^2\left(\frac{\theta}{2}\right) = (1 + \epsilon) \tan^2\left(\frac{E}{2}\right)

This can be rewritten as

\theta = 2 \, \mathop{\mathrm{arg}}\left(\sqrt{1-e} \, \cos\frac{E}{2} , \sqrt{1+e}\sin\frac{E}{2}\right)

A formula that finally concludes our journey.


This is everything for now. I’ve put many concepts on the table and, before we move on, we need to be perfectly at ease with the tree angular orbit measurements, the anomalies. In the next articles we will see how to use them to compute some basic orbital events (such as equinoxes) using these formulae.


I have some book that was extremely useful in this task:

  • Astronomical Algorithms by Jean Meeus. This book is a 20+ year old book for writing astronomical algorithms on a computer. For this reason the code examples are in BASIC. Yep. But the math and the core of the problems are all there. This book is still a gold mine if you are interested in this kind of works.
  • Introduction to Geodetic Astronomy by T.B. Thompson. There is no link for this, but you can use your web search ability to find a PDF version, somewhere. This is an even older book (December 1981) but, at least,  there is no obsolete code. The book is all about the celestial math governing the Earth and the Sun (and other orbiting spheres).
  • If you want something more recent, there is Astronomy on the Personal Computer by Montenbruck and Pfleger, but I didn’t read it. I know many people suggested me this book and the examples involve a more recent C++, but it costs a lot for a book that I need for a side project.

How hidden variables in statistical models affect social inequality

Use of machine learning is becoming ubiquitous and, even with a fancy name, it remains a tool in the statistical modeler belt. Every day, we leak billions of data from ourselves to companies ready to use it for their affair. Modeling through data get more common every day and mathematical model are the rulers of our life: they decide where we can work, if we can get a loan, how many years of jails we deserve, and more.

While this is ethically problematic by itself, a deeper, simple problem is polluting mathematical modeling around the world: hidden variables, variables that are a common root cause of some data we are sampling. To understand why they are such a big problem, let’s start with an example. Suppose we want to write a program to understand if a certain guy is a good worker for our company. We want to use an automated system because we don’t want that human weakness and prejudices to affect our hiring process! Right?

So we start collecting data about the candidates with a questionnaire. We put into it many common sense questions. For simplicity, assume we just have 3 questions: “How good was your school curriculum?”, “Have you ever had problem with the law?” and “Have you ever missed a payment with your creditors?”. They seem good questions. After all, our model is quite clear. Being good at school, being a good citizen and paying debts in time are clearly variables correlated to the variable “It is a good worker”.

This is the causality diagram for the “job candidate” example. The three sampling variables “School”, “Law Problems” and “Debts” are not independent variables. The hidden variable “Race” is a common cause for all of them. This has huge implications on the fairness of the model.

However, after some time we discover that the system is hiring mostly middle class white men. Apparently, being white a Caucasian man is directly correlated  to being a good worker. It makes no sense. That’s because of confounding hidden variables. In fact, even if we have not put race as an explicit variable, it can still affect all the other variables we are sampling. Race affects all the above variables. Race influence on average the wealth of your family. In turn, this will affect the quality of your education, the neighbor you grew up and how much you get targeted by the police.

The overall effect is that you are screwing individuals on the basis of the indirect effect of their race on the average outcome of your sampling variables.

But wait, it gets worse.

The second problem of this kind of model is that they are self-validating. If we use this model to select good job candidates, some people will have less job opportunity and therefore less money, and, in the end, less chance to pay debts on time, pushing them and their families in bad neighbors with more law problems and worse schools. In short, the model will amplify the same issues that the model got wrong in the first place, and doing so, it validates itself. A problem called retrocausality.

Sometime, we in AI community end up too much caught in the models charm, and we forget the effect that such models can have on the people. Machine Learning  is not immune to these problems. Machine Learning can learn the world inequalities and use them to confirm its internal model. And when we will apply those machine learning algorithm, we will contribute to amplify such inequalities.

This and many other problem are discussed in the book “Weapons of Math Destruction: How Big Data Increases Inequality and Threatens Democracy” by Cathy O’Neil. While I think the book is overly pessimistic in some parts, it is a good reading to look at statistical modeling from a different angle. It definitely helped me to consider the implications of bad mathematical modeling to people’s life. Sure, the book often is too focused on the risks of models respect to their benefits. But when we are talking about people life, I think even one innocent victim is just too much.

Update 19th September 2017

Some days ago a friend of mine showed me a recent real-life example of what I described here. I said that Machine Learning is not immune from discriminatory biases. As an example, let’s look at this tweet (image copy):

This image is the result of what a machine learning algorithm (word2vec) learns when trained on a Google News corpus. In particular, it shows which adjectives are associated to the word “he” and which adjectives are associated to the word “she”. As you can see, we are in stereotype-land!

The point is that the algorithm is trained on an already biased world, and therefore learn to be biased itself. It is just math and algorithm, but it is sexist. If we are not aware of this possibility, and we apply such ML algorithms, we may end up in amplifying the inequalities we are trying to avoid by using math and algorithm!

Playerunknown’s Battlegrounds did everything wrong. And doing so, it won.

This small article is born from a discussion I had with a friend of mine this week. He was writing a review on Playersunknown’s Battlegrounds (from now on, PUBG) and he ended up talking about the evolution of the genre and its triumph over every other competitor. The article was good but it did not enter in detail about, what I think, it is a greatly important and interesting question: Why PUBG? Why not any of the other dozens of battle royal games we were plagued in the last years?

PUBG is clearly a winner in this competition. It sold more than 8 million copies on Steam only, and I can see the trend going with the future release on consoles. The problem, in my opinion, is that, on paper, there is nothing in PUBG implementation that seems “right”. Nevertheless, it won.

Machiavelli once said that success is 50% luck. That’s definitely true for PUBG. But the other 50% must be researched in the PUBG qualities. Analyzing them, despite the massive “errors”, it is very important for any game designer.

Continue reading “Playerunknown’s Battlegrounds did everything wrong. And doing so, it won.”

Against Addiction and Gambling-like Mechanic in Free to Play Games

I want to take the cue from a last week massive Reddit thread on micro-transaction in Free2Play (F2P) games to give my opinion of the topic. I think it is important. We need to increase awareness that predatory practices in F2P games are incredibly close to gambling and share with it the same self-destructive and harmful addictive behavior. This is wrong in so many way: it is dangerous for the victims, it is dangerous for the game itself, and it is dangerous for the entire F2P model.

The Reddit thread presents this as a new discovery, but it is not. The trend is clear for a long time and there are a lot of discussions on the topic. Before we try to find a solution, let’s look at the different faces of the problem.

The Micro-Gambling Addiction: The User Perspective

When we talk about predatory marketing behaviors in F2P games, we talk about all that practices implemented to encourage/force people into spending more and more money in F2P games using excessive addiction/gambling inspired techniques. Every developer tries to make people spending money on their game. However, sometime F2P games push this too hard using addictive design mechanism with the goal of “trapping” people willing to put in the game unhealthy amount of money. And they do nothing to prevent this.

A common misconception when talking about this is that people usually assumes that the target of Predatory F2P games are the children. After all, we usually look to children as vulnerable creatures that can be easily tricked with games. This is wrong. Predatory F2P games targets are the so-called “whales”: people who can spend thousands of euros per month on a game. Children have no money, they cannot be whales.

In order to survive, F2P games need to catch some whales, and to do that they aim to vulnerable people using gambling-like techniques. We are talking about depressed people, people who had a big loss, people who have problem at works or in social context, people not satisfied with their life. F2P games give to this people a community, a goal, a deep sense of accomplishment. But in Predatory F2P all this comes with a price: a price these people need to pay to continue playing, to not let down their community/clans, to be competitive and continue to feel accomplished.

It is hard for people without these problems to understand how a person without a job can spend 3000$ in one session on MapleStory in order to craft a single weapon. But it happens, more than you think.

Is F2P Addiction as Gambling Addiction?

If this remember you something, you are right: gambling addiction. Let’s look at the symptom of gambling addiction (from here) and see if we may relate them to F2P addiction.

  • obsessing over any type of gambling – replace gambling with games and, check.
  • gambling to feel better about life – As I said before, check.
  • failing to control your gambling – This is clearly obvious for people spending 10000$ on a F2P game.
  • avoiding work or other commitments to gamble – Check.
  • neglecting bills and expenses and using the money for gambling – Sadly, check.
  • selling possessions to gamble – I am not aware of these cases, but I am sure that it is because I didn’t look well enough.
  • stealing money to gamble – Check.
  • lying about your gambling habit – Check.
  • feeling guilty after a gambling session – Check.
  • taking bigger and bigger risks while gambling – This require defining “risk” in F2P game spending, but I can assume that for F2P whales, there is a tendency of spending more and more with the time passing.

In my opinion, gambling addiction symptoms map with my experiences with F2P addicted people. But, unlike gambling, there is no warning, there is not the same public attention and F2P addiction is definitely hard to be recognized as a real pathology.

The Micro-Gambling Addiction: The Game Perspective

This concept is extremely well explained in the above video. I’ll try to summarize here the key points.

Because F2P games require whales to survive and because a handful of whales can represent 95% of the game revenues, the game slowly shifts their focus toward a whale-centric model. This is reflected in games becoming less and less fun for non-whales players. That’s how Pay-2-Win games are born.

But that’s not all. Games need non-whales customers, too. They need them, because they are the game population segment that feed the whales’ sense of accomplishment. Why I need to by that amazing sword if there is no one to crush with it?

This force the game to acquire new players faster than how the existing players quit. This, in turn, increases the advertising cost and exposure. Now, instead of a pay-2-win game, we have an annoying pay-2-win game with advertising popping up everywhere.

The self-feeding loop will continue indefinitely until the game is no more sustainable, leaving behind a battlefield of indifference or disgusted players.

Did the game improve over time? Did it leave a good memory to the old players? Did it offer a refreshing and fun experience? No. It trapped the whales into it as a parasite and pissed of everybody else. These are not the kind of products developers are proud to work in. These are not what games should be.

The Micro-Gambling Addiction: The F2P Model Perspective

The last victim of this practice is the F2P model itself. The F2P model is a good model. There is nothing inherently bad about it. Actually, F2P has many benefits, it allows everybody to play it and allows people willing to spend money on it to spend the amount of money they think the game is worth, and more.

Though, predatory F2P is actively damaging the F2P model itself. If the trend did not stop we will face the following problems:

  • Game studios that do not want to implement unethical marketing/design practices can go out of business because the finite amount of money of the F2P market is absorbed by those gambling/addiction-based games. Thus, making the F2P market less interesting for the majority of players.
  • F2P games in general may start to have a bad reputation among the core of the gaming community. In turn, this drives people away from the model. We can already see how F2P has become a term with which gamer “insult” games.
  • Governments may start acting in an indiscriminate way. Because we rarely see politicians understanding the technology they are going to regulate, I am sure that if something will happen will hit hard all the F2P model regardless of how much unethical their practices are.

We can already see some of these points in action and things are not going to improve in the foreseeable future.

Defending people from micro-gambling

Here it comes the final question: how can we stop this? As individual, we probably can’t. We can avoid such horrible F2P games but we do not make a difference. Only the “whales” matters.

But this is not a reason to stop trying. Here a simple list of things you can do.

  • Spread awareness of the problem. For now, this is not perceived as a social issue. But we have seen it definitely is. There clearly people out there that are putting themselves in financial problem territory with some game. This people need help. And nobody will help them if they think there is no problem.
  • If you know people affected by this kind of addiction try to help them. If they are not in such deep problems, keep an eye on them. Addiction is easy to snowball in much bigger addictions. Don’t be ashamed. We have reached the point where it is not a shame to ask for help for somebody spending too much at Poker. It is the same for people spending too much in some F2P game.
  • Every time it is possible, mark the connection between gambling and F2P predatory practices. Make clear that some games are using gambling related techniques. As the original Reddit thread suggest, if we stop using a generic micro-transaction for gambling-like mechanics in F2P games, it is easier to make people aware of the problem. Moreover, it will separate good F2P from bad F2P.

If you are a developer, instead, the obvious suggestion is to avoid to put heavy gambling inspired techniques in your game. I know that sometime they are accidental. But there are two easy tricks:

  • Try to make purchasable content not necessary for the game. A splendid example is Team Fortress 2 and Dota 2. In TF2 everything can be dropped, or can be bought to save time. In Dota 2, everything on sale is just cosmetic. This remove the urgency for people to buy stuff to be competitive and, at the same time, it allows people deeply involved in game to buy something to look cool.
  • Try to put a limit on the amount of money needed to unlock contents. If there is no more than X amount of € of contents per year it is impossible for vulnerable people to spend 3000€ in a month. For instance, you can release your game as F2P and,  when a single user buys a certain amount of F2P contents (e.g., 100€ or more), he/she unlocks the full game. For instance, this is done in Pokémon Picross, where the user can grind everything in a F2P fashion, or can buy the equivalent of 15€ of stuff to have complete access to the game contents. There are many other examples of this.

I am open to hear more solutions for this problem. If you have any other trick to help F2P addicted people, send me a message and I will update this section!

P.S: Hey, what about Trading-Card Games?

Oh dear God…

My definition of gambling-inspired micro-transaction (randomization of the outcome, unlimited spending, payed content required to be competitive) is quite broad. Writing this article, I realized that this definition includes games such Magic the Gathering or Hearthstone because of one of their core components: booster packs. Are booster packs considered gambling? Well… technically yes. It is, in fact, possible that people get addicted to such mechanic (I personally I think I had some physical addiction to the smell of freshly unpacked booster packs). The feedback of excitement and punishment/reward of opening a booster pack is exactly the same of spinning a slot machine.

I think there is a subtle difference though. Booster pack always gives you something of value that can be used or exchanged to get the card you really want. Evan virtual TCG games implements such mechanism in attempts to attenuate the gambling aspects. For instance, Hearthstone allow you to disenchant duplicated card and use the resulting materials to “craft” a more valuable card. Sure, it is not a zero-sum process, but it is better than a slot machine.

For this reason, I think they can give the same problem in some cases, but in a more light and controllable form. They lay in a gray area.

Again, I do not want to ban gambling-like mechanic. I want to make people aware of the problem so that we can protect vulnerable people.