How to Auto-run a Python Script in the Terminal of a Raspberry Pi When it Boots

1. Add this shebang in the first line of your script:

#!/usr/bin/env python

2. Make it executable by changing directory to where the script is and running this in your terminal:

chmod +x name_of_script.py

You can check this worked by typing ./name_of_script.py in the directory and seeing if it runs.

3. edit (using nano) ~/.config/lxsession/LXDE-pi/autostart to include the line:

@lxterminal --command='path_to_your_now_executable_python_script'

Now type, in your terminal, “reboot” to test.

Good luck!

MouseBot: Automating the Single Pellet Reaching Task

Single Pellet Reaching for Mice and Rats

The single pellet reaching task is used in pre-clinical drug research to evaluate new therapies and their potential to reverse paralysis of the upper limbs after stroke or spinal cord injury.

The video below shows a rat executing  the task where each sugar pellet is presented to the rat by a technician. The rat is removed from its home cage and placed in a clear perspex box. Sugar pellets are placed beyond and offset from a vertical slot (or, “reaching window”) and are reachable by only one paw depending on the side it is placed.

The rat smells that a pellet is present, extends its paw through the slot, rotates its wrist and grasps at the pellet. The rat then retracts the arm to bring the pellet to its mouth. In order to execute this task well, rats are trained daily for two weeks. Rats are considered trained when they are able to successfully reach, grasp and eat 70% of the pellets. Once they have reached this training stage, a brain or spinal cord injury is surgically induced. This hinders the rat’s ability to perform the pre-trained task as brain circuitry, the corticospinal tract, key for voluntary movement, degenerate. Neuroscientists assess the injured rats’ performance of the single pellet reaching task on a weekly basis, having been given a neurorehabilitative drug candidate or a control.

This task is a very good model for hand and arm function in humans, and the impairments after surgical induction of injury mimic the human condition closely.

Unfortunately, training a cohort of rats and mice for a large pre-clinical study on this task requires many hours of human labour. It is also subjective: the time of day, day of the week and person training the animal can all impact the performance of animals executing this task. Also, increasingly, research groups have began exploring high-intensity rehabilitation in conjunction with therapies, where 100 trials of pellet reaches are required per animal per session, where previously a session would terminate after 20 trials. The need to automate this task is very high.

MouseBot: Automation of the Single Pellet Reaching Task

The MouseBot is a robot I developed with Dr. Lawrence Moon and Dr. Dhireshan Gadiagellan at King’s College London. It is an automated solution to the issues outlined above

Below is a CAD animation of the MouseBot. Hardware was 3D printed and laser cut and designed using SolidWorks CAD.

The device’s firmware is written entirely in Python3. Pellets are placed in a high capacity hopper, driven through a chute and then deposited on a “spoon”. The spoon then rotates into the view of a camera. Real-time blob detection determines the presence of the sugar pellet on the spoon. Once detected, the coordinates of the pellet are used to drive the motor to position the pellet. The pellet’s position progressively increases from the reaching window (the slot) as mice get better at the task. When the pellet is positioned, a list is filled with NumPy arrays containing the pixel values, 640×480 in shape, generated at approximately 180 times per second with a maximum capacity of 700. When the pellet is dislodged, the NumPy arrays are encoded to video and stored with meta data (for example, the last microchip read by the on-board Radio Frequency Identity (RFID) reader) to a MongoDB cloud instance.

Videos are then downloaded, as they are generated, to a dedicated PC with NVIDIA GPUs, and they are fed through a trained neural network in order for key features in frames to be located.

The above gif shows the video from which frames were annotated, the below, the outputted labels from the neural network from a video it had not previously “seen”.

The location of the sugar pellet, paw’s digits and snout all contribute to determining the outcome of each trial (success or drop).

The entire device is placed within the home cage of animals and data is sent wirelessly as it is generated.

Getting started with Authorisation Code Flow and Spotipy

I recently wrote a post on how we can use Client Credentials Flow with Spotipy to retrieve publicly available data. Here, I describe how to use Authorisation Code Flow which will enable you to do things like update or remove tracks from a given playlist.

The first thing to do, in your terminal or command prompt, is type these commands, replacing each string with your client ID and secret generated when the initial app was created, and the redirect URL specified in the set-up.

export SPOTIPY_CLIENT_ID='your_client_ID'
export SPOTIPY_CLIENT_SECRET='your_client_Secret'
export SPOTIPY_REDIRECT_URI='the redirect URL you set'

This will pass these arguments to Spotipy’s utility class.

You should now be in a position to use Authorisation Code Flow. The script below is the Authorisation Code Flow equivalent of the program outlined here.

import sys
import spotipy
import spotipy.util as util

if len(sys.argv) > 1:
    username = sys.argv[1]
else:
    print "Usage: %s username" % (sys.argv[0],)
    sys.exit()

token = util.prompt_for_user_token(username, redirect_uri = 'http://localhost/')

if token:
    sp = spotipy.Spotify(auth=token)
    playlists = sp.user_playlists(username)
    while playlists:
        for i, playlist in enumerate(playlists['items']):
            print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['uri'],  playlist['name']))
        if playlists['next']:
            playlists = sp.next(playlists)
        else:
            playlists = None

To run the script, in terminal or a command line, type:

python <path/to/file> your_username

This should automatically open a browser window (if it doesn’t, copy and paste the URL generated in the terminal) which will let you login, in the familiar environment we’re used to, generating a token granting you authorisation to run the script.

Authorising Your First Spotipy App with Client Credentials Flow

A playlist I have on Spotify has collected a good number of followers over the years, which has attracted feature requests from artists, their managements and record labels. Keeping a playlist active so your follower count keeps growing can be a bit annoying, but Spotify’s Web API can make the automation of this easy. It also lets you do lots of other interesting things too, but getting started, especially for new beginners can be a bit daunting.

Here’s how you can get started quickly using the “Client Credentials Flow” (more on that later).

Using Spotipy, a python library that lets you interact with Spotify’s Web API, we can quickly write a program that will display a given user’s public playlists.

To use Spotipy (after installing it, instructions on how in the link above) you’ll need to make an app on https://developer.spotify.com and get your client ID and client secret. We will need these for authorisation. Spotify updated their API earlier this year to bring it inline with other web APIs meaning you need to have authorisation to use it. To get publicly available data from Spotify, “Client Credentials Flow” authorisation will suffice, if you want a user’s private information, you will need to use “Authorisation Code Flow” which will prompt that user to log-in. More info on this here.

The code to retrieve a given user’s public playlists can be seen here:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

client_credentials_manager = SpotifyClientCredentials(client_id='Your_Client_ID', client_secret='Your_Client_Secret')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

playlists = sp.user_playlists('Username')

while playlists:
    for i, playlist in enumerate(playlists['items']):
        print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['uri'],  playlist['name']))
    if playlists['next']:
        playlists = sp.next(playlists)
    else:
        playlists = None

By passing your client_ID and client_Secret as arguments (keep them as strings) in SpotifyClientCredential() you utilise Client Credentials Flow, and by replacing playlists = sp.user_playlists('Username') ‘username’ with your username of interest, running the program will, hopefully, list that user’s public playlists.

If you want to know how to use Authorisation Code Flow, let me know and I will write a separate post. Good luck!

So you want to learn Python? Insights from a newbie

Too long; didn’t read:

  • Get a Raspberry Pi
  • Sign-up to codecademy (free)
  • Have a project and end-goal in mind
  • Have patience
  • Get a nice integrated development environment (IDE) AKA a program that makes your code readable and nice
  • Have a crack!

Programming has been my escape for the past year and a half. Seriously. I have pretty much done nothing but. I absolutely love it. I love the feeling of getting something to work the way I want it to, having tinkered, edited and debugged until my head hurts. It’s a weird feeling. You know that cliché saying “It’s not the destination that counts, it’s the journey”? I think that holds very true for coding. It’s a journey, man.

I dipped into HTML and CSS way back when, but that introductory front-end stuff just wasn’t doing it for me and I gave up pursuing it. It was the moment when I saw a friend’s array of Raspberry Pis that made me want to dive back in; all of the components I didn’t understand and wires and flashing LEDs and motors and cogs and “AHHHHH!”. I felt like a 3 year old child on Christmas morning and I wanted a slice of that pie (pun definitely intended).

Anyway – to cut a long story short – I bought a Raspberry Pi. It wasn’t a hard choice given how unbelievably cheap they are. I mean… £4?! Four British pound sterling. I’ve bought beers more expensive than that.

“What is a Raspberry Pi?” I hear you ask. A Raspberry Pi (RPi) is a delicious little computer. Just like whatever it is you’re using to read this. Only this one bridges the world of software and hardware so well that it becomes a seamless and inviting portal. You can pretty much do anything you can think of with an RPi. Home automation? No problem. TweetBots? Easy, son.

So that’s how I got started with programming. I had a project in mind, and I wanted something that’ll help me get there. I think that’s the first step in your programming journey.

Have a project in mind…

The reason I say this is because it makes the learning experience less abstract. There’s tonnes of tutorials and resources available online that’ll teach you the syntax and walk you through basic programming projects that’ll add numbers or capitalise letters in a command line environment. But that quickly gets boring. Having a project in mind will keep your brain ticking through those tutorials (I recommend this one very highly), you’ll start thinking of ways you can apply the knowledge you acquire to the project you want to work on.

Have patience

I think patience is a requirement for most things in life but MY GOD is it a requirement of programming. Especially when you’re learning. Everything will look foreign, bold red errors will scream at you “SYNTAX ERROR, DO YOUR WRITING BETTER”, nothing will work and you will want to give up. By all means, give up… for 1 or 2 days, recalibrate and take stock, then return. Always return and keep doing so. One day it’ll all just start clicking, you’ll be able to problem solve purely in python and you’ll genuinely start thinking in a different way.

Download a nice IDE

If you do wind up buying a Raspberry Pi, you’ll probably spend a lot of time editing code in a console/command terminal. Terminals are handy for many a reason but coding here can be annoying. So is coding with TextEdit and Notepad. Download PyCharm and get cracking with that. It’s free and it’ll make your code look so much prettier. The whole debugging process (which you’ll come to get to know very well) will get a lot quicker and easier too.

Steal, copy and annotate

If there’s anything that truly stands out about the Raspberry Pi is its community. There are endless YouTube how-tos, forum posts and code in GitHub repositories. Don’t be afraid to copy and paste that stuff, guys and girls! Tinker with it and make it your own, try and understand it, annotate your work and share it with the world! We’re in this together.

Build

And finally, just keep going. If you can’t think of anything useful to build, build something useless, just build anything. Write your own story, be the next big thing, don’t worry about any of the other teams in your league, just win your own games and everything will take care of itself.

To finish, I’ll leave you with one of the most inspiring things I’ve heard from my favourite film-maker, Casey Neistat (which I’m probably about to badly paraphrase):

“There’s two things in life every person needs to ask themselves and figure out: 1. What do I like to do the most? and 2. How do I get paid doing that?”

Could coding be your ‘thing’?