Statdoc – keep your statistics projects organised

I recently spoke about my statdoc program at the Stata User Group Meeting in Canberra (http://www.stata.com/meeting/australia15/). It is a neat little program that quickly gathers information about your statistics projects and packs them into nicely formated html pages.

Check it out: https://github.com/mas802/statdoc

Posted in Uncategorized | Leave a comment

Brookstone ROVER 2.0 Skype Client

I recently got my hands on a Brookstone Rover 2.0, and figured it would make a nice little toy for my son’s grandparents to interact with him from overseas. There were a couple of dead ends, and I am still working on getting the video to the web. But I came up with a nice way to control the rover using Skype. Essentially I combined two python tools: http://home.wlu.edu/~levys/software/roverpylot/ and https://pypi.python.org/pypi/Skype4Py/ to let the rover be controlled with a few simple commands in a Skype chat (you need to have Skype client running). Currently the rover responds to @forward, @back, @left, @right. To lights on and off (@lon, @loff) and infrared mode on and off (@ion, @ioff), as well as to give the battery status (@b).

#!/usr/bin/env python

import Skype4Py
import time
import re
import rover
import cvutils
import sys
import signal


class SkypeBot(object):
  def __init__(self):
    self.skype = Skype4Py.Skype(Events=self)
    self.skype.FriendlyName = "Skype Bot"
    self.skype.Attach()
    
  def AttachmentStatus(self, status):
    if status == Skype4Py.apiAttachAvailable:
      self.skype.Attach()
    
  def MessageStatus(self, msg, status):
    if status == Skype4Py.cmsReceived:
      if msg.Chat.Type in (Skype4Py.chatTypeDialog, Skype4Py.chatTypeLegacyDialog):
        for regexp, target in self.commands.items():
          match = re.match(regexp, msg.Body, re.IGNORECASE)
          if match:
            msg.MarkAsSeen()
            reply = target(self, *match.groups())
            if reply:
              msg.Chat.SendMessage(reply)
            break

  def cmd_userstatus(self, status):
    if status:
      try:
        self.skype.ChangeUserStatus(status)
      except Skype4Py.SkypeError, e:
        return str(e)
    return 'Current status: %s' % self.skype.CurrentUserStatus

  def cmd_credit(self):
    return self.skype.CurrentUserProfile.BalanceToText

  def cmd_battery(self):
    return 'Battery at %d%%' % rover.getBatteryPercentage()

  def cmd_left(self):
    rover.setTreads(-1, 1)
    time.sleep(0.8)
    rover.setTreads(0, 0)
    return 'ok, turning left'

  def cmd_right(self):
    rover.setTreads(1, -1)
    time.sleep(0.8)
    rover.setTreads(0, 0)
    return 'ok, turning right'

  def cmd_forward(self):
    rover.setTreads(1, 1)
    time.sleep(0.8)
    rover.setTreads(0, 0)
    return 'ok, going forward'

  def cmd_back(self):
    rover.setTreads(-1, -1)
    time.sleep(0.8)
    rover.setTreads(0, 0)
    return 'ok, going back'

  def cmd_lightson(self):
    rover.turnLightsOn()
    return 'ok, lights on'

  def cmd_lightsoff(self):
    rover.turnLightsOff()
    return 'ok, lights off'

  def cmd_infraon(self):
    rover.turnInfraredOn()
    return 'ok, infrared on'

  def cmd_infraoff(self):
    rover.turnInfraredOff()
    return 'ok, infrared off'


  commands = {
    "@userstatus *(.*)": cmd_userstatus,
    "@credit$": cmd_credit,
    "@forward$": cmd_forward,
    "@back$": cmd_back,
    "@left$": cmd_left,
    "@right$": cmd_right,
    "@lon$": cmd_lightson,
    "@loff$": cmd_lightsoff,
    "@ion$": cmd_infraon,
    "@ioff$": cmd_infraoff,
    "@b$": cmd_battery
  }

def signal_handler(signal, frame):
    print 'You pressed Ctrl+C!'
    rover.close()
    sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

if __name__ == "__main__":
  rover = rover.Rover()
  print('Battery at %d%%' % rover.getBatteryPercentage())  
  
  bot = SkypeBot()
  while True:
    time.sleep(1.0)

  rover.close()

Additional Links I found on the way here

For Windows only:

https://www.ez-robot.com/EZ-Builder/ http://www.instructables.com/id/Brookstone-Rover/step6/Many-more/ http://www.ez-robot.com/Community/Forum/posts.aspx?threadId=2146

Detailed Thread

http://www.openipcam.com/forum/index.php?topic=261.0

Node.js implementation

https://github.com/wearefractal/rover/blob/master/RESEARCH.md

Python Code

http://home.wlu.edu/~levys/software/roverpylot/ http://isgroupblog.blogspot.com.au/2013/09/how-i-hacked-brookstone-rover-20.html

Tear Down

Rover 2 SpyTank Teardown

Russian

http://roboforum.ru/forum104/topic11710.html?style=9

Video to web

http://stackoverflow.com/questions/5825173/pipe-raw-opencv-images-to-ffmpeg http://stackoverflow.com/questions/16045654/using-opencv2-write-streaming-video-in-python

Posted in Code, Python, Toy | Tagged , | Leave a comment

sed -e “s/Standard economic theory predicts/Naive reasoning about monetary incentives leads to the misconseption that/r” LotsOfBehaviouralEconomics.pdf

Posted in Uncategorized | Leave a comment

dodrive.ado: how to create collaborative do files with google docs

Recently I got a request for a way to edit Stata do files like google docs for a collaborative project. Here my solution: just run a google docs document as a do file.

The first step is to install/run the following .ado file, you can move this into your ado folder if you want the functionality permanently, otherwise you have to run this each time you restart Stata and want to use it.

dodrive.ado:

/*

dodrive.ado

A small utility to run google docs files as stata do files 
for easy collaboration on data analysis.

(c) 2013-2015 Markus Schaffner

*/
cap program drop dodrive
program dodrive
	version 13
	syntax anything(name=gtoken)

	tempname inhandle
	tempname outhandle
	tempname val
	
	tempfile txtfile
	tempfile dofile
	
	// download the google docs as text

	copy "https://docs.google.com/document/export?format=txt&id=`gtoken'" `txtfile', replace text

	// get rid of the first three chars
	file open `inhandle' using `txtfile', read binary
	file seek `inhandle' 3
	file open `outhandle' using `dofile', write binary 
	file read `inhandle' %2bs `val'
	while r(eof)==0 {
	        file write `outhandle' %2bs (`val')
			file read `inhandle' %2bs `val'
	}
	file close `inhandle'
	file close `outhandle'

	do `dofile'
end

Then you have to create a google docs file and enter your Stata code into it. The document has to be visible to everybody with the link (under Share). Now copy the document token from the url (that is the bit with the random sequence of letters and numbers) …

Link to share

https://docs.google.com/document/d/1oui0F7Z3uoafzf7TzkmkOS8dyPIft6Xdiqaryu3CIPQ/edit?usp=sharing

Document token:

1oui0F7Z3uoafzf7TzkmkOS8dyPIft6Xdiqaryu3CIPQ

… and run the following command:

dodrive 1oui0F7Z3uoafzf7TzkmkOS8dyPIft6Xdiqaryu3CIPQ

Which, for my example should give the following output:

. dodrive 1oui0F7Z3uoafzf7TzkmkOS8dyPIft6Xdiqaryu3CIPQ

. // an example do file
. 
. 
. sysuse auto, clear
(1978 Automobile Data)

. 
. 
. reg price length

Source        SS       df       MS              Number of obs =      74
F(  1,    72) =   16.50
Model    118425867     1   118425867           Prob > F      =  0.0001
Residual    516639529    72  7175549.01           R-squared     =  0.1865
Adj R-squared =  0.1752
Total    635065396    73  8699525.97           Root MSE      =  2678.7

price       Coef.   Std. Err.      t    P>t     [95% Conf. Interval]

length    57.20224   14.08047     4.06   0.000     29.13332    85.27115
_cons   -4584.899   2664.437    -1.72   0.090    -9896.357     726.559

. 
. 
. test length

( 1)  length = 0

F(  1,    72) =   16.50
Prob > F =    0.0001

. 
end of do-file

You have to be smart about how you load and save data when collaborating, e.g. all use the same path, or simply manually switch to the right directory beforehand.

Now you are ready to collaboratively work on your do file.

Update: (31/10/2015) Updated to reflext google side changes to the URL. Also added the file to github: https://github.com/mas802/stata-utils

Posted in Code, Stata | Tagged , | 2 Comments

Overlay longitude / latitude data on a map with Stata

I recently came across the need to display some data with latitude/logitude information on a map (number of respondents to a survey on the Queensland/New South Wales border). Stata has a nice tool to display information about regions on a map called spmap (spmap on Stata FAQ), but I could not find how to do what I wanted.

But I found that with help from shp2dta (used for spmap as well) this becomes quite straight forward.

1. First you have to download the shape data for the region you are interested in. A quick google search will usually take you to some sort of government data that you can download for free. I got the data for Australia from the ABS (abs map shape file).

2. Install shp2dta in Stata, switch to the directory holding the shape files (there are a number of them), and apply shp2dta:

ssc install shp2dta
shp2dta using STE11aAust, data(aust_data) coor(aust_coordinates) genid(id)

3. Bring it together (Note: I want to illustrate where respondents come from; each response has a postcode that I matched with some postcode latitude (lat) and longitude (lon) data).

/*
plot the longitude/latitude data on a map
*/
// append the corresponding coordinates file created with shp2dta to your dataset
// ssc install shp2dta
append using ausmap/aust_coordinates.dta

// setup boundaries for the map you are interested in
local north = -24.5
local south = -34.6
local east = 155
local west = 147

// cut the map to size, note you can't just replace those with missing except islands
replace _X = `west' if _X < `west'
replace _X = . if _X > 155 // get rid of a small off-shore island
replace _Y = `south' if _Y < `south'
replace _Y = `north' if _Y > `north'

// remove outliers from original data
replace lon = . if lon < `west'
replace lat = . if lat < `south'

// basic plot for the map select only NSW (1) and QLD (3) from all the shapes
tw (area _Y _X if _ID==1 | _ID==3, cmissing(n) nodropbase) ///
   (scatter lat lon, jitter(1)), name(simple, replace)
graph export simple.png, replace

simple

4. Well, all that is left to do is make this graph prettier…

/*
now lets make it pretty by fixing the size and aspect ratio, draw
weighted circles below the scatter data and complete the frame
*/

// calculate aspect ratio and width and height of the graph
local ar = ( `north' - `south' )/( `east' - `west' )
local dx = ( `east' - `west' )
local dy = ( `north' - `south' )

// put the coordinates for the frame in the dataset
gen n = _n
replace _ID = -99 if n == 1
replace _Y = `north' if n == 1
replace _X = `west' if n == 1
replace _ID = -99 if n == 2
replace _Y = `north' if n == 2
replace _X = `east' if n == 2
replace _ID = -99 if n == 3
replace _Y = `south' if n == 3
replace _X = `east' if n == 3
replace _ID = -99 if n == 4
replace _Y = `south' if n == 4
replace _X = `west' if n == 4
replace _ID = -99 if n == 5
replace _Y = `north' if n == 5
replace _X = `west' if n == 5

// plot the graph with a few beautifications
tw (scatter lat lon [w=numberPerCode] if state == "QLD", mcolor(maroon*0.5)) ///
   (scatter lat lon [w=numberPerCode] if state == "NSW", mcolor(blue*0.5)) ///
   (area _Y _X if _ID==1 | _ID==3, cmissing(n) nodropbase fcolor(none) lwidth(0.15) lcolor(black)) ///
   (area _Y _X if _ID==-99, cmissing(n) nodropbase fcolor(none) lwidth(0.20) lcolor(black)) ///
   (scatter lat lon if state == "NSW", mcolor(blue) msize(0.3) jitter(1)) ///
   (scatter lat lon if state == "QLD", mcolor(maroon) msize(0.3) jitter(1)) ///
   , aspectratio(`ar') legend(off) yscale(off) xscale(off) ylabel(,nogrid) ysize(`dy') xsize(`dx') ///
   graphregion(color(white)) bgcolor(white) name(pretty, replace)
graph export respondant_map.png, width(2048) replace
graph export respondant_map.eps, replace

respondant_map

Posted in Code, Stata | 1 Comment

Stata Plugin for Eclipse (alpha)

This is a plugin I wrote for my own use, it allows to interact with stata directly from eclipse – my favorite IDE/editor. If you don’t know stata or eclipse, stop reading, this will not be useful for you. Also this is alpha software: expect many bugs, failures and complete loss of your data.

HowTo:

1. Put the mas.stataplugin.jar file into your eclipse dropin/ folder (no update site available yet).

2. Start eclipse and add the StataView and StataVarView. (Window -> Show View -> Other -> Stata)

3. Start stata and run interact.ado (you can also put it into your ado folder).

4. Start the interactive mode by typing “interact” in stata.

5. Open or create a .do file in eclipse and type in a command and use the run button to run it in stata.

Features:

– …

FAQ

None yet

UPDATE: 17/04/2014 – I entered new download links to fix the broken ones.

Posted in Code, Eclipse, Java, Stata | 7 Comments