Showing posts with label mac-os-x. Show all posts
Showing posts with label mac-os-x. Show all posts

Saturday, October 26, 2013

Moving back to Linux on the Laptop


Over the last 4 years I have owned a Macbook Pro. Couple of weeks ago (couple of hours after posting my previous blog post) the hard disk went click-click (I heard it, I had headphones on at the time) and died. After about 8-10 hours of googling and trying out various troubleshooting advices, I was able to resurrect the machine by formatting my hard disk and reinstalling the operating system from the recovery disk partition written to by OSX 10.8 (Mountain Lion), in the process suffering complete data loss.

I learned later that other users who recently upgraded to Mountain Lion had the same experience - disk crash, fixed by reformat and OSX reinstall. I had upgraded because I wanted to move to Java 1.7 - Snow Leopard, the previous OS, had support only for Java 1.6. I was able to recover all of my "production" Python scripts - stuff I wrote long ago but use day-to-day almost without thinking - thanks to a SugarSync account that only partially works (but it worked "well enough" in this particular case).

I was also able to get back most of my recent code (except the work in progress stuff I hadn't pushed) from various code repositories (GitHub, BitBucket, SourceForge, etc). Most of my EBooks are also available for re-download from my accounts at various publishers (Manning, Packt). I lost almost all my music except some songs which were scattered among various devices - EMusic was kind enough to give me a $50 credit to rebuild (a kernel of) my library.

Of course, the Macbook is about 4 years old and its not as if I expected to own it forever. I did hope that I could use it for about 6 years, given that the average life of my PC based laptops are about 2-3 years and this cost almost 2.5 times as much as one of those. At that point, I had planned on going back to using a Linux based PC laptop. Having heard the sound of the disk drive, I was pretty sure it was an unrecoverable hardware failure, so I went ahead and put this plan into motion. A bit premature, as it turned out, but I guess I have to live with the consequences of my actions...

The one major reason I liked the Macbook was its long battery life - 8 hours new, 4-5 hours now, still more than adequate for my purposes. I found one such system at LinuxCertified.com, a store that installs (and guarantees) Linux on popular laptop hardware. Since I have installed Linux before, I just wanted to know what hardware they use so as to maximize my chances of getting all features working under Linux.

I then took the specs for the Lenovo T530, added a few things - upgrade the CPU to a 4 core i5, increased memory from 2GB to 8GB, added an NVIDIA graphics card to support higher resolution (1600x900), and upgraded to the 9 cell (8 hours) battery instead of the 6 cell default - and placed an order at the Lenovo store. Ended up paying about the same amount (with tax) as the one advertised in LinuxCertified.com.

Once the Macbook came back to life, I had a change of heart and tried to cancel the order but Lenovo's return/cancellation policy is pretty draconian (at least by US standards) - once you hit the submit button, you have effectively bought it. Anyway, I figured that the disk on the Macbook crashed once, its only a matter of time before it dies again, so maybe just makes more sense to put it to pasture working on things like my kids' homework :-).

For the OS on the new Thinkpad, I had a 64 bit Ubuntu 13.04 disk from OSDisc.com purchased earlier for my work desktop. The only issue I faced was that the installer could not recognize the wired network during installation - however, once the machine came up with Ubuntu, it was able to recognize the wired (and wireless) connections. I am able to load Google-Chrome beta (to replace the Firefox default browser), watch and listen to lecture videos (for Coursera and other MOOC classes I am taking - I mention it because I can't get sound to work on my desktop). I haven't begun to use it fully (I am still typing this post on my Macbook), but all the software I need works fine on it (so far at least).

Looks wise, of course, this is a huge downgrade - almost like swapping a sports car for an SUV (the real kind) - the Macbook Pro is slim, sleek and sliver while the Thinkpad is thick, chunky and black. With respect to the OS though, I have worked with Unix long enough so Linux design choices just seem more logical, and I have always found the Mac OSX /Application, /Library, /System, etc trees somewhat strange and non-intuitive. Plus there is just more good free stuff on Linux than on OSX, so I am guessing my overall experience with this change would be positive.

So anyway, back to using Linux for everything again :-).

Sunday, January 20, 2013

Assembling a Python Machine Learning Toolkit


I had been meaning to read Peter Harrington's book Machine Learning In Action (MLIA) for a while now, and I finally finished reading it earlier this week (my review on Amazon is here). The book provides Python implementations of 8 of the 10 Top Algorithms in Data Mining listed in this paper (PDF). The math package used in the examples is Numpy, and the charts are built using Matplotlib.

In the past, the little ML work I have done has been in Java, because that was the language and ecosystem I knew best. However, given the experimental, iterative nature of ML work, its probably not the most ideal language to use. However, there are lots of options when it comes to languages for ML - over the last year, I have learned Octave (open-source version of MATLAB) for the Coursera Machine Learning class and R for the Coursera Statistics One and Computing for Data Analysis classes (still doing the second one). But because I know Python already, Python/Numpy looks easier to use than Octave, and Python/Matplotlib looks as simple as using R graphics. There is also the pandas package which provides R-like features, although I haven't used it yet.

Looking around on the net, I find that many other people have reached similar conclusions - ie, that Python seems to be the way to go for initial prototyping work in ML. I wanted to set up a small toolbox of Python libraries that will allow me to do this also. I settled on an initial list of packages based on the Scipy Superpack, but since I am still on Mac OS (Snow Leopard) I could not use the script from there. There were some issues I had to work through to make this to work, so I document this here, so if you are in the same situation this may help you.

Unlike the Scipy Superpack, which seems to prefer versions that are often the bleeding edge development versions, I decided to stick to the latest stable release versions for each of the libraries. Here they are:

  • numpy version 1.6.2: downloaded source tarball, built with "python setup.py build; sudo python setup.py install". Prior to this I had version 1.6.1 installed which gave me runtime problems when I tried to import pandas (see below), since pandas requires numpy >= 1.6.2. So I had to manually delete the numpy directories from my /Library/Python/2.6/site-packages directory before installing this version.
  • scipy version 0.11.0: downloaded source tarball, built with "python setup.py build; sudo python setup.py install".
  • matplotlib version 1.2.0: downloaded source tarball, built with "python setup.py build; sudo python setup.py install".
  • scikit_learn version 0.12: downloaded source tarball, built with "python setup.py build; sudo python setup.py install".
  • python-dateutil version 2.1: used "sudo pip install python-dateutil" to install. This is an "improved" version of the base dateutils package, and is needed by pandas. However, because of the way its installed you will have to manually delete the original dateutils package first (see my comment on this Stack Overflow thread for details).
  • pandas version 0.10: downloaded source tarball, built with "python setup.py build; sudo python setup.py install". This will automatically pull in a newer version of the pytz library as well.
  • cython version 0.17.4: downloaded source tarball, built with "python setup.py build; sudo python setup.py install". This is needed to build statsmodels, see this issue for details.
  • statsmodels version 0.4.0: downloaded source tarball, built with "python setup.py build; sudo python setup.py install".

You will notice that I prefer to download the source tarballs and build them locally, rather than use the automatic download and install options of easy_install. This is because this whole exercise took me two days. The first day I used the automatic download option and hit all sorts of version incompatibility problems, mainly caused by the older versions of numpy and python-dateutils as I described above. Specifically, I was seeing that pandas would automatically pull in the newer version of numpy, but then would build against the older version since that was on the PYTHONPATH. I guess once the problems were identified and dealt with, I could have used either version to build and install, but this is what ultimately worked for me.

During the time, in frustration, I also considered the Enthought Python Distribution Free Version (EPDfree) and even downloaded and installed it, but uninstalled it again because the Mac version is 32 bit (so limited to small data sizes) and I found the basic paid version ($200/year) too expensive. YMMV, of course. Another option with friendlier terms is Sage, but it seems to be much bigger than just a scientific Python distribution like EPD, so perhaps overkill for me at this stage.

Anyway, thanks to the examples in the MLIA book, I know enough to use numpy and matplotlib with Python right away, and I guess I will pick up the other stuff as I use them.

Update 2013-04-06: Few days ago I heard of the Anaconda distribution from Continuum Analytics via one of the mailing lists I subscribe to. They offer free 64 and 32 bit versions of Python 2.7 or 3.3 distributions geared towards scientific (and NLP/ML) use. Today I took the plunge and installed their 2.7 distribution. I was procrastinating and putting off the upgrade to Python 2.7 because of the number of packages I would have to reinstall, but the install was a snap, took less than 10 minutes to do this.

Friday, December 04, 2009

A Unison replacement with rsync

Before Unison, I used a simple rsync script to synchronize code between my laptop and desktop. If you are interested, it is described here. The script was a simple Python wrapper over the Unix rsync command, just so I didn't have to remember all the switches.

However, the script was overly simplistic, and required some discipline to ensure that files did not get clobbered during syncing. For one, you had to start with a known "clean" state, so anytime you wanted to make a change on your laptop, you would have to download the latest code from the desktop first. Once your changes were done, you would have to remember to upload your changes in.

Having used Unison for a while now, I have gotten used to it telling me that I am about to shoot myself in the foot, rather than having to figure it out for myself. So it was something of a setback when I could not get Unison to work on my Macbook Pro (syncing against a CentOS 5.3 based desktop), but I could not go back to using the old script anymore. I decided to add some smarts to the old program so it behaved similar to Unison.

Challenges

Unison does a bidirectional sync each time it is called. One can simulate this (sort of) using a pair of rsync calls (an upsync and a downsync) using the --update switch so newer files from each side are propagated across to the other.

Relying on the file timestamps has a few problems, though. First we assume that the clocks on both machines are close enough, an assumption which is probably mostly true since most modern machines run ntpd.

Second (and perhaps more importantly), there is a chance of one of your local changes being clobbered if there is a newer version of the same file on the remote machine. This can happen in my case as the files on my remote machine (my desktop) is under CVS control, so if someone just checked in a change to the file I synced earlier and changed, a "cvs update" on the remote machine before doing the next sync will overwrite the changes on the version of the file on my laptop.

There is also the reverse case where your local changes can propagate over a remote change that was previously committed, but doing a "cvs update" before a "cvs commit" should detect that, so I am not worried so much about handling that case.

Script

To handle the local file clobbering problem, in addition to simulating the bidirectional sync with a pair of rsync calls, I also build a snapshot of the files after each sync - the snapshot is really a pickled dictionary (serialized Map for you Java guys) of the MD5 checksums for each files after the sync. On the next sync call, I use the snapshot to find which files have changed locally. Then I do a downsync in --dry-run mode and remove from the downsync file list the files that have changed locally. This prevents files that have changed locally from being overwritten by any remote changes. I then do an upsync in --dry-run mode, and remove from the changed list those files that appear in the upsync list. The remaining files are essentially "conflicts" which the program does not know what to do with, and should defer to my decision (whether to upsync, downsync or ignore).

The user-interface (i.e., the configuration files and console output) are influenced heavily by Unison's, since I wanted to reuse my profiles as much as possible. The configuration files are stored in a .sync_conf directory under the home directory, as named files with key-value pair properties.

A sample script is shown below. It identifies the local and remote root directories for this profile, and specifies the file patterns that should be excluded from the sync.

1
2
3
local=/Users/sujit/test
remote=spal@localhost:/home/spal/test
excludes=.*,target/*,bin/*

If you look at the ~/.sync_conf directory, you will also find a .dat file for each profile after the first sync is done - this is the snapshot. If you delete the snapshot, then you should make sure that you don't have any outstanding local changes (make copies) and rerun the sync.

As you can figure out from the spal@localhost prefix on the remote key value, I use a local tunnel on my laptop to connect to my desktop over ssh. Since I have to do multiple rsync calls per sync, I needed to set up passwordless ssh to avoid having to type the password in multiple times.

Here is the code - like its previous incarnation, it is written in Python. The script is heavily documented, and I have already briefly described the algorithm above, so it should not be too hard to understand.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#!/usr/bin/python
# Does a somewhat brittle bi-directional sync. By brittle, I mean that
# this is tailored to my particular use-case rather than a general one.
# My use case is a laptop being sync'd to a desktop at work. The code
# on the desktop is under CVS control (so I can potentially recover
# clobbered files). The script tries to minimize the chance of clobbering
# files on the laptop.
#
import os
import sys
import getopt
import os.path
import cPickle
import hashlib

# CONFIG
CONF_DIR = "/Users/sujit/.sync_conf"
RSYNC_RSH = "ssh -p 9922"
# CONFIG

def usage():
  """
  Print usage information to the console and exits.
  """
  print "Usage: sync.py profile"
  print "       sync.py --list|--help"
  print "--list|-l: list available profiles"
  print "--help|-h: print this message"
  print "profile: name of profile.prf file to use"
  sys.exit(-1)

def list_profiles():
  """ 
  Print list of available profiles to the console and exits to
  the OS. Profiles are stored as .prf files in CONF_DIR.
  """
  print "Available Profiles:"
  for file in os.listdir(CONF_DIR):
    if (file.endswith(".prf")):
      print " ", file
  sys.exit(-1)

def abs_path(dirname, filename):
  """
  Convenience method to construct an absolute path for the given
  directory and file. Similar to the Java File constructor, except
  that this will not resolve properly in Windows systems (I think).
  @param dirname - the name of the directory
  @param filename - the name of the file.
  @return the absolute pathname for the file.
  """
  return os.sep.join([dirname, filename])

def get_configuration(profile):
  """
  Read the configuration off the .prf file into a dictionary
  for programmatic access.
  @param profile - the name of the sync profile.
  @return the dictionary containing configuration key-value pairs.
  """
  conf = {}
  profile_file = open(abs_path(CONF_DIR, profile + ".prf"), 'rb')
  for line in profile_file.readlines():
    (key, value) = line[:-1].split("=")
    conf[key] = value
  profile_file.close()
  return conf

def compute_file_md5_hash(file):
  """
  Computes the MD5 Hash of the named file. To avoid out of memory
  for large files, we read in the file in chunks of 1024 bytes each
  (any multiple of 128 bytes should work fine, since that is MD5's
  internal chunk size) and build up the md5 object.
  @param file - the name of the file to compute MD5 hash of.
  @return the MD5 digest of the file.
  """
  md5 = hashlib.md5()
  f = open(file, 'rb')
  while (True):
    chunk = f.read(1024)
    if (chunk == ""):
      break
    md5.update(chunk)
  f.close()
  return md5.digest()

def compute_md5_hashes(snapshot, dirname, fnames):
  """
  Visit named file and compute its MD5 hash, and store it into the
  snapshot dictionary.
  @param snapshot - a reference to the dictionary.
  @param dirname - the name of the current directory.
  @param fnames - the names of the files in the directory.
  """
  for fname in fnames:
    absname = abs_path(dirname, fname)
    if os.path.isfile(absname):
      snapshot[absname] = compute_file_md5_hash(absname)

def save_snapshot(profile, src):
  """
  Recursively traverse the directory tree rooted in src and compute
  the MD5 hash for each file. Write out the dictionary in pickled
  form to the snapshot (.dat) file.
  @param profile - the name of the sync profile.
  @param src - the local directory root.
  """
  snapshot = {}
  os.path.walk(src, compute_md5_hashes, snapshot)
  snapshot_file = open(abs_path(CONF_DIR, profile + ".dat"), 'wb')
  cPickle.dump(snapshot, snapshot_file, protocol=1)
  snapshot_file.close()

def load_snapshot(profile):
  """
  Loads the snapshot dictionary containing full path names of source
  files with their MD5 hash values from the pickled file.
  @param profile - the name of the sync profile.
  @return the dictionary of path name to MD5 hashes.
  """
  snapshot_file = open(abs_path(CONF_DIR, profile + ".dat"), 'rb')
  snapshot = cPickle.load(snapshot_file)
  snapshot_file.close()
  return snapshot

def check_if_changed(args, dirname, fnames):
  """
  Visits each file and computes the MD5 checksum, then compares it
  with the checksum available in the snapshot. If no checksum exists
  in the snapshot, it is considered to be a new file (ie, created
  since the last sync was done).
  @param args - a tuple containing the snapshot dictionary and the
             set of changed files so far.
  @param dirname - the name of the current directory.
  @param fnames - the names of the files in the directory.
  """
  (snapshot, changed_files) = args
  for fname in fnames:
    absname = abs_path(dirname, fname)
    try:
      orig_md5 = snapshot[absname]
      new_md5 = compute_file_md5_hash(absname)
      if (orig_md5 != new_md5):
        changed_files.add(absname)
    except KeyError:
      continue
    except TypeError:
      continue

def get_changed_since_sync(profile, src):
  """
  Computes a set of local file names which changed since the last time
  the sync was run. This is to prevent clobbering of local files by
  remote files containing a newer timestamp. The method walks the
  directory tree rooted in src and computes the checksum of each file
  in it, comparing it to the checksum from the snapshot. If the checksum
  differs, then it is written to the changed_files set.
  @param profile - the name of the sync profile.
  @param src - the local directory root.
  @return - a (possibly empty) set of changed file names, relative to
            the src directory.
  """
  snapshot = load_snapshot(profile)
  changed_files = set()
  os.path.walk(src, check_if_changed, (snapshot, changed_files))
  return map(lambda x: x.replace(src + os.sep, ""), changed_files)

def run_rsync_command(profile, src, dest, conf, force, files=[]):
  """ 
  Generate the rsync command for the OS to run based on input parameters.
  The output of the OS command is filtered to extract the files that
  are affected and a list of file names is returned.
  @param profile - the name of the sync profile.
  @param src - the local root.
  @param dest - the remote root.
  @param conf - a reference to the configuration dictionary.
  @param force - if set to false, rsync will be run in --dry-run mode,
                 ie, no files will be transferred.
  @param files - if provided, only the files in the list will be synced.
  @return a list of files affected.
  """
  # set up the basic command (we just add things to it for different
  # cases)
  command = " ".join(["rsync",
      "" if force else "--dry-run",
      "--cvs-exclude",
      " ".join(map(lambda x: "--exclude=" + x, conf["excludes"].split(","))),
      "--delete",
      "--update",
      "--compress",
      "-rave",
      "'" + RSYNC_RSH + "'"
  ])
  from_file_name = ""
  if (len(files) > 0):
    # create a text file and use --files-from parameter to only
    # sync files in the files-from file
    from_file_name = abs_path(CONF_DIR, profile + ".list")
    filelist = open(from_file_name, 'wb')
    for file in files:
      filelist.write(file.replace(conf["local"] + os.sep, "") + os.linesep)
    filelist.flush()
    filelist.close()
    command = " ".join([command,
      "--files-from=" + from_file_name, src + "/", dest])
  else:
    command = " ".join([command, src + "/", dest])
  # run the command
  result = []
  for line in os.popen(command):
    if (len(line.strip()) == 0 or
        line.find("file list") > -1 or
        line.find("total size") > -1 or
        (line.find("sent") > -1 and line.find("received") > -1)):
       continue
    result.append(line[:-1])
  if (len(from_file_name) > 0 and os.path.exists(from_file_name)):
    os.remove(from_file_name)
  return result

def bidirectional_sync(profile, src, dest, conf):
  """
  The algorithm consists of multiple rsync commands. Inline comments
  describe this in more detail. These checks are meant to prevent
  clobbering of local changes. The set of files that do not have a
  conflict (in either direction) are presented to the user for
  approval and two rsyncs are done. Then the conflicts are presented
  one by one. In most cases, the user should choose [u]psync.
  @param profile - the name of the sync profile. At the end of the
  sync operation, a snapshot of the current sync is stored.
  @param src - the local root.
  @param dest - the remote root.
  @param conf - the sync configuration.
  """
  # first find the local changes since the last sync. If
  # there is no .dat file, then ignore this step
  changed_since_sync = set()
  if (os.path.exists(abs_path(CONF_DIR, profile + ".dat"))):
    changed_since_sync = get_changed_since_sync(profile, src)
  # then do a dry-run of a downsync to get remote files to sync
  remote_changes = run_rsync_command(profile, dest, src, conf, False)
  # downsync only the files which are NOT in the changed_since_sync list.
  # To do this, we partition the remote_changes list into two sets
  non_conflicts, conflicts = [], []
  for remote_change in remote_changes:
    if (remote_change in changed_since_sync):
      conflicts.append(remote_change)
    else:
      non_conflicts.append(remote_change)
  remote_changes = []
  remote_changes.extend(non_conflicts)
  # do a dry-run of the upsync to get local files to upload
  local_changes = run_rsync_command(profile, src, dest, conf, False)
  # remove from conflicts that appear in changed_since_sync
  for local_change in local_changes:
    if (local_change in conflicts):
      conflicts.remove(local_change)
  # merge remote_ok and changed_since_sync, with the appropriate signage
  for remote_change in remote_changes:
    print "L<--R", remote_change
  for local_change in local_changes:
    print "L-->R", local_change
  if (len(remote_changes) + len(local_changes) > 0):
    yorn = raw_input("Is this OK [y/n/q]? ")
    if (yorn == 'y' or yorn == 'Y'):
      # do the rsync
      run_rsync_command(profile, src, dest, conf, True, local_changes)
      run_rsync_command(profile, dest, src, conf, True, remote_changes)
    elif (yorn == "q" or yorn == "Q" or yorn == "n" or yorn == "N"):
      return
  # lastly, take care of the conflicts on a per-file basis
  for conflict in conflicts:
    conflict_list = []
    action = raw_input("L<X>R " + conflict + " [u/d/n/q]? ")
    if (action == "u" or action == "U"):
      conflict_list.append(conflict)
      run_rsync_command(profile, src, dest, conf, True, conflict_list)
    elif (action == 'd' or action == 'D'):
      conflict_list.append(conflict)
      run_rsync_command(profile, dest, src, conf, True, conflict_list)
    elif (action == 'n' or action == 'N'):
      continue
    else:
      continue
  save_snapshot(profile, src)

def main():
  """
  This is how we are called. See usage() or call the script with the
  --help option for more information.
  """
  if (len(sys.argv) == 1):
    usage()
  (opts, args) = getopt.getopt(sys.argv[1:], "lh", ["list", "help"])
  for option, argval in opts:
    if (option in ("-h", "--help")):
      usage()
    elif (option in ("-l", "--list")):
      list_profiles()
  profile = sys.argv[1]
  # read the profile file
  conf = get_configuration(profile)
  # do the bidirectional sync
  bidirectional_sync(profile, conf["local"], conf["remote"], conf)

if (__name__ == "__main__"):
  main()

Usage

To get the list of profiles already available, type sync.py --list. To add or edit a profile, you have to go to the ~/.sync_conf directory and create or edit the profiles .prf file. This is actually simpler (copy an existing .prf and modify it) than doing it via a GUI.

A sample run is shown below. As you can see, it correctly detects changes on both systems. I have also tested the situation where a remote change is newer than a corresponding local change, and it successfully detects the conflict and allows me to upsync or downsync as I see fit.

1
2
3
4
5
6
7
sujit@cyclone:~$ sync.py test
L<--R ./
L<--R tunnel-indexer.prf
L-->R ./
L-->R tunnel-util.prf
Is this OK [y/n/q]? y
sujit@cyclone:~$

The script is obviously not a Unison replacement, but it works for me. I probably would start using Unison again if it became available, but until it is, this script should suffice.