<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Pyevolve</title>
	
	<link>http://pyevolve.sourceforge.net/wordpress</link>
	<description>by Christian S. Perone</description>
	<lastBuildDate>Wed, 06 Feb 2013 00:01:52 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/pyevolve" /><feedburner:info uri="pyevolve" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Rastreamento em tempo real de avioes em Porto Alegre utilizando Raspberry Pi + Radio UHF (SDR RTL2832U)</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/J3X6r2mu4O8/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2433#comments</comments>
		<pubDate>Wed, 06 Feb 2013 00:01:52 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2433</guid>
		<description><![CDATA[* This post is in Portuguese. SDR (Software-Defined Radio) SDR é uma área de radiocomunicação baseada em uma ideia muito simples: implementar em software o que antes era implementado em hardware (ex: mod/demod, filtros, etc). O fato do SDR estar se tornando uma tendência hoje se dá principalmente pelo baixo custo de alguns receptores como [...]]]></description>
			<content:encoded><![CDATA[<p>* This post is in <strong>Portuguese</strong>.</p>
<h3>SDR (<em>Software-Defined Radio</em>)</h3>
<p><a title="Wikipedia :: SDR" href="http://en.wikipedia.org/wiki/Software-defined_radio" target="_blank">SDR</a> é uma área de radiocomunicação baseada em uma ideia muito simples: implementar em software o que antes era implementado em hardware (ex: mod/demod, filtros, etc). O fato do SDR estar se tornando uma tendência hoje se dá principalmente pelo baixo custo de alguns receptores como por exemplo o RTL2832U (mais sobre ele depois) que hoje você pode encontrar facilmente por uns U$ 20.00, preço este muito barato se você levar em consideração o intervalo de cobertura das frequências de 22Mhz até 2200Mhz (dependendo do tuner). Neste intervalo dá pra se ter uma ampla cobertura de sinais de rádio AM/FM, rádio da polícia, TV, GSM, GPS, ADSB (este post é sobre o ADSB), comunicação marítma, LTE (ainda em definição no Brasil) e outras aplicações que estão inseridas neste intervalo de frequência.</p>
<p>Um sistema SDR é composto geralmente por: um receptor ligado ao computador ou qualquer outro dispositivo embarcado com um poder de processamento razoável (por meio de placa de captura de áudio, USB, etc) e um software que irá fazer o tratamento do sinal recebido. Neste <em>post</em> eu vou utilizar o Raspberry Pi como dispositivo embarcado para capturar e demodular os dados enviados pelos transponders presentes em aeronaves comerciais e domésticas.</p>
<h3>ADS-B (<em>Automatic dependent surveillance-broadcast</em>)</h3>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2013/02/adsb_op1.png" rel="lightbox[2433]"><img class="aligncenter size-full wp-image-2452" title="ADS-B" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2013/02/adsb_op1.png" alt="" width="640" height="361" /></a></p>
<p>Grande parte dos aviões modernos estão sendo equipados com <a title="Wikipedia :: ADS-B" href="http://en.wikipedia.org/wiki/Automatic_dependent_surveillance-broadcast" target="_blank">um dispositivo</a> que tem o objetivo de substituir os radares que existem hoje. Até o ano de 2020 todos os aviões que entrarem no espaço aéreo estadunidense deverão ter como item obrigatório um dispositivo compatível com ADS-B. O dispositivo ADS-B faz com que as aeronaves sejam visíveis aos radares em terra e também para outros aviões através do broadcast de mensagens com sua altura, velocidade, posição e muitas outras informações relevantes. A transmissão destas mensagens se dá através da frequência 1090Mhz, uma frequência dentro do intervalo de captura de maioria dos receptores SDR usando o chipset RTL2832U. A ideia deste post é usar o Raspberry Pi para receber este broadcast enviado diretamente pelo transponder dos aviões, demodular os frames e então utilizar um software para decodificar/interpretar os frames e plotar em um mapa a posição atual dos aviões em Porto Alegre / RS.</p>
<h3>Realtek RTL2832U</h3>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2013/02/dongle_rpi.png" rel="lightbox[2433]"><img src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2013/02/dongle_rpi.png" alt="" title="dongle_rpi" width="367" height="490" class="aligncenter size-full wp-image-2474" /></a><br />
Alguns receptores de TV digital USB utilizam o chipset da Realtek RTL2832U, como este meu acima. Em 2012 <a href="http://thread.gmane.org/gmane.linux.drivers.video-input-infrastructure/44461/focus=44461" target="_blank">foi descoberto</a> que este chipset permitia o envio de dados brutos do receptor para o host, permitindo assim seu uso para SDR. Existem alguns projetos com drivers para se comunicar com o dispositivo e receber estes dados (Linux e Windows), entre os quais o mais utilizado em Linux é o projeto <a title="Osmocom :: rtl-sdr" href="http://sdr.osmocom.org/trac/wiki/rtl-sdr" target="_blank">rtl-sdr</a>, que agrega além do driver alguns utilitários de linha de comando como por exemplo o &#8220;rtl_adsb&#8221; que utilizarei no Raspberry Pi para demodular o sinal ADS-B enviado pelas aeronaves; outro componente importante nos receptores USB é o tuner, que é responsável pelo ajuste da frequencia do rádio, no caso do meu dongle USB ele é o R820T que tem uma ótima sensibilidade mas tem um intervalo menor de cobertura do espectro quando comparado ao E4000 (da Elonics), veja a <a href="http://sdr.osmocom.org/trac/wiki/rtl-sdr" target="_blank">tabela no site</a> do projeto para saber o intervalo de cobertura de cada tuner e de outros hardwares suportados pelo rtl-sdr.</p>
<h3>Compilando o rtl-sdr no Raspberry Pi</h3>
<p>Estou utilizando o Raspberry Pi como host do dongle USB porque ele é um aparelho barato e o consumo de energia é muito baixo, ou seja, você pode deixá-lo ligado capturando o sinal ADS-B por quanto tempo quiser sem se preocupar com um gasto maior que 5 watts no pior caso.</p>
<p><strong>Baixando repositório</strong></p>
<div class="codecolorer-container bash default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="bash codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #c20cb9; font-weight: bold;">git</span> clone <span style="color: #c20cb9; font-weight: bold;">git</span>:<span style="color: #000000; font-weight: bold;">//</span>git.osmocom.org<span style="color: #000000; font-weight: bold;">/</span>rtl-sdr.git</div></td></tr></tbody></table></div>
<p><strong>Dependências</strong>: libusb-1.0-0-dev, cmake, compilador (gcc)</p>
<div> <strong>Criando arquivos para compilação e compilando</strong>:</div>
<div class="codecolorer-container bash default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br /></div></td><td><div class="bash codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #7a0874; font-weight: bold;">cd</span> rtl-sdr<span style="color: #000000; font-weight: bold;">/</span><br />
<span style="color: #c20cb9; font-weight: bold;">mkdir</span> build<br />
<span style="color: #7a0874; font-weight: bold;">cd</span> build<br />
cmake ..<span style="color: #000000; font-weight: bold;">/</span><br />
<span style="color: #c20cb9; font-weight: bold;">make</span><br />
<span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">make</span> <span style="color: #c20cb9; font-weight: bold;">install</span><br />
<span style="color: #c20cb9; font-weight: bold;">sudo</span> ldconfig</div></td></tr></tbody></table></div>
<div>E pronto, já estamos com o rtl-sdr instalado (driver a aplicativos extras).</div>
<h3>Recebendo sinal ADS-B</h3>
<p>Antes de mais nada, um pequeno teste para verificar se o rtl-sdr está encontrando corretamente o dongle USB:</p>
<div class="codecolorer-container bash default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br /></div></td><td><div class="bash codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">pi<span style="color: #000000; font-weight: bold;">@</span>raspberrypi ~ $ rtl_test <span style="color: #660033;">-t</span><br />
Found <span style="color: #000000;">1</span> device<span style="color: #7a0874; font-weight: bold;">&#40;</span>s<span style="color: #7a0874; font-weight: bold;">&#41;</span>:<br />
&nbsp;<span style="color: #000000;">0</span>: ezcap USB <span style="color: #000000;">2.0</span> DVB-T<span style="color: #000000; font-weight: bold;">/</span>DAB<span style="color: #000000; font-weight: bold;">/</span>FM dongle<span style="color: #000000; font-weight: bold;">&lt;/</span>pre<span style="color: #000000; font-weight: bold;">&gt;</span><br />
<span style="color: #000000; font-weight: bold;">&lt;</span>pre<span style="color: #000000; font-weight: bold;">&gt;</span>Using device <span style="color: #000000;">0</span>: ezcap USB <span style="color: #000000;">2.0</span> DVB-T<span style="color: #000000; font-weight: bold;">/</span>DAB<span style="color: #000000; font-weight: bold;">/</span>FM dongle<br />
Found Rafael Micro R820T tuner<br />
Supported gain values <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #000000;">29</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>: <span style="color: #000000;">0.0</span> <span style="color: #000000;">0.9</span> <span style="color: #000000;">1.4</span> <span style="color: #000000;">2.7</span> <span style="color: #000000;">3.7</span> <span style="color: #000000;">7.7</span><br />
<span style="color: #000000;">8.7</span> <span style="color: #000000;">12.5</span> <span style="color: #000000;">14.4</span> <span style="color: #000000;">15.7</span> <span style="color: #000000;">16.6</span> <span style="color: #000000;">19.7</span> <span style="color: #000000;">20.7</span> <span style="color: #000000;">22.9</span> <span style="color: #000000;">25.4</span> <span style="color: #000000;">28.0</span><br />
<span style="color: #000000;">29.7</span> <span style="color: #000000;">32.8</span> <span style="color: #000000;">33.8</span> <span style="color: #000000;">36.4</span> <span style="color: #000000;">37.2</span> <span style="color: #000000;">38.6</span> <span style="color: #000000;">40.2</span> <span style="color: #000000;">42.1</span> <span style="color: #000000;">43.4</span> <span style="color: #000000;">43.9</span><br />
<span style="color: #000000;">44.5</span> <span style="color: #000000;">48.0</span> <span style="color: #000000;">49.6</span><br />
No E4000 tuner found, aborting.<br />
pi<span style="color: #000000; font-weight: bold;">@</span>raspberrypi ~ $</div></td></tr></tbody></table></div>
<p>Note que o meu dongle é um RTL2832U com o tuner R820T, ao executar o &#8220;rtl_test -t&#8221; é também exibida uma lista com os ganhos suportados pelo dongle.</p>
<p>Como a frequência utilizada pelo ADS-B é de <strong>1090MHz</strong>, uma antena boa seria uma <strong>discone </strong>ou uma <strong>dipolo </strong>confeccionada com as dimensões corretas para esta frequência. Como ainda não tenho os plugs adequados tive que utiliar a antena que veio junto com o dongle, que mesmo sendo de baixa qualidade e não relacionada com a frequência do ADS-B ainda consegue receber os sinais (<em>de fato, mesmo desconectando a antena eu consigo receber os frames das aeronaves</em>), mesmo com o dongle em um ambiente fechado (minha casa fica há uns 6-10km do aeroporto de Porto Alegre / RS).</p>
<p>Para receber e demodular os frames eu utilizei o utilitário &#8220;rtl_adsb&#8221; (ele vem junto com o pacote do rtl-sdr). Ao ser executado, ele ajustará o tuner para a frequência do transponder das aeronaves em 1090MHz e logo após fará a demodulação dos frames para o formato hexadecimal:</p>
<div class="codecolorer-container bash default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br /></div></td><td><div class="bash codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">pi<span style="color: #000000; font-weight: bold;">@</span>raspberrypi ~ $ rtl_adsb<br />
Found <span style="color: #000000;">1</span> device<span style="color: #7a0874; font-weight: bold;">&#40;</span>s<span style="color: #7a0874; font-weight: bold;">&#41;</span>:<br />
&nbsp; <span style="color: #000000;">0</span>: &nbsp;Realtek, RTL2838UHIDIR, SN: 00000013<br />
<br />
Using device <span style="color: #000000;">0</span>: ezcap USB <span style="color: #000000;">2.0</span> DVB-T<span style="color: #000000; font-weight: bold;">/</span>DAB<span style="color: #000000; font-weight: bold;">/</span>FM dongle<br />
Found Rafael Micro R820T tuner<br />
Tuner gain <span style="color: #000000; font-weight: bold;">set</span> to automatic.<br />
Tuned to <span style="color: #000000;">1090000000</span> Hz.<br />
Sampling at <span style="color: #000000;">2000000</span> Hz.<br />
Exact sample rate is: <span style="color: #000000;">2000000.052982</span> Hz<br />
<span style="color: #000000; font-weight: bold;">*</span>825566cf477b3124c64b17e74b15;<br />
<span style="color: #000000; font-weight: bold;">*</span>e6c7d7fdb34c855db6972204ea14;<br />
<span style="color: #000000; font-weight: bold;">*</span>d1e27bb95df2454ca547c87718a2;<br />
<span style="color: #000000; font-weight: bold;">*</span>906bc5a59b5c5053226fb94f3460;<br />
<span style="color: #000000; font-weight: bold;">*</span>a6f51dc76353efeeabfbfe6946cb;<br />
<span style="color: #000000; font-weight: bold;">*</span>e78ed3aaf547fcd87e8e4f41cea3;<br />
<span style="color: #000000; font-weight: bold;">*</span>d26a5ecacdb7051f2ebe18efc613;</div></td></tr></tbody></table></div>
<p>Cada frame inicia sempre com um asterisco na frente e cada um destes frames foi enviado diretamente por um transponder de um avião ou é uma requisição terra->ar de alguma base em terra. O que precisamos agora é fazer a decodificação destes frames para poder extrair o tipo do frame, latitude, longitude, callsign, origem e destino do avião, etc. Não existem hoje muitas alternativas open-source para fazer o plot dos aviões em um mapa, o melhor que eu encontrei foi o <a href="http://www.virtualradarserver.co.uk/Screenshots.aspx" title="Virtual Radar Server :: Screenshots" target="_blank">Virtual Radar Server</a> que é open-source e roda também em Linux, além de ter uma interface web bem amigável e plotar as aeronaves usando o Google Maps.<br />
Para fazer com que o Virtual Radar Server conecte no Raspberry Pi, primeiramente precisamos fazer o streaming via TCP dos frames que o &#8220;rtl_adsb&#8221; está recebendo no Raspberry Pi, o que dá para resolver utilizando o &#8220;netcat&#8221; mesmo:</p>
<div class="codecolorer-container bash default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="bash codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">rtl_adsb <span style="color: #000000; font-weight: bold;">|</span> netcat <span style="color: #660033;">-lp</span> <span style="color: #000000;">8080</span></div></td></tr></tbody></table></div>
<p>Neste caso ele irá escutar na porta 8080 e enviar os frames ADS-B para o cliente que conectar nele. Logo após é só especificar o IP/porta do Raspberry Pi no Virtual Radar Server e se tudo der certo e você conseguir receber algum frame de algum transponder, você verá uma tela parecida com esta mostrada abaixo com o <strong>rastreamento dos aviões em tempo real</strong>:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2013/02/three.png" rel="lightbox[2433]"><img src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2013/02/three.png" alt="" title="three" width="950" height="458" class="aligncenter size-full wp-image-2479" /></a></p>
<p>No screenshot você pode ver um avião da GOL (GOL1446) se dirigindo ao aeroporto (logo a frente onde diz São João) a uma velocidade de 250km/h e descendo a uma velocidade de 195 metros por minuto. Geralmente os aviões enviam o broadcast da mensagem com a posição a cada segundo, tudo vai depender da sua antena, receptor e condições de difusão. Com a minha antena pequena e no meio de prédios eu consegui capturar o broadcast de aviõe em até uns 80km de distância, espero melhorar isto com uma outra antena, só preciso achar o material agora =)</p>
<p><em>- Christian S. Perone</em></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/J3X6r2mu4O8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2433</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2433</feedburner:origLink></item>
		<item>
		<title>Raspberry Pi &amp; Arduino: a laser pointer communication and a LDR voltage sigmoid</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/lI4INlQ95n4/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2383#comments</comments>
		<pubDate>Sun, 19 Aug 2012 23:17:18 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2383</guid>
		<description><![CDATA[So I finally got some more time to play with my Raspberry Pi GPIOs and Arduino, this post will explain how to use a LDR (Photoresistor, Light Dependent Resistor) on the Raspberry Pi to detect a laser light emitted by an Arduino. Plugging the laser module on Arduino Isn&#8217;t easy to plug a module when [...]]]></description>
			<content:encoded><![CDATA[<p>So I finally got some more time to play with my Raspberry Pi GPIOs and Arduino, this post will explain how to use a <a title="Wikipedia :: LDR" href="http://en.wikipedia.org/wiki/Photoresistor" target="_blank">LDR</a> (<em>Photoresistor, Light Dependent Resistor</em>) on the Raspberry Pi to detect a laser light emitted by an Arduino.</p>
<p><span id="more-2383"></span></p>
<h1>Plugging the laser module on Arduino</h1>
<p>Isn&#8217;t easy to plug a module when you have no datasheet or some wiring schemes, the chances are that you&#8217;ll probably burn it if you provide a current greater than the supported. The module I have was bought on the DX.com and it came with 3 pins, &#8220;-&#8221; mark, &#8220;S&#8221; mark and a middle pin without any mark, I assumed that the &#8220;S&#8221; meant &#8220;Signal&#8221; and the &#8220;-&#8221; is the GND pin so I started plugging it on the Arduino pin 14 with a 440 ohm resistor and later I discovered that a 100 ohm resistor was giving the best bright laser without burning it; my advice is to not connect direct any of these modules without a resistor to limit the current, otherwise you&#8217;ll end up burning the diode. Here is the photo of the laser diode in front of the LDR:</p>
<div id="attachment_2387" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ldr_laser.jpg" rel="lightbox[2383]"><img class="size-medium wp-image-2387  " title="ldr_laser" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ldr_laser-300x126.jpg" alt="" width="300" height="126" /></a><p class="wp-caption-text">LDR and Laser (click to enlarge)</p></div>
<p>Here is the wiring scheme to plug the laser on the Arduino:</p>
<div id="attachment_2389" class="wp-caption aligncenter" style="width: 410px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/arduinolaserdiode.png" rel="lightbox[2383]"><img class="size-full wp-image-2389" title="arduinolaserdiode" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/arduinolaserdiode.png" alt="" width="400" height="169" /></a><p class="wp-caption-text">Wiring scheme for the laser</p></div>
<p>And here is the scheme on the breadboard of the Arduino with the 100 ohm resistor:</p>
<div id="attachment_2391" class="wp-caption aligncenter" style="width: 257px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/laser_arduino_scheme.jpg" rel="lightbox[2383]"><img class="size-medium wp-image-2391" title="laser_arduino_scheme" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/laser_arduino_scheme-247x300.jpg" alt="" width="247" height="300" /></a><p class="wp-caption-text">The &#8220;S&#8221; is on the pin 12.</p></div>
<p>In order to test the laser, I just uploaded this program to Arduino, it just blinks the laser module:</p>
<div class="codecolorer-container c default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #993333;">int</span> laserPin <span style="color: #339933;">=</span> <span style="color: #0000dd;">12</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #993333;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
<span style="color: #009900;">&#123;</span><br />
&nbsp; pinMode<span style="color: #009900;">&#40;</span>laserPin<span style="color: #339933;">,</span> OUTPUT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; digitalWrite<span style="color: #009900;">&#40;</span>laserPin<span style="color: #339933;">,</span> HIGH<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><br />
<br />
<span style="color: #993333;">void</span> loop<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
<span style="color: #009900;">&#123;</span><br />
&nbsp; digitalWrite<span style="color: #009900;">&#40;</span>laserPin<span style="color: #339933;">,</span> HIGH<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; delay<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; digitalWrite<span style="color: #009900;">&#40;</span>laserPin<span style="color: #339933;">,</span> LOW<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; delay<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">2000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<h1>Look Ma, no ADC !</h1>
<p>Since Raspberry Pi doesn&#8217;t comes with an <a title="Wikipedia :: Analog-to-digital Converter" href="http://en.wikipedia.org/wiki/Analog-to-digital_converter" target="_blank">Analog-to-digital converter</a> (ADC) like Arduino, connecting a LDR to its GPIOs pins is a little tricky (when you don&#8217;t have an <a title="Raspberry Pi :: Gertboard" href="http://www.raspberrypi.org/archives/1734" target="_blank">Gertboard</a>). The <a href="http://www.raspberrypi-spy.co.uk/2012/08/reading-analogue-sensors-with-one-gpio-pin/" target="_blank">traditional approach</a> is to use a capacitor and then time its charging according to the LDR resistance, this isn&#8217;t a precise measure, but it works good for most applications. What I&#8217;m going to do here is another approach, since I just want to measure if there is a laser light present or not (I&#8217;m not interested on the light energy), I don&#8217;t need to time the capacitor charging.</p>
<p>The first step was to measure the resistance that the LDR creates when the laser light is present, to do that I turned the pin 12 to HIGH on the Arduino and then measured the resistance on the LDR with the multimeter:</p>
<div id="attachment_2395" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/laser_ldr_on.jpg" rel="lightbox[2383]"><img class="size-medium wp-image-2395" title="laser_ldr_on" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/laser_ldr_on-300x101.jpg" alt="" width="300" height="101" /></a><p class="wp-caption-text">Laser emitting on the LDR</p></div>
<p>And the measure was roughly 200 ohms, when the laser wasn&#8217;t pointing to the LDR (even with the day light) the resistance was around the 2k ohm. Now we know that we have to build a circuit that is will use the interval of 0 ohms to 400 ohms (a good margin) as the threshold to activate/deactivate the GPIO pin of the Raspberry Pi.</p>
<p>The challenge now was how to create a circuit that would set the GPIO pin of the Raspberry Pi according to a defined threshold. It turns out that with the help of <a title="Oli Graser Blog" href="http://blog.irwellsprings.com/" target="_blank">Oli Graser</a> (see more about the circuit <a title="Electronics Stackexchange" href="http://electronics.stackexchange.com/questions/38258/plugging-a-ldr-into-gpio-pins-of-a-raspberry-pi" target="_blank">here</a>), I discovered that you can create a voltage <a title="Wikipedia :: Sigmoid Function" href="http://en.wikipedia.org/wiki/Sigmoid_function" target="_blank">sigmoid</a> with a voltage divider circuit outputing to a general transistor, and this is really awesome, can you imagine something like a <a title="Wikipedia :: Logistic Regression" href="http://en.wikipedia.org/wiki/Logistic_regression" target="_blank">logistic regression</a> built in hardware ? Absolutely interesting.</p>
<h1>Voltage divider and the &#8220;sigmoid&#8221; circuit</h1>
<p>And here is the schematics of the voltage divider using the transistor as control of the GPIO pin:</p>
<div id="attachment_2404" class="wp-caption aligncenter" style="width: 410px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/rpi_sigmoid3.png" rel="lightbox[2383]"><img class="size-full wp-image-2404" title="rpi_sigmoid3" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/rpi_sigmoid3.png" alt="" width="400" height="385" /></a><p class="wp-caption-text">Circuit</p></div>
<p>The first part of this circuit is the LDR and the R2 resistor, together they work as voltage divider, when the laser is off, the LDR resistance is very high and then the voltage that goes to the base of the transistor Q1 (I used a BC547B) is very low, making the GPIO pin 4 state to go HIGH, when the laser is on, the LDR resistance is very low and the voltage going to the base of the transistor is enough to activate the circuit and makes the GPIO ping 4 state to go LOW since the the current will flow to the path of less resistance, which is to the GND.</p>
<p>Below you can see the graph of the simulation I&#8217;ve done using the amazing <a title="Circuit Lab" href="https://www.circuitlab.com/" target="_blank">Circuit Lab</a> service:</p>
<div id="attachment_2406" class="wp-caption aligncenter" style="width: 510px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/dc_sweep_ldr.png" rel="lightbox[2383]"><img class="size-large wp-image-2406" title="dc_sweep_ldr" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/dc_sweep_ldr-1024x660.png" alt="" width="500" height="322" /></a><p class="wp-caption-text">The X axis is the LDR resistance and the Y axis is the GPIO pin 4 voltage.</p></div>
<p>You can see in this graph is very similar of a sigmoid function, I&#8217;ve chosen the threshold by setting the voltage divider bottom transistor R2 to 100 ohms, you can adjust this as you wish to make, for LDR 500 ohms threshold I calculated 500 ohm * (0.7v / 0.3v) = 106 ohms (close to the 100 ohm resistor I used), the higher the bottom resistor value you use, the higher will be the center of the sigmoid.</p>
<p>Here is the circuit already built on the breadboard:</p>
<div id="attachment_2407" class="wp-caption aligncenter" style="width: 170px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/DSC00474.jpg" rel="lightbox[2383]"><img class="size-medium wp-image-2407" title="DSC00474" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/DSC00474-160x300.jpg" alt="" width="160" height="300" /></a><p class="wp-caption-text">Circuit on breadboard (click to enlarge)</p></div>
<p>And a zoom on the voltage divider part:</p>
<div id="attachment_2408" class="wp-caption aligncenter" style="width: 528px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/voltage_divider.jpg" rel="lightbox[2383]"><img class="size-full wp-image-2408" title="voltage_divider" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/voltage_divider.jpg" alt="" width="518" height="556" /></a><p class="wp-caption-text">Voltage divider part of the circuit</p></div>
<p>And a zoom on the transistor part:</p>
<div id="attachment_2409" class="wp-caption aligncenter" style="width: 586px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/transistor_part.jpg" rel="lightbox[2383]"><img class="size-full wp-image-2409" title="transistor_part" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/transistor_part.jpg" alt="" width="576" height="559" /></a><p class="wp-caption-text">Transistor part of the circuit</p></div>
<p>And finally, the complete mount of the system:</p>
<div id="attachment_2410" class="wp-caption aligncenter" style="width: 510px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/complete.jpg" rel="lightbox[2383]"><img class="size-large wp-image-2410" title="complete" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/complete-1024x747.jpg" alt="" width="500" height="364" /></a><p class="wp-caption-text">Complete setup (click to enlarge)</p></div>
<p>I used tape to fix the components on the table (there, I fixed it !).</p>
<h1>Reading the GPIO state from Raspberry Pi using Python</h1>
<p>To setup (as INPUT) and read the GPIO pin 4 of the Raspberry Pi (you can see the pins <a title="Raspberry Pi GPIO Pins" href="http://elinux.org/RPi_Low-level_peripherals" target="_blank">explanation here</a>) I used the <a title="RPi.GPIO" href="http://pypi.python.org/pypi/RPi.GPIO" target="_blank">RPi.GPIO</a> Python module, to install it just use &#8220;sudo pip install RPi.GPIO&#8221;, but you&#8217;ll need to have the package &#8220;python-dev&#8221; installed first if you&#8217;re using Raspbian distro. Here is the code to read and show the GPIO pin 4 value:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">import</span> RPi.<span style="color: black;">GPIO</span> <span style="color: #ff7700;font-weight:bold;">as</span> GPIO<br />
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span><br />
<br />
GPIO.<span style="color: black;">setmode</span><span style="color: black;">&#40;</span>GPIO.<span style="color: black;">BCM</span><span style="color: black;">&#41;</span><br />
GPIO.<span style="color: black;">setup</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">4</span>, GPIO.<span style="color: black;">IN</span><span style="color: black;">&#41;</span><br />
<br />
<span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #008000;">True</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; input_value = GPIO.<span style="color: #008000;">input</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Input Value (PIN 4):&quot;</span>, input_value<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0.1</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>And that is it, I hope you liked it and learned something new like I have learned doing this =) the next step will be to check how far I can transmit data using the laser pointer, I discovered that I can read using Python without any problems a change frequency of 2 miliseconds on the Raspberry Pi, this should be better using C code, I still need to implement the transmission protocol.</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/lI4INlQ95n4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2383</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2383</feedburner:origLink></item>
		<item>
		<title>Genetic Programming and a LLVM JIT for restricted Python AST expressions</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/so1j9TBW3uI/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2353#comments</comments>
		<pubDate>Thu, 16 Aug 2012 01:26:39 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2353</guid>
		<description><![CDATA[A small intro on the rationale So I&#8217;m working on a Symbolic Regression Machine written in C/C++ called Shine, which is intended to be a JIT for Genetic Programming libraries (like Pyevolve for instance). The main rationale behind Shine is that we have today a lot of research on speeding Genetic Programming using GPUs (the [...]]]></description>
			<content:encoded><![CDATA[<h1>A small intro on the rationale</h1>
<p>So I&#8217;m working on a Symbolic Regression Machine written in C/C++ called <a title="Shine Documentation" href="http://shine.readthedocs.org/" target="_blank">Shine</a>, which is intended to be a JIT for Genetic Programming libraries (like <a title="Pyevolve" href="http://pyevolve.sourceforge.net/0_6rc1" target="_blank">Pyevolve</a> for instance). The main rationale behind Shine is that we have today a lot of research on speeding Genetic Programming using GPUs (the GPU fever !) or any other special hardware, etc, however we don&#8217;t have many papers talking about optimizing GP using the state of art compilers optimizations like we have on clang, gcc, etc.</p>
<p>The &#8220;hot spot&#8221; or the component that consumes a lot of CPU resources today on Genetic Programming is the evaluation of each individual in order to calculate the fitness of the program tree. This evaluation is often executed on each set of parameters of the &#8220;training&#8221; set. Suppose you want to make a symbolic regression of a single expression like the Pythagoras Theorem and you have a linear space of parameters from 1.0 to 1000.0 with a step of 0.1 you have 10.000 evaluations for each individual (program tree) of your population !</p>
<p>What Shine does is described on the image below:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/shine_process_overview.png" rel="lightbox[2353]"><img class="size-full wp-image-2356 alignnone" title="shine_process_overview" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/shine_process_overview.png" alt="" width="667" height="72" /></a></p>
<p>It takes the individual of the Genetic Programming engine and then converts it to <a title="LLVM: IR Documentation" href="http://www.llvm.org/docs/LangRef.html" target="_blank">LLVM Intermediate Representation</a> (LLVM assembly language), after that it runs the transformation passes of the LLVM (here is where the true power of modern compilers enter on the GP context) and then the LLVM JIT converts the optimized LLVM IR into native code for the specified target (X86, PowerPC, etc).</p>
<p>You can see below the Shine architecture:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/shine_diagram.png" rel="lightbox[2353]"><img class="size-full wp-image-2358 alignnone" title="shine_diagram" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/shine_diagram.png" alt="" width="505" height="639" /></a></p>
<p>This architecture brings a lot of flexibility for Genetic Programming, you can for instance write functions that could be used later on your individuals on any language supported by the LLVM, what matters to Shine is the LLVM IR, you can use any language that LLVM supports and then use the IR generated by LLVM, you can mix code from C, C++, Ada, Fortran, D, etc and use your functions as non-terminal nodes of your Genetic Programming trees.</p>
<p>Shine is still on its earlier development, it looks a simple idea but I still have a lot of problems to solve, things like how to JIT the evaluation process itself instead of doing calls from Python using ctypes bindings of the JITed trees.</p>
<h1>Doing Genetic Programming on the Python AST itself</h1>
<p>During the development of Shine, an idea happened to me, that I could use a restricted Python <a title="Python :: ast module" href="http://docs.python.org/library/ast.html" target="_blank"><strong>Abstract Syntax Tree</strong></a> (AST) as the representation of individuals on a Genetic Programming engine, the main advantage of this is the flexibility and the possibility to reuse a lot of things. Of course that a shared library written in C/C++ would be useful for a lot of Genetic Programming engines that doesn&#8217;t uses Python, but since my spare time to work on this is becoming more and more rare I started to rethink the approach and use Python and the LLVM bindings for LLVM (<a title="LLVMPY" href="http://www.llvmpy.org/" target="_blank">LLVMPY</a>) and I just discovered that is pretty easy to JIT a restricted set of the Python AST to native code using LLVM, and this is what this post is going to show.</p>
<h1>JIT&#8217;ing a restricted Python AST</h1>
<p>The most amazing part of LLVM is obviously the amount of transformation passes, the JIT and of course the ability to use the entire framework through a simple API (ok, not so simple sometimes). To simplify this example, I&#8217;m going to use an arbitrary restricted AST set of the Python AST that supports only subtraction (-), addition (+), multiplication (*) and division (/).</p>
<p>To understand the Python AST, you can use the Python parser that converts source into AST:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">import</span> ast<br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> astp = ast.<span style="color: black;">parse</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;2*7&quot;</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ast.<span style="color: black;">dump</span><span style="color: black;">&#40;</span>astp<span style="color: black;">&#41;</span><br />
<span style="color: #483d8b;">'Module(<br />
&nbsp; &nbsp; body=[Expr(<br />
&nbsp; &nbsp; &nbsp; &nbsp; value=BinOp(<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; left=Num(n=2), op=Mult(), right=Num(n=7)<br />
&nbsp; &nbsp; &nbsp; &nbsp; )<br />
&nbsp; &nbsp; )]<br />
)'</span></div></td></tr></tbody></table></div>
<p>What the parse created was an Abstract Syntax Tree containing the <strong>BinOp</strong> (<em>Binary Operation</em>) with the left operator as the number 2, the right operator as the number 7 and the operation itself as <strong>Multiplication</strong>(Mult), very easy to understand. What we are going to do to create the LLVM IR is to create a visitor that is going to visit each node of the tree. To do that, we can subclass the Python <a href="http://docs.python.org/library/ast.html#ast.NodeVisitor" title="Python :: ast.NodeVisitor" target="_blank">NodeVisitor</a> class from the <strong>ast</strong> module. What the NodeVisitor does is to visit each node of the tree and then call the method &#8216;visit_OPERATOR&#8217; if it exists, when the NodeVisitor is going to visit the node for the BinOp for example, it will call the method &#8216;visit_BinOp&#8217; passing as parameter the BinOp node itself.</p>
<p>The structure of the class for for the JIT visitor will look like the code below:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #808080; font-style: italic;"># Import the ast and the llvm Python bindings</span><br />
<span style="color: #ff7700;font-weight:bold;">import</span> ast<br />
<span style="color: #ff7700;font-weight:bold;">from</span> llvm <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span><br />
<span style="color: #ff7700;font-weight:bold;">from</span> llvm.<span style="color: black;">core</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span><br />
<span style="color: #ff7700;font-weight:bold;">from</span> llvm.<span style="color: black;">ee</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span><br />
<span style="color: #ff7700;font-weight:bold;">import</span> llvm.<span style="color: black;">passes</span> <span style="color: #ff7700;font-weight:bold;">as</span> lp<br />
<br />
<span style="color: #ff7700;font-weight:bold;">class</span> AstJit<span style="color: black;">&#40;</span>ast.<span style="color: black;">NodeVisitor</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">pass</span></div></td></tr></tbody></table></div>
<p>What we need to do now is to create an initialization method to keep the last state of the JIT visitor, this is needed because we are going to JIT the content of the Python AST into a function and the last instruction of the function needs to return what was the result of the last instruction visited by the JIT. We also need to receive a LLVM Module object in which our function will be created as well the closure type, for the sake of simplicity I&#8217;m not type any object, I&#8217;m just assuming that all numbers from the expression are integers, so the closure type will be the LLVM integer type.</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, module, parameters<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">last_state</span> = <span style="color: #008000;">None</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">module</span> = module<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Parameters that will be created on the IR function</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">parameters</span> = parameters<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">closure_type</span> = Type.<span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># An attribute to hold a link to the created function</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># so we can use it to JIT later</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">func_obj</span> = <span style="color: #008000;">None</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>._create_builder<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> _create_builder<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># How many parameters of integer type</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; params = <span style="color: black;">&#91;</span><span style="color: #008000;">self</span>.<span style="color: black;">closure_type</span><span style="color: black;">&#93;</span> <span style="color: #66cc66;">*</span> <span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">parameters</span><span style="color: black;">&#41;</span><br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># The prototype of the function, returning a integer</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># and receiving the integer parameters</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; ty_func = Type.<span style="color: black;">function</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">closure_type</span>, params<span style="color: black;">&#41;</span><br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Add the function to the module with the name 'func_ast_jit'</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">func_obj</span> = <span style="color: #008000;">self</span>.<span style="color: black;">module</span>.<span style="color: black;">add_function</span><span style="color: black;">&#40;</span>ty_func, <span style="color: #483d8b;">'func_ast_jit'</span><span style="color: black;">&#41;</span><br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Create an argument in the function for each parameter specified</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">for</span> index, pname <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">enumerate</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">parameters</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">func_obj</span>.<span style="color: black;">args</span><span style="color: black;">&#91;</span>index<span style="color: black;">&#93;</span>.<span style="color: black;">name</span> = pname<br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Create a basic block and the builder</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; bb = <span style="color: #008000;">self</span>.<span style="color: black;">func_obj</span>.<span style="color: black;">append_basic_block</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;entry&quot;</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">builder</span> = Builder.<span style="color: #dc143c;">new</span><span style="color: black;">&#40;</span>bb<span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Now what we need to implement on our visitor is the &#8216;visit_OPERATOR&#8217; methods for the <strong>BinOp</strong> and for the <strong>Num</strong>and <strong>Name</strong> operators. We will also implement the method to create the return instruction that will return the last state.</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:400px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br />34<br />35<br />36<br />37<br />38<br />39<br />40<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">&nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># A 'Name' is a node produced in the AST when you</span><br />
&nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># access a variable, like '2+x+y', 'x' and 'y' are</span><br />
&nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># the two names created on the AST for the expression.</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> visit_Name<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, node<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># This variable is what function argument ?</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; index = <span style="color: #008000;">self</span>.<span style="color: black;">parameters</span>.<span style="color: black;">index</span><span style="color: black;">&#40;</span>node.<span style="color: #008000;">id</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">last_state</span> = <span style="color: #008000;">self</span>.<span style="color: black;">func_obj</span>.<span style="color: black;">args</span><span style="color: black;">&#91;</span>index<span style="color: black;">&#93;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">last_state</span><br />
<br />
&nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Here we create a LLVM IR integer constant using the </span><br />
&nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Num node, on the expression '2+3' you'll have two</span><br />
&nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Num nodes, the Num(n=2) and the Num(n=3).</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> visit_Num<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, node<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">last_state</span> = Constant.<span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">closure_type</span>, node.<span style="color: black;">n</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">last_state</span><br />
&nbsp; <br />
&nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># The visitor for the binary operation</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> visit_BinOp<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, node<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Get the operation, left and right arguments</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; lhs = <span style="color: #008000;">self</span>.<span style="color: black;">visit</span><span style="color: black;">&#40;</span>node.<span style="color: black;">left</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; rhs = <span style="color: #008000;">self</span>.<span style="color: black;">visit</span><span style="color: black;">&#40;</span>node.<span style="color: black;">right</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; op = node.<span style="color: black;">op</span><br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Convert each operation (Sub, Add, Mult, Div) to their</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># LLVM IR integer instruction equivalent</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">isinstance</span><span style="color: black;">&#40;</span>op, ast.<span style="color: black;">Sub</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; op = <span style="color: #008000;">self</span>.<span style="color: black;">builder</span>.<span style="color: black;">sub</span><span style="color: black;">&#40;</span>lhs, rhs, <span style="color: #483d8b;">'sub_t'</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">elif</span> <span style="color: #008000;">isinstance</span><span style="color: black;">&#40;</span>op, ast.<span style="color: black;">Add</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; op = <span style="color: #008000;">self</span>.<span style="color: black;">builder</span>.<span style="color: black;">add</span><span style="color: black;">&#40;</span>lhs, rhs, <span style="color: #483d8b;">'add_t'</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">elif</span> <span style="color: #008000;">isinstance</span><span style="color: black;">&#40;</span>op, ast.<span style="color: black;">Mult</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; op = <span style="color: #008000;">self</span>.<span style="color: black;">builder</span>.<span style="color: black;">mul</span><span style="color: black;">&#40;</span>lhs, rhs, <span style="color: #483d8b;">'mul_t'</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">elif</span> <span style="color: #008000;">isinstance</span><span style="color: black;">&#40;</span>op, ast.<span style="color: black;">Div</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; op = <span style="color: #008000;">self</span>.<span style="color: black;">builder</span>.<span style="color: black;">sdiv</span><span style="color: black;">&#40;</span>lhs, rhs, <span style="color: #483d8b;">'sdiv_t'</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">last_state</span> = op<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">last_state</span><br />
<br />
&nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># Build the return (ret) statement with the last state</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> build_return<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">builder</span>.<span style="color: black;">ret</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">last_state</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>And that is it, our visitor is ready to convert a Python AST to a LLVM IR assembly language, to run it we&#8217;ll first create a LLVM module and an expression:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">module = Module.<span style="color: #dc143c;">new</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'ast_jit_module'</span><span style="color: black;">&#41;</span><br />
<span style="color: #808080; font-style: italic;"># Note that I'm using two variables 'a' and 'b'</span><br />
expr = <span style="color: #483d8b;">&quot;(2+3*b+33*(10/2)+1+3/3+a)/2&quot;</span><br />
node = ast.<span style="color: black;">parse</span><span style="color: black;">&#40;</span>expr<span style="color: black;">&#41;</span><br />
<span style="color: #ff7700;font-weight:bold;">print</span> ast.<span style="color: black;">dump</span><span style="color: black;">&#40;</span>node<span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Will output:</p>
<pre>
Module(body=[Expr(value=BinOp(left=BinOp(left=BinOp(left=BinOp(
left=BinOp(left=BinOp(left=Num(n=2), op=Add(), right=BinOp(
left=Num(n=3), op=Mult(), right=Name(id='b', ctx=Load()))), op=Add(),
right=BinOp(left=Num(n=33), op=Mult(), right=Num(n=2))), op=Add(),
right=Num(n=1)), op=Add(), right=Num(n=3)), op=Add(),
right=Name(id='a', ctx=Load())), op=Div(), right=Num(n=2)))])
</pre>
<p>Now we can finally run our visitor on that generated AST the check the LLVM IR output:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">visitor = AstJit<span style="color: black;">&#40;</span>module, <span style="color: black;">&#91;</span><span style="color: #483d8b;">'a'</span>, <span style="color: #483d8b;">'b'</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><br />
visitor.<span style="color: black;">visit</span><span style="color: black;">&#40;</span>node<span style="color: black;">&#41;</span><br />
visitor.<span style="color: black;">build_return</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<span style="color: #ff7700;font-weight:bold;">print</span> module</div></td></tr></tbody></table></div>
<p>Will output the LLVM IR:</p>
<pre>
; ModuleID = 'ast_jit_module'

define i32 @func_ast_jit(i32 %a, i32 %b) {
entry:
  %mul_t = mul i32 3, %b
  %add_t = add i32 2, %mul_t
  %add_t1 = add i32 %add_t, 165
  %add_t2 = add i32 %add_t1, 1
  %add_t3 = add i32 %add_t2, 1
  %add_t4 = add i32 %add_t3, %a
  %sdiv_t = sdiv i32 %add_t4, 2
  ret i32 %sdiv_t
}
</pre>
<p>Now is when the real fun begins, we want to run LLVM optimization passes to optimize our code with an equivalent GCC -O2 optimization level, to do that we create a PassManagerBuilder and a PassManager, the PassManagerBuilder is the component that adds the passes to the PassManager, you can also manually add arbitrary transformations like dead code elimination, function inlining, etc:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">pmb = lp.<span style="color: black;">PassManagerBuilder</span>.<span style="color: #dc143c;">new</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<span style="color: #808080; font-style: italic;"># Optimization level</span><br />
pmb.<span style="color: black;">opt_level</span> = <span style="color: #ff4500;">2</span><br />
<br />
pm = lp.<span style="color: black;">PassManager</span>.<span style="color: #dc143c;">new</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
pmb.<span style="color: black;">populate</span><span style="color: black;">&#40;</span>pm<span style="color: black;">&#41;</span><br />
<br />
<span style="color: #808080; font-style: italic;"># Run the passes into the module</span><br />
pm.<span style="color: black;">run</span><span style="color: black;">&#40;</span>module<span style="color: black;">&#41;</span><br />
<span style="color: #ff7700;font-weight:bold;">print</span> module</div></td></tr></tbody></table></div>
<p>Will output:</p>
<pre>
; ModuleID = 'ast_jit_module'

define i32 @func_ast_jit(i32 %a, i32 %b) nounwind readnone {
entry:
  %mul_t = mul i32 %b, 3
  %add_t3 = add i32 %a, 169
  %add_t4 = add i32 %add_t3, %mul_t
  %sdiv_t = sdiv i32 %add_t4, 2
  ret i32 %sdiv_t
}
</pre>
<p>And here we have the optimized LLVM IR of the Python AST expression. The next step is to JIT that IR into native code and then execute it with some parameters:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">&nbsp; &nbsp; ee = ExecutionEngine.<span style="color: #dc143c;">new</span><span style="color: black;">&#40;</span>module<span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; arg_a = GenericValue.<span style="color: #008000;">int</span><span style="color: black;">&#40;</span>Type.<span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; arg_b = GenericValue.<span style="color: #008000;">int</span><span style="color: black;">&#40;</span>Type.<span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: #ff4500;">42</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; retval = ee.<span style="color: black;">run_function</span><span style="color: black;">&#40;</span>visitor.<span style="color: black;">func_obj</span>, <span style="color: black;">&#91;</span>arg_a, arg_b<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Return: %d&quot;</span> <span style="color: #66cc66;">%</span> retval.<span style="color: black;">as_int</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Will output:</p>
<pre>
Return: 197
</pre>
<p>And that&#8217;s it, you have created a AST->LLVM IR converter, optimized the LLVM IR with the transformation passes and then converted it to native code using the LLVM execution engine. I hope you liked =)</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/so1j9TBW3uI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2353</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2353</feedburner:origLink></item>
		<item>
		<title>Raspberry Pi no Brasil</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/Z1R3hTTtHcI/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2310#comments</comments>
		<pubDate>Thu, 02 Aug 2012 12:29:34 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2310</guid>
		<description><![CDATA[* This post is in portuguese Bom, finalmente chegou meu tão esperado Raspberry Pi, consegui efetuar a compra através de uma fila de espera (estou nesta fila desde o primeiro dia de Março de 2012) na Farnell Newark do Brasil que fez a importação de um (ou mais) lotes da Element 14 e agora está distribuindo [...]]]></description>
			<content:encoded><![CDATA[<p><em>* This post is in portuguese</em></p>
<p>Bom, finalmente chegou meu tão esperado <a title="Raspberry Pi Project Site" href="http://www.raspberrypi.org/" target="_blank">Raspberry Pi</a>, consegui efetuar a compra através de uma fila de espera (estou nesta fila desde o primeiro dia de <strong>Março de 2012</strong>) na <a title="Farnell Newark" href="http://www.farnellnewark.com.br/" target="_blank">Farnell Newark</a> do Brasil que fez a importação de um (ou mais) lotes da Element 14 e agora está distribuindo aqui no Brasil. Como moro em <strong>Porto Alegre </strong>no Rio Grande do Sul, o preço total (juntamente com frete) do RPi somaram <strong>R$ 182,22</strong> reais, um valor <strong>bem acima </strong>do esperado para o &#8220;computador de $30 dólares&#8221;, graças ao nosso gentil governo que como todos já devem ter notado, usa uma <strong>EXCELENTE</strong> estratégia para incentivar a pesquisa científica, obrigando desta forma os brasileiros a construirem seu próprio hardware usando bambu ou Pau-brasil, mas isto é outra história.</p>
<p>O atendimento da Farnell Newark foi ótimo, a vendedora foi muito atenciosa e sempre respondeu meus questionamentos em um curtíssimo intervalo de tempo, logo após efetuar o pagamento, demorou apenas 1 dia para o aparelho chegar (foi despachado através da UPS). Segue abaixo uma foto dele (clique para ampliar):</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/rpi-board.jpg" rel="lightbox[2310]"><img class="aligncenter size-medium wp-image-2311" title="rpi-board" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/rpi-board-300x189.jpg" alt="" width="300" height="189" /></a></p>
<h1>Primeiros passos: cartão SD</h1>
<p>A primeira tarefa que precisei fazer para fazê-lo funcionar foi a preparação de um cartão SD. Como não consegui encontrar em nenhum lugar que fui um cartão SD de 4GB eu utilizei um micro-SD da Kingston de 4GB (<strong>class 4</strong>). É importante sempre verificar a <a title="RPi - Verified Peripherals" href="http://elinux.org/RPi_VerifiedPeripherals#SD_cards" target="_blank">Wiki do projeto</a> antes de comprar qualquer cartão SD ou dispositivo USB para o seu Raspberry Pi, pois lá você vai encontrar uma lista de periféricos que comprovadamente funcionam e os que ainda estão problemáticos. Eu aconselho a compra de um cartão <strong>class 4</strong> pois houve relatos de problemas com alguns cartões <strong>class 10</strong>, mas se você já tiver um cartão <strong>class 10</strong> não custa tentar a sorte, este é um problema que provavelmente já deve ter sido corrigido no Kernel do <a href="http://www.raspbian.org/" target="_blank">Raspbian</a>.</p>
<p>Para preparar o cartão você precisa escolher antes uma distro Linux, eu escolhi o Raspbian que é um port do Debian Wheezy para arm otimizado para &#8220;<em>hard float</em>&#8220;, o que ajuda bastante na performance de aplicações que fazem bastante uso de operações de ponto flutuante. Além de ser Debian e ter toda a infinidade de pacotes disponíveis no repositório (no momento em que estou escrevendo já existem mais de 30 mil pacotes do Debian já compilados para armhf), ele está funcionando muito bem com todos dispositivos que utilizei até agora (mouse usb, teclado usb, card sd, ethernet, hdmi video/audio, etc.).</p>
<h1>Fonte de energia (power supply)</h1>
<p>Bom, após ter preparado meu cartão SD eu comprei uma power supply USB, esta da foto abaixo:</p>
<div id="attachment_2315" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps.jpg" rel="lightbox[2310]"><img class="size-medium wp-image-2315" title="ps" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps-300x221.jpg" alt="" width="300" height="221" /></a><p class="wp-caption-text">Carregador USB &#8220;importado&#8221;</p></div>
<p>Para ligar seu RPi você vai precisar de uma fonte USB de 5V com no mínimo 500mA de corrente disponível, não adianta tentar ligar seu Raspberry Pi na USB do computador.</p>
<p>Como nem tudo é tão simples, ao ligar meu RPi ele logo acustou no boot problemas com o módulo ethernet <a href="https://github.com/raspberrypi/linux/issues/60" target="_blank">como este</a> e meu teclado USB não funcionava. O RPi ficava simplesmente travado e sem conexão ethernet alguma, os LEDs nem acendiam.</p>
<p>Sempre desconfie da sua fonte de energia em primeiro lugar ao enfrentar problemas como este, ainda mais aqui no Brasil com todas essas fontes de energia USB &#8220;importadas&#8221;.</p>
<p>Meu primeiro reflexo foi verificar a voltagem que este <em>power supply</em> estava fornecendo, usando os contatos <strong>TP1 </strong>e<strong> TP2</strong> da placa (você pode ver estes contatos como uns buracos na placa na imagem do RPi). O TP1 está ligado no Vin da fonte de energia e o TP2 no GND (terra) da fonte. Ao ligar o voltímetro, ele mostrou a voltagem abaixo:</p>
<div id="attachment_2316" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_voltagem.jpg" rel="lightbox[2310]"><img class="size-medium wp-image-2316" title="ps_voltagem" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_voltagem-300x225.jpg" alt="" width="300" height="225" /></a><p class="wp-caption-text">Voltagem do carregador USB &#8220;importado&#8221;</p></div>
<p>Uma fonte de energia que supostamente deveria fornecer 5v estava fornecendo 5.44V, bem acima do limite de +5% ou -5% tolerado por muitos dispositivos USB como teclados, etc. o RPi possui um regulador de voltagem (<a href="http://pdf.dzsc.com/SE8/SE8117.pdf" rel="nofollow">SE8117T33</a>) que faz a regulagem da entrada de 5V para 3.3V, este regulador tem o 1.1V como voltagem de <em>dropout</em>, ou seja, para que ele forneça um sinal estável de 3.3V ele precisa ter no mínimo 3.3V+1.1V = 4.4V de entrada, até aí tudo bem, pois estamos fornecendo 5.44V, o problema é que este regulador funciona para distribuição de apenas alguns componentes internos do RPi e não para os dispositivos USB e alguns outros componentes (o Vin da fonte é ligado direto aos periféricos USB), ao fornecer 5.44V ele está ultrapassando um limite de 5% que seria entre 4.75V e 5.25V. Este intervalo de voltagem é o ideal para o seu Raspberry Pi, é sempre importante checar se a sua fonte de energia está dentro deste intervalo e afastado dos limites superiores e inferiores. Um dos fatores que pode causar uma queda da voltagem da sua fonte é o próprio cabo micro USB, que acaba atuando como uma resistência, por isso é sempre bom ter um cabo de qualidade (e curto) e uma fonte de qualidade.</p>
<p>No fim da história tive que trocar minha fonte por uma da Samsung que eu já tinha (do Galaxy Tab P1000-L 7&#8243;), este da foto abaixo:</p>
<div id="attachment_2317" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_samsung.jpg" rel="lightbox[2310]"><img class="size-medium wp-image-2317" title="ps_samsung" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_samsung-300x284.jpg" alt="" width="300" height="284" /></a><p class="wp-caption-text">Carregador de celular Samsung</p></div>
<p>Ao trocar o power supply &#8220;importado&#8221; por este da Samsung (imagem acima), a voltagem agora ficou:</p>
<div id="attachment_2318" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_samsung_voltagem.jpg" rel="lightbox[2310]"><img class="size-medium wp-image-2318" title="ps_samsung_voltagem" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_samsung_voltagem-300x225.jpg" alt="" width="300" height="225" /></a><p class="wp-caption-text">Voltagem do carregador USB da Samsung</p></div>
<p>Em estáveis 4.91V, dentro limite aceitável. Após esta troca, tudo passou a funcionar perfeitamente e sem nenhum problema. Fica então a dica para quem for ligar pela primeira vez seu RPi.</p>
<p>Eu testei também um carregador de iPad da Apple, que ficou também um pouco abaixo do esperado e decidi não usá-lo, segue a foto do carregador e a voltagem dele abaixo:</p>
<div id="attachment_2319" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_apple.jpg" rel="lightbox[2310]"><img class="size-medium wp-image-2319" title="ps_apple" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_apple-300x287.jpg" alt="" width="300" height="287" /></a><p class="wp-caption-text">Carregador USB da Apple</p></div>
<div id="attachment_2320" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_apple_voltagem.jpg" rel="lightbox[2310]"><img class="size-medium wp-image-2320" title="ps_apple_voltagem" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/ps_apple_voltagem-300x225.jpg" alt="" width="300" height="225" /></a><p class="wp-caption-text">Voltagem do carregador USB da Apple</p></div>
<h1> Finalmente boot !</h1>
<p>Após todo este trabalho com o carregador, as coisas finalmente funcionaram corretamente e o RPi fez o <em>boot</em> sem problemas como no screenshot abaixo (estou usando uma TV LG de 42&#8243;):</p>
<div id="attachment_2323" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/tv_lg_boot.jpg" rel="lightbox[2310]"><img class="size-medium wp-image-2323" title="tv_lg_boot" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/tv_lg_boot-300x225.jpg" alt="" width="300" height="225" /></a><p class="wp-caption-text">Boot do RPi em TV LG (HDMI), clique para aumentar</p></div>
<p>O RPi tem processadores CPU e GPU realmente incríveis, o boot dele é rápido e a saída na TV ficou realmente muito boa em full hd.</p>
<div id="attachment_2337" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/uname.png" rel="lightbox[2310]"><img class="size-medium wp-image-2337" title="uname" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/uname-300x14.png" alt="" width="300" height="14" /></a><p class="wp-caption-text">uname no Raspbian</p></div>
<p>Para testar o processador ARM, que fica em um clock padrão de 700Mhz (<em>você pode fazer overclock até 1Ghz, mas ainda não me aventurei sem um dissipador decente, mas você pode subir para 800Mhz com segurança</em>) eu rodei os <em>benchmarks</em> do OpenSSL, seguem os resultados abaixo:</p>
<div id="attachment_2324" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/openssl_bench.png" rel="lightbox[2310]"><img class="size-medium wp-image-2324" title="openssl_bench" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/openssl_bench-300x300.png" alt="" width="300" height="300" /></a><p class="wp-caption-text">Benchmark do OpenSSL no RPi</p></div>
<p>Segue também screenshot do <strong>/proc/cpuinfo</strong> com os BogoMIPS:</p>
<div id="attachment_2325" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/cpuinfo.png" rel="lightbox[2310]"><img class="size-medium wp-image-2325" title="cpuinfo" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/cpuinfo-300x127.png" alt="" width="300" height="127" /></a><p class="wp-caption-text">/proc/cpuinfo</p></div>
<p>No Raspberry Pi (ao menos usando Raspbian) você pode escolher como será feito o split da memória RAM dele, o padrão vem com 128MB para CPU e 128MB para a GPU (processador gráfico), como eu não estou usando tanto o GPU por hora eu fiz um split de 224MB para o CPU e apenas 32MB para a GPU, para fazer isto você só precisa copiar o arquivo de boot em cima do que é utilizadao para o boot (start.elf) e faz um reboot, segue screenshot dos arquivos abaixo, note que o SHA1 do split de 224 é iguao ao do start.elf:</p>
<div id="attachment_2326" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/bootsplitram2.png" rel="lightbox[2310]"><img class="size-medium wp-image-2326" title="bootsplitram2" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/bootsplitram2-300x188.png" alt="" width="300" height="188" /></a><p class="wp-caption-text">RAM Split (224MB CPU + 32MB GPU)</p></div>
<p>Após remover 4 dos 6 terminais disponíveis para liberar um pouco mais de memória, a minha memória ficou assim (rodando server do OpenSSH e sem ambiente X):</p>
<div id="attachment_2328" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/free.png" rel="lightbox[2310]"><img class="size-medium wp-image-2328" title="free" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/free-300x73.png" alt="" width="300" height="73" /></a><p class="wp-caption-text">Memória do RPi após split da RAM</p></div>
<p>Fiquei muito satisfeito com este split, você ainda pode fazer outras coisas para liberar memória do seu RPi, como por exemplo trocar o OpenSSH pelo dropbear, etc. <a href="http://extremeshok.com/blog/debian/raspberry-pi-raspbian-tuning-optimising-optimizing-for-reduced-memory-usage/" target="_blank">Aqui tem um ótimo artigo</a> sobre isto.</p>
<p>Algo que não posso deixar passar também é o Python:</p>
<div id="attachment_2334" class="wp-caption aligncenter" style="width: 310px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/pythonplatform.png" rel="lightbox[2310]"><img class="size-medium wp-image-2334" title="pythonplatform" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/pythonplatform-300x43.png" alt="" width="300" height="43" /></a><p class="wp-caption-text">Python no Raspberry Pi</p></div>
<p>&nbsp;</p>
<h1>Arduino vs Raspberry Pi</h1>
<p>Muitos vêem o Raspberry Pi como um concorrente fatal do Arduino, a percepção que tive porém foi muito diferente. Acredito que o Raspberry Pi vai ser um ótimo companheiro para o Arduino, você inclusive pode utilizar o Arduino na própria USB do Raspberry Pi ou usar alguma outra interface UART ou algo assim. Tenho muitos projetos em mente pra começar usando Arduino e Raspberry Pi, espero poder ter tempo de postar sobre eles aqui no blog. Para quem está ansioso para comparar o tamanho do Raspberry Pi com o Arduino, segue abaixo um comparativo entre o Duemilanove, o RPi e uma moeda de 1 real (não podia faltar hehe):</p>
<div id="attachment_2329" class="wp-caption aligncenter" style="width: 288px"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/arduino_and_rpi.jpg" rel="lightbox[2310]"><img class="size-medium wp-image-2329" title="arduino_and_rpi" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/08/arduino_and_rpi-278x300.jpg" alt="" width="278" height="300" /></a><p class="wp-caption-text">Arduino e Raspberry Pi lado a lado</p></div>
<h1>Conclusão</h1>
<p>Você provavelmente não encontrará no Brasil um hardware tão bem elaborado como o Raspberry Pi por estre preço (mesmo alto) de R$ 182,00. Recomendo o RPi para todo mundo que tem o mínimo de interesse, eu poderia ficar aqui falando muita coisa sobre o RPi, sobre os polyfuses usados no design dele, sobre a Gertboard que está por vir, sobre as distribuições disponíveis, etc. Logo farei mais alguns posts sobre os projetos usando o RPi também. Espero que tenham gostado da avaliação.</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/Z1R3hTTtHcI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2310</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2310</feedburner:origLink></item>
		<item>
		<title>Review Board – Review Requests plotting using Python</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/5-lOiocj9y0/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2285#comments</comments>
		<pubDate>Sat, 07 Jul 2012 16:46:29 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2285</guid>
		<description><![CDATA[Review Board is one of these projects that Python community is always proud of, I really think that it became the de facto standard for code reviews nowadays. Review Board comes with an interesting an very useful REST API which you can use to retrieve information about the code reviews, comments, diffs and every single [...]]]></description>
			<content:encoded><![CDATA[<p><a title="Review Board" href="http://www.reviewboard.org/" target="_blank">Review Board</a> is one of these projects that Python community is always proud of, I really think that it became the <em>de facto</em> standard for code reviews nowadays. Review Board comes with an interesting an <a title="Review Board :: Web API Guide" href="http://www.reviewboard.org/docs/manual/1.6/webapi/">very useful REST API</a> which you can use to retrieve information about the code reviews, comments, diffs and every single information stored on its database. So, I created a small Python script called <a title="Github:: rbstats" href="https://github.com/perone/rbstats" target="_blank">rbstats</a> that retrieves information about the Review Requests done by the users and then plots a heat map using <a title="Matplotlib" href="http://matplotlib.sourceforge.net/" target="_blank">matplotlib</a>. I&#8217;ll show an example of the use on the <a title="Apache :: Review Board" href="https://reviews.apache.org/r/" target="_blank">Review Board system</a> of the Apache foundation.</p>
<p>To use the tool, just call it with the API URL of the Review Boars system, i.e.:</p>
<pre>python rb_stats.py
--max-results 80 https://reviews.apache.org/api</pre>
<p>an then you&#8217;ll get a graphical plot like this (<em>click to enlarge</em>):</p>
<p style="text-align: center;"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/07/plot_apache_1.png" rel="lightbox[2285]"><img class="aligncenter size-medium wp-image-2298" title="plot_apache_1" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/07/plot_apache_1-300x194.png" alt="" width="300" height="194" /></a></p>
<p>Where the &#8220;hottest&#8221; points are weighted according to the number of the code reviews that the user have created to the other axis user. You can also plot the statistics by user, for instance of the user <strong>benjaminhindman</strong> using the <strong>autumn</strong> colormap and with 400 max results:</p>
<pre>python rb_stats.py 
--max-results 400 
--from-user benjaminhindman 
--colormap autumn https://reviews.apache.org/api</pre>
<p>&nbsp;</p>
<p>Click to enlarge the image:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/07/plot_user_1.png" rel="lightbox[2285]"><img class="aligncenter size-medium wp-image-2299" title="plot_user_1" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/07/plot_user_1-300x209.png" alt="" width="300" height="209" /></a></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/5-lOiocj9y0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2285</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2285</feedburner:origLink></item>
		<item>
		<title>Accessing HP Cloud OpenStack Nova using Python and Requests</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/9BU1OtLc0w4/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2232#comments</comments>
		<pubDate>Thu, 02 Feb 2012 18:23:48 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2232</guid>
		<description><![CDATA[So, my request to enter on the free and private beta season of the new HP Cloud Services was gently accepted by the HP Cloud team, and today I finally got some time to play with the OpenStack API at HP Cloud. I&#8217;ll start with the first impressions I had with the service: The user [...]]]></description>
			<content:encoded><![CDATA[<p>So, my request to enter on the free and private beta season of the new HP Cloud Services was gently accepted by the <a title="Twitter :: hpcloud" href="https://twitter.com/hpcloud" target="_blank">HP Cloud team</a>, and today I finally got some time to play with the OpenStack API at HP Cloud. I&#8217;ll start with the first impressions I had with the service:</p>
<p>The user interface of the management is very user-friendly, the design is much like of the Twitter Bootstrap, see the screenshot below of the &#8220;Compute&#8221; page from the &#8220;Manage&#8221; section:</p>
<p style="text-align: center;"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/compute_images_xss.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2248" title="compute_images_xss" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/compute_images_xss.png" alt="" width="540" height="307" /></a></p>
<p>As you can see, they have a set of 4 Ubuntu images and a CentOS, I think that since they are still in the beta period, soon we&#8217;ll have more default images to use.</p>
<p>Here is a screenshot of the instance size set:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/compute_sizes_ss.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2239" title="compute_sizes_ss" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/compute_sizes_ss.png" alt="" width="428" height="178" /></a></p>
<p>Since they are using OpenStack, I really think that they should have imported the vocabulary of the OpenStack into the user interface, and instead of calling it &#8220;Size&#8221;, it would be more sensible to use &#8220;<a title="OpenStack :: Wiki :: Flavour" href="http://docs.openstack.org/cactus/openstack-compute/developer/openstack-compute-api-1.1/content/ch04s04.html" target="_blank">Flavour</a>&#8220;.</p>
<p>The user interface still doesn&#8217;t have many features, something that I would really like to have is a &#8220;Stop&#8221; or something like that for the instances, only the &#8220;Terminate&#8221; function is present on the Manage interface, but those are details that they should be still working on since they&#8217;re only in beta.</p>
<p>Another important info to cite is that the access to the instances are done through SSH using a generated RSA key that they provide to you.</p>
<p>Let&#8217;s dig into the OpenStack API now.</p>
<h2>OpenStack API</h2>
<p>To access the OpenStack API you&#8217;ll need the credentials for the authentication, HP Cloud services provide these keys on the Manage interface for each zone/service you have, see the screenshot below (with keys <em>anonymized</em> of course):</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/api_keys_ss.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2255" title="api_keys_ss" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/api_keys_ss.png" alt="" width="672" height="187" /></a>Now, <a title="OpenStack :: Authentication" href="http://docs.openstack.org/api/openstack-compute/1.1/content/Authentication-d1e444.html" target="_blank">OpenStack authentication</a> could be done in different schemes, the scheme that I know that HP supports is the token authentication. I know that there is a lot of clients already supporting the OpenStack API (some have no documentation, some have weird API design, etc.), but the aim of this post is to show how easy would be to create a simple interface to access the OpenStack API using Python and <a title="Python Requests" href="http://docs.python-requests.org/" target="_blank">Requests</a> (HTTP for Humans !).</p>
<p>Let&#8217;s start defining our authentication scheme by sub-classing Requests <strong>AuthBase</strong>:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">class</span> OpenStackAuth<span style="color: black;">&#40;</span>AuthBase<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, auth_user, auth_key<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">auth_key</span> = auth_key<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">auth_user</span> = auth_user<br />
<br />
<span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__call__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, r<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; r.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'X-Auth-User'</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">self</span>.<span style="color: black;">auth_user</span><br />
&nbsp; &nbsp; r.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'X-Auth-Key'</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">self</span>.<span style="color: black;">auth_key</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> r</div></td></tr></tbody></table></div>
<p>As you can see, we&#8217;re defining the X-Auth-User and the X-Auth-Key in the header of the request with the parameters. These parameters are respectively your Account ID and  Access Key we cited earlier. Now, all you have to do is to make the request itself using the authentication scheme, which is pretty easy using Requests:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">ENDPOINT_URL = <span style="color: #483d8b;">'https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/'</span><br />
ACCESS_KEY = <span style="color: #483d8b;">'Your Access Key'</span><br />
ACCOUNT_ID = <span style="color: #483d8b;">'Your Account ID'</span><br />
response = requests.<span style="color: black;">get</span><span style="color: black;">&#40;</span>ENDPOINT_URL, auth=OpenStackAuth<span style="color: black;">&#40;</span>ACCOUNT_ID, ACCESS_KEY<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>And that is it, you&#8217;re done with the authentication mechanism using just a few lines of code, and this is how the request is going to be sent to the HP Cloud service server:</p>
<p style="text-align: center;"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/auth_request.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2260" style="border: 0pt none;" title="auth_request" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/auth_request.png" alt="" width="464" height="314" /></a></p>
<p> This request is sent to the HP Cloud Endpoint URL (https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/). Let&#8217;s see now how the server answered this authentication request:</p>
<p style="text-align: center;"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/auth_response.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2264" style="border: 0pt none;" title="auth_response" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/auth_response.png" alt="" width="478" height="314" /></a></p>
<p style="text-align: left;">You can show this authentication response using Requests by printing the <strong>header</strong> attribute of the request Response object. You can see that the server answered our request with two important header items: X-Server-Management-URL and the X-Auth-Token. The management URL is now our new endpoint, is the URL we should use to do further requests to the HP Cloud services and the X-Auth-Token is the authentication Token that the server generated based on our credentials, these tokens are usually valid for 24 hours, although I haven&#8217;t tested it.</p>
<p style="text-align: left;">What we need to do now is to sub-class the Requests AuthBase class again but this time defining only the authentication token that we need to use on each new request we&#8217;re going to make to the management URL:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">class</span> OpenStackAuthToken<span style="color: black;">&#40;</span>AuthBase<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, request<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">auth_token</span> = request.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'x-auth-token'</span><span style="color: black;">&#93;</span><br />
<br />
<span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__call__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, r<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; r.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'X-Auth-Token'</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">self</span>.<span style="color: black;">auth_token</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> r</div></td></tr></tbody></table></div>
<p style="text-align: left;">Note that the OpenStackAuthToken is receiving now a response request as parameter, copying the X-Auth-Token and setting it on the request.</p>
<p style="text-align: left;">Let&#8217;s consume a service from the OpenStack API v.1.1, I&#8217;m going to call the <a title="OpenStack :: API :: List Servers" href="http://docs.openstack.org/api/openstack-compute/1.1/content/List_Servers-d1e2078.html" target="_blank">List Servers API</a> function, parse the results using JSON and then show the results on the screen:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #808080; font-style: italic;"># Get the management URL from the response header</span><br />
mgmt_url = response.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'x-server-management-url'</span><span style="color: black;">&#93;</span><br />
<br />
<span style="color: #808080; font-style: italic;"># Create a new request to the management URL using the /servers path</span><br />
<span style="color: #808080; font-style: italic;"># and the OpenStackAuthToken scheme we created</span><br />
r_server = requests.<span style="color: black;">get</span><span style="color: black;">&#40;</span>mgmt_url + <span style="color: #483d8b;">'/servers'</span>, auth=OpenStackAuthToken<span style="color: black;">&#40;</span>response<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><br />
<br />
<span style="color: #808080; font-style: italic;"># Parse the response and show it to the screen</span><br />
json_parse = json.<span style="color: black;">loads</span><span style="color: black;">&#40;</span>r_server.<span style="color: black;">text</span><span style="color: black;">&#41;</span><br />
<span style="color: #ff7700;font-weight:bold;">print</span> json.<span style="color: black;">dumps</span><span style="color: black;">&#40;</span>json_parse, indent=<span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p style="text-align: left;">And this is what we get in response to this request:</p>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:400px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br />34<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">{<br />
&nbsp; &nbsp; &quot;servers&quot;: [<br />
&nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;id&quot;: 22378,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;uuid&quot;: &quot;e2964d51-fe98-48f3-9428-f3083aa0318e&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;links&quot;: [<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;href&quot;: &quot;https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/20817201684751/servers/22378&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;rel&quot;: &quot;self&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;href&quot;: &quot;https://az-1.region-a.geo-1.compute.hpcloudsvc.com/20817201684751/servers/22378&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;rel&quot;: &quot;bookmark&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;name&quot;: &quot;Server 22378&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; },<br />
&nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;id&quot;: 11921,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;uuid&quot;: &quot;312ff473-3d5d-433e-b7ee-e46e4efa0e5e&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;links&quot;: [<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;href&quot;: &quot;https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/20817201684751/servers/11921&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;rel&quot;: &quot;self&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;href&quot;: &quot;https://az-1.region-a.geo-1.compute.hpcloudsvc.com/20817201684751/servers/11921&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;rel&quot;: &quot;bookmark&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;name&quot;: &quot;Server 11921&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; ]<br />
}</div></td></tr></tbody></table></div>
<p style="text-align: left;">And that is it, now you know how to use Requests and Python to consume OpenStack API. If you wish to read more information about the API and how does it works, you can read the <a title="OpenStack :: Documentation" href="http://docs.openstack.org/" target="_blank">documentation here</a>.</p>
<p style="text-align: left;"><em>- Christian S. Perone</em></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/9BU1OtLc0w4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2232</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2232</feedburner:origLink></item>
		<item>
		<title>Announce: Stallion v0.2 released !</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/GKni4Uhz3QM/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2220#comments</comments>
		<pubDate>Fri, 16 Dec 2011 00:20:29 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2220</guid>
		<description><![CDATA[I just tagged and released the v0.2 version of the Stallion. In the change log (Github project page), you can see that a lot of bugs were fixed and some new features were introduced in this release. I added compatibility with almost all Python 2.x versions, PyPy 1.7+ (and probably older versions too), I also [...]]]></description>
			<content:encoded><![CDATA[<p>I just tagged and released the v0.2 version of the Stallion. In the change log (<a title="Github :: Stallion" href="https://github.com/perone/stallion" target="_blank">Github project page)</a>, you can see that a lot of bugs were fixed and some new features were introduced in this release. I added compatibility with almost all Python 2.x versions, PyPy 1.7+ (and probably older versions too), I also fixed the compatibility with the Internet Explorer browser, now you should be able to use Stallion with Chrome, Firefox and IE.</p>
<p>The most important feature introduced is the global checking for updates (a lot of people requested it):</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/classifiers.png" rel="lightbox[2220]"><img class="aligncenter size-full wp-image-2221" title="classifiers" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/classifiers.png" alt="" width="273" height="202" /></a></p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates_avail.png" rel="lightbox[2220]"><img class="aligncenter size-full wp-image-2227" title="updates_avail" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates_avail.png" alt="" width="270" height="325" /></a></p>
<p>The new checking is under the menu &#8220;PyPI Repository&#8221;. Another new feature is the refactoring on the visual appearance of the package classifiers:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/classifiers2.png" rel="lightbox[2220]"><img class="aligncenter size-medium wp-image-2222" title="classifiers2" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/classifiers2-298x300.png" alt="" width="298" height="300" /></a></p>
<p>Some small visual enhancements were also introduced, like the little gray marker next to the selected package:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/selected_package.png" rel="lightbox[2220]"><img class="aligncenter size-full wp-image-2223" title="selected_package" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/selected_package.png" alt="" width="163" height="94" /></a></p>
<p>I hope you liked, I&#8217;m looking forward to implement more features as soon as possible, but a new version shouldn&#8217;t be released until next year.</p>
<p><strong>Visit the <a title="Github :: Stallion" href="https://github.com/perone/stallion" target="_blank">project page at Github</a> to get instructions on how to update or install Stallion.</strong></p>
<p>- Christian S. Perone</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/GKni4Uhz3QM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2220</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2220</feedburner:origLink></item>
		<item>
		<title>Announce: ‘Stallion’ – Python Package Manager</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/TJ5AXHMX0IM/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2200#comments</comments>
		<pubDate>Sun, 04 Dec 2011 17:35:57 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2200</guid>
		<description><![CDATA[I&#8217;m happy to announce the first release v.0.1 of the Stallion project. Stallion is a visual Python package manager compatible with Python 2.6 and 2.7 (I still haven&#8217;t tested it with Python 2.5). The motivation behind Stallion is to provide an user friendly visualization with some management features (most of them are still under development) [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m happy to announce the first release v.0.1 of the Stallion project. Stallion is a visual Python package manager compatible with Python 2.6 and 2.7 (I still haven&#8217;t tested it with Python 2.5).</p>
<p>The motivation behind Stallion is to provide an user friendly visualization with some management features (most of them are still under development) for Python packages installed on your local Python distribution. Stallion is intended to be used specially for Python newcomers.</p>
<p>The project is <a title="Github :: Stallion" href="https://github.com/perone/stallion" target="_blank">currently hosted at Github</a>, so feel free to<strong> fork, contribute, make suggestion, report bugs, etc.</strong></p>
<h3>Installation</h3>
<p>All you need to do to install Stallion is to use your favorite Python distribution system, examples:</p>
<blockquote>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">user@machine:~/$ pip install stallion<br />
or<br />
user@machine:~/$ easy_install stallion</div></td></tr></tbody></table></div>
</blockquote>
<p>By doing this on your prompt (Windows/Linux), the pip/setuptools will download and install external dependencies (Flask, Jinja, docutils, etc.).<br />
After installing Stallion, you need to start the local server by using:</p>
<blockquote>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">user@machine:~/$ python -m stallion.main</div></td></tr></tbody></table></div>
</blockquote>
<p>And if it&#8217;s all ok, Stallion will start the server on localhost only at the port 5000, so all you need to do now is to browse into the URL <strong>http://localhost:5000</strong></p>
<p>You can also download install packages from the <a title="PyPI :: Stallion" href="http://pypi.python.org/pypi/Stallion/0.1" target="_blank">PyPI repository</a>.</p>
<h3>See some screenshots (click to enlarge)</h3>
<p>Click on the screenshots below to enlarge.</p>
<p style="text-align: center;">Home</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/main_page.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2207" title="main_page" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/main_page-300x162.png" alt="" width="300" height="162" /></a></p>
<p style="text-align: center;">Installed package information</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/distr.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2209" title="distr" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/distr-300x254.png" alt="" width="300" height="254" /></a></p>
<p style="text-align: center;">Package metadata</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/metadata.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2210" title="metadata" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/metadata-190x300.png" alt="" width="190" height="300" /></a></p>
<p style="text-align: center;">Check PyPI for updates available</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2211" title="updates" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates-300x218.png" alt="" width="300" height="218" /></a><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates2.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2212" title="updates2" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates2-300x204.png" alt="" width="300" height="204" /></a></p>
<p style="text-align: center;">PyPI version mismatch diagnosis<a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/diagnosis.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2213" title="diagnosis" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/diagnosis-300x217.png" alt="" width="300" height="217" /></a></p>
<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/TJ5AXHMX0IM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2200</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2200</feedburner:origLink></item>
		<item>
		<title>Hacking into Python objects internals</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/ecB1PeGDVFA/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2171#comments</comments>
		<pubDate>Thu, 24 Nov 2011 00:26:52 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2171</guid>
		<description><![CDATA[You know, Python represents every object using the low-level C API PyObject (or PyVarObject for variable-size objects) structure, so, concretely, you can cast any Python object pointer to this type; this inheritance is built by hand, every new object must have a leading macro called PyObject_HEAD which defines the PyObject header for the object. The [...]]]></description>
			<content:encoded><![CDATA[<p>You know, Python represents every object using the low-level C API <strong>PyObject </strong>(or <strong>PyVarObject</strong> for variable-size objects) structure, so, concretely, you can cast any Python object pointer to this type; this inheritance is built by hand, every new object must have a leading macro called <strong>PyObject_HEAD</strong> which defines the <strong>PyObject</strong> header for the object. The <strong>PyObject</strong> structure is declared in <a href="http://hg.python.org/cpython/file/d1bdafa161e7/Include/object.h#l106" target="_blank"><span style="color: #008080;">Include/object.h</span></a> as:</p>
<div class="codecolorer-container c default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> _object <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; PyObject_HEAD<br />
<span style="color: #009900;">&#125;</span> PyObject<span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>and the PyObject_HEAD macro is defined as:</p>
<div class="codecolorer-container c default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339933;">#define PyObject_HEAD                   \<br />
&nbsp; &nbsp; _PyObject_HEAD_EXTRA                \<br />
&nbsp; &nbsp; Py_ssize_t ob_refcnt;               \<br />
&nbsp; &nbsp; struct _typeobject *ob_type;</span></div></td></tr></tbody></table></div>
<p>&#8230; with two fields (<em>forget the<strong> _PyObject_HEAD_EXTRA</strong>, it&#8217;s only used for a tracing debug feature</em>) called <strong>ob_refcnt</strong> and <strong>ob_type</strong>, representing the reference counting for the object and the type of the object. I know you can use <strong>sys.getrefcount</strong> to get the reference counting of an object, but hacking the object memory using ctypes is by far more powerful, since you can get the contents of any field of the object (in cases where you don&#8217;t have a native API for that), I&#8217;ll show more examples later, but lets focus on the reference counting field of the object.</p>
<h3>Getting the reference count (ob_refcnt)</h3>
<p>So, in Python, we have the built-in function <strong>id()</strong>, this function returns the identity of the object, but, looking at its definition on CPython implementation, you&#8217;ll notice that <strong>id()</strong> returns the memory address of the object, see the source in <a href="http://hg.python.org/cpython/file/d1bdafa161e7/Python/bltinmodule.c#l904" target="_blank"><span style="color: #008080;">Python/bltinmodule.c</span></a>:</p>
<div class="codecolorer-container c default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #993333;">static</span> PyObject <span style="color: #339933;">*</span><br />
builtin_id<span style="color: #009900;">&#40;</span>PyObject <span style="color: #339933;">*</span>self<span style="color: #339933;">,</span> PyObject <span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span><br />
<span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">return</span> PyLong_FromVoidPtr<span style="color: #009900;">&#40;</span>v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>&#8230; the function <strong>PyLong_FromVoidPtr</strong> returns a Python long object from a void pointer. So, in CPython, this value is the address of the object in the memory as shown below:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> value = <span style="color: #ff4500;">666</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">hex</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><br />
<span style="color: #483d8b;">'0x8998e50'</span> <span style="color: #808080; font-style: italic;"># memory address of the 'value' object</span></div></td></tr></tbody></table></div>
<p>Now that we have the memory address of the object, we can use the Python ctypes module to get the reference counting by accessing the attribute <strong>ob_refcnt</strong>, here is the code needed to do that:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> value = <span style="color: #ff4500;">666</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> value_address = <span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value<span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_refcnt = ctypes.<span style="color: black;">c_long</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span>value_address<span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_refcnt<br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>What I&#8217;m doing here is getting the integer value from the <strong>ob_refcnt</strong> attribute of the <strong>PyObject</strong> in memory.  Let&#8217;s add a new reference for the object &#8216;value&#8217; we created, and then check the reference count again:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> value_ref = value<br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value_ref<span style="color: black;">&#41;</span> == <span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value<span style="color: black;">&#41;</span><br />
<span style="color: #008000;">True</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_refcnt<br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Note that the reference counting was increased by 1 due to the new reference variable called &#8216;value_ref&#8217;.</p>
<h3>Interned strings state (ob_sstate)</h3>
<p>Now, getting the reference count wasn&#8217;t even funny, we already had the <strong>sys.getrefcount</strong> API for that, but what about the <a title="Wikipedia :: String Interning" href="http://en.wikipedia.org/wiki/String_interning" target="_blank">interned state of the strings</a> ? In order to avoid the creation of different allocations for the same string (and to speed comparisons), Python uses a dictionary that works like a &#8220;cache&#8221; for strings, this dictionary is defined in <a href="http://hg.python.org/cpython/file/d1bdafa161e7/Objects/stringobject.c#l16" target="_blank"><span style="color: #008080;">Objects/stringobject.c</span></a>:</p>
<div class="codecolorer-container c default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #808080; font-style: italic;">/* This dictionary holds all interned strings.  Note that references to<br />
strings in this dictionary are *not* counted in the string's ob_refcnt.<br />
When the interned string reaches a refcnt of 0 the string deallocation<br />
function will delete the reference from this dictionary.<br />
<br />
Another way to look at this is that to say that the actual reference<br />
count of a string is:  s-&amp;gt;ob_refcnt + (s-&amp;gt;ob_sstate?2:0)<br />
*/</span><br />
<span style="color: #993333;">static</span> PyObject <span style="color: #339933;">*</span>interned<span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>I also copied here the comment about the dictionary, because is interesting to note that the strings in the dictionary aren&#8217;t counted in the string&#8217;s <strong>ob_refcnt</strong>.</p>
<p>So, the interned state of a string object is hold in the attribute <strong>ob_sstate</strong> of the string object, let&#8217;s see the definition of the Python string object:</p>
<div class="codecolorer-container c default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; PyObject_VAR_HEAD<br />
&nbsp; &nbsp; <span style="color: #993333;">long</span> ob_shash<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #993333;">int</span> ob_sstate<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #993333;">char</span> ob_sval<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #808080; font-style: italic;">/* Invariants:<br />
&nbsp; &nbsp; *     ob_sval contains space for 'ob_size+1' elements.<br />
&nbsp; &nbsp; *     ob_sval[ob_size] == 0.<br />
&nbsp; &nbsp; *     ob_shash is the hash of the string or -1 if not computed yet.<br />
&nbsp; &nbsp; *     ob_sstate != 0 iff the string object is in stringobject.c's<br />
&nbsp; &nbsp; *       'interned' dictionary; in this case the two references<br />
&nbsp; &nbsp; *       from 'interned' to this object are *not counted* in ob_refcnt.<br />
&nbsp; &nbsp; */</span><br />
<span style="color: #009900;">&#125;</span> PyStringObject<span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>As you can note, strings objects inherit from the PyObject_VAR_HEAD macro, which defines another header attribute, let&#8217;s see the definition to get the complete idea of the structure:</p>
<div class="codecolorer-container c default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339933;">#define PyObject_VAR_HEAD               \<br />
&nbsp; &nbsp; PyObject_HEAD                       \<br />
&nbsp; &nbsp; Py_ssize_t ob_size; /* Number of items in variable part */</span></div></td></tr></tbody></table></div>
<p>The <strong>PyObject_VAR_HEAD</strong> macro adds another field called <strong>ob_size</strong>, which is the number of items on the variable part of the Python object (i.e. the number of items on a list object). So, before getting to the <strong>ob_sstate</strong> field, we need to shift our offset to skip the fields<strong> ob_refcnt (long)</strong>, <strong>ob_type (void*)</strong> (from <strong>PyObject_HEAD</strong>), the field <strong>ob_size (long)</strong> (from <strong>PyObject_VAR_HEAD</strong>) and the field <strong>ob_shash</strong> <strong>(long)</strong> from the <strong>PyStringObject</strong>. Concretely, we need to skip this offset (3 fields with size <strong>long</strong> and one field with size <strong>void*</strong>) of bytes:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_sstate_offset = ctypes.<span style="color: black;">sizeof</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_long</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">3</span> + ctypes.<span style="color: black;">sizeof</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_voidp</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_sstate_offset<br />
<span style="color: #ff4500;">16</span></div></td></tr></tbody></table></div>
<p>Now, let&#8217;s prepare two cases, one that we know that isn&#8217;t interned and another that is surely interned, then we&#8217;ll force the interned state of the other non-interned string to check the result of the <strong>ob_sstate</strong> attribute:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> a = <span style="color: #483d8b;">&quot;lero&quot;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> b = <span style="color: #483d8b;">&quot;&quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;l&quot;</span>, <span style="color: #483d8b;">&quot;e&quot;</span>, <span style="color: #483d8b;">&quot;r&quot;</span>, <span style="color: #483d8b;">&quot;o&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ctypes.<span style="color: black;">c_long</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>a<span style="color: black;">&#41;</span> + ob_sstate_offset<span style="color: black;">&#41;</span><br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ctypes.<span style="color: black;">c_long</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>b<span style="color: black;">&#41;</span> + ob_sstate_offset<span style="color: black;">&#41;</span><br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ctypes.<span style="color: black;">c_long</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>intern<span style="color: black;">&#40;</span>b<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> + ob_sstate_offset<span style="color: black;">&#41;</span><br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Note that the interned state for the object &#8220;a&#8221; is 1 and for the object &#8220;b&#8221; is 0. After forcing the interned state of the variable &#8220;b&#8221;, we can see that the field <strong>ob_sstate</strong> has changed to 1.</p>
<h3>Changing internal states (evil mode)</h3>
<p>Now, let&#8217;s suppose we want to change some internal state of a Python object through the interpreter. Let&#8217;s try to change the value of an int object. Int objects are defined in <a href="http://hg.python.org/cpython/file/d1bdafa161e7/Include/intobject.h#l22" target="_blank"><span style="color: #008080;">Include/intobject.h</span></a>:</p>
<div class="codecolorer-container c default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; PyObject_HEAD<br />
&nbsp; &nbsp; <span style="color: #993333;">long</span> ob_ival<span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span> PyIntObject<span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>As you can see, the internal value of an int is stored in the field <strong>ob_ival</strong>, to change it, we just need to skip the <strong>ob_refcnt</strong> <strong>(long)</strong> and the <strong>ob_type (void*)</strong> from the <strong>PyObject_HEAD</strong>:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> value = <span style="color: #ff4500;">666</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_ival_offset = ctypes.<span style="color: black;">sizeof</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_long</span><span style="color: black;">&#41;</span> + ctypes.<span style="color: black;">sizeof</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_voidp</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_ival = ctypes.<span style="color: black;">c_int</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value<span style="color: black;">&#41;</span>+ob_ival_offset<span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_ival<br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">666</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_ival.<span style="color: black;">value</span> = <span style="color: #ff4500;">8</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> value<br />
<span style="color: #ff4500;">8</span></div></td></tr></tbody></table></div>
<p>And that is it, we have changed the value of the int value directly in the memory.</p>
<p>I hope you liked it, you can play with lots of other Python objects like lists and dicts, note that this method is just intended to show how the Python objects are structured in the memory and how you can change them using the native API, but obviously, you&#8217;re not supposed to use this to change the value of ints lol.</p>
<p><strong>Update 11/29/11</strong>: <em>you&#8217;re not supposed to do such things on your production code or something like that, in this post I&#8217;m doing lazy assumptions about arch details like sizes of primitives, etc. <strong>Be warned</strong>.</em></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/ecB1PeGDVFA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2171</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2171</feedburner:origLink></item>
		<item>
		<title>C++11 user-defined literals and some constructions</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/gsv4C4Q0CDs/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2104#comments</comments>
		<pubDate>Mon, 21 Nov 2011 23:39:20 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
		
		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2104</guid>
		<description><![CDATA[I was taking a look at the proposal N2765 (user-defined literals) already implemented on the development snapshots of the GCC 4.7 and I was thinking in how user-defined literals can be used to create some interesting and sometimes strange constructions. Introduction to user-defined literals C++03 has some literals, like the &#8220;f&#8221; in &#8220;12.2f&#8221; that converts [...]]]></description>
			<content:encoded><![CDATA[<p>I was taking a look at the proposal <a title="User-define literals" href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf" target="_blank">N2765</a> (<strong>user-defined literals</strong>) already implemented on the development snapshots of the <a title="GCC 4.7 Changelog" href="http://gcc.gnu.org/gcc-4.7/changes.html" target="_blank">GCC 4.7</a> and I was thinking in how user-defined literals can be used to create some interesting and sometimes strange constructions.</p>
<h3>Introduction to user-defined literals</h3>
<p>C++03 has some literals, like the &#8220;f&#8221; in &#8220;12.2f&#8221; that converts the double value to float. The problem is that these literals aren&#8217;t very flexible since they&#8217;re pretty fixed, so you can&#8217;t change them or create new ones. To overcome this situation, C++11 introduced the concept of <strong>&#8220;user-defined literals&#8221;</strong> that will give to the user, the ability to create new custom literal modifiers. The new user-defined literals can create either built-in types (e.g. int) or user-define types (e.g. classes), and the fact that they could be very useful is an effect that they can return objects instead of only primitives.</p>
<p>The new syntax for the user-defined literals is:</p>
<div class="codecolorer-container cpp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">OutputType operator <span style="color: #FF0000;">&quot;&quot;</span> _suffix<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>literal_string<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></div></td></tr></tbody></table></div>
<p>&#8230; in the case of a literal string. The <strong>OutputType</strong> is anything you want (object or primitive), the &#8220;_suffix&#8221; is the name of the literal modifier, isn&#8217;t required to use the underline in front of it, but if you don&#8217;t use you&#8217;ll get some warnings telling you that suffixes not preceded by the underline are reserved for future standardization.</p>
<h3>Examples</h3>
<h4>Kmh to Mph converter</h4>
<div class="codecolorer-container cpp default codecolorer-noborder" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666;">// stupid converter class</span><br />
<span style="color: #0000ff;">class</span> Converter<br />
<span style="color: #008000;">&#123;</span><br />
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; Converter<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">double</span> kmph<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> m_kmph<span style="color: #008000;">&#40;</span>kmph<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ~Converter<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">double</span> to_mph<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> m_kmph <span style="color: #000040;">/</span> <span style="color:#800080;">1.609344</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">double</span> m_kmph<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #666666;">// user-defined literal</span><br />
Converter operator <span style="color: #FF0000;">&quot;&quot;</span> kmph<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">long</span> <span style="color: #0000ff;">double</span> kmph<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> Converter<span style="color: #008000;">&#40;</span>kmph<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Converter: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #008000;">&#40;</span>80kmph<span style="color: #008000;">&#41;</span>.<span style="color: #007788;">to_mph</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// note that I'm using parenthesis in order to</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// be able to call the 'to_mph' method</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>Note that the literal for for numeric types should be either <strong>long double</strong> (for floating point literals) or <strong>unsigned long long</strong> (for integral literals). There is no signed type, because a signed literal is parsed as an expression with a sign as unary prefix and the unsigned number part.</p>
<h4>std::string literal</h4>
<div class="codecolorer-container cpp default codecolorer-noborder" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> operator <span style="color: #FF0000;">&quot;&quot;</span> s <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span> p, <span style="color: #0000ff;">size_t</span> n<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> std<span style="color: #008080;">::</span><span style="color: #007788;">string</span><span style="color: #008000;">&#40;</span>p,n<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;convert me to a string&quot;</span>s.<span style="color: #007788;">length</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// here you don't need the parenthesis, note that the</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// c-string was automagically converted to std::string</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<h4>system() call</h4>
<div class="codecolorer-container cpp default codecolorer-noborder" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">int</span> operator <span style="color: #FF0000;">&quot;&quot;</span> ex<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>cmd, <span style="color: #0000ff;">size_t</span> num_chars<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">system</span><span style="color: #008000;">&#40;</span>cmd<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #FF0000;">&quot;ls -lah&quot;</span>ex<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<h4>alias and std::map</h4>
<div class="codecolorer-container cpp default codecolorer-noborder" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">typedef</span> std<span style="color: #008080;">::</span><span style="color: #007788;">map</span><span style="color: #000080;">&lt;</span>std<span style="color: #008080;">::</span><span style="color: #007788;">string</span>, <span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span> MyMap<span style="color: #008080;">;</span><br />
MyMap create_map<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; MyMap m<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; m<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">&quot;lol&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">7</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> m<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<span style="color: #0000ff;">auto</span> m <span style="color: #000080;">=</span> create_map<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">int</span><span style="color: #000040;">&amp;</span> operator <span style="color: #FF0000;">&quot;&quot;</span> m<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>key, <span style="color: #0000ff;">size_t</span> length<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> m<span style="color: #008000;">&#91;</span>key<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;lol&quot;</span>m <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// 7</span><br />
&nbsp; &nbsp; <span style="color: #FF0000;">&quot;lol&quot;</span>m <span style="color: #000080;">=</span> <span style="color: #0000dd;">2</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;lol&quot;</span>m <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// 2</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<h3>References</h3>
<p><a href="http://en.wikipedia.org/wiki/C%2B%2B11#User-defined_literals" title="Wikipedia :: C++11 (User-defined literals)" target="_blank">Wikipedia :: C++11 (User-defined literals)</a></p>
<p><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf" title="Proposal N2765" target="_blank">Proposal N2765</a></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/gsv4C4Q0CDs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2104</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2104</feedburner:origLink></item>
	</channel>
</rss>
