C Interaction

In [1]:
%%file functions.c

#include <stdio.h>

double dprod(double *x, int n);

void dcumsum(double *a, double *b, int n);

double dprod(double *x, int n)
{
    int i;
    double y = 1.0;
    
    for (i = 0; i < n; i++)
        y *= x[i];
    return y;
}

void dcumsum(double *a, double *b, int n)
{
    int i;
    
    b[0] = a[0];
    for (i = 1; i < n; i++)
        b[i] = a[i] + b[i-1];
}
Overwriting functions.c

In [2]:
!gcc -c -Wall -O2 -Wall -ansi -pedantic -fPIC -o functions.o functions.c
!gcc -o libfunctions.so -shared functions.o
In [3]:
!file libfunctions.so
libfunctions.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped

In [4]:
import numpy
import ctypes

_libfunctions = numpy.ctypeslib.load_library('libfunctions', '.')

_libfunctions.dprod.argtypes = [numpy.ctypeslib.ndpointer(dtype=numpy.float), ctypes.c_int]
_libfunctions.dprod.restype  = ctypes.c_double

_libfunctions.dcumsum.argtypes = [numpy.ctypeslib.ndpointer(dtype=numpy.float), numpy.ctypeslib.ndpointer(dtype=numpy.float), ctypes.c_int]
_libfunctions.dcumsum.restype  = ctypes.c_void_p


def dprod(x, n=None):
    if n is None:
        n = len(x)
    x = numpy.asarray(x, dtype=numpy.float)
    return _libfunctions.dprod(x, int(n))

def dcumsum(a, n):
    a = numpy.asarray(a, dtype=numpy.float)
    b = numpy.empty(len(a), dtype=numpy.float)
    _libfunctions.dcumsum(a, b, int(n))
    return b
In [5]:
dprod([1,2,3,4,5]) 
Out[5]:
120.0
In [6]:
a = rand(100000)
In [7]:
res_c = dcumsum(a, len(a)) 
In [8]:
res_c
Out[8]:
array([  9.88379380e-01,   1.56630971e+00,   1.94774871e+00, ...,
         4.98985284e+04,   4.98988152e+04,   4.98996419e+04])
In [9]:
timeit  dcumsum(a, len(a)) 
1000 loops, best of 3: 814 µs per loop

In [10]:
timeit a.cumsum()
1000 loops, best of 3: 741 µs per loop

In [11]:
a.cumsum()-dcumsum(a, len(a)) 
Out[11]:
array([ 0.,  0.,  0., ...,  0.,  0.,  0.])

Javascript Interaction

In [11]:
from IPython.core.display import HTML, Javascript
In [12]:
# load the Google Maps API library
# TO DO:  make it easy to add API key

def gmap_init():
    js = """
window.gmap_initialize = function() {};
$.getScript('https://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=gmap_initialize');
"""
    return Javascript(data=js)

gmap_init()
Out[12]:
In [13]:
%%html
<style type="text/css">
  .map-canvas { height: 300px; }
</style>
In [14]:
# generate a random id

import uuid
div_id = 'i' + str(uuid.uuid4())

html = """<div id="%s" class="map-canvas"/>""" % (div_id)

js = """
<script type="text/Javascript">
  (function(){
    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(-34.397, 150.644)
      };

    var map = new google.maps.Map(document.getElementById('%s'),
          mapOptions);
  })();  
</script>
""" % (div_id)

HTML(html+js)
Out[14]:
In [15]:
import uuid

def gmap(lat=37.8717,long=-122.2728,zoom=8):

    div_id = 'i' + str(uuid.uuid4())

    html = """<div id="%s" class="map-canvas"/>""" % (div_id)

    js = """
    <script type="text/Javascript">
      (function(){
        var mapOptions = {
            zoom: %s,
            center: new google.maps.LatLng(%s, %s)
          };

        var map = new google.maps.Map(document.getElementById('%s'),
              mapOptions);
      })();  
    </script>
    """ % (zoom, lat,long, div_id)

    return HTML(html+js)
In [16]:
import jinja2

TEMPLATE = """{{greeting}}, {{name}}"""

my_template = jinja2.Template(TEMPLATE)
my_template.render(greeting="hello", name="RY")
Out[16]:
u'hello, RY'
In [17]:
%%html
<div id="markers" class="map-canvas"/>
In [18]:
%%javascript

var myLatlng = new google.maps.LatLng(37.8717,-122.2728);

var mapOptions = {
  zoom: 8,
  center: myLatlng
};

var map = new google.maps.Map(document.getElementById('markers'),
  mapOptions);

// To add the marker to the map, use the 'map' property
var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title:"Berkeley"
});
In [19]:
%%html
<div id="circles" class="map-canvas"/>
In [20]:
%%javascript

// This example creates circles on the map, representing
// populations in the United States.

// First, create an object containing LatLng and population for each city.
var citymap = {};
citymap['chicago'] = {
  center: new google.maps.LatLng(41.878113, -87.629798),
  population: 2842518
};
citymap['newyork'] = {
  center: new google.maps.LatLng(40.714352, -74.005973),
  population: 8143197
};
citymap['losangeles'] = {
  center: new google.maps.LatLng(34.052234, -118.243684),
  population: 3844829
};
var cityCircle;


var mapOptions = {
    zoom: 4,
    center: new google.maps.LatLng(37.09024, -95.712891),
    mapTypeId: google.maps.MapTypeId.TERRAIN
};


  var map = new google.maps.Map(document.getElementById('circles'),
      mapOptions);

  // Construct the circle for each value in citymap.
  // Note: We scale the population by a factor of 20.
  for (var city in citymap) {
    var populationOptions = {
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35,
      map: map,
      center: citymap[city].center,
      radius: citymap[city].population / 20
    };
    // Add the circle for this city to the map.
    cityCircle = new google.maps.Circle(populationOptions);
  }
In [20]:
 
In []: