Sunday, May 30, 2010

research made simple with zotero

If you are into study/research of any kind (academic/non-academic) which involves reading up things and keeping track of them then you are in for a great productivity boost.  This will help if you are reading books/news/articles/wikipedia/journals or any such sort of thing. The too I'm talking about is zotero
With zotero you can save proper bibliographic references of lots of material you see on the internet and manage/search/cite them in various forms. Its really difficult to describe all the wonderful things zotero can do for your research, so it'll be really good for you if you watch the screencast http://www.zotero.org/support/screencast_tutorials/zotero_tour

Some features you'll find helpful:
Collect:

  • Single click saving of references. For example single click on any sciencedirect article, if you have subscribed (as in my college), a single click will save all information about the article, including the pdf (with well thought name instead of fulltext.pdf) if its available.
  • To enable saving pdf select in Zotero Preferences->General tab -> automatically attach associated pdfs and other files when saving.
  • In search tab in preferences, you may also want to enable indexing of pdfs if you need.
  • Clicking on sites with references to lots of articles (wikipedia references, cited by in Scopus etc), you can easily select all the references you need to save
Manage:
  • You can search all your saved articles, add notes, tags etc
  • You can group all articles in collections based on topic
  • You can create saved searches based on various criteria
Cite:
  • To cite an article(s) simply select them and right click to 'create bibliography from selectd articles' and choose a format style from the many available (including all popular journals) and you are done
  • If you are using bibtex to manage bibliographies for your article then select the articles and right click to do 'export selected items' and select bibtex format
  • Zotero plugins are available for Openoffice and MS Office too, so you can easily insert the references in your articles, without the pain of collecting anf formatting
Share:
  • If you work in team then this is a really wonderful feature. Create a simple login on the zotero server (you can also use openid)
  • In zotero preferences->sync tab enter your zotero login details and enable sync my library and group library.
  • All synced items (including attached pdfs) are available on the internet anywhere without even installing zotero addon. You just need to login to zotero and see your collection. This is very useful if your college has access to some journals but when you are somewhere else in a conference and you need to check and article. 100 MB space is freely available and you can buy even more.
  • 'My library' is your personal collection. Group libraries are shared collections, which can be shared with other people you are working with.
So what are you waiting for, install it now. If you did not install it yet, then you need to watch the screencast http://www.zotero.org/support/screencast_tutorials/zotero_tour now

    Saturday, May 29, 2010

    numpy array performance / divide and conquer considered harmful

    This is again a post about python code speed, the data and inference are more than a few months old but still valid.
    Here's a spreadsheet showing speed of array math operations (+, -, *, /) between numpy arrays and python lists.
    Check this spreadsheet to see the timings of various operations
    https://spreadsheets.google.com/ccc?key=0AomYDYyBBNkkdHAtMkdHMF9TZ29lMmZQV3UwYkxWNFE&hl=en

    The operations I considered for comparison were:

    • x+0.1
    • x-0.1
    • x*0.1
    • x/0.1
    • x*(1/0.1)
    • x+y
    • x-y
    • x*y
    • x/y
    • [p+yp[j] for j,p in enumerate(xp)]
    • [xp[j]+yp[j] for j in xrange(i)]
    where x and y are numpy arrays, xp and yp are python lists, all of size N which is varied for the comparison.
    The raw timings data is available here:
      https://spreadsheets.google.com/pub?key=0AomYDYyBBNkkdHAtMkdHMF9TZ29lMmZQV3UwYkxWNFE&hl=en&output=html

      See the timings plot yourself
      Conclusion:
      • Use numpy arrays for size > 10
      • Avoid division as much as you can to improve the speed of your numerical codes
      • Instead of x/0.1 do x*(1/0.1) . This itself causes large speedup as N is increased.
      • x/0.1 and x/y take almost the same time
      • +, -, * take almost same time, / takes much more time, and its expense increases as N is increased.
      • Once again, do not divide.
      • The same thing is valid in cython code also. Avoid division even in cython code, and even if you are using double instead of numpy arrays (buffer). Rewrite expressions to minimize the usage of division operator.

      Wednesday, May 26, 2010

      cython timings test

      The TASK : To optimize cython functions

      Detailed: functions which depend on a once initialized attribute value

      This often comes handy in many cases, for example to write a Laplacian function of a scalar field in spherical/axisymmetric coordinate system, you would need three independent cases for 1,2,3 dimensions for performance purposes and if u do not write all functions as general 3D functions.


      The test CODE : test_kernel.pyx


      cdef class Kernel:
          cdef int dim
          cdef double (*func)(Kernel,double)
          def __init__(self, dim=1):
              self.dim = dim
              if dim == 1:
                  self.func = self.func1
              elif dim == 2:
                  self.func = self.func2
        
          cdef double func1(self, double x):
              return 1+x
        
          cdef double func2(self, double x):
              return 2+x
        
          cdef double c_func(self, double x):
              '''this is only to make function signature compatible with func1 and func2'''
              return self.func(self, x)
        
          def p_func(self, double x):
              return self.func(self, x)
        
          cpdef double py_func(self, double x):
              return self.func(self, x)
        
          cpdef double py_c_func(self, double x):
              return self.c_func(x)
        
          def py_func1(self, x):
              return self.func1(x)
        
          def py_func2(self, x):
              return self.func2(x)
        
          cdef double func_common(self, double x):
              cdef int dim = self.dim
              if dim == 1:
                  return 10+x
              elif dim == 2:
                  return 20+x
        
          def py_func_c_common(self, x):
              return self.func_common(x)
        
          cpdef double py_func_common(self, double x):
              cdef int dim = self.dim
              if dim == 1:
                  return 10+x
              elif dim == 2:
                  return 20+x

      Compilation command:
          cython -a test_kernel.pyx;
          gcc <optimization-flag> -shared -fPIC test_kernel.c -lpython2.6 -I /usr/include/python2.6/ -o test_kernel.so
      where optimization flag is either empty or "-O2" or "-O3"

      Cython optimization
      Tip 1:
      Type (cdef) as many variables as you can. You also need to type the locals in each function. Try to try to use C data types wherever possible.
      Tip 2:
      use:
          cython -a file.pyx
      command to generate a html file which shows lines which cause expensive python functions to be called. Clicking on a line shows the corresponding C code generated, highlighting expensive calls in shades of red. Try to eliminate as many such calls as you can.

      The TEST :

      time_kernel.py

      import timeit

      def time(s):
          '''returns time in microseconds'''
          t = 1e6*timeit.timeit(s,'import test_kernel;k1=test_kernel.Kernel(1);k2=test_kernel.Kernel(2);',number=1000000)/1000000.
          print s, t
          return t

      time('k1.p_func(0)')
      time('k1.py_func(0)')
      time('k1.py_func1(0)')
      time('k1.py_c_func(0)')
      time('k1.py_func_c_common(0)')
      time('k1.py_func_common(0)')

      time('k2.p_func(0)')
      time('k2.py_func(0)')
      time('k2.py_func2(0)')
      time('k2.py_c_func(0)')
      time('k2.py_func_c_common(0)')
      time('k2.py_func_common(0)')

      Timings :



      functiontime (μs)(ns)

      Optimization flag ->None-O2-O3sum(k1+k2)/2penalty
      1k1.p_func(0)0.201780.183210.180350.188450.193680.0000
      2k1.py_func(0)0.232240.185990.183930.200720.195411.7345
      3k1.py_func1(0)0.214770.189910.192520.199070.198024.3456
      4k1.py_c_func(0)0.233950.191960.192430.206110.197613.9311
      5k1.py_func_c_common(0)0.195660.184580.190620.190290.197673.9960
      6k1.py_func_common(0)0.219810.187070.189840.198910.195101.4237
      7k2.p_func(0)0.204480.183880.181940.19010

      8k2.py_func(0)0.217980.188590.184370.19698

      9k2.py_func2(0)0.204130.181240.181940.18910

      10k2.py_c_func(0)0.231140.191660.192380.20506

      11k2.py_func_c_common(0)0.198600.187830.187450.19129

      12k2.py_func_common(0)0.216090.187470.186400.19666


      Average0.215600.186810.187030.19648


      Result :

      The best is to write separate C function and a python accessor function.

      task
      functionpenalty cost (ns)
      C function + python accessor : base casep_func
      cpdef instead of defpy_func1.7345
      calling a cdef class method instead of a function pointer attributepy_func1,py_func24.3456
      one extra c function callpy_c_func3.9311
      (def + cdef) instead of (cpdef)py_func_c_common-py_func_common2.5723
      One C comparison vs one C function callpy_func_common1.4237

      Conclusion :

      As can be clearly seen that the results are clearly inconclusive :)
      This was a small test carried on my laptop with no controlled environment. Also thought the results seemed close to repeatable, nevertheless many trials should be conduction and each value should have a standard deviation also to check the repeatability. However one clear conclusion is do not forget to add optimization flags. Setuptools already does that for you.
      Also using a function pointer is not so bad after all. It would become more advantageous in case of more number of comparisons.
      Cython provides great speedups (who didn't know that :) ). The pure python version of py_func_common took 0.408μs for dim=1 and 0.518μs for dim=2
      These results are purely from python point of view. The effect of cdef/cpdef should also be considered in c/cython code which calls these functions.

      CAVEAT:

      I am no optimization expert. I have done this out of out of sheer boredom :)
      If anyone wants to verify, you are welcome
      Any information content is purely coincindental

      Tuesday, April 27, 2010

      Tracing python programs

      Coming with the easier python debugging enabled by the new gdb with python hooks is another awesome python feature coming in the new Fedora "Goddard" 13 release. That is tracing of python processes and their function calls. This feature is developed on top of systemtap, the linux analogue of Sun's awesome Dtrace system tracer.
      So what does it mean? For the uninitiated, it implements hooks (tracepoints) in the python main shared libraries (libpython.so and libpython3.so) so that systemtap can trace whenever a python function is entered/exited in any python process on the system. This means you can anytime check a python process to see which functions are being called and how many times etc. This has really cool uses. More information about this feature is available at https://fedoraproject.org/wiki/Features/SystemtapStaticProbes#Python_2

      Just to illustrate the use try the following examples (from the above link)
      First install python-debuginfo. Now add yourself to stapdev and stapusr groups or run the following command as root:
          $ stap /usr/share/doc/python3-libs-3.1.2/pyfuntop.stp
      This will display a top like output on the terminal showing the python functions which are called by all running processes and the number of times its being called. Its fun to watch, just run a python program and check all the functions being called :)
      Here's a sample output from my laptop

      PID                                                                         FILENAME   LINE                       FUNCTION  CALLS
       15479                                 /usr/lib/python2.6/site-packages/yum/packages.py    261                         verCMP  15768
       15479                                 /usr/lib/python2.6/site-packages/yum/packages.py    270                        __cmp__  15767
       15479                             /usr/lib/python2.6/site-packages/rpmUtils/updates.py    129                   returnNewest   9045
       15479                           /usr/lib/python2.6/site-packages/rpmUtils/miscutils.py     36                     compareEVR   1191
       15479                                 /usr/lib/python2.6/site-packages/yum/packages.py     48                   comparePoEVR    578
       15479                                 /usr/lib/python2.6/site-packages/yum/packages.py    296                          verEQ    556
       15479                                 /usr/lib/python2.6/site-packages/yum/packages.py     55                 comparePoEVREQ    556
       15479                                 /usr/lib/python2.6/site-packages/yum/__init__.py    778                             2
       15479                                 /usr/lib/python2.6/site-packages/yum/__init__.py    206                     _getConfig      2
       15479                                   /usr/lib/python2.6/site-packages/yum/config.py     69                        __get__      2
       15479                                         /usr/lib64/python2.6/logging/__init__.py   1026                          debug      1
       15479                                         /usr/lib64/python2.6/logging/__init__.py   1236                   isEnabledFor      1
       15479                                         /usr/lib64/python2.6/logging/__init__.py   1222              getEffectiveLevel      1
       15479                             /usr/lib/python2.6/site-packages/rpmUtils/updates.py    272                      doUpdates      1
      
      This shows the functions called during a 1 second interval (the script updates the display every second) by checking of available updates by packagekit.
      Another system script displays the python function call hierarchy of any program you run. Try this by running
          $ stap -v /usr/share/doc/python-libs-2.6.4/systemtap-example.stp -c python
      Now you will get a python terminal after a long hierarchy of function calls. Here you can see all python functions called for each line you enter on the python terminal. Its not as much fun, but useful if you want to check where all those extra unneeded function calls are being made.
      Read a short writeup from the developer of these features at http://fedoraproject.org/wiki/Python_in_Fedora_13 and also check http://press.redhat.com/2010/04/27/fedora-13-spotlight-feature-exploring-new-frontiers-of-python-development/

      Saturday, April 24, 2010

      hard disk speed and os partition

      I knew this for quite some time, but now i have experimental evidence also that installing your os and keeping your home partition near the front of the hard disk results in more responsive computer. This is because conventional hard disks are rotary which means the read data faster from the outer sectors than from the inner sectors. So the next time you install your os keep it near the front partition.
      Here's a screenshot of the palimpsest utility (Applications -> system tools -> disk utility in fedora, package gnome-disk-utility) showing the read only benchmark speed and access (seek) times. As you can see the initial part has nearly double the speed than the last part. Seek times don't show any such obvious relation.

      Friday, April 23, 2010

      Easier cython/python/c debugging with new GDB

      We all know how debugging is an dreaded integral part of every programmer's work. It can also be fun sometimes depending on the time to deadline, complexity of the bug and time already spent.
      So if anyone is still left who does assignments or other programs without debugging (using print statements etc) then please consider learning it. Else you are simply increasing your work and frustration.
      For debugging in any programming language my advise would be to use the eclipse debugger gui which provides all the standard features present in any debugger and integration with java, c/c++, python and a host of other languages.

      This post was not about plain debugging. Its about the new features in GDB 7 (the GNU debugger) which enables writing pretty printers in python. More information can be had from the net. However it means a much easier debugging experience with cython. The good folks at Fedora have written some cool scripts to integration python scripting capability of gdb to enable easier cython debugging.
      Check out the awesomeness at https://fedoraproject.org/wiki/Features/EasierPythonDebugging
      In short now you can do the following easily with the new gdb

      • automatically display python frame information in PyEval_EvalFrameEx in gdb backtraces, including in ABRT:
        • python source file, line number, and function names
        • values of locals, if available
      • name of function for wrapped C functions
       This gonna make my life easier, especially since my DD project is in cyton/python.

      Also not to forget the uber cool features it could enable not only for python developers but for all. As an example check out the blog at http://labs.trolltech.com/blogs/2010/04/22/peek-and-poke-vol-3/

      Thursday, March 4, 2010

      funny slashdot comment about windows

      Are you saying that this linux can run on a computer without windows underneath it, at all ? As in, without a boot disk, without any drivers, and without any services ? That sounds preposterous to me. If it were true (and I doubt it), then companies would be selling computers without a windows. This clearly is not happening, so there must be some error in your calculations. I hope you realise that windows is more than just Office ? Its a whole system that runs the computer from start to finish, and that is a very difficult thing to acheive. A lot of people dont realise this. Microsoft just spent $9 billion and many years to create Vista, so it does not sound reasonable that some new alternative could just snap into existence overnight like that. It would take billions of dollars and a massive effort to achieve. IBM tried, and spent a huge amount of money developing OS/2 but could never keep up with Windows. Apple tried to create their own system for years, but finally gave up recently and moved to Intel and Microsoft. Its just not possible that a freeware like the Linux could be extended to the point where it runs the entire computer fron start to finish, without using some of the more critical parts of windows. Not possible. I think you need to re-examine your assumptions.

      Saturday, February 27, 2010

      Increasing coursework

       I just realized that the coursework in my college increases at a very fast pace as the years go by.
      Here's the proof:
      my directory sizes of the data in each year's courseware. 4th years data is as yet incomplete as mid-terms are just over and half a sem is still remaining. (y* are the year's coursework directories)

      [pankaj@localhost courseware]$ du -sh y*
      158M    y1
      322M    y2
      1.7G    y3
      2.2G    y4

      UPDATE: The score is 6.9 GB for y4 at the end of the year, most of it is a single course, with hundreds of MB of datasets and simulation videos

      real programmers

      i just found a funny old article about programming. I'm glad i'm not a 'real' programmer (just for your information, i'm a complex programmer)
      check the link http://www.pbm.com/~lindahl/real.programmers.html

      Tuesday, February 23, 2010

      my academic schedule

      Now you know how stupid my lectures are scheduled.
      Legend:
      Blue : Moodle calendar (academic assignments, submissions etc)
      Green : Indian holidays
      Yellow : My edited calendar for lecture schedules and other academic things :)

      Thursday, November 26, 2009

      Installing Salome platfrom on Fedora (12 x86_64)

      The salome platform is a good open source platform for FEA/CFD etc. It includes a good preprocessor to easily create geometries, mesh them in a variety of ways and also import/export various types of formats. I generally use it with OpenFOAM, which is a FVM library and collection of programs to solve various types of flows and also structures and other problems.
      Check them out at http://www.salome-platform.org/ and http://www.openfoam.com/features/
      So the main thing i'm writing this is as a reminder to me and to save hoursof other people's time who try installing salome-platform on any of the modern linux distros.

      Step 1 > Download the package. If the package is not available for you distro choose debian or mandriva whichever is closer to your distro (both work in case of fedora)
      Step 2 > Extract (tar -xvf filename) to a convenient location (your home or anywhere else doesn't matter. u can delete this later)
      Step 3 > Change the file config_files/gcc-common.sh to match your installation of gcc. I replaced gcc_root="/usr/bin".
      Step 4 > Run ./runInstall. Choose appropriate options in the gui and finish the wizard.
      Step 5 > To run salome type:
      $ . KERNEL_<version>/salome.sh
      $ runSalome
      Thats it
      Step 6 > Now steps 1 to 5 are simple, anyone can do it without any help. Here comes the main point which took me hours despite me already having installed and used various versions of salome in previous fedora installations.
      If you see an error message like

      Configure parser: Warning : could not find user configuration file
      runSalome running on localhost
      Configure parser: Warning : could not find user configuration file
      Searching for a free port for naming service: 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 - OK
      Searching Naming Service ++++++++++Failed to narrow the root naming context
      Traceback (most recent call last):
        File "/opt/salome_5.1.2/KERNEL_5.1.2/bin/salome/runSalome.py", line 648, in useSalome
          clt = startSalome(args, modules_list, modules_root_dir)
        File "/opt/salome_5.1.2/KERNEL_5.1.2/bin/salome/runSalome.py", line 429, in startSalome
          clt=orbmodule.client(args)
        File "/opt/salome_5.1.2/KERNEL_5.1.2/bin/salome/orbmodule.py", line 48, in __init__
          self.initNS(args or {})
        File "/opt/salome_5.1.2/KERNEL_5.1.2/bin/salome/orbmodule.py", line 81, in initNS
          sys.exit(1)
      SystemExit: 1

      on running salome then here's what you need to do.

      1 > edit /etc/hosts (of course you need root for that) and make sure you have a line such as

      127.0.0.1 <hostname>

      in there. Most probably on a desktop system <hostname> will be localhost

      2 > If you still get the same error then
      delete any lines in /etc/hosts corresponding to IPv6, i.e. of the type

      ::1 localhost

      This is the part that took me hours to figure out. So now you know, omniorb probably does not support IPv6 as of yet. Someone should hopefully fix it soon.

      Sunday, November 15, 2009

      Why i use Fedora linux

      This question crops up fairly too often in my conversation with friends who use linux (most of them use ubuntu). So i decided to settle the matter once and for all.
      My reason for using fedora is simple, its the same reason why some people like strawberry flavoured ice-creams and some hate it, its THEIR OWN PREFERENCE.
      Also i first started with fedora because it was the first linux i ever saw (in my NSL computer lab for cs101 course). Yes, contrary to popular belief, i did not use linux from my childhood, the first computer in my home was 3 months before i joined IIT. And the first linux i saw was in IIT. I event learnt my first two languages C/C++ and Java by READING BOOKS, and even read the complete print copy of "Dive into Python" before actually diving into python!
      The first linux i used was Knoppix live which came with a dvd of a magazine. I used it exclusively for 2 weeks as i didn't know how to install an os. Then after burning about 6-7 cds (i wasted a few) i installed my first linux, Fedora 5 Bordeaux and have installed every Fedora release ever since, and never felt the need to change my distro. Most of them are mostly the same from the inside.

      However, just in case you want to make points, i'll list a few:
      http://fedoraproject.org/wiki/Overview

      • Fedora (+RH) devs work hard on bringing new features in linux. Many of the new features in linux are brought by them. For example the latest features in linux have been developed by fedora/RH devs including but not limited to the NetworkManager, pulseaudio, packagekit,.pulseaudio and many more. Also check http://fedoraproject.org/wiki/Red_Hat_contributions
      •  The openness of fedora is what i really like and wish all the world were so open. By this open i do not mean open-source code, i mean openness of mind, acceptance of others, openness of governance, openness of activities, no hidden agenda.
      • The fedora features mention exactly what is there in a new fedora release (many of the things are own contributions). Compare http://fedoraproject.org/wiki/Releases/12/FeatureList with http://www.ubuntu.com/products/whatisubuntu/910features . I couldn't figure out what different from the previous release apart from firefox 3.5, openoffice 3.1 and ubuntuone.
      • Fedora stays closer to upstream and is generally more updated.
      • http://fedoraproject.org/wiki/Foundations
      As someone put it somewhere on a blog, Fedora is about doing right, Ubuntu is about making things work. Of course you could make things work in short term by a few hacks,  but long term working requires doing the right thing :-)

      Wednesday, October 7, 2009

      use more screen space in firefox

      Many of my friends and not so friends have seemed to like google chrome browser in that it makes available more screen space for the web page to display. Of course its a good things, especially for laptops with wider screens and scant vertical space. However not many know that firefox has been customizable enough for long so that you can make available more space for you if you need. Though it cannot compete with chrome, you can still extract much more from it. Here's my compact menubar+addressbar+bookmarks bar in firefox all in a single line.
      To do this right click on the menubar and click customize. Then modift the toolbars and menubars to your hearts content.

      Here's my firefox compact look especially for notebooks. Also notice how the fastdial extension gives you access to most frequently used websites without the need of a separate bookmarks toolbar.


      Notice what i did. Moved the addressbar, search bar and bookmarks bar into the menubar. Thats it.
      Here's the customization screen


      So enjoy the more real estate in firefox.

      Saturday, October 3, 2009

      thermal handler : protect your computer from overheat

      So recently i started encoding some of the videos i had from dvds into compressed formats as the dvds are getting scratched and damaged. So i used the avidemux program for it. However my laptop gets overheated a lot during high cpu usage.
      Other problems with overheating came when i had to run my dsmc and other assignments. Since they run for a looong time, my laptop overheats and i used to keep it hanging on its side during overnight runs. To my horror once when i compiled openfoam on my laptop overnight, i saw it shutdown in the morning with a failed compile and overheat. So here's my solution for all those who suffer from the problem of overheating computers (for linux users only).
      Checkout the all new "thermal handler" from yours truly. The solution for all your computer overheat problems due to high cpu usage.
      What it does:
      Checks the temperature periodically and pauses processes using high cpu when a certain temperature is reached (default 90) and resumes them when the temperature falls below a certain value (default 65). None of your data crashes. The programs resume from the same state they were paused. No data loss. (Note that root processes cant be paused by the user)
      What you need to do:
      just run from a shell:

      $ python thermal_handler.py [temp_lo [, temp_hi]]

      Here's thermal handler at work:



      Download it from here : http://home.iitb.ac.in/%7Epankajp/web/downloads/thermal_handler.py

      EDIT: Thanks to Prashant Agrawal for reporting that the initial version didn't work on AMD cpus and helping me to test. I've updated the file to work on AMD cpus now. check it out

      Friday, October 2, 2009

      animate2

      Now i present before you the much improved animate2.
      Here are the major changes

      • Plot saving is fixed when multiple subplots are present
      • animate() is retained for compatibility, new users are expected to use animate2() with changed api for the function
      • Much more customizability
      • Plot frame traits (properties) can now be specified. Ex: plot title, axes labels, ticks, colors etc using extended traits notation to set the plot object properties
      • Each plot (line) can be customized. Plots can now be of various types such as scatted, line etc. Their properties can also be set such colors, thickness, style (dot-dash etc). Plots can also be labelled to add legends to the plot
      • Read the docstrings and the examples in __main__. They explain a lot of common uses.
      So what are you waiting for. Try the latest animate2. Dont forget to check out the demo sample usage in the '__main__' section of the file
      Check out the video below



      Video with subtitles explaining the video is available here:
      http://home.iitb.ac.in/%7Epankajp/web/downloads/animate2.mkv


      Requirements:
      To run this you will need the Enthought tool suite ETS (only traits with wx backend and chaco are required)
      Hope this is useful for someone.
      You can get the code animate.py from here that is:
      http://home.iitb.ac.in/%7Epankajp/web/downloads/animate.py

      Wednesday, September 23, 2009

      Animate simulations in python

      I've recently written a nice short code in python to animate the results (plots) of a simulation using chaco (part of Enthought ETS)
      It is not actually very difficult, but i've just made up this one for myself, and it also has some cool features, so i thought i'd share it with others may as well benefit from it.

      • This if useful for you if you ever do coding in python and need to plot somethings which may change with time. Example lets say you are plotting the evolution of temperature over a rod with time or solving a 1D Euler equation (say shock tube problem)
      • This code provides a simple function to do it easily.
      • You can play-pause the code (simulation) at any time.
      • You can zoom-pan theplot
      • You can plot multiple subplots in a single window (Example the velocity, density and pressure in a shock tube problem)
      • You can edit axis labels, font, grids using gui
      • You can save the plots
      Usage:
      This is the only function defined in the file  you need to know:
      def animate(func, delay=0.1, total_time=0.0, time_factor=1.0, size=(800, 600), title='Plot'):
          '''function to animate the values returned by a function
         
          func : function which returns a tuple of x,y values to animate on each call
              x is shape (N,), y is shape (N,) or (p,N), N is number of points, p is number of plots (properties)
          delay is the time interval in which to call the func after the previous func has returned(seconds)
          total_time is the time at which to stop the animation
                  animation will stop when total_time > self.time / time_factor
                  total_time <= 0 will continue indefinitely
          time_factor is the time to display as title (displayed_time=time/time_factor)
          In the plot window:
              pressing 'p' key will toggle animation play-pause
              pressing Ctrl-S will open a dialog to save a rendering of the plot
              pressing 'ESC' will reset the zoom level of the plot
              double clicking on some parts of the plot allows you to edit them in a gui,
                  (axis titles, grids, ticks etc)
              if the window becomes unresponsive, pause the animation for a while
          '''


      The docstring explains most of the things you need to know.
      Here's how you could use it:
      First we see how to animate a single plot (A moving sine wave in this case)
      from animate import animate
      from numpy import linspace, sin
      x = linspace(-10, 10, 101)
      i = 0.0
      def get_data():
          global i
          i += 0.1
          return x + i, sin(x + i)
      animate(func=get_data)

      The above code snippet will generate a nice moving animation window. Here's a plot from the same


      Plotting multiple values is just as simple. You only need to pass on a tuple of the y values:
      from animate import animate
      from numpy import linspace, sin, cos
      x = linspace(-10, 10, 101)
      i = 0.0
      def get_data2():
          global i

          i += 0.1
          return x + i, (1 / (1 + x ** 2), sin(x + i), cos(x + i), sin(x + i), cos(x + i),)

      animate(func=get_data2)
      Here's a plot from the above snippet:

      As you can see i have tried to make it as easy as possible without losing out on functionality.

      Requirements:
      To run this you will need the Enthought tool suite ETS (only traits with wx backend and chaco are required)
      Hope this is useful for someone.
      You can get the code animate.py from here that is:
      http://home.iitb.ac.in/%7Epankajp/web/downloads/animate.py

      Friday, September 18, 2009

      cutie kitten


      cutie kitten, originally uploaded by pankaj86.
      Such a lovely pair of kitten.
      So much contrast yet so much togetherness.
      Friendship knows no barriers.
      Hope men could learn.

      (Courtesy Suchit, this pic was taken by Suchit http://suchit-de-fundae.blogspot.com/ using his mobile cam in the mess of hostel 6)

      Flickr

      This is a test post from flickr, a fancy photo sharing thing.

      Wednesday, September 2, 2009

      No smoking

      All the junta out there, listen, please STOP smoking. Ya thats right, stop smoking, stop it NOW.
      FREEZE,
      Now throw away that cigarette in your hand and empty you wallets of the packets.
      Now repeat with me thrice
          I will not smoke
          I will not smoke
          I will not smoke
      If you are feeling withdrawal symptoms, contact me, i can help you and take you to rehab. Don't worry, its not worse than dying of choked lungs and killing many others in the process. Its also better than some fanatic like me shooting your brain at point blank range just for that single smoke.

      join us in the mission, spread the word
      http://www.thetruth.com/

      Tuesday, September 1, 2009

      Blend it like Blender

      Few days back this summer, i decided to be a bit creative and joined a free (as in freedom) workshop on blender in my college. I attended only a few days, but blender was really impressive. The main aim of the workshop was to teach sufficient blender to enable you to create educational content. As such it was not meant to teach character animation. So in just a few days, i learnt a lot of basics of 3D modeling. Most of the initial time was taken up in learning the interface, but i can assure you that once you learn it, it enables you to be highly productive.
      So here's a sample of what i did after just 3 days of learning blender. Of course as you know what happens in life, i've never been able to spend any time on blender since then...


      The blend files can be downloaded from here Blender .blend file, Textures
      Hope sometime i do get time to learn all the cool features of blender