Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – optimizing collision detection with Cython


  1. Define a function with Cython:

    %cython
    import numpy
    
    def cython_collisions(x, y, z, radius):
        num_particles = len(x)
        collisions = numpy.zeros(num_particles, dtype=numpy.bool)
    
        r_min = numpy.float64(4*radius**2)
    
        for i in range(num_particles):
            if i>0:
                d2 = numpy.power((x[i]-x[0:i]),2) \
                    + numpy.power((y[i]-y[0:i]),2) \
                    + numpy.power((z[i] - z[0:i]),2)
                if d2.min() < r_min:
                   collisions[i] = True
               
            if i+1 < num_particles:
                d2 = numpy.power((x[i]-x[i+1:]),2) \
                    + numpy.power((y[i]-y[i+1:]),2) \
                    + numpy.power((z[i]-z[i+1:]),2)
                if d2.min() < r_min:
                    collisions[i] = True
                    
        return collisions

    When you run this cell, it may take a minute or two to compile for the first time. The results will look similar to this:

  2. In another cell, enter...