Showing posts with label science. Show all posts
Showing posts with label science. Show all posts

Saturday, May 16, 2009

Animal displacement pressures

Animals are often being driven from areas that humans find habitable or in some cases, those that humans make habitable. Still the mountains around LA, in spite of tremendous human population pressures, remain relatively devoid of human habitation. But all other land nearby that is even remotely flat is occupied by humans and the occasional possum. Most other complex life forms have been forced into the surrounding mountains, become extinct, or been moved out by ASPCA.

The animals who have survived are now in a new environment. Few of them are naturally hill-climbers, and none of them naturally manage the pollution well. This type of animal displacement can be found in a huge number of urban centers affecting a large number of large mammals and reptiles. Fish have been depopulated to extinction and forced into new climates that are harsher or less accessible to humans. Many prominent scientists and environmentalists are concerned about the large open areas of the oceans devoid of life and how few mountain-lions survive. Yet these examples open up opportunities for other life and complex life living in new areas simply means that life will need to adapt.

The three-eyed frog from the Simpsons is one possible outcome from this animal displacement, but more likely, the mutations and adaptations will be more mundane and prepare these animals for hillsides (not the fish of course), mountains, and deep forests. When the inevitable flooding comes from polar melting and the more flooding on coasts, these animals may be more adapted to dealing with space and land pressures.

Of course, a bunny rabbit that can climb montains like a goat seems odd, but if that works for the bunnies....

Saturday, April 11, 2009

Decreasing maintenence through formatting

How important is formatting to the development process? Is aligning function names with tabs important?

It's startling how much a difference a little white-space can make in the readability of a header file. Here we have the identical class in two different scenarios. Notice how much quicker the class on the left makes sense to you and how much more quickly you can assess it's usefulness to you. As a quick test, look at the class on the right... does it allow networking? Does it write to a database? Now look at the class on the left... does it render? Which member variable stores position?

If you try to answer the questions posed above, you will find that the class on the left is almost instantly interpreted and almost a brain-dead exercise. The class on the right is almost excruciating to read. Now you might think that no programmer on Earth would ever write the code on the right, but sadly, you'd be wrong: just a few weeks ago, I ran into this exact scenario where I was put in charge of similar, nightmarish code and told to not make any changes. This example isn't even long, around 30 lines where the code I had was over 80 lines.

Without color highlighting, this situation is slightly harder for reading both cases, but in many cases, all types will be types internal to the company and thus color highlighting won't be displayed.

By aligning all functions as I have done on the left, much like you would see in a spreadsheet program (or a phone book), you can easily ascertain the functionality of this class. This dramatically improves the time to find the "right" class to do the work you need. While this doesn't affect the experienced programmer who knows the code base, new hires become almost instantly productive. Studies in code reuse and programmer productivity (HP, IBM, MS, et al) have all shown that well-aligned code can increase programmer productivity in general, not just for new hires. The extra white-space in between functions and between functions and their return values makes a huge difference. I would suggest that both are about the same in importance.

Please, for the sake of all programmers who follow you, including yourself, follow the white space example on the left.







//------------------------------------------
class AI_Bot : public StellarObject
{
public:
AI_Bot ();
void Clear ();

BotState GetBotState () const;
BotTarget GetBotTarget () const;
UUID GetPlayerTarget () const;

//---------------------------------------

virtual void Setup ();
virtual void Draw ();
virtual void Update (GameData&);

//---------------------------------------

protected:

bool CheckForTransition () const;
void BeginTranition ();
bool IsInTransition () const;
void ResetState ();

void UpdatePosition ();
void IsPossibleToInterruptCurrentState ();

BotState myState;
BotTarget myTarget;
uint32_t timeOfLastStateChange;
BotState transistioningState;
UUID playerTarget;
Vector destination;
SpaceStation* baseDestination;
SpaceStation* homeDestination;
BasicProjectile* selectedWeapon;
};

//------------------------------------------


//------------------------------------------

class AI_Bot : public StellarObject
{
public:
AI_Bot();
void Clear();
BotState GetBotState()const;
BotTarget GetBotTarget()const;
UUID GetPlayerTarget()const;
virtual void Setup();
virtual void Draw();
virtual void Update(GameData&);
protected:
bool CheckForTransition()const;
void BeginTranition();
bool IsInTransition()const;
void ResetState();
void UpdatePosition();
void IsPossibleToInterruptCurrentState();
BotState myState;
BotTarget myTarget;
uint32_t timeOfLastStateChange;
BotState transistioningState;
UUID playerTarget;
Vector destination;
SpaceStation* baseDestination;
SpaceStation* homeDestination;
BasicProjectile* selectedWeapon;
};

//------------------------------------------

Tuesday, March 24, 2009

Concurency on modern hardware

Multi-threading is a challenge for most programmers. Just the basics in threading are a little confusing. Then there is the challenge of thinking about shared resources, memory, thread-contention, cache coherency, memory bus stalls, and starvation. I'd like to briefly discuss each of these topics to create a sense of familiarity for the reader.

Overview:
What is the point of concurrency? Why use multi-threading? So how does it all fit together?

Al of these are valid questions and I'll start with the simplest question first: what is the point of concurrency.
Concurrency exists to take advantage of fast hardware. It does so often by putting different applications on different pieces of hardware. When multiple pieces of hardware are not available, it staggers the execution of applications allowing each to run for a short period. The basic idea is that CPUs are available so the OS will try to move applications around to make each appliaction run faster.

Concurrency also exists to add the appearance of "stability". What can happen in OSs that don't support concurrency is the appearance that an application is 'hung' and not executing properly. You have probably seen this in Windows from time to time when you log into a website and the browser never returns. Many things can cause this like long-waits, a program caught in an endless loop, or even a bad memory access. In any case, the program hangs. Without concurrency, the entire computer would lockup, not just your program and then you'd spend more time rebooting.

We'll discuss the other two questions throughout the rest of this discussion.

Basics:
Processes [Wiki] are the equivalent of a computer program. These are usually applications but if you bring up your Activity monitor (or Task manager), you'll see a lot of processes running which are not visible applications. These are often things related to networking, the OS, time applications, and so on. There are other things called cron processes, batch processes, and drivers which also take up CPU time but don't always appear in your Activity monitor. Each process has its own memory, performance characteristics, needs for the file system, and many other characteristics which have the potential to interfere with other processes. The differences between a thread are subtle and beyond the cope of this discussion: just consider them to be the same for now.

Concurrency [Wiki] allows us to take advantage of multiple pieces of hardware when available. When not available, all modern OS's allow multi-threading which is similar. The concept is one of allowing your CPU to execute multiple processes simultaneously. When the hardware is available, such as a Dual core Pentium or a Six core XBox360, each process can execute on a separate piece of hardware and stay out of the way of other processes, theoretically. The reality is much more complex. When hardware is not available (only one CPU for example), then the OS will stagger execution of programs making them take turns. Process1 will work for a while, then the OS will interrupt Process1 to allow Process2 to run a little bit. After a short time, the OS will interrupt Process2 and continue running Process1. This is a highly simplified example, but illustrates the basics of what all modern OSs must do.

Interrupt [Wiki] is a hardware-driven change of direction. Basically, an interrupt is like a telephone and no matter what you're doing, when that phone rings you stop and answer the phone. An interrupt usually comes from some external hardware and notifies the CPU that something has changed. In modern CPUs, this is most often a timer that tells the CPU that a certain amount of time has elapsed and this is often the cue for the CPU to change from one process to another. Even when multiple CPUs are available, the interrupts are going crazy telling the CPUs that a file has finished loading, that a DMA has completed, that a timer has gone off, or that a user has hit a key on the keyboard.

Kernel [Wiki] is the low-level code that makes determinations about which process has a chance to run every time it receives an interrupt. It routes events, suspends processes, and makes timing choices.

Process dispatch or allocation has to do with putting processes on different pieces of hardware (CPUs) for execution. This is a decision made by the OS (OSs make algorithmic choices, not true decisions) and can be overridden by configuration files. In fact, on the XBox360, you can specify on which CPU any threads will be created. Many other OSs allow similar dispatch models and configuration capabilities.

Parallel computing [Wiki] allows us to setup situations where a single task can be completed by different processes running simultaneously, often on different CPUs or chips. This is typically accomplished by the concept of scatter-and-gather where a single task is subdivided into multiple smaller tasks, the results are computed on different CPUs, and then the results are pulled together into a final result by one of the CPUs.

Race conditions [Wiki] specify some of the basic problems with threading and concurrency in general. These happen when two processes compete for the same resource and can lead to deadlock or starvation. In either case, things don't work as planned and can cause some processes to stall or not execute at all.

Synchronization [Wiki] is the traffic cop that you need to put into place to make all of this work. Basically, synchronization objects work directly with hardware to control who is accessing any given resource at any given time. This can be a piece of memory, a file, or even a section of code that only one process should execute at a time. These synchronization objects are all similar and are built on the concept of atomics which are CPU-level operations that can be executed in a single clock-cycle (very fast).

Memory bus [Wiki] is the access to RAM and can be a major bottleneck in computers with multiple CPUs.

Why use multi-threading?
Concurrency is hard. Even very experienced programmers can have great difficulty managing 'wait states', synchronization, performance problems, and design. This makes the justification of the effort to do multi-threading even more tenuous. Still, it's hard to argue with the ability to do things twice as fast (or more with more hardware). Also, the appearance of an application that responds to user interaction while opening and reading a file increases the likelihood that consumers will consider your software more professional and stable.

Other considerations are things like allowing your application to do two things simultaneously are useful since a user can only type so quickly. If you consider a word processor, it can look up words as you type, spell check, grammer check, and auto save. All of this is managed through multi-threading. Gone are the days where you had a separate step of spell-checking before printing your document (does anyone but me still remember those days?)

Also, other applications like MSN Messenger, AIM, and others allow you to stay connected to the internet while typing, adding smiley faces, and updating friend-status. In a manner of speaking, all of this is just plain magic.

How does it all fit together?
Most OSs offer a method that looks like this:
bool CreateThread (FunctionPointer, StackSize, PriorityLevel);

This can take a variety of parameters, but often it takes a stack pointer (just a pointer to RAM or a RAM size request), a pointer to a function or some code, and a priority for the thread. That's all there is to the OS support. The rest is up to you. You need to manage the synchronization but the OS will usually do the rest. Some specialized hardware has special Macros or methods to allow you to tell the OS where to put the thread (which CPU), but generally, you don't worry about such things.

A critical determination is the priority. Another may be the stack size. Let me explain why these are important. The priority affects the Kernel and helps the OS decide whether to allow a process or thread run. All threads having equal priority means that the Kernel simply let's each run in turn in a round-robin manner. Once a thread has higher priority than others, it has the potential to prevent other threads from running very much (called starvation) but can also mean that a small piece of code that you want to run quickly will receive as much of the CPU as the Kernel will give it. Low priority threads run "in the background" and can accomplish tasks with little effect on user experience. For most purposes, you should set your threads to "Below normal" thread priority unless you are certain that you don't mind affecting the user experience.

The stack size can be important too depending on what you are doing. The stack size affects stack frame which is the amount of memory available for a series of function calls available on the stack, not the free store. Every time you call a function, the current function you are in must push its data onto the stack and then load up some values which are also pushed onto the stack for inside the new function. If you are using recursion, this size can grow rather quickly. You will probably need a minimum size of 4K, but plan on needing a lot more like 16k or maybe as much as a meg is you are sorting some large dataset.

There are a few synchronization tricks and foibles to watch for and I will detail the half dozen of these in a future blog. For now, just remember to use the mutex, use it in any access to a resource or variable that you have, and use it very close to the access, not in the earliest access case or broadly. Code for this often looks like this:

void SomeBigMultithreadedClass::Foo()
{
m_Mutex.Lock();

// do something expensive like allocate RAM, access a file, etc.

m_Mutex.Unlock();
}
Many more details will come in my next blog.

Sunday, February 22, 2009

Derivitives of position

Given the position of a particle or object, you can take the position over time as in the following eqn: v = (p2-p1) / t
which is one way of expressing velocity or movement.

In a similar manner, you can measure velocity over time to yield acceleration thusly: a = (v2-v1)/t

You might be surprised to learn that further derivations exist for acceleration over time and even further. These are the following (I am not making this up):
Jerk = (a2-a1)/t
Jounce = (Jerk2 - Jerk1)/t

Above that we have the following derivatives:
5th: Crackle
6th: Pop
7th: Lock
8th: Drop

These can be quite useful, particularly jerk which can be used to great effect in camera controls and animation. Once we get to Jounce, these derivatives begin to lose further value. There are some other alternatives which are less serious but still useful sometimes. Those are:
  • snap - the same as jounce
  • crackle - change in snap over time
  • pop - change in crackle over time
In calculus terms:
v = ∆p / ∆t = dp/dt
a = ∆v / ∆t = dv/dt
k = ∆a / ∆t = da/dt (jerk)
c = ∆k / ∆t = dk/dt (jounce)

It turns out that position is the 1st derivative of absement. Absement (or absition) refers to the -1th time-derivative of displacement (or position), i.e. the integral of position over time.

Happy physics and animation

Thursday, January 29, 2009

Color basics in computer-based color

Let's start with the knowledge that white is composed of all colors combined and black is the absence of all color.

Computer-based color is a little different than other more natural forms of color.

First of all, we are talking about a form of light called additive color. This is similar to when you take three colored lights and shine them at a wall and can be seen in projection boxes with separate red-green-blue projection lights. Even TVs have these colors: when you step close to a TV (about 8-10 cm), you can see the tiny RGB dots that make up color TV. Additive colors are typically composed by using Red, Green, and Blue. These are called the color primitives.

Additive color works by adding light to the 'scene'. The Sun generates this kind of light as do light bulbs. We can also find this additive light in Black Lights, Christmas Lights, and so on. Since white is composed of all colors, adding together red, green, and blue additive colors produces white. Turning off these lights produces no color, better known as black.

Print color typically uses subtractive color. Most things in the world are subtractive in nature. These things remove color from the 'scene'. The reason that a basketball is orange is not because it glows orange. Rather, when white light or near-white-light bounces off of a basketball, the basketball removes all colors that are not close to orange (and possibly red and yellow). To obtain black, you need to remove all color being reflected. To obtain white, you need to reflect all color.

The color primitives of subtractive color are Red, Yellow, and Blue. All visible colors can be composed using some combination of these. Printers typically use Cyan, Magenta, Yellow, and Black to obtain a better black than can be made by mixing the other inks. Basically, inks and paints work by removing visible color. Remove all color and you have black. Remove none and you have white.

Secondly, our eyes have a strong bias toward green. [Wikipedia] This means that we can see a lot more shades of green than we can of red or blue. We find that computers often produce colors in equal amounts: the same amount of red as green for example. This means that computers do not completely produce color the way that we see it.

Lastly, computers are capable of producing colors which do not naturally occur, but our eyes are still quite capable of viewing. Some of these include the color fuschia/magenta and cyan. These colors are often used in bitmaps as areas that artists want to be 'see thru' and so the computer can ignore them. These colors are also amazingly annoying to use on displays and backgrounds because our eyes are not adapted to viewing them.

The way that computer color is represented when writing software is either by coloring an area with small integers (range of 0-255) or floats (range 0-1). For the rest of this blog I will use the integer representation. A 'triple' is used to contain the color value so that red is (255, 0, 0), green is (0, 255, 0), and blue is (0, 0, 255). When reading these numbers, keep in mind that you are effectively controlling the dimmer on lights: 0 is closest to off and 255 is fully on. As you control the red channel from 0 upwards, you end up with black, then brownish, then dark red, then red, then bright red.

Common combinations of color also include:
White (255, 255, 255) note how all channels (colors) are fully on.
Orange (255, 128, 0)
Purple (191, 0, 191)
Yellow (255, 255, 0)
Pink (255, 200, 200) see how close it is to white
Cyan (0, 255, 255)
Fuschia/Magenta (255, 0, 255)

Those are the super basics but it should give you a sense on how to control color on web sites, displays, and in computer programming.

Good luck

Wednesday, January 21, 2009

Why insects fly around a light at night

I figured this out by watching their behavior under unusual circumstances, but is goes like this: insects move toward a light source attempting to "find the way out". They most often don't know the difference between day and night (some insects clearly do) except for the amount of light available. When in a garage that has the door closing, they will fly toward the available light for a way out of the garage. The same is true of a cupboard, a closet, or what have you.

In the case of a light bulb, they are simply doing the same thing that a buzzing fly attempts to do as s/he busily bounces off of the glass of your indoor window: s/he is repeatedly trying to get outside to where the light and warmth are. It's kind of funny really, but they just want outside and if they can just find a way through that little crack in the glass of the lightbulb, they can make it outside.

Just my 2¢.

Thursday, December 25, 2008

Why women are better at communications and social skills and why men are better at math and sciences

First let's dispense with the idea that women and men are all that different at anything. There is a much bigger gap between an average male and a below average male in mathematics than there is between an average male and an average female. The same goes for science and the opposite is true for communication and social skills.

Secondly, let's look at what the difference is. A few studies show that men are, on average, around 3% better than women at math and science, and that women are better, on average, by the same amount in communications and social sciences. These differences are small (almost minute) and simply do not account for the differences in the number of science and math papers published by men or the psychology papers published by women. Also, this does not account for the differences in other areas like linguistics, a very technical area, chemistry, and biology.

While the number of graduates from university now favor women (around 70% of graduates from post secondary education are female in 2006), the record shows that women are poorly represented in papers, journals, and in the sheer number of major discoveries in math and sciences. So why is it that more women are now graduating from university than men and yet they aren't surpassing men in these areas which usually require higher education.

The biggest thing that we need to consider is disposition. Men are more interested in cars, computers, and non-human things: usually things of a mechanical nature. Women are more interested in people, social hobbies, and things that are social. Secondly, a socialization that more women have to sitting around talking about personal matters is part of this equation. People are interesting and women definitely gravitate toward the study of people. Men gravitate toward things that could be considered anti-social or things that prove their manhood (sports, fishing, and so on). Obviously, these generalizations are somewhat silly, but sadly, there is a lot of truth to them. In the grand scheme of things, the mad male scientist hiding away in his lab is a more acceptable stereotype to us than the mad female one. This is the cultural side that also influences how women view the world. Here is a recent article from New Scientist discussing this aspect: Link

One more note about disposition: many of these traits are linked to needs of the species. The male, in order to prove his manhood, must stand out from others and is thus competitive with his peers far more often than females. We find this type of behavior strongly favored across the spectrum of animals. Most Western and Far Eastern societies discourage these behaviors and we are slowly seeing the diminishing of males in scholarly pursuits. This has been widely documented in recent decades. This competitive behavior leads men to pursue simple things like chess far more often than women (see previous link). It also leads to Math leagues, Physics competitions, and so on. There are few, if any, French competitions, History leagues, or Economics debate clubs in Western Education. The result is that boys shy away from these fields, Economics being excepted. There is no better way to interest a male in a subject than to make it competitive.

Females, by contrast, favor teamwork and group success over self pursuits. The result is obvious. They build stronger families, by contrast, and they often have larger circles of friends. They are often the nucleus of any community and they maintain strong bonds of friendship throughout life. Recent studies say that this is a major factor in female longevity and another reason that widows live well for many years while widowers most often die within a year or their spouse's demise.

We'll continue to examine the differences in men and women from a lot of different directions, but I will argue that we need look no further than the corpus callosum. The reader may reference this brain structure definition here: http://en.wikipedia.org/wiki/Corpus_callosum. Let me offer this simple metaphor: the corpus callosum is the network allowing both sides of the brain to communicate. In men, this network is overall larger than in women, but the splenium (part of this network) is larger in women. We are neglecting individual differences because given any male, his corpus callosum may or may not be larger than any given female. Still, the averages persistently show differences in size of these two regions. Let me emphasize that these differences in size are very small. Keep in mind that disposition is just as important as any physical differences may be.

Before I go off the deep end, and earn the ire of millions of women everywhere, keep in mind that in the hind portion of the corpus callosum (the splenium) is larger in females. This area is not necessarily related to communications of any particular type, but because it is the thickest portion of the corpus callosum, it has the "densest layer of communication" between the brain hemispheres. So, in a way, women have a larger corpus callosum, but not overall. Another thing to consider, albeit with little empirical evidence, is the physical location of the splenium in relation to the brain structures normally associated with math, science, music, and linguistics: the left temporal lobe. The splenium is not close to the left temporal lobe and may not facilitate any communications between the left and the right hemisphere; this seems unlikely, but at the very least, communication through this brain structure is not as great as through other parts of the corpus callosum.

For the sake of science, let us ignore overall brain size. The brain size in males is slightly larger than females but many studies have concluded that brain size makes no significant difference as to the overall cognitive abilities of anyone. The quality of the connections has long been recognized as the major contributing factor to the quality of cognition and/or thought. With this handy knowledge in tow, we can march toward our goal: with the corpus callosum as the major network of cells and dendrites allowing the brain hemispheres to communicate, is it any wonder that at the highest levels of math and science intelligence, we find men. Toward the midbrain and hind brain, we tend to find socialization and thus women are clearly leaders when it comes to social skills like psychology, teaching, and salesmanship (ask any automart who their best sales people are). This is no way implies that either men or women are superior... in fact I might argue that women have the most social advantages in life while men make the best mad scientists (comedy is intentional here).

A recent book called Outliers discusses the effects of a small advantage given to someone over time. It discusses financial advantages, birthdates, and other matters which seem to provide no clear advantage to anyone, but in the year-after-year way that life works, these accumulate to be huge advantages. It discusses how people born before certain dates have more chance of succeeding at university because those date are close to 'cut off" dates that are required for children entering school at the ages of 5. The small advantage given to children early on accumulate over time to make major differences in adulthood.

The physical argument goes something like this: while the differences in math and science intelligence are very small, the long-term effects are gargantuan. The other factors of disposition and social pressure contribute to this and provide men an enormous advantage in maths and sciences at the highest levels over the very best women. This same advantage is afforded women in sociability, salesmanship, and teaching where the very best women are far superior in these areas of life than the very best men.

So, in conclusion, let me say this: a boy locked in room playing with his computer (more likely a video game) is common and a girl playing dress-up with her dolls and barbies is common. We can try to change the nature of humans, but I believe that it all comes down to the corpus callosum.

This blog is more food-for-thought than anything else. I don't prove very much of this but most of it is widely available information and long-since proven. I’d love to hear your feedback, positive or negative (of which I expect plenty).

Sunday, November 9, 2008

Lack of terse science and engineering measurements

As many people know, the metric system is great in terms of managing powers of ten and simplified unit conversion. However, it isn't very intuitive. Let me explain: the measurement of a person who is 5'6" is a measurement that nearly everyone can wrap his/her hear around. The reasons are partly cultural and mostly comparative: people tend to be able to compare numbers under 20 readily, and have trouble with any number over 20. As an example, 165 cm is relatively meaningless to most English speakers and is a less intuitive measurement. How tall is 165 cm compared to 185 cm?

In fact, most imperial measurements are more intuitive than the metric system (the rod, mile, and peck being excepted).

As one minor way of making the metric system simpler, we could work with easier names. I realize that this argument does not follow from the above justification, but naming is a key part of the success of any product or system. (iPod vs Sansa).

So for the following measurements, let me suggest some names.

mim - millimeter (simpler name)
duse - 25 millimeters (replacement for the inch)
gounce - 25 grams (replacement for the ounce, almost)
cup - 250 grams (the equivalent of 8 ounces)
sot - 1 1/2 meters (useful for everyday height. My height is 1 sot - 25, my sister is 1 sot - 18)
trisot - 4 1/2 meters (typical roof height)
mistud (mee-stud) - 40 cm (useful for studs in a house which are normally 16" on center)
guy - 30 cm (replacement for the foot, great for wire, or other linear measurements)
square guy - 30 cm2 (replacement for sq ft, great for housing measurements like a room
that is 300 square guy)
clik - kilometer (common military term for distance)
wale - 10 kilometers (simple name for common distances -
3 wales between London and Brentwood
4 wales between East Village and Long Beach -NY)

These are simple suggestions and I would love for us to start using such measurements.