Sunday, September 26, 2010

Programming for iPhone

  1. The work of handling various buttons and labels in a Window-based application gets delegated to a class called project-nameAppDelegate. In this class methods should be defined to respond to actions that take place in the iPhone's window, such as the pressing of a button or the movement of a slider. This class will also have instance variables whose values correspond to some control in the iPhone's window, such as the name of a label or the text displayed in an edible text box. These variables are called outlets, and like the action routines, in Interface Builder, those instance variables have to be connected to the actual control in the iPhone's window.

Saturday, September 25, 2010

Core Motion Framework

  • There are 8 header files - they can be grouped into four categories: Initialization (CMMotionManager.h), Reporting (CMError.h, CMErrorDomain.h, and CMLogItem.h), Combined Motion Sensing (CMDeviceMotion.h), and Individual Motion Sensing (CMAccelerometer.h, CMAttitude.h and CMGyro.h).
  • After creating an instance of CMMotionManager, an application can use it to receive 3 types of motion: raw accelerometer data, raw gyroscope data, and processed device-motion data. The processed device-motion data provided by Core Motion's sensor fusion algorithms gives the device's attitude and rotation-rate; the direction of gravity, and the acceleration the user is imparting to the device.
  • An application can take one of 2 approaches when receiving motion data: by handling it at specified update intervals or periodically sampling the motion data.
  • For handling motion updates at specified intervals, the following 3 steps should be taken: (Step:1) set accelerometerUpdateInterval property in the unit of seconds, (Step:2) call startAccelerometerUpdatesToQueue: withHandler:, passing in a block of type CMAccelerometerHandler, and (Step:3) accelerometer data is passed into the block as CMAccelerometerData. Similar 3 steps should be taken for Gyroscope or Device Motion.
  • For periodic sampling of motion data, the following 2 steps should be taken: (Step:1) call startAccelerometerUpdates, and (Step:2) periodically access CMAccelerometerData objects by reading accelerometerData property. Similar 2 steps should be taken for Gyroscope and Device Motion.
  • The availability of hardware and its activity status are accessible through the following 2 properties: accelerometerAvailable and accelerometerActive. Similar 2 properties are there for Gyroscope and Device Motion.
  • CMAccelerometerData has a struct type property called acceleration (CMAcceleration) which contains 3 double's for the accelerations along the 3 axes in the unit of G's (gravitational force).
  • CMGyroData has a struct type property called rotationRate (CMRotationRate) which contains 3 double's for the rotation rates around the 3 axes in the unit of radians per second. The sign follows the right hand rule: if the right hand is wrapped around one of the axes such that the tip of the thumb points toward the positive direction of that axis, a positive rotation is one toward the tips of the other fingers.
  • CMDeviceMotion encapsulates measurements of the attitude, rotation rate, and acceleration of a device. There is a catch: the accelerometer by itself actually measures the sum of two distinct acceleration vectors: gravity and user acceleration; user acceleration being the acceleration that the user imparts on the device. Due to the fact that Core Motion is able to track a device's attitude using both the gyroscope and the accelerometer, it can differentiate between those two acceleration vectors, namely gravity and user acceleration. The 2 properties: gravity and userAcceleration, correspond to them. In toto, CMDeviceMotion has 4 properties: attitude (CMAttitude type, orientation of the device relative to a given frame of reference), gravity (CMAcceleration type, a vector expressed in the device's reference frame), rotationRate (CMRotationRate type, contains a measurement of gyroscope data whose bias has been removed by Core Motion Algorithms and is different from CMGyroData that gives raw gyroscope data), and userAcceleration (CMAcceleration type).
  • CMAttitude represents a measurement of the device's attitude at a point in time. It offers 3 different mathematical representations of attitude: a rotation matrix (as rotationMatrix property of type CMRotationMatrix), a quaternion (as quaternion property of type CMQuaternion), and Euler angles (in radians, as roll, pitch, and yaw properties). Roll is a rotation around a longitudinal axis that passes through the device from its top to bottom, pitch is a rotation around a lateral axis that passes through the device from side to side, and yaw is a rotation around an axis that runs vertically through the device and this axis is perpendicular to the body of the device, with its origin at the center of gravity and directed toward the bottom of the device. CMRotationMatrix is of struct type and it contains 9 double's representing 9 entries (m11 through m33, e.g., m31 is the element in row 3 and column 1) of a 3-by-3 rotation matrix. CMQuaternion is also of struct type having 4 doubles (x (a value for X-axis), y, z, and w) in it. A quaternion offers a way to parameterize attitude. If q is an instance of CMQuaternion, mathematically it represents the following unit quaternion: q.x * i + q.y * j + q.z * k + q.w and a unit quaternion represents a rotation of theta radians about the unit vector {x, y, z} and {q.x, q.y, q.z, q.w} satisfies 4 relations: q.x = x * sin(theta/2), q.y = y*sin(theta/2), q.z = z*sin(theta/2), and q.w = cos(theta/2). CMAttitude class has a crucial instance method called, multiplyByInverseOfAttitude which takes in a CMAttitude object and multiplies its inverse with the receiving CMAttitude object and it replaces the receiving object with the change of attitude with respect to the passed-in attitude object. In order to use a CMAttitude object as a reference, it must be cached and passed as an argument to this method in subsequent calls.
  • CMLogItem is a base class for Core Motion classes that handle specific types of motion events. Objects of this class represent a piece of time-tagged data that can be logged to a file. It has a read-only property called, timestamp, of type NSTimeInterval which records the time when a motion-event measurement was taken.
  • CMErrorDomain has a NSString in it called, CMErrorDomain and it identifies the domain of the NSError objects returned from Core Motion.
  • CMError is of enum type which currently (description is forthcoming, says the library reference!) has one value defined in it called, CMErrorNull = 100.

General Theory of Relativity

  1. Accelerated frame of reference is described by a transformation to a curvilinear co-ordinate system.
  2. Physical laws in a uniform gravitational field is identical to those same laws expressed in an accelerated frame of reference (or a curvilinear co-ordinate system).
  3. Tidal force is the obstruction to replacing a non-uniform gravitational field with an accelerated frame of reference. Curvature is the obstruction to describing a non-flat surface with the rectilinear co-ordinates. There is a connection: tidal force originates from the curvature of space-time!
  4. Einstein's Law of Gravitation has two parts in it: (part: 1) how the geometry of space-time changes when matter is present - namely, that the curvature expressed in terms of the excess radius is proportional to the mass inside a sphere and this law should be true in any moving system (Einstein's Field Equation) and (part: 2) how objects move if there are only gravitational forces - namely, that objects move so that their proper time between two end conditions is a maximum (Einstein's Equation of Motion). The three discrepancies from Newton's Law of Gravitation, first derived by Einstein have been experimentally confirmed: The orbit of Mercury is not a fixed ellipse; starlight passing near the sun is deflected twice as much as you would think; and the rates of clocks depend on their location in a gravitational field. Whenever the predictions of Einstein have been found to differ from the ideas of Newtonian mechanics, Nature has chosen Einstein's.

Friday, September 24, 2010

Special Theory of Relativity

Galilean transformations imply that all physical laws remain identical in uniform motion. If the Galilean transformations are inserted into Maxwell's equations, they do not remain identical [Problem:1]. Moreover, Maxwell's theory concludes that a disturbance in the electromagnetic field travels at the same speed (speed of light) in all directions even if the source of the disturbance is moving. Michelson-Morley's (M-M) experiment shows that velocity addition theorem does not work for light [Problem:2]. In order to solve the two problems, Lorentz devised a set of transformations. Under Lorentz transformations Maxwell's equations remain identical, and the length contraction (required by the transformation) account for the null result in the M-M experiment. Einstein said, all physical laws are identical under: not Galilean, but Lorentz transformations. And that's it.

Wednesday, September 22, 2010

Recreational Experiments

  1. Build a Foucault's Pendulum and prove that the earth is rotating.
  2. Perform Cavendish's experiment for finding out the Gravitational Constant.
  3. Perform Romer's Experiment for finding out the speed of light from observing the moons of Jupiter.

Tuesday, September 21, 2010

Excerpts from Advice to a Young Scientist

  1. ...they should have more than one string to their bow and should be willing to take no for an answer if the evidence points that way.
  2. ...if once a scientist experiences the exhilaration of discovery and the satisfaction carrying through a really tricky experiment - once he has felt that deeper and more expansive feeling Freud called the "oceanic feeling" that is the reward for any real advancement of the understanding - then he is hooked and no other kind of life will do.
  3. Most able scientist I know have something for which "explanatory impulsion" is not too grand a description. Immanuel Kant spoke of a "restless endeavor" to get at the truth of things, though in the context of the not wholly convincing argument that nature would hardly have implanted such an ambition in our breasts if it had not been possible to gratify. A strong sense of unease and dissatisfaction always goes with lack of comprehension. ...Perhaps the restless unease I am writing of is an adult equivalent of that childish fear of the dark that can be dispelled, Bacon said, only by kindling a light in nature.
  4. ...application, diligence, a sense of purpose, the power to concentrate, to persevere and not to be cast down by adversity - by finding out after long and weary inquiry, for example, that a dearly loved hypothesis is in large measure mistaken.
  5. The novice who tries his hand at research and finds himself indifferent to or bored by it should leave science without any sense of self-reproach or misdirection. ... A scientist who pulls out may regret it all his life or he may feel liberated; if the latter, he probably did well to quit, but any regret he felt would be well-founded, for several scientists have told me with an air of delighted wonderment how very satisfactory it is that they should be paid - perhaps even adequately paid - for work that is so absorbing and deeply pleasurable as scientific research.
  6. A graduate student should by all means attach himself to a department doing work that has aroused his enthusiasm, admiration or respect; no good will come of merely going wherever a job offers, irrespective of the work in progress.
  7. It can be said with complete confidence that any scientist of any age who wants to make important discoveries must study important problems. Dull or piffling problems yield dull or piffling answers. It is not enough that a problem should be "interesting" - almost any problem is interesting if it is studied in sufficient depth.
  8. Isolation is disagreeable and bad for graduate students.
  9. Because the newly graduated Ph.D. is still very much a beginner, a new migratory movement has grown up in modern science that is spreading as rapidly as the at one time newfangled habit (deplored in the Oxford of my days) of taking Ph.D.s at all. This new movement is the migration of "postdocs." Graduate research and attendance at conferences usually gives graduate students powers of judgment that they often wish they had had before they embarked on their graduate work. Later on they will know a great deal more than they did at first about the places where really exciting and important work is going on, preferably in congenial company. To one or other such group the most energetic postdocs will try to attach themselves. Senior scientists welcome them because as they have chosen to come they are likely to make good colleagues; for their part, the postdocs are introduced to a new little universe of research.
    Whatever may be thought about the Ph.D. the treadmill, this new postdoctoral revolution is an unqualifiedly good thing, and it is very much to be hoped that patrons and benefactors of science will not allow it to anguish.
  10. The great incentive to learning a new skill or supporting discipline is an urgent need to use it. For this reason, very many scientist (I certainly among them) do not learn new skills or master new disciplines until the pressure is upon them to do so; thereupon they can be mastered pretty quickly.
  11. Too much book learning may crab and confine the imagination, and endless poring over the research of others is sometimes psychologically a research substitute, much as reading romantic fiction may be substitute for real-life romance.
  12. The beginner must read, but intently and choosily and not too much.
  13. It is psychologically most important to get results, even if they are not original. Getting results, even by repeating another's work, brings with it a great accession of self-confidence; the young scientist feels himself one of the club at last, can chip in at seminars and at scientific meetings with "My own experience was ..." or "I got exactly the same results" or "I'd be inclined to agree that for this particular purpose medium 94 is definitely better than 93," and then can sit down again, tremulous but secretly exultant.
  14. ... imaginative guesswork that is the generative act in science.
  15. ... their spouses are in the grip of a powerful obsession that is likely to take the first place in their lives outside the home, and probably inside too; they may not there may not then be many romps on the floor with the children and the wife of a scientist may find herself disproportionately the man as well as the woman about the house when it comes to mending fuses, getting the car serviced, or organizing the family holiday.
  16. To be creative, scientists need libraries and laboratories and the company of other scientists; certainly a quiet and untroubled life is a help.
  17. An ambitious young scientist is marked out by having no time for anybody or anything that does not promote or bear upon his work.
  18. The ambitious make too obvious a point of being polite to those who can promote their interests and are proportionately uncivil to those who cannot.
  19. The traditional reason given for a scientist's reluctance to write a paper is that it takes time away from research; but the real explanation is that writing a paper - writing anything, indeed, even the begging letters that are necessary if a laboratory is to remain solvent - is something most scientists know they are bad at: it is a skill they have not acquired.
  20. The only way to learn how to write is above all else to read, to study good models, and to practice. I do not mean to practice in the sense in which young pianists practice "The Merry Peasant," but practice by writing whenever writing is called for, instead of making excuses for not doing so, and writing, if necessary, over and over again, until clarity has been achieved and the style, if not graceful, is at least not raw and angular.
  21. In writing a paper, a young scientist should make up his mind about whom he is addressing. The easy way out is to address one's professional colleagues only - and of them, only those who work in a field cognate with one's own. This is not at all the way to go about it. A scientist should reflect that his more intelligent peers probably browse in the literature for intellectual recreation and might like to find out what he is up to. The time will come, moreover, when a young scientist will be judged upon his written work by referees and adjudicators. They are entitled to feel annoyed - and often do - when they can't make out what the paper is about or why the author undertook the investigation, anyway.
  22. A formal paper should therefore begin with a paragraph of explanation that describes the problem under investigation and the main lines of the way the author feels he has been able to contribute to its solution. Great pains should be taken over the paper's summary, which should make use of the whole of the journal's ration of space (one-fifth or one-sixth of the length of the text, as the case may be), and its composition is the severest test of an author's literary skill, particularly in days when "precis writing" has been dropped from the syllabus in most schools for fear of stifling the scholars' creative afflatus.
  23. A summary must be complete in its own limits. It may well start with a statement of the hypothesis under investigation and end with its evaluation.
  24. The number of references cited in the literature list (be always scrupulously careful to observe the house style) should be that which is sufficient and necessary; it may be a symptom of scientmanship to quote references from journals published so long ago that librarians desperate for space have long since had them stashed away in the galleries of disused mines.
  25. ...experiments are very often designed not in such a way as to prove anything to be true - a hopeless endeavor - but rather to refute a "null hypothesis."
  26. Observation is a critical and purposive process; there is a scientific reason for making one observation rather than another. What a scientist observes is always a small part only of the whole domain of possible objects of observation. Experimentation, too, is a critical process, one that discriminates between possibilities and gives direction to further thought.
  27. In real life it is not like this. The truth is not in nature waiting to declare itself, and we cannot know a priori which observations are relevant and which are not; every discovery, every enlargement of the understanding begins as an imaginative preconception of what the truth might be. This imaginative preconception - a "hypothesis" - arises by a process as easy or as difficult to understand as any other creative act of mind; it is a brainwave, an inspired guess, the product of a blaze of insight. It comes, anyway, from within and connot be arrived at by the exercise of any known calculus of discovery.
  28. A hypothesis so permissive as to accommodate any phenomena tells us precisely nothing; the more phenomena it prohibits, the more informative it is.
  29. ... falsification is a logically stronger process than what sometimes people rather recklessly refer to as "proof"...
  30. A scientist is, then a seeker of truth. The truth is that which he reaches out for, the direction toward which his face is turned. Complete certainty is beyond his reach, though, and many questions to which he would like answers lie outside the universe of discourse of natural science.
  31. ... an ambition that a scientist can always achieve: he can try to understand.
  32. Science will dry up only if scientists lose or fail to exercise the power or incentive to imagine what the truth might be.

Friday, September 17, 2010

Heroes

I have been in love with the lives of Ramanujan, Einstein, and recently Michael Faraday.
Ramanujan was an Indian mathematician. He lived for only about thirty odd years, during the years connecting the nineteenth and the twentieth centuries. He was self-taught; mostly by proving the theorems in Carr's book. He was picked up by the famous English mathematician G. H. Hardy and was then known throughout the world. He was not philosophically deep and diverse by the way, his only love which seems to be on the edge of obsessiveness was what is now known as Number Theory. It was a romantic story anyways.
Einstein is known to all, more or less. His is one of the few great names in science. His passion was Physics. He was neither a prodigy nor extraordinary in his academic standing. He did his principal works during the beginning years of the twentieth century. He was a patent clerk then. He studied physics during his poly-technique life being indifferent to any other subject and continued studying during his time as a clerk. During his adolescence, he stumbled upon an idea: what would light look like if one could travel with it side-by-side? Light then should have seemed to be standing still, but nowhere he could find the description of a standing wave. He intermittently thought about the problem and ultimately in 1905 among other three important works proposed his revolutionary solution to the Aether mystery which has been called The Special Theory of Relativity since then. Later he extended this theory to incorporate acceleration and it was known as The General Theory of Relativity. In a sense, he too, was self-taught and worked out of pure passion.
While reading The Grand Design by Hawking, I have known some personal stories of Michael Faraday. He had to quit school at the age of thirteen and worked as a book-binder. The books he had to tend, were his source of learning. He did simple and cheap experiments out of curiosity. Later he was able to discover the influence of magnetic field both on electric charges and on polarized light, hitting upon the clue that all of these: electricity, magnetism, and light; are intimately connected. Besides, he fathered the concept of force field which had been the principal way of explaining how forces act upon bodies at a distance, till now. It is a treat to see how, on an overarching glass plate, the iron fillings get oriented (one or two taps to help them to win over friction) exactly according to the magnetic field extending between north and south poles of a magnet. He lived and worked during the first half of the nineteenth century. He also was self-taught and passion-driven.

Tuesday, September 14, 2010

Programming in Objective C

  • In Objective C, setter and getter methods are automatically generated by the compiler if @property (in the interface file, .h) and @synthesize (in the implementation file, .m) keywords are used.
  • Every instance variable is protected by default.
  • Objective C has the garbage collection mechanism built into it, but not all platforms support it, e.g., iPhone.
  • A variable defined outside a method is not only a global variable but it is an external variable also. To make a variable global within the file, but not externally accessible, the keyword, "static" should be used.
  • #ifdef DEBUG along with #endif is a neat way to contextually switch on or off all the debugging statements embedded inside the source.
  • The default return type of a function is "int" whereas that for a method is "id". Functions are external by default, in order to restrict access to it, the keyword "static" should be used.
  • Foundation framework has NSString class to work with strings. There are immutable and mutable strings. NSNumber is the class for working with numbers. Similarly NSArray is the class to be used when arrays are to be used, and there are mutable and immutable arrays. NSMutableArray is a subclass of NSArray (immutable).
  • Dictionary is a collection of key/value pairs. It can be mutable or immutable. For a mutable dictionary, entries can be dynamically added and removed. Dictionaries can be searched on a particular key, and their contents may be enumerated. The keys must be unique and they can be of any object type, typically strings though. The value associated with a key can be of any object type except for nil.
  • A Set is a collection of unique objects, it can be mutable or immutable. Operations on a Set includes: searching, adding, and removing members (valid for mutable sets); comparing two sets; and finding union and intersection of two sets.
  • NSFileManager lets one to work with files. The available operations are: create a new file, read from an existing file, write data to a file, rename a file, remove (delete) a file, test for the existence of a file, determine the size of the file along with other attributes, make a copy of a file, and test two files for the equality of their contents. Operations such as create, read, or delete can be performed on directories. It is possible to link files, i.e., the same files can exist under different names or even in different directories. To open a file and perform multiple reads and writes on it, NSFileHandle's methods are needed. NSFileHandle enables one to open a file for reading, writing, or updating; seek a specified position within a file; and read or write a specified number of bytes from or to a file. The methods from NSFileHandle can also be applied to devices or sockets.
  • About program 16.1 (Programming in Objective C 3rd Edition): The current working directory while running the program in XCode is build/debug, so the testfile must be there. Methods such as: copyPath: toPath: handler:, movePath: toPath: handler:, fileAttributesAtPath: traverseLink:, moveFileAtPath: handler:, removeFileAtPath: handler:, and stringWithContentsOfFile: have been deprecated; these methods must be replaced with: copyItemAtPath: toPath: error:, moveItemAtPath: toPath: error:, attributesOfItemAtPath: error:, removeItemAtPath: error:, and stringWithContentsOfFile: ecoding: (e.g., NSUTF8StringEncoding) error: methods.
  • For program 16.3: Use createDirectoryAtPath: withIntermediateDirectories: attributes: error: method to create the new directory.
  • Autorelease pools are distinct from built-in garbage collection, therefore, iPhone still has access to autorelease pools even though it doesn't support garbage collection. An object can be attached to the NSAutoReleasePool by sending "autoRelease" message to it, but doing that does not change its reference count. Reference count of an object is automatically handled while adding and removing to or from a collection (e.g., an array); in other cases the programmer has to keep track of the count explicitly in order to ensure that the system will actually free up the memory. Every "retain" message to an object increases the reference count by 1 and every "release" decrements it by 1. When an object is created its reference count is set to 1. If the reference count of an object comes down to 0, the system frees up (calls "deallocate") the memory. All in all, creation of an object must be paired up with a "release", and every intermediate "retain" must be paired up with an intermediate "release".
  • Constant strings have no mechanism for counting references, they can never be released. The value of the "retainCount" of a constant string is the largest possible unsigned integer value, or UINT_MAX (for some systems the largest possible signed int value, INT_MAX), in the standard header file limits.h.
  • Assigning a copy of an object using copy or mutableCopy method to another object reference is called "shallow" copying; it is equivalent to assigning a reference of the first object to the reference of the second one. If the object being copied is a collection of objects, then subsequent changes to the original object or its copy affect both of them, because they both point to the same memory locations. To break the tie between them, "deep" copying is required.
  • In order to have a copy method for your class, copyWithZone: (NSZone*) and/or mutableCopyWithZone: (NSZone*) must be implemented. The "Zone" argument enables you to work with different zones of the total memory for your program which might be useful for programs that allocate a lot of memory. The idea is to optimize allocation by grouping them into zones.
  • Saving an object to a file and reading it back can be performed in two ways: property lists and key-valued coding. NSString, NSDictionary, NSArray, NSDate, NSData, or NSNumber objects can use writeToFile:atomically: method to write contents to a file. In case of writing out a dictionary or an array, this method writes the data in the format of an XML property list (plist). When you create a plist from a dictionary, the keys in the dictionary must all be NSString type objects. The elements of an array or the values in a dictionary can be NSString, NSArray, NSDictionary, NSData, NSDate, and NSNumber type objects. For reading back data from a file, you can use one of these methods as it fits: dictionaryWithContentsOfFile:, arrayWithContentsOfFile:, dataWithContentsOfFile:, and stringWithContentsOfFile: .
  • NSKeyedArchiver, on the other hand, provides more flexibility: one can save and read any type of object with it. Here an archived object acquires a key, and for retrieving the object from the archive this key is used. iPhone does allow it.
  • In order to save and read objects of one's own classes, one has to provide encoder and decoder in those classes. "Deep" copying involves archiving. The idea is to archive from the source object to a NSData or file and then unarchive to the new object.

Monday, September 6, 2010

Interesting libraries in iOS 4.0

iOS 4.0 has two nice libraries: Core Motion Framework and Accelerate Framework. I am interested in developing an Inertial Navigation System on iPhone which will use the phone's accelerometer and gyroscope data and these two libraries seem quite useful.
In Core Motion Framework, an instance of CMDeviceMotion encapsulates measurements of the attitude (phone's orientation with respect to a frame of reference), rotation rate, and acceleration of a device. Core Motion can give user acceleration (free from the acceleration due to gravity). Moreover, CMRotationRate property contains a measurement of gyroscope data whose bias has been removed by Core Motion Algorithms. The identically named property of CMGyroData, on the other hand, gives raw data from the gyroscope.
Accelerate Framework has been provided to facilitate mathematical computations. It contains C APIs for vector and matrix math, digital signal processing, large number handling, and image processing.