## Skin and bits

June 30, 2015

My wife and I have a problem.
Well, I mean, not a problem, per se. We are “of divided opinions”.
She wants to have a baby. I want to program. The two are obviously incompatible.
And it’s not that she doesn’t like to program, she loves it very much, coding away her will and command; it’s just, she also wants to have a kid.

We went to a marriage counselor. The psychologist looked at me like I was crazy and said that the desire to have a baby is a natural human quality, but the desire to program is not a natural human quality. Well, one thing’s for sure, he’s not getting any more of my money.
I took her to the hospital to the place where they keep all the babies. I had thought that the sight of dozens of screaming amorphous lumps will sober her up. Instead, she literally melted. Every additional screaming amorphous lump she saw made her eyes grow even puppier. It turns out it’s a maternal instinct or something, to turn into a dripping puddle at the sight of screaming amorphous lumps. We eventually left – I mean, the staff drove us out yelling “how the hell did you get in here?!” – with the sole achievement of further increasing her desire for a child.
I reminded her that potential employers frown upon pregnant women. I noted that while “I reared children and brought them up, but they have rebelled against me”, no prophet ever foretold “I compiled programs and linked them up, but they segfaulted against me.” I warned her against the physical dangers embedded in childbirth. I explained that the open source community is full of comments, forums and technical support, but mankind’s source code is proprietary, undocumented, and can only be understood through reverse engineering. I remarked that a git-commit can always be reverted, but you cannot push a baby back into the womb. I elaborated the finest examples and claims, and generally flung such powerful and crushing arguments for my cause, such convincing and uncompromising rhetoric and logic, that she hadn’t even a speck of a chance to refuse them.
She refused them.
She tried to explain something about finding happiness in life and the miracle of childbirth, or something like that, I don’t know, I didn’t really pay any attention. I was confident that I was in the right. Which was too bad, since she was confident that she was in the right.
We had a little bit of a fight over it. Plates were thrown. They were plastic, so nothing broke – I knew buying them would pay off eventually. We agreed to separate for a week and think things through on our own. Well, I mean, she agreed, I didn’t have much of a choice. I rented a room in a tattered downtown hotel. I took my laptop with me, and they had free wifi, so instead of thinking things through on my own, I mostly programmed.
But at night, sitting on the sweat-soaked bed, with the ceiling fan slowly turning as if caught in trance, creaking every three turns, I couldn’t help but think things through on my own. Think about all sorts of things. On kids and the desire to leave a mark in the world. On the meaning of life and the fact that we are just microscopic grains of dust against the vast cosmos. On whether node.js was really the right choice for my server-side. On the joy of seeing your own flesh and blood grow up and learn to walk and talk and decide to get body piercing in dubious places. On whether it’s worth losing the woman you love for code. On whether it’s better to use a red-black tree or an AVL.
For many an hour, I sat.
Thoughts flowed through and around me, and with them, answers.
After a week I came home. She hadn’t changed the locks!
“I have a solution!” we both said at the same time.
“You first!” we both said at the same time.
Ok, in these cases you need to choose a random number between 1 and 20 and wait that amount of seconds. I chose 4, which is the standard random number according to IEEE. She chose a larger one.
“I was such an ass,” I said.
“Yes, you were an ass,” she said. “But I have a solution.”
“It’s so obvious.”
“It feels so right.”
“All this time, it was just sitting right in front of us.”
“Where did this stupid idea come from that the desire to have a baby and the desire to program are mutually incompatible?”
“Why not combine the love of kids with the love of bits?”
“It’s such a wonderful idea! I’m so happy you think like I do!”
“I love you.”
“I love you.”
“Let’s go do it, right now!”
And so, my wife and I embarked on the most magical journey that a man and a woman can experience as a couple: writing together our first artificial intelligence.

June 18, 2015

Did you know? Women are underrepresented in mathematics and science oriented faculties in Israel. In fact, to say “women are underrepresented” is a HUGE underrepresentation of how little women there are. For example, in the Technion you can count the number of female faculty members on three fingers, but the total faculty member count is almost 70 (this includes the emeritus and retired professors, which is generally ok, since why shouldn’t there be female emeriti? Anyway, even without them, the percentage of women is in the single digits). The statistics aren’t much better for other faculties and universities.
This was in the news lately, as the ministry of science released a report on the issue. This is a Good Thing: now people are aware of the problem, and will positively definitely surely immediately act to do something about it. At least, the minister of science said he would!
(Though you can bet that so did all the previous ministers of science. That’s not to say that things aren’t better than they were before, and that no efforts were invested – I’m sure many efforts were invested, and surely things are (slightly) better than before. It just takes a lot of time to fix these things, and the reasons for the underrepresentation are probably deeply rooted inside both Israeli culture and its education system, and will not be changed by a simple government program but rather by prolonged erosion as older generations are replaced by (hopefully) more equality-oriented fresh ones).

But being aware of the problem is half the solution, right? And now you, although you aren’t a minister of science just yet, you can do your part to complete the other half.

What can you do, anyway, at least on the personal level? There are many apparent reasons as to why women are underrepresented in academia and industry, but the first thing you can do is to stop discriminating against them.
“Me? Discriminating against women?! Blasphemy, heresy, and outright profanity! To call me a misogynist is an injustice so immense, just to think it should result in indictment!”
Woha there. That might be true, but it turns out that women are discriminated against when being evaluated on their work, performance, academic record, lecturing, writing, reading, lion taming, dressing habits, or pretty much anything you can think of when compared to men. I take as an example a notable study found here. In this study, members from various faculties of different universities were asked to rank application materials of a student applying for a laboratory manager position. All faculty members received exactly the same c.v and statement letters to review, apart from one difference: in half the forms the name of the student was that of a male (it was “John”), and in the other it was female (it was ”Jennifer”). They gave scores on “competence”, “hireability”, “deserving-of-mentoring” and salary. Here is one graph from that paper:

The application forms were identical, yet the results – not so: male students had better rankings on average than female ones. One possible conclusion is that just seeing a female name on top of a c.v causes people to rank the applicants lower / seeing a male name causes them to rank higher (there may be other possible conclusions, and the study itself may be biased / shoddy; I admit I am no expert in statistics and experimental methods in psychology, and cannot judge the quality of the study better than your average jack-o’-the-mathematics-student. For the rest of this post, I assume the above conclusion is true).

A good question to ask is, “how many people are susceptible to this bias? After all, most people aren’t in HR, and don’t have to review c.v’s and interview people all the time.” Of course it depends on where you are in life both spatially and temporally. In academia, at least, it’s almost inevitable to have to do something similar at some point in your life, even as a grad student: for example, teaching assistants assist in checking homework assignments and exams (the latter are supposed to be anonymous for precisely the reason of reducing biases). Then again, most people aren’t in academia, either.

Knowing this happens, can we overcome it? I think it’s safe to say that many biases such as these are subconscious, in that it seems odd to me that reviewers sit down and genuinely say to themselves, “Oh! I see a woman’s name here! Curse this curriculum vitae, it belongs to an inferior and devilish creature and should be burned at once.” (alternatively, “Oh! I see a man’s name here! This blessed angel will receive all the gifts my prowess can gather”, but we’ll stick with the female-negative instead of male-positive version. To distinguish between the two, the study should have also sent neutral / nameless application forms).
Indeed, it is hard to openly declare “This candidate is a woman, and for that she must suffer! Minus 10 points for Gryffindor”, because Western society today, for most part, denounces that kind of activity. However, it’s much easier to just say to yourself, “I don’t know, I don’t feel very strongly about this candidate-who-happens-to-be-female”, and subtract 10 points regardless. Probably the decision to rate the applications as they did was made at a far deeper level.
But fighting subconscious decisions is hard. Unless we have very well defined metrics, e.g we accept candidates based exclusively on the number of publications (in which case we can have contemporary machines grade and sort them), there will always be a “gut feeling” in part of the selection process. Many times this can be a good thing, since “gut feeling” is based on your previous experience and helps make generally not-so-bad choices when facing decisions with many uncertainties and missing information (and there is a lot of missing information here; we have reduced the candidate’s entire life to a statement essay and some recommendation letters). However, if that gut feeling is tainted with ethnic and gender biases, how are we to know how strong they are? How are we to differentiate between Good Gut Feeling and Sexist Gut Feeling?

The proper thing to do is just find out our biases and fix them. To think to yourself, “What are the objective qualities I am looking for? What merits and flaws does this woman have? If this had been a man, would I have rated him any differently?” But this is hard, since this is not a man, and the Golden Objective Qualities will not always reveal themselves to you, and as you review the application with all these things in mind, there will be a nagging voice at the back of your head whispering in distress, “this is a female, damn it don’t screw this up, you need to rate her fairly, does that mean giving +5 points by default, no, that would be biased as well, what to do what to do what to do?!” The resultant evaluation might be too high, because of the positive anti-bias you are trying to apply, or it might be too low, because of the fear of such a positive anti-bias.
It’s sort of like performing a mechanical task, such as walking, or playing the piano, or hitting a baseball. If you stop to think about how you are going to do it, you will fumble. Once you become self conscious about it, you have put yourself in a pitfall.

But herein, I think, lies a possible key to success. In order to overcome bias, we must refrain from actively thinking about that bias, yet still evade it when it comes. The only way to do that is to actively train yourself, so that when the moment of truth arrives, you will do do it passively. Naturally.
This would be an obvious “given” in in a society where gender equality is the norm. In that case, your whole life you would observe unbiased decisions and non-discrimination. Living a regular life would be considered “training” in itself. But that’s not the case today (evidently), so as in all mechanical learning, we must train.

What I’m offering is: the brain works in mysterious ways. It’s capable of meta-thought, and that meta-thought disrupts it. However, it’s great at learning habits, and habits can be reinforced by training, i.e by feedback. With enough feedback, using some inner mechanisms-which-we-don’t-yet-understand, our brain can master all sorts of skills; some of which we have a very hard time replicating algorithmically and precisely. Why not use this ability to learn how to rate job applications with equality?
(Just some examples of our majestic abilities: face recognition, language acquisition, playing tennis, finding rhymes, and understanding sarcasm. You may object that the brain is hardwired explicitly to solve some of these; that’s ok, we still require a learning process to use them. Also, no need to go into details of different algorithms which do attempt to solve these problems).

This requires a training system. I propose the following:

Introducing www.ungenderbiasme.com! (patent pending; link not yet up). In this site you can methodologically train to remove gender biases when reviewing job applications and c.v’s. It’s quite simple: you log into the site and start reviewing both male and female applications (either randomly generated, or selected real ones). Like the study cited earlier, the same application forms are reviewed by many people around the world, with the only difference being the name and gender of the applicant. So we suppose that when you rank an application, 5000 people from around the globe will rank the same form, assuming the applicant is female; another 5000 will rank the form, but assuming the applicant is male.

Of course, as described above, during this ranking process you will be gender conscious. You will fret and wonder if you are unconsciously overranking or underranking. You will make mistakes. That’s ok though, as the whole purpose of the site is to let you know when you are doing it too much or too little. Once you submit your ranking, your scores are compared to the scores of everyone else in the world who reviewed the same application form as you.

There are several possibilities as to how to do this; here is one. Suppose you rank a female applicant. Your scores are then calibrated against the scores of the people who ranked the same female applicant. If you ranked significantly higher than say 95% of the others, you might just tend to be generous; if you ranked significantly lower  than most of the others, you might just have higher standards. This calibration is cumulative and takes into consideration all your previous rankings as well.
After the calibration, your scores are compared to those of the people who ranked the same male applicant as you did. Now you can see if you are gender biased! (at least compared to the rest of the population). After every form you review, you receive immediate feedback: “You scored this female candidate *way* higher than others scored the corresponding male candidate. Perhaps you overshot in your attempt to fix the world?”.
Effectively, the site provides an indicator as to how gender-biased a reviewer you are. By doing many such reviews (of course they are all short and fun to do), you learn to correct yourself by trial and error. Do this enough times, and you will no longer have to think about being unbiased; it will become part of your review process. Hopefully this will also trickle into the rest of your life, and not just the Job-Application-Checker side of you.

The naysayers will say that there are some difficulties here. You compare yourself to the rest of the world, but who said that the world knows what it’s doing? After all, if all was well, we wouldn’t need this site in the first place. Also, what happens when people start getting better? Does this model incorporate the fact that as time goes on, the world’s population will get better at unbiasing themselves? There should also be some stronger incentives to use this site than “you-will-be-a-morally-better-person-afterwards”, as many times people don’t seem to care about that (maybe it should be mandatory in order to get a professorship in all universities?).

But most importantly, does this scam even work? Who said that this gender bias, as a cognitive behavior, is similar to the mostly-mechanical skills I listed such as hitting a baseball? Who said that it can be trained this way? Even if it could, what guarantees that this specific method will work?

So the site isn’t up yet, and for good reason. Instead, I call out to you, fellow psychology and human behavior researchers! A clinical trial in the trainability of gender biases is yearning to be held. Surveying the harsh-to-be-a-woman environment of today, surely you have the incentive; now just find the money and time, and start performing world-bettering research!

(Alternatively: perhaps such studies already exist but I am ignorant of them (did not come up in a short google search). If so, show!)

## Book review: Rendezvous with Rama

June 12, 2015

Imagine you are a child. Your parents have just told you they have a surprise for you, and are going to take you somewhere special. Excited, you let them blindfold you and get in the car. As the drive goes on, a million (or so it seems to your nine-year-old self) different possibilities pop into your head: is it Disneyland? Or better yet, Disneyworld? Are you going to get a puppy? Is it the beach? Or maybe it’s all a ruse, and they’re taking you to the dentist? Is it the zoo? You wonder how the seatbelt manages to contain so much anticipation condensed in one spot.
Suddenly, the car stops. The engine stills, and the sounds of a busy street come rushing in. Being told to keep the blindfold, you are led through some door.
A myriad of scents and sounds strike you like a shockwave. Some familiar, most new and sensual, the unexplored marketplace is awaiting at the tips of your fingers. What new toys will you find? What new smells? What new tastes? Running through the aisles, a new adventure is about to begin.

This is how I felt like while reading “Rendezvous with Rama” by Arthur C. Clarke. Telling about the first encounter with an alien artifact, the novel evoked within me a thrill of exploration and awe that no other book has ever managed to produce. It’s because of the questions, you see. As the human team of explorers investigate the artifact, they learn a few scattered bits about how it operates, what it can do, and why. But they are only scattered bits; the most vital parts are shrouded in mystery, and the book leaves many more open questions than answered ones. This puts upon you that luring sensation, that thumper of hearts, that there is so much that we don’t yet know – about our world, and about what we can do with it.
Through heavy use of (almost accurate) science and technology, Clarke indeed conveys the impression that such things are indistinguishable from magic; and how magical they can be! And he does this to great extent; turning the final pages, I could not snuff out the thought, that perhaps it’s a bit of a loss that I didn’t study robotics as well as mathematics. But not all is lost.
You see, the books you read, the ideas you come across, all help shape the way you think, all nudge you into some direction or other. I do not yet dare say that “Rendezvous with Rama” was “life-changing” – if only because I have just recently finished it, and life takes time to change. But I do know that the push it gave was a large one, and definitely in the right direction – forward.

## The many faces of Mona Lisa

April 4, 2015

Or: fooling around with image processing kernels.

Original greyscale:

Edge fit + bw cutoff:

Partition into multiple bw images and taking Laplacians:

Plain Laplacian + bw cutoff:

High frequency removal by partitioning into multiple bw images:

Sexy dark high frequency removal:

Subtracting low frequencies from original image:

Overshooting Laplace central element (does this filter make me look old and cracking?):

And yet, throughout the whole process, she just keep smiling.

## A singlet’s lament

February 14, 2015

Valentine’s day is upon us. A poem.
Hebrew follows English.

When I see your wavefunction collapse into the arms of another man, I feel all my eigenvalues degenerate to zero.
You seem so happy together; happier with every measurement, like he is a ladder operator and you, so much more than a good number, are unbounded from above.
Now I am unitary, and can only toss coins into the infinite potential well that glares before me and wish for a steady state. I wanted to take action sooner, I did, I really did but did not dare, for fear I scatter you away.
If only we shared a bound state, I would span your entire space;
If only you’d let me tunnel into your life, the rest of our lifeline would be square integrable;
If only you’d let me, we would form a pair of equal-energy Fermions,
You up and me down,
Or you down and me up,
Or any superposition of the two, our worlds fractionally spinning,
We’d commute left and right, definitely positive and coherent only towards each other;
Resonating for small angles even when you were offbeat;
We could have been entangled forever, never splitting up,
Connected together no matter the distance,
Our future no longer shrouded by uncertainty;
We could have built a warm and cosy house in the reciprocal lattice, a place to call our own;
We could have lived in spherical harmony, rotational symmetry,
We could have,
We could…
But no more.
There is no vacant orbital.
When I see your wavefunction collapse into the arms of another man, I feel all my eigenvalues degenerate to zero,
And the perturbation in my heart just keeps growing and growing,
And I don’t know how much longer I can keep going
Before they have to clean up the gory remains, the tragedy making front headlines in the newspapers,
“Lethal result for the famous experiment
As scientist places himself as ‘Schrödinger’s cat’”.

כשאני רואה את פונקציית הגל שלך קורסת אל תוך זרועותיו של אדם אחר, אני מרגיש
איך כל הערכים העצמיים שלי מתנוונים.
אתם נראים כל כך שמחים ביחד, מאושרים יותר בכל מדידה, כאילו הוא אופרטור סולם ואת, כל כך הרבה יותר מסתם מספר טוב, מצביך העצמיים לא חסומים.
עכשיו אני אוניטרי, אני יכול רק להטיל מטבעות לבאר הפוטנציאל האינסופי שפעור לפני ולקוות למצב יציב. רציתי לפעול מוקדם יותר, באמת שרציתי אבל לא העזתי, מחשש שאפזר אותך לכל עבר. אומרים שחבר הוא לא קיר פוטנציאל, אבל אני כבר מעורער.
לו רק היינו חולקים מצב קשור, הייתי פורש לך מרחב שלם;
לו רק נתת לי להתמנהר לחייך, שארית חיינו הייתה אינטגרבילית בריבוע;
לו רק נתת לי, היינו יוצרים זוג פרמיונים שווי אנרגיה,
את למעלה ואני למטה,
או את למטה ואני למעלה,
או כל סופרפוזיציה של כל השילובים, עולמינו חצי מסתובב;
היינו מתחלפים מימין ומשמאל, חיוביים בהחלט וקוהרנטים רק אחד כלפי השני;
הייתי יכול להיות הצמוד ההרמיטי שלך, להתלכסן יחד איתך בכל בסיס,
להכנס איתך לרזוננס גם בזוויות קטנות;
היינו יכולים להשזר ולעולם לא להפרד,
להיות תלויים ללא תלות במרחק,
עתידנו המשותף כבר לא עפוף בחוסר וודאות;
היינו יכולים לבנות בקתה קטנה וחמימה בשריג ההופכי, מקום לקרוא לו בית;
היינו יכולים לחיות בהרמוניה ספרית, ללא חשש מסיבובים;
היינו יכולים,
היינו יכולים,
היינו…
היינו יכולים לעשות את כל אלו,
אבל לא עוד.
אין אורביטל פנוי.
כשאני רואה את פונקציית הגל שלך קורסת אל תוך זרועותיו של אדם אחר, אני מרגיש איך כל הערכים העצמיים שלי מתנוונים,
וההפרעה רק גדלה עם הזמן,
ואני לא יודע עוד כמה אוכל להמשיך
לפני שינקו את השאריות המדממות, ובעיתונות יסקרו את הטרגדיה,
“תוצאה קטלנית לניסוי המפורסם
בעוד מדען שם את עצמו בתור ‘החתול של שרדינגר'”

## There are no zeros in physics

February 5, 2015

I recently read an article by Joseph Ford: “How random is a coin toss?” (1983). In it, Ford talks about the relation between completely deterministic systems and the seemingly random behaviour they sometimes produce. “Roulette wheel spins, dice throws […] are universally presumed to be completely random despite their obvious underlying determinism. Weather, human behavior and the stock market are, on the other hand, commonly regarded as strictly deterministic, notwithstanding their seemingly frivolous unpredictability.”

Through arguments on chaotic orbits and algorithmic complexity, he claims that eventually we must throw away our continuum descriptions of physics (this is regardless of quantum mechanics; see footnote), as those require calculations and measurements with infinite precision; however, as our computers are finite and our measurements imprecise, any actual calculation we do will have errors. In chaotic systems, which vastly outnumber the non-chaotic ones, these errors increase exponentially, and our predictions break down.

Instead of a continuum, we will use a number set that does not rely on infinite precision: only those numbers which can be algorithmically computed in finite time. This pretty much means only the rationals, it would seem. Now, in a way, we already roughly do this, and every time we run numerical simulations we restrict ourselves to the rationals, plus maybe a few other selected numbers. However, this is not included in our main physical theory, but is a byproduct of our finite machines.

An interesting point which especially caught my attention is:
“We thus eliminate the last infinities, the infinitely large

$\infty = (1+1+1+...)$

and the infinitely small

$0 = (1+1+1+...)^{-1}$

And indeed, while checking for equality is a difficult topic in floating point computations, our computers still allow us to assign the perfectly rational “0” to a variable. Yet in reality, it is very unlikely to encounter a physical property with a perfect 0 value. As a statistical, averaged property I might expect it to appear quite a lot, but as a deterministic one – less so.

Here are two nice points of wisdom I encountered during my studies which emphasize this:

1) I remember clearly one of our classes in Waves in the third semester. We were talking about damped harmonic motion, and the professor, analysing the damping coefficient, said something along the lines of: “we see here that there are two types of solutions: overdamping, if ξ > 1, and underdamping, if ξ < 1”. At this point, a student raised his hand and asked, “what about the critical damping, for ξ = 1?”. To this the professor replied: “nonsense, that is just a mathematical joke; a true physical system will never have a ξ value equal to exactly one!”

2) In solid state, and in practically any field in physics, whenever there is a local minimum in a potential, the physicists like to say that at that point, the system behaves as a harmonic oscillator. Why? Because then the derivative is 0, and the second derivative is positive. Looking at the Taylor expansion:

$V(x)=x_0+V'(x_0)(x-x_0)+\frac{1}{2}V''(x_0)(x-x_0)^2+O((x-x_0)^3)$

We know that $V'(x_0)=0$, and if we neglect the higher order terms, we get the equations for a harmonic oscillator. A question naturally arises: why must the second derivative be positive? Maybe it too is 0, and the smallest power in the Taylor series is at least 3? My Solid State TA gives the following answer: when dealing with physical systems, it’s so enormously hard to actually get a 0, that in essence the quadratic coefficient is almost always finite; the curvature must be very unique for both the first and second derivatives to be 0.
A good follow up question would then be: if it’s so hard to get a 0, why can we assume that the first derivative is 0? My answer to this: this stems from the fact that the potential has an actual extremum; having or not having an extremum is a physical binary quality, and so appears in physical variables. If we throw a ball up and it comes back down, we know that at some point it reached some maximal height and had a velocity 0 (even if we cannot pinpoint the exact moment of time with infinite precision, we know it exists and can compute around it, at least using continuum physics). A unique curvature, however, is in the continuum.

*Note: Ford mentions, but does not expand much on, the use of infinite precision in quantum mechanics, which is usually deterministic in its evolution but statistical in its measurements. I tend to see strength in his arguments only when we are purely deterministic.

## Programming complex transformations

December 2, 2014

Facebook should change their “It’s complicated” status to “It’s complex”. That way, real people with imaginary girlfriends could spread the news to all their friends!

– Ancient proverb

We were learning about conformal maps in complex function theory. While we did plenty of “circles are sent to circles” and “connected components are sent to connected components”, it’s almost obvious that we barely got to see any actual map in action.
I remembered that I saw some very nice geometrical transforms in the wonderful Youtube series “Dimensions” by Leys, Ghys and Alvarez (link here), and decided to write a small program of my own that, given a picture, can apply any (reasonable) complex function to it, treating it as a transformation on pictures.

What does this mean? We can think of a picture as an array of pixels, each with its own $x$ and $y$ values. Treating the center of the picture as $(0,0)$, each pixel has a different coordinate. The pair $(x,y)$ in $\mathbb{R}^2$ can be treated as $z = x + iy$ in the complex plane. We can then take this complex number and put it in any complex function $f(z)$; the result is some other complex number, $w = a + ib$. We then interpret this new number as the coordinates of a new pixel; so in the new picture, the color at position $(a,b) = f(x+iy)$ will be the same as the color at position $(x,y)$ in the original picture.

If $f$ is a funky enough function, the results should be awesome, and this lets you understand a little better what all sorts of analytic functions do (analytic functions preserve angles between the two pictures, so however twisted things get, we’ll always have some sanity).

Here, look at what happened to our poor tiger (original image courtesy of Wikipedia commons):

This…

Turns to this…

(confession: ok, this mapping isn’t a standard conformal map; read more to see what’s actually happening here).

I’ll now describe some of the problems and solutions I ran into; if you just want to see more pretty pictures, feel free to do just that.

The naive way to get a mapping is to do just what was described in the above explanation: take the original picture, and for each pixel $(x,y)$, plot it at $f(x,y)$. Unfortunately this has several problems. These stem mainly from discretization: the coordinates of the pixels come in integer units, and two nearby pixels will always differ by at least 1 in one of their coordinates. Proper scaling can make this discretization as small as we wish, so effectively we can have any two nearby pixels differ by $\frac{1}{n}$ for any $n$ of our choice, but problems can still occur.

The first problem is that even if your function is onto, meaning that it’s possible to designate the color of every pixel in the new picture, the result may still have gaping holes or “isolated pixels”. This severity of this problem depends on the function itself (I guess it generally depends on whether the absolute value of its derivative is close to 1 or not), and for some choices of $f$, your end product might only be partially filled.
In this example, generated naively by $f = \sqrt{z}$, the top of the picture is falling to pieces (also, it’s evident that the edges of the picture are getting left out, though this is because our source picture is finite, not due to discretization).

A partial solution is to “fill in the blanks” by averaging over neighboring pixels: each blank pixel will take the average color its nearest neighbors. Assuming that the picture is not “too broken up”, this can work just fine – if holes are completely surrounded, you won’t really notice the difference (and it almost makes sense theoretically to do this, in terms of the middle-value theorem). Indeed, running this fix helps the picture quite a lot, although there are still untreated areas which cannot be helped:

The second problem is that some transformations can span over enormous scales. For example, with the transformation $z \rightarrow \frac{-1}{z}$, the interior of the unit disc exchanges places with the exterior. This means that when going over the pixels, ones very close to the origin are going to get sent way off to the edge of the new image, while ones far away are all going to be sent near the origin.

The result is that while the new image is very very large, most of the “interesting” things (aka – most of the actual original picture) is contained in a very, very small region. Look at this example of $z \rightarrow \frac{-1}{z}$:

Not very interesting, is it?

You can adjust for this phenomenon if you know where to cut off your picture, ignoring the endpoints that are way off. But how can you know in advance the size of your image, or which points are good and which are not? This generally requires analyzing your function beforehand, which we do not want to do.

As a (very) partial fix, I noticed that most of these image points are isolated – the discretization means that two remote points will probably not be directly near each other. I wrote some small cleanup code that finds these points and eliminates them, rescaling the picture appropriately. Of course, there will always be isolated points; in fact, due to the discrete nature, every point in the new picture is isolated, so in effect we have to specify how close two points have to be to each other to be considered neighbors or not; this is done according to the resolution of the target image.

In any case, the code I wrote works iteratively. Here are the first three iterations:

You can see that as we iterate, the pictures get better (and focus more on what’s important, the actual head of the tiger, instead of empty space). However, I would still consider this to be rather inadequate (although we do get a “particle-erosion” effect for free, which is cool).

A third problem with this method is that f doesn’t have to be a one-to-one function, meaning that there may be two possible colors for a given pixel in the generated picture. How do we decide which one to take? Do we combine? Do we override? This is a general problem not due to discretization, and I just ignored it here (the code overrides new pixels). Here is $f(z)=z^2$:

For our last image with this method, here is $\log(\text{tiger})$.

The naive method is riddled with problems and artifacts. However, there is a way that generally treats discretization better, and while it also has some black empty space, and some pixelated areas, it doesn’t tend to have small annoying holes (for nice functions, anyway).

The solution is this: instead of going over all the pixels $x,y$ in the original picture and computing the coordinates of the pixel in the new picture, $w = f(x+iy)$, we go over all the pixels $(a,b)$ in the new picture, and calculate the inverse $x+iy=f^{-1}(a+ib)$. If we do not exceed the size of the original picture, we basically ensure that we will not have holes in the result, because we actually go over each pixel and calculate its color, instead of having it “get picked by accident”, as was in the original method.

This method eliminates all the sporadic and isolated holes and points we had using the naive way. Here is $f(z) = \frac{-1}{z}$ using the inverse method:

Much better!
Of course, there are still a few problems:

1. The edges are pixelated – this is because they all draw from basically the same region – the immediate center of the tiger’s face – and a small region that is smeared over a large area is pixelated.
2. There is still a gaping hole in the center. In order to fill it up, we would need an even larger original tiger image – the inverse of these points is out of bounds. In fact, for this specific function, $\frac{1}{z}$, we always have some finite dark area at the center, since we do not work with infinite pictures. There are ways to overcome this, but not with simple finite image transformations.

One drawback of this method is that we need to directly specify the inverse of $f$. This may be simple, in case of simple functions like $\sqrt{z}$ or $\frac{1}{z}$, but in general it may not always be easy.
Further, there may be artifacts arising from this methods. For example, suppose we want to see the map $f(z) = \sqrt{z}$. In order to use the inverse method, we would have to calculate $z^2$ for all the points in the original image.
But the equation $w^2 = z$  has two solutions for $w$: both $\sqrt{z}$ and $- \sqrt{z}$! When using the inverse method while giving $z^2$ as an inverse function, we get a different image from the direct method:

And indeed, notice – the tiger has been replicated! This can never happen with the direct method, which by definition maps each point only once.

Now you see how I cheated you a bit with the first picture in this post – it cannot be the result of a conformal map, since there are clearly multiple instances of the tiger! In fact, it was created by calculating the inverse of $\frac{1}{z-100(1+i)} + \frac{2.5}{z+100(1+i)}$.

That’s it for now; happy mapping!