Skip to main content

SciPy-Simulator

For the last few weeks I have been working on a Simulink / Labview / Ptolemy II like program for modelling... all sorts of stuff!! I am interested in modeling with different systems of computation, and of course some engineering problems, mechanical and electrical control etc. Ptolemey II is an open source java based system which a whole lot of people from Berkley have been working on for a number of years - I am not trying to match what they have - or get anywhere near the breadth that the commercial products Simulink and Labview have. But I do think something useful is very achievable - and of course leveraging what I can from Ptolemy II and basing mine on Python - heavily using SciPy, NumPy and MatPlotLib.

So far I have been working on the semantics - in essence creating a new language for defining models by using blocks (or Actors) that carry out a very specific function. An example actor might be a Ramp Source or a Sin Function. Each of these actors run in their own thread and communicate via dedicated Channels - which are based on the thread safe fifo queue implementation in the Python standard library. These base level actors can be composed together to create models, which are also actors in their own right - running in their own thread with all communication occurring through input and output channels.

The final goal is to have a visual interface - drag and drop blocks around, then connect up the model with channels. For now the whole thing is code based, so one of the more complicated models I have made is a simple pulse width modulator generator.

Here is the full code that defines and runs the model:
'''
Created on 13/12/2009

@author: brian
'''


from models.actors import Plotter, Ramp, Summer, Copier, Sin, GreaterThan, Subtractor, Constant, PassThrough
from models import CTSinGenerator
import matplotlib.pyplot as plt
from models.actors.Actor import MakeChans

import logging
logging.basicConfig(level=logging.INFO)
logging.info("Logger enabled")


def run_multi_sum():
    '''
    This example connects 3 sources ( 2 ramps and a random) to a summer block
    The final output AND one of the ramps are dynamically plotted.
    
    The components are all generating the same sequence of tags so are always
    synchronised
    '''
    sim_time = 0.02
    sim_res = 10000
    
    wire_names = ('ramp',
                  'sin',
                  'const_offset',
                  'offset_sin',
                  'ramp_probe',
                  'ramp_plot',
                  'offset_sin_probe',
                  'sin_plot',
                  'diff',
                  'pwm_bool',
                  'on_value',
                  'off_value',
                  'pwm_value'
                  )
    raw_wires = MakeChans(len(wire_names))
    
    wires = dict(zip( wire_names, raw_wires ))
    
    ramp_src = Ramp(wires['ramp_probe'], freq=500, simulation_time=sim_time, resolution=sim_res)
    sin_src = CTSinGenerator(wires['sin'], amplitude=0.5, freq=50.0, phi=0.0, timestep=1.0/sim_res, simulation_time=sim_time)
    const_src = Constant(wires['const_offset'], 0.5, resolution=sim_res, simulation_time=sim_time)
    
    offset_sin_sum = Summer([wires['sin'], wires['const_offset'] ], wires['offset_sin_probe'])
    
    ramp_cloning_probe = Copier(wires['ramp_probe'], [wires['ramp'], wires['ramp_plot']])
    ramp_plotter = Plotter(wires['ramp_plot'])
    
    sin_cloning_probe = Copier(wires['offset_sin_probe'], [wires['offset_sin'], wires['sin_plot']])
    sin_plotter = Plotter(wires['sin_plot'])

    # Output = sin - ramp
    subtractor = Subtractor(wires['offset_sin'], wires['ramp'], wires['diff'])

    # Want to see when that is > 0
    comparison = GreaterThan(wires['diff'], wires['pwm_bool'], threshold=0.0, boolean_output=True)
    if_device = PassThrough(wires['pwm_bool'], wires['on_value'], wires['pwm_value'], else_data_input=wires['off_value'])
    output_value_on = Constant(wires['on_value'], 1.0, resolution=sim_res, simulation_time=sim_time)
    output_value_off = Constant(wires['off_value'], 0.0, resolution=sim_res, simulation_time=sim_time)
    
    pwm_plotter = Plotter(wires['pwm_value'])
    
    components = [ramp_src, 
                  sin_src,
                  const_src,
                  offset_sin_sum,
                  ramp_cloning_probe, 
                  ramp_plotter, 
                  sin_cloning_probe, 
                  sin_plotter, 
                  subtractor,
                  comparison,
                  if_device,
                  output_value_on,
                  output_value_off,
                  pwm_plotter
                  ]

    logging.info("Starting simulation")
    [component.start() for component in components]
        
    logging.debug("Finished starting actors")

    logging.info('The program will stay "running" while the plot is open')
    plt.show()   

    [component.join() for component in components]
        

    logging.debug("Finished running simulation")
    

if __name__ == '__main__':
    run_multi_sum()

And here is the output:



This relatively simple model has 15 threads, and takes no time at all to run. There is still a long way to go, but if you are interested check out the project homepage on google code: http://scipy-sim.googlecode.com
Or clone the source directly with: hg clone https://scipy-sim.googlecode.com/hg/ scipy-sim

Popular posts from this blog

Bluetooth with Python 3.3

Since about version 3.3 Python supports Bluetooth sockets natively. To put this to the test I got hold of an iRacer from sparkfun . To send to New Zealand the cost was $60. The toy has an on-board Bluetooth radio that supports the RFCOMM transport protocol. The drive  protocol is dead easy, you send single byte instructions when a direction or speed change is required. The bytes are broken into two nibbles:  0xXY  where X is the direction and Y is the speed. For example the byte 0x16 means forwards at mid-speed. I was surprised to note the car continues carrying out the last given demand! I let pairing get dealt with by the operating system. The code to create a  Car object that is drivable over Bluetooth is very straight forward in pure Python: import socket import time class BluetoothCar : def __init__ ( self , mac_address = "00:12:05:09:98:36" ): self . socket = socket . socket ( socket . AF_BLUETOOTH , socket . SOCK_STREAM , socket .

Matplotlib in Django

The official django tutorial is very good, it stops short of displaying data with matplotlib - which could be very handy for dsp or automated testing. This is an extension to the tutorial. So first you must do the official tutorial! Complete the tutorial (as of writing this up to part 4). Adding an image to a view To start with we will take a static image from the hard drive and display it on the polls index page. Usually if it really is a static image this would be managed by the webserver eg apache. For introduction purposes we will get django to serve the static image. To do this we first need to change the template. Change the template At the moment poll_list.html probably looks something like this: <h1>Django test app - Polls</h1> {% if object_list %} <ul> {% for object in object_list %} <li><a href="/polls/{{object.id}}">{{ object.question }}</a></li> {% endfor %} </ul> {% else %} <p>No polls

Homomorphic encryption using RSA

I recently had cause to briefly look into Homomorphic Encryption , the process of carrying out computations on encrypted data. This technique allows for privacy preserving computation. Fully homomorphic encryption (FHE) allows both addition and multiplication, but is (currently) impractically slow. Partially homomorphic encryption just has to meet one of these criteria and can be much more efficient. An unintended, but well-known, malleability in the common RSA algorithm means that the multiplication of ciphertexts is equal to the multiplication of the original messages. So unpadded RSA is a partially homomorphic encryption system. RSA is beautiful in how simple it is. See wikipedia to see how to generate the public ( e , m ) and private keys ( d , m ). Given a message x it is encrypted with the public keys it to get the ciphertext C ( x ) with: C ( x ) = x e mod m To decrypt a ciphertext C ( x ) one applies the private key: m = C ( x ) d mod m The homomorphic prop