<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Rafael Barreto</title>
	<atom:link href="http://rafaelbarreto.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://rafaelbarreto.com</link>
	<description>Biased random thoughts about technical stuff</description>
	<lastBuildDate>Fri, 11 Nov 2011 18:42:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='rafaelbarreto.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Rafael Barreto</title>
		<link>http://rafaelbarreto.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://rafaelbarreto.com/osd.xml" title="Rafael Barreto" />
	<atom:link rel='hub' href='http://rafaelbarreto.com/?pushpress=hub'/>
		<item>
		<title>Aspect-like abstractions and Python metaclasses</title>
		<link>http://rafaelbarreto.com/2011/09/12/aspect-like-abstractions-and-python-metaclasses/</link>
		<comments>http://rafaelbarreto.com/2011/09/12/aspect-like-abstractions-and-python-metaclasses/#comments</comments>
		<pubDate>Mon, 12 Sep 2011 20:11:44 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.com/?p=892</guid>
		<description><![CDATA[If you follow this blog you know I enjoy Python. Many of my posts are Python related and this is a trend here. However, I&#8217;m not one of those fanboys that talk about technologies as religions. Most of the time I prefer to work on more dense and formal computing themes, like Machine Learning, and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=892&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:center;"><a href="http://xkcd.com/353/" target="_blank"><img class="aligncenter" title="Python: programming is fun again!" src="http://imgs.xkcd.com/comics/python.png" alt="" width="518" height="588" /></a></p>
<p style="text-align:justify;">If you follow this blog you know I enjoy Python. Many of my posts are Python related and this is a trend here. However, I&#8217;m not one of those fanboys that talk about technologies as religions. Most of the time I prefer to work on more dense and formal computing themes, like Machine Learning, and do not care much about specific technologies (despite being needed tools, they are ephemeral). And this is the very reason I REALLY enjoy Python =). It seems confusing, but makes complete sense to me. Because I like formal stuff, I prefer abstract to concrete. And Python is one of the few languages I know in which I can remain at a high level of abstract thinking while building concrete real world stuff. Let me demonstrate this abstraction power in a practical use case.</p>
<p style="text-align:justify;">Consider the plug-in infrastructure I described in this <a title="A very lightweight plug-in infrastructure in Python" href="http://rafaelbarreto.com/2011/08/25/a-very-lightweight-plug-in-infrastructure-in-python/" target="_blank">previous post</a>. Although extremely simple, that general design is good enough for many scenarios. It defines a common interface and employs a little of meta-programming to auto-discover the plug-ins. However, it has a serious flaw. Let&#8217;s look at the following code snippet:</p>
<p><pre class="brush: python;">
class Troublemaker(Plugin):

    def setup(self):
        raise RuntimeError(&quot;I'm a troublemaker and I'll not let you set me up.&quot;)

    def teardown(self):
        raise RuntimeError(&quot;I'm a troublemaker and I'll not let you tear me down.&quot;)

    def run(self, *args, **kwards):
        raise RuntimeError(&quot;I'm a troublemaker and I'll not let you run me.&quot;)
</pre></p>
<p style="text-align:justify;">From the designed infrastructure point of view, this is a completely fine plug-in and will be discovered and loaded without problems. So, what&#8217;s wrong? Well&#8230; the <code>Troublemaker</code> methods are supposed to be called many times in a couple of different points by the main application. In order to avoid program crashes, code for exception handling and logging (for plug-in debug purposes) must be inserted in ALL THESE POINTS. It&#8217;s not difficult to see this doesn&#8217;t scale up. Imagine if the plug-ins common interface had 10 methods&#8230; what a hell hum?</p>
<p style="text-align:justify;">The problem here is a fundamental one. Plug-ins must obey a simple rule which wasn&#8217;t addressed in the designed infrastructure:</p>
<blockquote>
<p style="text-align:justify;">A plug-in should be hermetic. Exceptions should not leak and all abnormal situations should be logged.</p>
</blockquote>
<p style="text-align:justify;">But how this requirement can be enforced by the design? <em>There must be some kind of abstraction barrier between the plug-ins methods and the callers taking responsibility for handling and logging any exception, no matter where and when they occur</em>. Does it smell like a typical <a title="Aspect Oriented Programming" href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" target="_blank">Aspect Oriented Programming</a> (AOP) problem domain to you? The <a title="Cross-cutting concern" href="http://en.wikipedia.org/wiki/Cross-cutting_concern" target="_blank">cross-cutting concerns</a> are the exceptions handling and logging, which are spread across the main application. We want to isolate these concerns, so&#8230; yes, this sounds like AOP to me and that&#8217;s why it&#8217;s difficult to imagine a clean and low invasive solution using only normal OO constructs: <em>thinking using the wrong paradigm</em> =P.</p>
<p style="text-align:justify;">Some AOP concepts can be easily implemented in Python using the notion of <em>metaclass</em>. There are lots of good materials about this subject on the net (for example, <a title="What's a metaclass in Python?" href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python" target="_blank">this discussion at SO</a>) and I&#8217;ll not replicate them. However, a brief overview comes in handy for those unfamiliar with the idea.</p>
<p style="text-align:justify;">A class can be viewed as a template for the creation of objects, which are entities that modify their states by responding to messages. Thus, a class defines the messages and how they are responded by the objects (the objects shape). Different objects of the same class can have different states, but they share the same shape.</p>
<p style="text-align:justify;">So far, nothing new. The surprise is that, in Python, <em>classes are themselves objects</em> (like all Python data). This is very easy to see:</p>
<p><pre class="brush: python; light: true;">
&gt;&gt;&gt; class Original(object): pass
...
&gt;&gt;&gt; Copied = Original
&gt;&gt;&gt; Copied == Original
True
&gt;&gt;&gt; x = Copied()
&gt;&gt;&gt; x.__class__.__name__
'Original'
</pre></p>
<p style="text-align:justify;">Since a class is also an object, and objects are produced using a class as template, what is the template of a class? In other words, what&#8217;s the class of a class? Guess who said: a <em>metaclass</em>. Metaclasses are templates, recipes of how classes are created. The default Python metaclass is <code>type</code>:</p>
<p><pre class="brush: python; light: true;">
&gt;&gt;&gt; Copied.__class__.__name__
'type'
</pre></p>
<p style="text-align:justify;">Yeah&#8230; <code>type</code> is a class used to create other classes. When the <code>class</code> keyword is found in a source code, the Python interpreter uses <code>type</code> to create the class. This means you can create classes at run-time. For instance, <code>class Original(object): pass</code> is completely equivalent to <code>type("Original", (object,), {})</code>.</p>
<p style="text-align:justify;">And what&#8217;s the class of <code>type</code> metaclass?</p>
<p><pre class="brush: python; light: true;">
&gt;&gt;&gt; type.__class__.__name__
'type'
</pre></p>
<p style="text-align:justify;">Aha! Here the interpreter cheats a bit as you can see, but that&#8217;s necessary. After all, we are engineers and not philosophers to ask what&#8217;s the class of a metaclass&#8230; =P</p>
<p style="text-align:justify;">Anyway&#8230; the important point here is that Python allows you to create your own metaclass and customize how classes are created by inheriting from <code>type</code>. Why would you like to do this? Well&#8230; indeed, most of the time you SHOULD NOT DO THIS. As <a title="The Zen of Python" href="http://www.python.org/dev/peps/pep-0020/" target="_blank">Tim Peters</a> once said:</p>
<blockquote>
<p style="text-align:justify;">Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don&#8217;t (the people who actually need them know with certainty that they need them, and don&#8217;t need an explanation about why).</p>
</blockquote>
<p style="text-align:justify;">But there are some use cases in which a metaclass is the perfect solution. The <a title="A very lightweight plug-in infrastructure in Python" href="http://rafaelbarreto.com/2011/08/25/a-very-lightweight-plug-in-infrastructure-in-python/" target="_blank">plug-in infrastructure</a> is a good example. A very simple metaclass is used to guarantee the registration of any loaded class deriving from <code>Plugin</code>, and this is the whole plug-in auto-discovery mechanism.</p>
<p style="text-align:justify;">Another use case is that described in the beginning of this post: to intercept plug-in calls to log and handle any exception. Let&#8217;s be more generic here: to <em>intercept method calls</em> to log and handle any exception. It would be nice if we could do something like this:</p>
<p><pre class="brush: python;">
class Test1(object):

    # log this method BUT RAISE any exception
    @traceablecallable
    def normalMethod(self):
        pass

    # log this method BUT RAISE any exception
    @traceablecallable
    def troublemakerMethod(self):
        raise RuntimeError()

class Test2(Test1):
    pass

class Test3(Test1):

    def normalMethod(self):
        print &quot;I'm a normal method&quot;

    # log this method and SUPPRESS any exception
    @securetraceablecallable
    def troublemakerMethod(self):
        super(Test3, self).troublemakerMethod()

test3 = Test3()
test3.normalMethod()
test3.troublemakerMethod()
test2 = Test2()
test2.normalMethod()
test1 = Test1()
test1.normalMethod()
test1.troublemakerMethod()
</pre></p>
<p>&#8230;generating as output:</p>
<p><pre class="brush: plain; light: true;">
INFO:calling Test3:normalMethod
I'm a normal method
INFO:calling Test3:troublemakerMethod
INFO:calling Test1:troublemakerMethod
ERROR:exception at Test1:troublemakerMethod: RuntimeError(&quot;&quot;)
ERROR:exception at Test3:troublemakerMethod: RuntimeError(&quot;&quot;)
INFO:calling Test1:normalMethod
INFO:calling Test1:normalMethod
INFO:calling Test1:troublemakerMethod
ERROR:exception at Test1:troublemakerMethod: RuntimeError(&quot;&quot;)
------------------------------------------------------------
Traceback (most recent call last):
  ...
RuntimeError
</pre></p>
<p style="text-align:justify;">Try to figure out what&#8217;s going on here for a moment. <code>traceablecallable</code> and <code>securetraceablecallable</code> are just <em>inheritable annotations</em> meaning:</p>
<ul>
<li style="text-align:justify;"><code>traceablecallable</code>: log any call to this callable; log any exception and raise it</li>
<li style="text-align:justify;"><code>securetraceablecallable</code>: log any call to this callable; log any exception and suppress it</li>
</ul>
<p style="text-align:justify;">A callable is anything that can be called in Python, such as a method or a function. If that was possible, our use case would be solved in a very elegant way. It turns out this is really possible using the metaclass magic:</p>
<p><pre class="brush: python; highlight: [22,32,53,55,56];">
class TraceableMeta(type):

    _MODES = { &quot;TRACE&quot; : 1,
               &quot;SECURE_TRACE&quot; : 2 }

    def __init__(cls, name, bases, attrs):
        super(TraceableMeta, cls).__init__(name, bases, attrs)

        cls.__tracedcallables__ = {}

        for base in bases:
            cls.__tracedcallables__.update(getattr(base, &quot;__tracedcallables__&quot;,
                                                   {}))

        traceModes = (getattr(v, &quot;__tracemode__&quot;, None) for v in attrs.values())

        cls.__tracedcallables__.update({k : v for k, v in zip(attrs.keys(), \
            traceModes) if v in TraceableMeta._MODES.values()})

        for k, v in cls.__tracedcallables__.items():
            if attrs.has_key(k):
                setattr(cls, k, _tracedCallableProxy(getattr(cls, k), v))

def _tracedCallableProxy(c, traceMode):

    callableMod = inspect.getmodule(c)
    if callableMod:
        callableMod = callableMod.__name__
    callableDefOrig = c.im_class.__name__ if hasattr(c, &quot;im_class&quot;) \
                                          else callableMod

    def callableProxy(*args, **kwards):
        try:
            logging.info(&quot;calling %s:%s&quot; % (callableDefOrig, c.__name__))
            return c(*args, **kwards)
        except Exception as e:
            logging.error(&quot;exception at %s:%s: %s(\&quot;%s\&quot;)&quot; % (callableDefOrig,
                          c.__name__, e.__class__.__name__, e.__str__()))
            if traceMode != TraceableMeta._MODES[&quot;SECURE_TRACE&quot;]:
                raise e

    return callableProxy

def _traceabledecorator(traceMode):

    def decorator(c):
        if callable(c):
            c.__tracemode__ = traceMode
        return c

    return decorator

traceablecallable = _traceabledecorator(TraceableMeta._MODES[&quot;TRACE&quot;])

securetraceablecallable = _traceabledecorator( \
    TraceableMeta._MODES[&quot;SECURE_TRACE&quot;])
</pre></p>
<p style="text-align:justify;">I&#8217;ll not explain all this code, just the idea. Basically, <code>TraceableMeta</code> is a metaclass that checks for the <code>traceablecallable</code> and <code>securetraceablecallable</code> annotations in the methods of the <em>to be created</em> class and its bases. The annotated methods are then replaced by a <em>proxy</em> responsible for doing the exception handling and logging stuff. One great thing about metaclasses is that they are inherited. Thus, for example, if <code>A</code> has <code>TraceableMeta</code> as metaclass and <code>B</code> inherits from <code>A</code>, then <code>TraceableMeta</code> is also metaclass of <code>B</code>. So, even overridden methods in derived classes lacking explicit annotations are considered, making the functionality provided by <code>TraceableMeta</code> totally transparent in the class hierarchy.</p>
<p style="text-align:justify;">How can this be used by the plug-in infrastructure? It&#8217;s pretty simple. Just redefine the plug-in common interface:</p>
<p><pre class="brush: python; highlight: [1,12,16,20,24];">
class PluginMeta(TraceableMeta):

    def __init__(cls, name, bases, attrs):
        super(PluginMeta, cls).__init__(name, bases, attrs)
        if not hasattr(cls, &quot;registered&quot;):
            cls.registered = []
        else:
            cls.registered.append(cls)

class Plugin(object):

    __metaclass__ = PluginMeta

    ...

    @securetraceablecallable
    def setup(self):
        raise NotImplementedError()

    @securetraceablecallable
    def teardown(self):
        raise NotImplementedError()

    @securetraceablecallable
    def run(self, *args, **kwargs):
        raise NotImplementedError()
</pre></p>
<p style="text-align:justify;">Tell the truth. How many languages do you know out there in which you could devise a solution like this in 56 lines of code? <em>That&#8217;s all about abstraction</em>. And that&#8217;s why I REALLY like Python =D.</p>
<br />Filed under: <a href='http://rafaelbarreto.com/category/python/'>Python</a> Tagged: <a href='http://rafaelbarreto.com/tag/aop/'>aop</a>, <a href='http://rafaelbarreto.com/tag/metaprogramming/'>metaprogramming</a>, <a href='http://rafaelbarreto.com/tag/python-2/'>python</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/892/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=892&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2011/09/12/aspect-like-abstractions-and-python-metaclasses/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>

		<media:content url="http://imgs.xkcd.com/comics/python.png" medium="image">
			<media:title type="html">Python: programming is fun again!</media:title>
		</media:content>
	</item>
		<item>
		<title>A PyQt widget for OpenCV camera preview</title>
		<link>http://rafaelbarreto.com/2011/08/27/a-pyqt-widget-for-opencv-camera-preview/</link>
		<comments>http://rafaelbarreto.com/2011/08/27/a-pyqt-widget-for-opencv-camera-preview/#comments</comments>
		<pubDate>Sun, 28 Aug 2011 02:30:02 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[OpenCV]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[camera]]></category>
		<category><![CDATA[opencv]]></category>
		<category><![CDATA[pyqt]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.com/?p=814</guid>
		<description><![CDATA[This is a hands-on post where I&#8217;ll show how to create a PyQt widget for previewing frames captured from a camera using OpenCV. In the process, it&#8217;ll be clear how to use OpenCV images with&#160;PyQt. I&#8217;ll not explain what PyQt and OpenCV are because if you don&#8217;t know them yet, you probably don&#8217;t need it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=814&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">This is a hands-on post where I&#8217;ll show how to create a <a title="PyQt" href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" target="_blank">PyQt</a> widget for previewing frames captured from a camera using <a title="OpenCV" href="http://opencv.willowgarage.com/wiki/" target="_blank">OpenCV</a>. In the process, it&#8217;ll be clear how to use OpenCV images with&nbsp;PyQt. I&#8217;ll not explain what PyQt and OpenCV are because if you don&#8217;t know them yet, you probably don&#8217;t need it and this post is not for you =P.</p>
<p style="text-align:justify;">The main reason for integrating&nbsp;PyQt and OpenCV is to provide&nbsp;a&nbsp;more sophisticated UI for applications using&nbsp;OpenCV as basis for computer vision tasks.&nbsp;In my specific case, I needed it in the facial recognition prototype used in the <a title="Interview on Globo TV about facial&nbsp;recognition" href="http://rafaelbarreto.com/2011/08/21/interview-on-globo-tv-about-facial-recognition/" target="_blank">interview for Globo TV</a> I posted last week. I usually don&#8217;t write about such specific things, but there&#8217;s little information about it on the net. So I&#8217;d like to make a contribution sharing my findings.</p>
<p style="text-align:justify;">The first problem to be solved is to show a <code>cv.iplimage</code> (the type of an OpenCV image in Python) object in a generic PyQt widget. This is easily solved&nbsp;by inheriting from&nbsp;<code><a title="PyQt4.QtGui.QImage reference" href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qimage.html" target="_blank">QtGui.QImage</a></code> this way:</p>
<p><pre class="brush: python; highlight: [14,15,16,17];">
import cv

from PyQt4 import QtGui

class OpenCVQImage(QtGui.QImage):

    def __init__(self, opencvBgrImg):
        depth, nChannels = opencvBgrImg.depth, opencvBgrImg.nChannels
        if depth != cv.IPL_DEPTH_8U or nChannels != 3:
            raise ValueError(&quot;the input image must be 8-bit, 3-channel&quot;)
        w, h = cv.GetSize(opencvBgrImg)
        opencvRgbImg = cv.CreateImage((w, h), depth, nChannels)
        # it's assumed the image is in BGR format
        cv.CvtColor(opencvBgrImg, opencvRgbImg, cv.CV_BGR2RGB)
        self._imgData = opencvRgbImg.tostring()
        super(OpenCVQImage, self).__init__(self._imgData, w, h, \
            QtGui.QImage.Format_RGB888)
</pre></p>
<p style="text-align:justify;">The important lines here are 14-17:</p>
<ul>
<li style="text-align:justify;">Line 14 converts the image from BGR to RGB format. OpenCV images loaded from files or queried from the camera <em>often</em> (not always; adapt it to your scenario) are delivered in BGR format, which is not what PyQt expects. Thus, I convert the image to RGB before going on. What happens if you skip this step? Well&#8230; nothing critical&#8230; the image will be shown with the channels R and B flipped.</li>
<li style="text-align:justify;">Line 15 saves a reference to the <code>opencvRgbImg</code> byte-content to prevent the garbage collector from deleting it when <code>__init__</code> returns. <em>This is very important</em>.</li>
<li style="text-align:justify;">Lines 16-17 call the <code>QtGui.QImage</code> base class constructor passing the byte-content, dimensions and format of the image.</li>
</ul>
<p style="text-align:justify;">Done! If all you want is to show an OpenCV image in a PyQt widget, that&#8217;s all you need. However, for a camera preview it&#8217;s better to have a more convenient and complete API. Specifically, it must be straightforward to connect a camera device to a widget and still keep them decoupled. There should be one camera device, which can be seen as a frame provider,&nbsp;to many widgets:</p>
<p><a href="http://rafaelbarreto.files.wordpress.com/2011/08/camera_device-widget_relationship.png" target="_blank"><img class="size-full wp-image-818 aligncenter" title="CameraDevice-CameraWidget relationship" src="http://rafaelbarreto.files.wordpress.com/2011/08/camera_device-widget_relationship.png?w=580&#038;h=197" alt="" width="580" height="197" /></a></p>
<p style="text-align:justify;">And the frames must be manipulated independently by the widgets, i.e., the widgets must have complete control over the frames delivered to them.</p>
<p style="text-align:justify;">The camera device can be encapsulated like this:</p>
<p><pre class="brush: python; highlight: [18,19,20,26,32];">
import cv

from PyQt4 import QtCore

class CameraDevice(QtCore.QObject):

    _DEFAULT_FPS = 30

    newFrame = QtCore.pyqtSignal(cv.iplimage)

    def __init__(self, cameraId=0, mirrored=False, parent=None):
        super(CameraDevice, self).__init__(parent)

        self.mirrored = mirrored

        self._cameraDevice = cv.CaptureFromCAM(cameraId)

        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self._queryFrame)
        self._timer.setInterval(1000/self.fps)

        self.paused = False

    @QtCore.pyqtSlot()
    def _queryFrame(self):
        frame = cv.QueryFrame(self._cameraDevice)
        if self.mirrored:
            mirroredFrame = cv.CreateImage(cv.GetSize(frame), frame.depth, \
                frame.nChannels)
            cv.Flip(frame, mirroredFrame, 1)
            frame = mirroredFrame
        self.newFrame.emit(frame)

    @property
    def paused(self):
        return not self._timer.isActive()

    @paused.setter
    def paused(self, p):
        if p:
            self._timer.stop()
        else:
            self._timer.start()

    @property
    def frameSize(self):
        w = cv.GetCaptureProperty(self._cameraDevice, \
            cv.CV_CAP_PROP_FRAME_WIDTH)
        h = cv.GetCaptureProperty(self._cameraDevice, \
            cv.CV_CAP_PROP_FRAME_HEIGHT)
        return int(w), int(h)

    @property
    def fps(self):
        fps = int(cv.GetCaptureProperty(self._cameraDevice, cv.CV_CAP_PROP_FPS))
        if not fps &gt; 0:
            fps = self._DEFAULT_FPS
        return fps
</pre></p>
<p style="text-align:justify;">I&#8217;ll not go through all this code because it&#8217;s not complex. Essentially, it uses a timer (with interval defined by the <em>fps</em>; lines 18-20) to query the camera for a new frame and emits a signal passing the captured frame as parameter (lines 26 and 32). The timer is important to avoid spending CPU time with unnecessary pooling. The rest is just bureaucracy.</p>
<p style="text-align:justify;">Now, let&#8217;s see the camera widget itself. The main purpose of it is to draw the frames delivered by the camera device. But, before drawing a frame, it must allow anyone interested to process it, changing it if necessary without interfering with any other camera widget. Here&#8217;s the code:</p>
<p><pre class="brush: python; highlight: [24,25,26,35,39];">
import cv

from PyQt4 import QtCore
from PyQt4 import QtGui

class CameraWidget(QtGui.QWidget):

    newFrame = QtCore.pyqtSignal(cv.iplimage)

    def __init__(self, cameraDevice, parent=None):
        super(CameraWidget, self).__init__(parent)

        self._frame = None

        self._cameraDevice = cameraDevice
        self._cameraDevice.newFrame.connect(self._onNewFrame)

        w, h = self._cameraDevice.frameSize
        self.setMinimumSize(w, h)
        self.setMaximumSize(w, h)

    @QtCore.pyqtSlot(cv.iplimage)
    def _onNewFrame(self, frame):
        self._frame = cv.CloneImage(frame)
        self.newFrame.emit(self._frame)
        self.update()

    def changeEvent(self, e):
        if e.type() == QtCore.QEvent.EnabledChange:
            if self.isEnabled():
                self._cameraDevice.newFrame.connect(self._onNewFrame)
            else:
                self._cameraDevice.newFrame.disconnect(self._onNewFrame)

    def paintEvent(self, e):
        if self._frame is None:
            return
        painter = QtGui.QPainter(self)
        painter.drawImage(QtCore.QPoint(0, 0), OpenCVQImage(self._frame))
</pre></p>
<p style="text-align:justify;">Again&#8230; I&#8217;ll not go through all this. The really important stuff is in the lines 24-26, 35 and 39. As stated before, it&#8217;s paramount that the widgets sharing a camera device don&#8217;t interfere with each other. In this case, all widgets receives the same frame, which in fact is a reference to the same memory location. This means that if a widget modifies a frame, the others will see it. Clearly, this is not desirable. So, every widget saves its own version of the frame (line 24). This way, they can do whatever they want safely. However, to process the frame is not&nbsp;responsibility&nbsp;of the widget. Thus, it emits a signal with the <em>saved frame</em> as parameter (line 25) and anyone connected to it can do the hard work.</p>
<p style="text-align:justify;">It remains to draw the frame, what is done overriding the <code>paintEvent</code> method (line 35) of the <code><a title="PyQt4.QtGui.QWidget reference" href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qwidget.html" target="_blank">QtGui.QWidget</a></code> class. The relevant lines are 26 and 39. Line 26 forces a schedule of a&nbsp;<em>paint event</em> and line 39&nbsp;effectively&nbsp;draws it when a <em>paint event</em> occurs (using <code>OpenCVQImage</code> as you can see).</p>
<p style="text-align:justify;">The following snippet shows how to use all this together:</p>
<p><pre class="brush: python; highlight: [4,17,19,20,23];">
def _main():

    @QtCore.pyqtSlot(cv.iplimage)
    def onNewFrame(frame):
        cv.CvtColor(frame, frame, cv.CV_RGB2BGR)
        msg = &quot;processed frame&quot;
        font = cv.InitFont(cv.CV_FONT_HERSHEY_DUPLEX, 1.0, 1.0)
        tsize, baseline = cv.GetTextSize(msg, font)
        w, h = cv.GetSize(frame)
        tpt = (w - tsize[0]) / 2, (h - tsize[1]) / 2
        cv.PutText(frame, msg, tpt, font, cv.RGB(255, 0, 0))

    import sys

    app = QtGui.QApplication(sys.argv)

    cameraDevice = CameraDevice(mirrored=True)

    cameraWidget1 = CameraWidget(cameraDevice)
    cameraWidget1.newFrame.connect(onNewFrame)
    cameraWidget1.show()

    cameraWidget2 = CameraWidget(cameraDevice)
    cameraWidget2.show()

    sys.exit(app.exec_())
</pre></p>
<p style="text-align:justify;">See that two <code>CameraWidget</code> objects share the same <code>CameraDevice</code> (lines 17, 19 and 23), but only the first processes the frames (lines 4 and 20). The result is two widgets showing different images resulting from the same frame, as expected:</p>
<p><a href="http://rafaelbarreto.files.wordpress.com/2011/08/camerawidget_demo.png" target="_blank"><img class="size-full wp-image-802  aligncenter" title="CameraWidget demo" src="http://rafaelbarreto.files.wordpress.com/2011/08/camerawidget_demo.png?w=604&#038;h=339" alt="" width="604" height="339" /></a></p>
<p style="text-align:justify;">Now you can embed <code>CameraWidget</code> in a PyQt application and have a fresh OpenCV camera preview. Cool huh? I hope you enjoyed it =P.</p>
<p style="text-align:justify;">Until next&#8230;</p>
<br />Filed under: <a href='http://rafaelbarreto.com/category/computer-vision/opencv/'>OpenCV</a>, <a href='http://rafaelbarreto.com/category/python/'>Python</a> Tagged: <a href='http://rafaelbarreto.com/tag/camera/'>camera</a>, <a href='http://rafaelbarreto.com/tag/opencv-2/'>opencv</a>, <a href='http://rafaelbarreto.com/tag/pyqt/'>pyqt</a>, <a href='http://rafaelbarreto.com/tag/python-2/'>python</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/814/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/814/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/814/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/814/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/814/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/814/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/814/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/814/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/814/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/814/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/814/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/814/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/814/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/814/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=814&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2011/08/27/a-pyqt-widget-for-opencv-camera-preview/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>

		<media:content url="http://rafaelbarreto.files.wordpress.com/2011/08/camera_device-widget_relationship.png" medium="image">
			<media:title type="html">CameraDevice-CameraWidget relationship</media:title>
		</media:content>

		<media:content url="http://rafaelbarreto.files.wordpress.com/2011/08/camerawidget_demo.png" medium="image">
			<media:title type="html">CameraWidget demo</media:title>
		</media:content>
	</item>
		<item>
		<title>A very lightweight plug-in infrastructure in Python</title>
		<link>http://rafaelbarreto.com/2011/08/25/a-very-lightweight-plug-in-infrastructure-in-python/</link>
		<comments>http://rafaelbarreto.com/2011/08/25/a-very-lightweight-plug-in-infrastructure-in-python/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 01:40:31 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.com/?p=759</guid>
		<description><![CDATA[For some applications, run-time extensibility is a major requirement. There are lots of examples out there: browsers, media players, photo editors, etc. All these softwares can be easily extended with new functionality using plug-ins. How is this done? It seems like complex stuff. Indeed, it really is, specially when you are using a bureaucratic language [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=759&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">For some applications, run-time extensibility is a major requirement. There are lots of examples out there: browsers, media players, photo editors, etc. All these softwares can be easily extended with new functionality using <a title="Plug-in" href="http://en.wikipedia.org/wiki/Plug-in_(computing)" target="_blank">plug-ins</a>. <em>How is this done?</em></p>
<p style="text-align:justify;">It seems like complex stuff. Indeed, it really is, specially when you are using a bureaucratic language like Java or digging into the low level with C. However, when there aren&#8217;t security concerns, the extensions are of limited scope and a language with great introspection power like Python is being used, this can be a piece of cake =P.</p>
<p style="text-align:justify;">Let&#8217;s see&#8230; suppose the plug-ins provide their services by means of the following contract interface:</p>
<p><pre class="brush: python;">
class Plugin(object):

    def setup(self):
        raise NotImplementedError

    def teardown(self):
        raise NotImplementedError

    def run(self, *args, **kwards):
        raise NotImplementedError
</pre></p>
<p style="text-align:justify;">Given this, a basic plug-in infrastructure should have as features:</p>
<ul>
<li style="text-align:justify;">A way to <em>auto-discover</em> subclasses of <code>Plugin</code> on-demand at run-time</li>
<li style="text-align:justify;">A <em>centralized</em> way to access these subclasses</li>
</ul>
<p style="text-align:justify;">Thanks to the black magic of Python metaclasses (I&#8217;m assuming you are familiar with them; otherwise, see <a title="What is a metaclass in Python?" href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python" target="_blank">this excellent SO discussion</a>), it&#8217;s very simple to implement those features:</p>
<p><pre class="brush: python;">
class Plugin(object):

    class __metaclass__(type):

        def __init__(cls, name, base, attrs):
            if not hasattr(cls, 'registered'):
                cls.registered = []
            else:
                cls.registered.append(cls)

   ...
</pre></p>
<p style="text-align:justify;">Now, every time a subclass of <code>Plugin</code> is defined, it is added to <code>Plugin.registered</code> so that there&#8217;s a centralized way to access the plug-ins. But the problem of auto-discovery still remains because a plug-in class must be defined to the metaclass trick work, which requires the import of the modules containing the plug-in classes definitions. However, this is easy to fix:</p>
<p><pre class="brush: python;">
import imp
import logging
import pkgutil

class Plugin(object):

    class __metaclass__(type):

        ...

    @classmethod
    def load(cls, *paths):
        paths = list(paths)
        cls.registered = []
        for _, name, _ in pkgutil.iter_modules(paths):
            fid, pathname, desc = imp.find_module(name, paths)
            try:
                imp.load_module(name, fid, pathname, desc)
            except Exception as e:
                logging.warning(&quot;could not load plugin module '%s': %s&quot;,
                                pathname, e.message)
            if fid:
                fid.close()

    ...
</pre></p>
<p style="text-align:justify;">The class method <code>load</code> forces the import of any module found in a path list. Consequently, an explicit import is not needed in order to discover the plug-ins, making the application itself fully decoupled of them.</p>
<p style="text-align:justify;">As an usage example, if you had defined subclasses <code>SamplePlugin1</code> and <code>SamplePlugin2</code> of <code>Plugin</code> in some module located at <code>"./plugins/",</code> you could access them this way:</p>
<p><pre class="brush: python; light: true;">
&gt;&gt;&gt; Plugin.load(&quot;plugins/&quot;)
&gt;&gt;&gt; Plugin.registered
[&lt;class 'SamplePlugin1'&gt;, &lt;class 'SamplePlugin2'&gt;]
</pre></p>
<p style="text-align:justify;">Of course, this is extremely simple. There&#8217;s no sandbox (which implies security issues) and the plug-ins are passive (the application call their methods, instead of them calling methods of a <em>plug-in API</em>). However, for many programs this is enough and anything more complex would be over-engineer.</p>
<p style="text-align:justify;">That&#8217;s it. This is a common problem in software engineering, so I hope this is useful. =)</p>
<br />Filed under: <a href='http://rafaelbarreto.com/category/python/'>Python</a> Tagged: <a href='http://rafaelbarreto.com/tag/plugins/'>plugins</a>, <a href='http://rafaelbarreto.com/tag/python-2/'>python</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/759/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/759/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/759/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/759/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/759/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/759/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/759/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/759/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/759/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/759/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/759/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/759/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/759/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/759/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=759&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2011/08/25/a-very-lightweight-plug-in-infrastructure-in-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>
	</item>
		<item>
		<title>Interview on Globo TV about facial recognition</title>
		<link>http://rafaelbarreto.com/2011/08/21/interview-on-globo-tv-about-facial-recognition/</link>
		<comments>http://rafaelbarreto.com/2011/08/21/interview-on-globo-tv-about-facial-recognition/#comments</comments>
		<pubDate>Sun, 21 Aug 2011 10:26:49 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[Computer Vision]]></category>
		<category><![CDATA[biometry]]></category>
		<category><![CDATA[facial recognition]]></category>
		<category><![CDATA[globo]]></category>
		<category><![CDATA[interview]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.com/?p=724</guid>
		<description><![CDATA[Hey there, with about a month of delay here goes an interview with me on Globo TV (the biggest TV station in Brazil) about facial recognition. The interview is in portuguese&#8230; so, sorry the international audience =P. At some time in the future I&#8217;ll make the prototype used in the interview available for download. I&#8217;m famous [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=724&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Hey there,</p>
<p style="text-align:justify;">with about a month of delay here goes an interview with me on <a title="Globo TV International" href="http://www.globotvinternational.com/" target="_blank">Globo TV</a> (the biggest TV station in Brazil) about facial recognition. The interview is in portuguese&#8230; so, sorry the international audience =P. At some time in the future I&#8217;ll make the prototype used in the interview available for download.</p>
<p style="text-align:justify;">I&#8217;m famous now!! =D=D</p>
<p style="text-align:center;"><span class='embed-youtube' style='text-align:center; display: block;'><iframe class='youtube-player' type='text/html' width='604' height='370' src='http://www.youtube.com/embed/odT8AsTDKF4?version=3&amp;rel=1&amp;fs=1&amp;showsearch=0&amp;showinfo=1&amp;iv_load_policy=1&amp;wmode=transparent' frameborder='0'></iframe></span></p>
<p style="text-align:justify;"><strong>Original Source</strong>: <a title="Biometria facial - parte 2" href="http://video.globo.com/Videos/Player/Noticias/0,,GIM1562718-7823-BIOMETRIA+FACIAL++PARTE+2,00.html" target="_blank">http://video.globo.com/Videos/Player/Noticias/0,,GIM1562718-7823-BIOMETRIA+FACIAL++PARTE+2,00.html</a></p>
<br />Filed under: <a href='http://rafaelbarreto.com/category/computer-vision/'>Computer Vision</a> Tagged: <a href='http://rafaelbarreto.com/tag/biometry/'>biometry</a>, <a href='http://rafaelbarreto.com/tag/facial-recognition/'>facial recognition</a>, <a href='http://rafaelbarreto.com/tag/globo/'>globo</a>, <a href='http://rafaelbarreto.com/tag/interview/'>interview</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/724/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/724/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/724/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/724/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/724/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/724/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/724/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/724/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/724/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/724/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/724/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/724/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/724/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/724/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=724&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2011/08/21/interview-on-globo-tv-about-facial-recognition/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>
	</item>
		<item>
		<title>Comparing objects by memory location in Haskell</title>
		<link>http://rafaelbarreto.com/2011/08/21/comparing-objects-by-memory-location-in-haskell/</link>
		<comments>http://rafaelbarreto.com/2011/08/21/comparing-objects-by-memory-location-in-haskell/#comments</comments>
		<pubDate>Sun, 21 Aug 2011 06:14:13 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[equivalence of procedures]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[pointers]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.com/?p=670</guid>
		<description><![CDATA[Recently I needed to compare two objects for memory equivalence in Haskell. That is, I was looking for a function like: The first thing you might ask is: &#8220;why the hell are you doing this in Haskell?&#8221;. And your surprise is understandable. However, once in a while a project requires you lower the level and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=670&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Recently I needed to compare two objects for <em>memory equivalence</em> in Haskell. That is, I was looking for a function like:</p>
<p><pre class="brush: plain; light: true;">
isMemoryEquivalent :: a -&gt; a -&gt; Bool
</pre></p>
<p style="text-align:justify;">The first thing you might ask is: &#8220;why the hell are you doing this in Haskell?&#8221;. And your surprise is understandable. However, once in a while a project requires you lower the level and go dirty =P.</p>
<p style="text-align:justify;">I was writing a Scheme interpreter (which will be the subject of a post soon) and this need came out in the <a title="Scheme R5RS - Equivalence Predicates" href="http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.1" target="_blank"><code>equal?</code></a> built-in procedure implementation. This procedure checks if two Scheme objects can be regarded as the same, i.e., if they are equivalent. It&#8217;s not difficult to see that this is extremely difficult for procedures (in fact, <a title="Lambda Calculus: Undecidability of Equivalence" href="http://en.wikipedia.org/wiki/Lambda_calculus#Undecidability_of_equivalence" target="_blank">it&#8217;s impossible in the general case</a>).</p>
<p style="text-align:justify;">For example, try to think about an efficient algorithm to compare the following procedures:</p>
<p><pre class="brush: plain; light: true;">
(define (succ1 x)
  (+ x 1))

(define (succ2 x)
  (- (+ x 2) 1))
</pre></p>
<p style="text-align:justify;">One possibility is to check if the domains of <code>succ1</code> and <code>succ2</code> are the same. If this was the case, you could evaluate <code>succ1</code> and <code>succ2</code> over the domain and compare the results. But this is a naïve approach seldom possible in practice. It assumes the domains can be known (in dynamic typed languages such as Scheme this is impossible). And even if the domains can be known, it should be finite (or practically finite), which is almost always not true. Think about float numbers, arbitrary precision integers, tree-like data structures, etc. Not to mention the efficiency problems that arise when the procedures are costly, e.g., a factorial procedure. Well, this is not exactly new if you know a bit about theory of computation, but think about it concretely makes it clear.</p>
<p style="text-align:justify;">The alternative is relax the definition of the <code>equal?</code> procedure: two procedures are said to be equal if they are stored in the same memory location (their memory pointers are equal). That is, <code>(equal? (lambda (x) x) (lambda (x) x))</code> must return <code>#f</code>.</p>
<p style="text-align:justify;">But there isn&#8217;t native pointers in Haskell. To implement this behavior in the interpreter I need to use the extension infrastructure of the Haskell environment. In my case, the Haskell environment is the excellent <a title="GHC compiler" href="http://www.haskell.org/ghc/" target="_blank">GHC</a> compiler and the suitable infrastructure is the <a title="GHC Foreign module" href="http://haskell.org/ghc/docs/7.0.1/html/libraries/base/Foreign.html" target="_blank"><code>Foreign</code></a> module. Using it, I can implement <code>isMemoryEquivalent</code> as follows:</p>
<p><pre class="brush: plain;">
import Foreign

isMemoryEquivalent :: a -&gt; a -&gt; IO Bool
isMemoryEquivalent obj1 obj2 = do
    obj1Ptr &lt;- newStablePtr obj1
    obj2Ptr &lt;- newStablePtr obj2
    let result = obj1Ptr == obj2Ptr
    freeStablePtr obj1Ptr
    freeStablePtr obj2Ptr
    return result
</pre></p>
<p style="text-align:justify;">It&#8217;s quite easy to understand this code snippet. It acquires the pointers to the objects, compares, and releases them. This acquire/release process is needed because the garbage collector is free to move objects through memory, invalidating pointers. So, first the object of interest must be locked in a safe memory location before going any further and released at the end. This is accomplished by the <code><a title="GHC Foreign module" href="http://haskell.org/ghc/docs/7.0.1/html/libraries/base/Foreign.html" target="_blank">Foreign</a></code> module functions <code>newStablePtr</code> and <code>freeStablePtr</code>, respectively. Another important point to note is the use of the IO monad since pointer operations can be viewed as a kind of IO.</p>
<p style="text-align:justify;">This is quite a specific topic, but it&#8217;s instructive about how you can lower the level with Haskell. One interesting thing is that a low level in Haskell is indeed very high =P. Anyway&#8230; kids, don&#8217;t try this without adult supervision, ok? =P</p>
<br />Filed under: <a href='http://rafaelbarreto.com/category/functional-programming/'>Functional programming</a>, <a href='http://rafaelbarreto.com/category/functional-programming/haskell/'>Haskell</a>, <a href='http://rafaelbarreto.com/category/functional-programming/scheme/'>Scheme</a> Tagged: <a href='http://rafaelbarreto.com/tag/equivalence-of-procedures/'>equivalence of procedures</a>, <a href='http://rafaelbarreto.com/tag/haskell-2/'>haskell</a>, <a href='http://rafaelbarreto.com/tag/pointers/'>pointers</a>, <a href='http://rafaelbarreto.com/tag/scheme-2/'>scheme</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/670/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/670/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/670/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/670/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/670/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/670/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/670/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/670/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/670/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/670/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/670/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/670/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/670/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/670/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=670&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2011/08/21/comparing-objects-by-memory-location-in-haskell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>
	</item>
		<item>
		<title>What do we mean by data after all?</title>
		<link>http://rafaelbarreto.com/2011/08/05/what-do-we-mean-by-data-after-all/</link>
		<comments>http://rafaelbarreto.com/2011/08/05/what-do-we-mean-by-data-after-all/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 21:50:07 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[sicp]]></category>
		<category><![CDATA[structure and interpretation of computer programs]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.wordpress.com/?p=628</guid>
		<description><![CDATA[I&#8217;m reading Structure and Interpretation of Computer Programs (the famous SICP)&#8230; what a fantastic book! I&#8217;ve not finished it yet, but until now I can surely say it&#8217;s the best book about Computer Science I ever touched since I started my studies in this field. This book is about abstraction&#8230; about how to control the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=628&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://rafaelbarreto.files.wordpress.com/2011/08/lambda.png"><img class="aligncenter size-medium wp-image-722" title="lambda" src="http://rafaelbarreto.files.wordpress.com/2011/08/lambda.png?w=204&#038;h=300" alt="" width="204" height="300" /></a></p>
<p style="text-align:justify;">I&#8217;m reading <a title="Structure and Interpretation of Computer Programs" href="http://mitpress.mit.edu/sicp/" target="_blank">Structure and Interpretation of Computer Programs</a> (the famous SICP)&#8230; what a fantastic book! I&#8217;ve not finished it yet, but until now I can surely say it&#8217;s the best book about Computer Science I ever touched since I started my studies in this field.</p>
<p style="text-align:justify;">This book is about <em>abstraction</em>&#8230; about how to control the complexity of expressing ideas. And this is, in fact, the real deal of Computer Science: How to formalize ideas of <em>process</em> (the &#8220;How To&#8221; knowledge)&nbsp;in a manageable way. All these &#8220;modern&#8221; concepts of first order functions, closures, dynamic typing, message passing (a.k.a. object orientation) are nothing more than instances of a more fundamental one: <em>abstraction</em>.</p>
<p style="text-align:justify;">It&#8217;s interesting to see that these &#8220;modern&#8221; things are not new at all, being well-known to many academics already in the 1970s. If it&#8217;s true that a lot of academics sometimes lose the sight of reality, it&#8217;s also true that most CS professionals are alienated to the technology, when what really matters for their work is the thinking. If this wasn&#8217;t the case, maybe the old things wouldn&#8217;t be new today =P. This book opens the mind to this and I&#8217;d like to have placed&nbsp;my&nbsp;hands on it a long time ago. Perhaps, I just wasn&#8217;t prepared =).</p>
<p style="text-align:justify;">The SICP uses a dialect of <a title="Lisp" href="http://en.wikipedia.org/wiki/Lisp_(programming_language)" target="_blank">Lisp</a> called <a title="Scheme" href="http://en.wikipedia.org/wiki/Scheme_(programming_language)" target="_blank">Scheme</a> to introduce its subject. I&#8217;ve always heard wonders about this language from very smart people (e.g. Peter Norvig, Paul Graham, Richard Stallman), and I&#8217;ve tried to learn it a few times. But, I couldn&#8217;t see why all those smart people&nbsp;revered Scheme. It seemed to me just like another functional language, with an exotic notation and a lack of practical purpose. This bothered me because I really think that if a lot of smart people like something that I don&#8217;t, there&#8217;s something wrong with me =P. The problem was an extraordinary idea needs an extraordinary presentation to be fully understood and afford that &#8220;<em>aha! moment</em>&#8220;. I wasn&#8217;t exposed to such presentation until&nbsp;SICP.</p>
<p style="text-align:justify;">One of the greatest insights SICP gives is that all in the ideal world of software is <em>process </em>(or <em>procedure</em>, which is the expression of a <em>process</em>), <strong>even data</strong>. And this vision of data is so confusing and surprising I decided to write a post about it. Let&#8217;s see what it means using a SICP example.</p>
<p style="text-align:justify;">Suppose we&#8217;d like to develop a rational number library. First, I need to understand what a rational number is: two integers representing the numerator and the denominator. So, in order to operate with rational numbers we&#8217;ll need a constructor and selectors for the numerator and the denominator. In Scheme it could be something like:</p>
<p><pre class="brush: plain; light: true;">
(define (make-rat n d) ...)
(define (numer x) ...)
(define (denom x) ...)
</pre></p>
<p style="text-align:justify;">From these basics we can implement procedures for a rational number arithmetic:</p>
<p><pre class="brush: plain;">
(define (add-rat x y)
  (make-rat (+ (* (numer x) (denom y))
               (* (numer y) (denom x)))
            (* (denom x) (denom y))))

(define (mul-rat x y)
  (make-rat (* (numer x) (numer y))
            (* (denom x) (denom y))))

...
</pre></p>
<p style="text-align:justify;">The arithmetic procedures see a rational number by means of the constructor and the selectors, which are themselves procedures. Thus, until now, despite we think about rational numbers as data, we are working with procedures. But you can say: &#8220;you are tricking me, after all the selectors are working over CONCRETE data&#8221;. It seems reasonable&#8230; let&#8217;s implement <code>make-rat</code>,&nbsp;<code>numer</code>, <code>denom</code> and investigate this. One possibility is to represent a rational number through <em>pairs</em> using the <code>cons</code>, <code>car</code> and <code>cdr</code> Scheme primitive procedures.</p>
<p><pre class="brush: plain;">
(define (make-rat n d)
  (cons n d))

(define (numer x)
  (car x))

(define (denom x)
  (cdr x))
</pre></p>
<p style="text-align:justify;">The <code>cons</code> procedure receives two things (doesn&#8217;t matter what they really are) and returns a pair. <code>car</code>/<code>cdr</code> extracts the first/last element of a pair. Seeing this you say: &#8220;Aha! I was right, there&#8217;s a CONCRETE data called pair. Thus, there&#8217;s a difference between procedures and data. Constructors and selectors are just a simple abstraction on top of the real concrete data.&#8221; But this is not true because <code>cons</code>, <code>car</code> and <code>cdr</code> are just procedures like <code>make-rat</code>, <code>numer</code> and <code>denom</code>. Nothing says pairs are CONCRETE data. Consider the following implementation of those&nbsp;procedures:</p>
<p><pre class="brush: plain;">
(define (cons n d)
  (define (dispatch m)
    (cond ((= m 0) n)
          ((= m 1) d)))
  dispatch)

(define (car z)
  (z 0))

(define (cdr z)
  (z 1))
</pre></p>
<p style="text-align:justify;">Pay attention to them until you understand. Can you see that &#8220;CONCRETE data called pair&#8221; is just another procedure? Just a <em>process</em>? It does not exist concretely, it&#8217;s an <em>abstraction</em> of the <strong>idea of a pair</strong>. You may argument that numbers are concrete data&#8230; &#8220;1, 2, 3&#8230; this kind of basic stuff is primitive, there&#8217;s no way it can be a procedure&#8221; you might say. Indeed, it can. For the natural numbers they&#8217;re called <a title="Church Numerals" href="http://en.wikipedia.org/wiki/Church_encoding" target="_blank">Church Numerals</a> because were defined by <a title="Alonzo Church" href="http://pt.wikipedia.org/wiki/Alonzo_Church" target="_blank">Alonzo Church</a> in his work on <a title="Lambda calculus" href="http://en.wikipedia.org/wiki/Lambda_calculus" target="_blank"><strong>λ</strong>-calculus</a>.</p>
<p style="text-align:justify;">This is a little mind-boggling at first since we are used to think about procedures and data as separate complementary things, but they aren&#8217;t. If you see a program as a <em>representation of thought</em> and you recognize that <em>data is just a thought</em>, this idea becomes clear. Although this seems like just a curiosity, this notion is extremely important because at the end it&#8217;s just abstraction and Computer Science is all about this.</p>
<p style="text-align:justify;">Of course, if data is procedure, can any procedure be seem as data? No&#8230; what distinguishes <em>processes</em> that are data from those that aren&#8217;t are the restrictions (or axioms) over the&nbsp;<em>processes</em>. For instance, if&nbsp;<code>make-rat</code>,&nbsp;<code>numer</code>,&nbsp;<code>denom</code> defines a rational number it must&nbsp;be true that:</p>
<p><pre class="brush: plain; light: true;">
(= (/ (numer (make-rat n d))
      (denom (make-rat n d)))
   (/ n d))
</pre></p>
<p>The same way, for the <code>cons</code>,&nbsp;<code>car</code>,&nbsp;<code>cdr</code> we must have:</p>
<p><pre class="brush: plain; light: true;">
(eq? (car (cons a b)) a)
(eq? (cdr (cons a b)) b)
</pre></p>
<p style="text-align:justify;">To summarize we could define data as: <strong>procedures + axioms over them</strong>.</p>
<p style="text-align:justify;"><strong>PS</strong>: An important thing here is the use of Scheme to demonstrate these concepts. Why not use C or Python or any other mainstream language? After all, the behavior of the&nbsp;code presented could be emulated in other languages than Scheme. The point is that Scheme was designed to make these concepts transparent. When you write a Scheme program, you think this way. In fact, this way of thinking is based on a solid elegant theory called <a title="Lambda calculus" href="http://en.wikipedia.org/wiki/Lambda_calculus" target="_blank"><strong>λ</strong>-calculus</a>&nbsp;(the basis of <a title="Church Numerals" href="http://en.wikipedia.org/wiki/Church_encoding" target="_blank">Church Numerals</a>) and Scheme was conceived to model it. This is the reason Scheme seems so elegant to me. All just fit right. It&#8217;s the most <a title="Orthogonality in programming languages" href="http://en.wikipedia.org/wiki/Orthogonality_(programming)" target="_blank">orthogonal language</a> I know and this does not make the programmer&nbsp;unproductive, quite the contrary.</p>
<br />Filed under: <a href='http://rafaelbarreto.com/category/functional-programming/'>Functional programming</a>, <a href='http://rafaelbarreto.com/category/functional-programming/scheme/'>Scheme</a> Tagged: <a href='http://rafaelbarreto.com/tag/sicp/'>sicp</a>, <a href='http://rafaelbarreto.com/tag/structure-and-interpretation-of-computer-programs/'>structure and interpretation of computer programs</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/628/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/628/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/628/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/628/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/628/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/628/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/628/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/628/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/628/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/628/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/628/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/628/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/628/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/628/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=628&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2011/08/05/what-do-we-mean-by-data-after-all/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>

		<media:content url="http://rafaelbarreto.files.wordpress.com/2011/08/lambda.png?w=204" medium="image">
			<media:title type="html">lambda</media:title>
		</media:content>
	</item>
		<item>
		<title>OpenCV 2.2 + Webcam + Windows not working</title>
		<link>http://rafaelbarreto.com/2011/06/05/opencv-2-2-webcam-windows-not-working/</link>
		<comments>http://rafaelbarreto.com/2011/06/05/opencv-2-2-webcam-windows-not-working/#comments</comments>
		<pubDate>Sun, 05 Jun 2011 12:41:48 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[OpenCV]]></category>
		<category><![CDATA[not working]]></category>
		<category><![CDATA[opencv]]></category>
		<category><![CDATA[webcam]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.wordpress.com/?p=595</guid>
		<description><![CDATA[Hey there&#8230; it has been a while since my last post&#8230; but I&#8217;m here again, although I&#8217;ll not stay long =P. This will be a short post&#8230; another quick and dirty tip. I&#8217;ve been very busy and without the time to post something really substantial. However, I think this can be helpful, so&#8230; These days [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=595&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Hey there&#8230;</p>
<p style="text-align:justify;">it has been a while since my last post&#8230; but I&#8217;m here again, although I&#8217;ll not stay long =P. This will be a short post&#8230; another quick and dirty tip. I&#8217;ve been very busy and without the time to post something really substantial. However, I think this can be helpful, so&#8230;</p>
<p style="text-align:justify;">These days I had a problem using my webcam with OpenCV 2.2 in Windows. Most of the time I use Linux and never had any problem like this, but last week I needed to use OpenCV 2.2 + Windows for a Computer Vision project and figured out that my webcam simply do not work in this configuration: when I try to create a <em>capture</em> object, a window opens requiring I select the device. However, it does not succeed, even if I select the device correctly.</p>
<p style="text-align:justify;">Oddly, this does not occur with OpenCV 2.1 + Windows. Thus, I concluded it&#8217;s a bug in OpenCV 2.2, specifically in the <em>highgui</em> package. Apparently, this version of OpenCV is using a back-end for cameras different from DirectShow, despite OpenCV supports it and, as I know, this is the recommended way of accessing cameras in Windows.</p>
<p style="text-align:justify;">A solution is to force OpenCV to use DirectShow, what can be done by defining the macros <code>HAVE_VIDEOINPUT</code> and <code>HAVE_DSHOW</code> during the building configuration. Just edit the flag <code>CMAKE_C_COMPILER</code> adding the proper options. For example, if you&#8217;re building OpenCV using Visual Studio, append &#8220;<code>/DHAVE_DSHOW /DHAVE_VIDEOINPUT</code>&#8221; to that flag.</p>
<p style="text-align:justify;">Well, this worked for me&#8230; I hope it can be helpful to you =).</p>
<p style="text-align:justify;"><strong>PS</strong>: As a matter of fact, this is a bug in the setup of the OpenCV building, not a bug in OpenCV itself.</p>
<br />Filed under: <a href='http://rafaelbarreto.com/category/computer-vision/opencv/'>OpenCV</a> Tagged: <a href='http://rafaelbarreto.com/tag/not-working/'>not working</a>, <a href='http://rafaelbarreto.com/tag/opencv-2/'>opencv</a>, <a href='http://rafaelbarreto.com/tag/webcam/'>webcam</a>, <a href='http://rafaelbarreto.com/tag/windows/'>windows</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/595/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=595&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2011/06/05/opencv-2-2-webcam-windows-not-working/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>
	</item>
		<item>
		<title>Accessing the frontal camera in Galaxy Tab (Android 2.2)</title>
		<link>http://rafaelbarreto.com/2011/04/30/accessing-the-frontal-camera-in-galaxy-tab-android-2-2/</link>
		<comments>http://rafaelbarreto.com/2011/04/30/accessing-the-frontal-camera-in-galaxy-tab-android-2-2/#comments</comments>
		<pubDate>Sat, 30 Apr 2011 20:08:19 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android 2.2]]></category>
		<category><![CDATA[camera]]></category>
		<category><![CDATA[galaxy tab]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.wordpress.com/?p=574</guid>
		<description><![CDATA[This is just a quick tip for those of you trying to access the frontal camera in Android 2.2. Probably, you&#8217;d found out that it&#8217;s not so easy as it should be. The Android 2.2 does not have any official support for frontal cameras. In fact, the Android 2.2 does not have ANY official support [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=574&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">This is just a quick tip for those of you trying to access the frontal camera in Android 2.2. Probably, you&#8217;d found out that it&#8217;s not so easy as it should be. The Android 2.2 does not have any official support for frontal cameras. In fact, the Android 2.2 does not have ANY official support for more than ONE camera. So, OFFICIALLY it&#8217;s not possible to use the frontal camera of your device if it&#8217;s Android 2.2 powered. What a shame&#8230; seriously&#8230; this is a quite basic feature&#8230; shouldn&#8217;t be that difficult. Fortunately, the Google <a href="http://developer.android.com/reference/android/hardware/Camera.CameraInfo.html">fixed this</a> in Android 2.3. But, thanks to Android fragmentation, I cannot just upgrade my system and, consequently, I&#8217;m stuck with Android 2.2. Again&#8230; what a shame&#8230; =S</p>
<p style="text-align:justify;">After almost one week of googling, my fellow <a href="http://www.linkedin.com/in/albuquerquehugo">Hugo</a> discovered a workaround for the particular case of Galaxy Tab (the device we&#8217;re using). I&#8217;m not sure if it&#8217;ll work in other Android 2.2 device&#8230; if you try it, let me know the result. So here is what you have to do:</p>
<p><pre class="brush: java; highlight: [3];">
Camera camera = Camera.open();
Camera.Parameters cameraParameters = camera.getParameters();
cameraParameters.set(&quot;camera-id&quot;, 2);
camera.setParameters(cameraParameters);
</pre></p>
<p style="text-align:justify;">The magic is done in the third line with the parameter <code>"camera-id"</code>. I think this is self-explanatory, thus I&#8217;m finishing here. Until next post and good luck with it =).</p>
<p style="text-align:justify;"><strong>UPDATE:</strong> it seems this won&#8217;t work with <code>camera.takePicture</code></p>
<p style="text-align:justify;"><strong>UPDATE:</strong> of course, you need to put the following in <code>AndroidManifest.xml</code>:</p>
<p><pre class="brush: xml;">
&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;
&lt;uses-feature android:name=&quot;android.hardware.camera&quot; /&gt;
</pre></p>
<br />Filed under: <a href='http://rafaelbarreto.com/category/android/'>Android</a> Tagged: <a href='http://rafaelbarreto.com/tag/android-2/'>android</a>, <a href='http://rafaelbarreto.com/tag/android-2-2/'>android 2.2</a>, <a href='http://rafaelbarreto.com/tag/camera/'>camera</a>, <a href='http://rafaelbarreto.com/tag/galaxy-tab/'>galaxy tab</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/574/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/574/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/574/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/574/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/574/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/574/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/574/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/574/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/574/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/574/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/574/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/574/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/574/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/574/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=574&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2011/04/30/accessing-the-frontal-camera-in-galaxy-tab-android-2-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>
	</item>
		<item>
		<title>Meta-programming in C++, a functional language for your compiler!</title>
		<link>http://rafaelbarreto.com/2011/04/28/meta-programming-in-c-a-functional-language-for-your-compiler/</link>
		<comments>http://rafaelbarreto.com/2011/04/28/meta-programming-in-c-a-functional-language-for-your-compiler/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 05:28:55 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[cplusplus]]></category>
		<category><![CDATA[metaprogramming]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.wordpress.com/?p=540</guid>
		<description><![CDATA[My last post was 2 years ago&#8230; apparently I don&#8217;t have any discipline to keep a blog =P. But I&#8217;ll try again this time. The following is just a very interesting piece of code showing the meta-programming capabilities of C++. Unfortunately this is a quite unknown and considered super advanced feature. However, it&#8217;s not that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=540&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">My last post was 2 years ago&#8230; apparently I don&#8217;t have any discipline to keep a blog =P. But I&#8217;ll try again this time.</p>
<p style="text-align:justify;">The following is just a very interesting piece of code showing the meta-programming capabilities of C++. Unfortunately this is a quite unknown and considered super advanced feature. However, it&#8217;s not that complicated and, if used appropriately, can originate very elegant (and useful) code. By the other hand, you can do many REALLY sick things with it. Sure, there&#8217;s nothing new here. After all, as Stroustrup himself once pointed out: <a href="http://www.research.att.com/~bs/bs_faq.html#really-say-that">&#8220;In C++ it&#8217;s harder (<em>to shoot yourself in the foot</em>), but when you do, you blow off your whole leg&#8221;</a>.</p>
<p><pre class="brush: cpp;">
template&lt;int N&gt; struct F {
    enum { value = N * F&lt;N-1&gt;::value };
}

template&lt;&gt; struct F&lt;0&gt; {
    enum { value = 1 };
}

int x = F&lt;5&gt;::value;
</pre></p>
<p style="text-align:justify;">So&#8230; can you tell the value of x at COMPILE TIME? Made it right who said 120. But&#8230; why? If you understand meta-programming there&#8217;s nothing surprising here. However, for those who don&#8217;t, it can be crypt. Think about the <em>templated</em> struct as a function evaluated at compile time and you immediately understand it. The struct F is just a recursive implementation of a factorial.</p>
<p style="text-align:justify;">Because templated declarations are resolved at compile time, you can implement VERY, VERY sophisticated pre-processing logic in your code. As templates can be specialized and recursively declared, you have an almost full functional programming language embedded in your C++ compiler. In fact, the C++ meta-programming capability is Turing complete as Steve Meyer points out in his book <a href="http://www.amazon.com/Effective-Specific-Improve-Programs-Designs/dp/0321334876">Effective C++</a>. Can you appreciate how amazing this is? There are libraries using this to extend C++ itself, providing additional features to the language. One example is <a href="http://www.boost.org/doc/libs/?view=category_Metaprogramming">Boost</a>.</p>
<p style="text-align:justify;">Although meta-programming is fantastic, we all know: there&#8217;s no free-lunch. It&#8217;s not hard to see that meta-programming has a HUGE potential to slow down the build. You can even write code that falls into infinite loop DURING compilation (try &#8220;<code>int x = F&lt;-1&gt;::value;</code>&#8221;; in fact, it&#8217;ll lead to a stack overflow, not an infinite loop&#8230; but you got the idea =P). Not to mention the possible negative impact in readability.</p>
<p style="text-align:justify;">Ok&#8230; this is it&#8230; I believe this was nicer than the previous posts (most people seem to think floating-point is boring) =P. During these 2 years a lot of things changed. The most important: I changed my research area. I&#8217;m not working with floating-point stuff anymore. Despite I like it, I&#8217;ve discovered a much more interesting topic to study: machine learning (and, collaterally, computer vision). So, hereafter likely you&#8217;ll see posts related to it&#8230; if my laziness in writing contribute, of course =D.</p>
<br />Filed under: <a href='http://rafaelbarreto.com/category/c/'>C++</a>, <a href='http://rafaelbarreto.com/category/functional-programming/'>Functional programming</a> Tagged: <a href='http://rafaelbarreto.com/tag/c-2/'>c++</a>, <a href='http://rafaelbarreto.com/tag/cplusplus/'>cplusplus</a>, <a href='http://rafaelbarreto.com/tag/metaprogramming/'>metaprogramming</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/540/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=540&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2011/04/28/meta-programming-in-c-a-functional-language-for-your-compiler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>
	</item>
		<item>
		<title>Controlling FPU rounding modes with Python</title>
		<link>http://rafaelbarreto.com/2009/03/30/controlling-fpu-rounding-modes-with-python/</link>
		<comments>http://rafaelbarreto.com/2009/03/30/controlling-fpu-rounding-modes-with-python/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 05:33:30 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[Floating-Point Numbers]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scientific Computing]]></category>
		<category><![CDATA[floating-point]]></category>
		<category><![CDATA[fpu]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[rounding]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.wordpress.com/?p=69</guid>
		<description><![CDATA[Hey folks! In the previous post I talked a little about the theory behind the floating-point arithmetic and rounding methods. This time I&#8217;ll try a more practical approach showing how to control the rounding modes that FPUs (Floating-Point Units) employ to perform their operations. For that I&#8217;ll use Python. But, first let me introduce the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=69&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Hey folks! In the previous post I talked a little about the theory behind the floating-point arithmetic and rounding methods. This time I&#8217;ll try a more practical approach showing how to control the rounding modes that FPUs (Floating-Point Units) employ to perform their operations. For that I&#8217;ll use Python. But, first let me introduce the <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/fenv.h.html" target="_blank">&lt;fenv.h&gt;</a> header of the ANSI C99 standard.</p>
<p style="text-align:justify;">The ANSI C99 standard establishes the <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/fenv.h.html" target="_blank">&lt;fenv.h&gt;</a> header to control the floating-point environment of the machine. A lot of functions and constants allowing to configure the properties of the floating-point system (including rounding modes) are defined in this header. In our case, the important definitions are:</p>
<h3>Functions</h3>
<ul>
<li><code>int fegetround()</code> &#8211; Returns the current rounding mode</li>
<li><code>int fesetround(int mode)</code> &#8211; Sets the rounding mode returning 0 if all went ok and some other value otherwise</li>
</ul>
<h3>Constants</h3>
<ul>
<li><code>FE_TOWARDZERO</code> &#8211; Flag for&nbsp;<em>round to zero</em></li>
<li><code>FE_DOWNWARD</code> &#8211; Flag for&nbsp;<em>round toward minus infinity</em></li>
<li><code>FE_UPWARD</code> &#8211; Flag for&nbsp;<em>round toward plus infinity</em></li>
<li><code>FE_TONEAREST</code> &#8211; Flag for&nbsp;<em>round to nearest</em></li>
</ul>
<p style="text-align:justify;">Unfortunately, not all compilers fully implement the ANSI C99 standard. Therefore, there is no guarantee on the portability of code that uses the <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/fenv.h.html" target="_blank">&lt;fenv.h&gt;</a> header. Considering this caveat, the GCC compiler supports it, which makes it possible to build a Python extension wrapping the features of <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/fenv.h.html" target="_blank">&lt;fenv.h&gt;</a>.&nbsp;However, this is not a smart way to reach our goal since it would require forcing users to compile the source code of the extension. An alternative is to use the <a href="http://docs.python.org/library/ctypes.html" target="_blank">ctypes</a> Python module to instantiate the libm (part of the standard C library used by GCC, typically&nbsp;<a href="http://www.gnu.org/software/libc/" target="_blank">glibc</a>,&nbsp;that implements <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/fenv.h.html" target="_blank">&lt;fenv.h&gt;</a>):</p>
<p><pre class="brush: python; light: true;">
from ctypes import cdll
from ctypes.util import find_library
libm = cdll.LoadLibrary(find_library('m'))
</pre></p>
<p style="text-align:justify;">The constants that identify the rounding modes are usually defined as macros in <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/fenv.h.html" target="_blank">&lt;fenv.h&gt;</a> and, therefore, are not accessible via <a href="http://docs.python.org/library/ctypes.html" target="_blank">ctypes</a>. We need to redefine them in Python. The problem is that they vary according the processor so that it is necessary to establish some logic on the result of the function <code><a href="http://docs.python.org/library/platform.html" target="_blank">platform.processor()</a></code>. Right now, however, I just have a x86 processor to test, so I will use the constants for it only:</p>
<p><pre class="brush: python; light: true;">
FE_TOWARDZERO = 0xc00
FE_DOWNWARD = 0x400
FE_UPWARD = 0x800
FE_TONEAREST = 0
</pre></p>
<p style="text-align:justify;">Now, just call the appropriate functions:</p>
<p><pre class="brush: python; light: true;">
&gt;&gt;&gt; back_rounding_mode = libm.fegetround()
&gt;&gt;&gt; libm.fesetround(FE_DOWNWARD)
0
&gt;&gt;&gt; 1.0/10.0
0.099999999999999992
&gt;&gt;&gt; libm.fesetround(FE_UPWARD)
0
&gt;&gt;&gt; 1.0/10.0
0.10000000000000001
&gt;&gt;&gt; libm.fesetround(back_rounding_mode)
</pre></p>
<p style="text-align:justify;">But, what about the MS Visual Studio? Well&#8230; the standard C library of this compiler, <a href="http://msdn.microsoft.com/en-us/library/abx4dbyh.aspx" target="_blank">msvcrt</a> (MS Visual Studio C Run-Time Library), does not support&nbsp;<a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/fenv.h.html" target="_blank">&lt;fenv.h&gt;</a>. Nonetheless, MS Visual Studio implements a set of non-standard (quite typical&#8230;) constants and functions specialized in manipulating the properties of the machine FPU. These constants and functions are defined in the&nbsp;<a href="http://msdn.microsoft.com/en-us/library/y0ybw9fy.aspx" target="_blank">&lt;float.h&gt;</a> header distributed with that compiler. The following definitions are of particular interest to us:</p>
<h3>Functions</h3>
<ul>
<li><code>unsigned int _controlfp(unsigned int new, unsigned int mask)</code> &#8211; Sets/gets the control vector of the floating-point system (more information <a href="http://msdn.microsoft.com/en-us/library/e9b52ceh.aspx" target="_blank">here</a>)</li>
</ul>
<h3>Constants</h3>
<ul>
<li><code>_MCW_RC = 0x300</code> &#8211; Control vector mask for information about rounding modes</li>
<li><code>_RC_CHOP = 0x300</code> &#8211; Control vector value for&nbsp;<em>round to zero</em> mode</li>
<li><code>_RC_UP = 0x200</code> &#8211; Control vector value for <em>round toward plus infinity</em> mode</li>
<li><code>_RC_DOWN = 0x100</code> &#8211; Control vector value for&nbsp;<em>round toward minus infinity</em> mode</li>
<li><code>_RC_NEAR = 0</code> &#8211; Control vector value for&nbsp;<em>round to nearest</em> mode</li>
</ul>
<p style="text-align:justify;">Analogous to the previous case:</p>
<p><pre class="brush: python; light: true;">
&gt;&gt;&gt; _MCW_RC = 0x300
&gt;&gt;&gt; _RC_UP = 0x200
&gt;&gt;&gt; _RC_DOWN = 0x100
&gt;&gt;&gt; from ctypes import cdll
&gt;&gt;&gt; msvcrt = cdll.msvcrt
&gt;&gt;&gt; back_rounding_mode = msvcrt._controlfp(0, 0)
&gt;&gt;&gt; msvcrt._controlfp(_RC_DOWN, _MCW_RC)
590111
&gt;&gt;&gt; 1.0/10.0
0.099999999999999992
&gt;&gt;&gt; msvcrt._controlfp(_RC_UP, _MCW_RC)
590367
&gt;&gt;&gt; 1.0/10.0
0.10000000000000001
&gt;&gt;&gt; msvcrt._controlfp(back_rounding_mode, _MCW_RC)
589855
</pre></p>
<p style="text-align:justify;">For sure, it is not convenient to type all this every time you want to change the rounding mode. Nor it is appropriate to guess&nbsp;the standard C library of the system. But you can always create functions encapsulating this behavior. Something like this:</p>
<p><pre class="brush: python;">
def _start_libm():
    global TO_ZERO, TOWARD_MINUS_INF, TOWARD_PLUS_INF, TO_NEAREST
    global set_rounding, get_rounding
    from ctypes import cdll
    from ctypes.util import find_library
    libm = cdll.LoadLibrary(find_library('m'))
    set_rounding, get_rounding = libm.fesetround, libm.fegetround
    # x86
    TO_ZERO = 0xc00
    TOWARD_MINUS_INF = 0x400
    TOWARD_PLUS_INF = 0x800
    TO_NEAREST = 0

def _start_msvcrt():
    global TO_ZERO, TOWARD_MINUS_INF, TOWARD_PLUS_INF, TO_NEAREST
    global set_rounding, get_rounding
    from ctypes import cdll
    msvcrt = cdll.msvcrt
    set_rounding = lambda mode: msvcrt._controlfp(mode, 0x300)
    get_rounding = lambda: msvcrt._controlfp(0, 0)
    TO_ZERO = 0x300
    TOWARD_MINUS_INF = 0x100
    TOWARD_PLUS_INF = 0x200
    TO_NEAREST = 0

for _start_rounding in _start_libm, _start_msvcrt:
    try:
        _start_rounding()
        break
    except:
        pass
else:
    print &quot;ERROR: You couldn't start the FPU module&quot;
</pre></p>
<p style="text-align:justify;">In this case, the constants and functions to be called, as well as the standard C library instantiated, are abstracted.&nbsp;Just use the constants <code>TO_ZERO</code>, <code>TOWARD_MINUS_INF</code>, <code>TOWARD_PLUS_INF</code>, <code>TO_NEAREST</code> and the functions <code>set_rounding</code>, <code>get_rounding</code>.</p>
<p style="text-align:justify;">So, that&#8217;s it&#8230; I hope this has been useful to you somehow (I doubt it&#8230; :P) or, at least, that it was interesting&#8230; Until next time&#8230;</p>
<br />Posted in Floating-Point Numbers, Python, Scientific Computing Tagged: floating-point, fpu, python, rounding <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/69/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=69&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2009/03/30/controlling-fpu-rounding-modes-with-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>
	</item>
		<item>
		<title>Aritmética de ponto flutuante</title>
		<link>http://rafaelbarreto.com/2009/03/14/aritmetica-de-ponto-flutuante/</link>
		<comments>http://rafaelbarreto.com/2009/03/14/aritmetica-de-ponto-flutuante/#comments</comments>
		<pubDate>Sun, 15 Mar 2009 01:23:52 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[Floating-Point Numbers]]></category>
		<category><![CDATA[Scientific Computing]]></category>
		<category><![CDATA[arithmetic]]></category>
		<category><![CDATA[floating-point]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.wordpress.com/?p=21</guid>
		<description><![CDATA[Opa pessoal! Depois das apresentações, um post com alguma coisa útil&#8230; ou não :P. Vou falar sobre algo em que trabalhei há um tempinho atrás na universidade e que acho muito interessante: o sistema de ponto flutuante. Para alguns esse assunto pode ser bastante massante, mas um conhecimento básico sobre ponto flutuante é de extrema [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=21&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Opa pessoal! Depois das apresentações, um post com alguma coisa útil&#8230; ou não :P. Vou falar sobre algo em que trabalhei há um tempinho atrás na universidade e que acho muito interessante: o sistema de ponto flutuante. Para alguns esse assunto pode ser bastante massante, mas um conhecimento básico sobre ponto flutuante é de extrema importância para qualquer pessoa que trabalhe de forma séria com informática porque problemas derivados do seu uso eventualmente se tornam grandes armadilhas. Enfim&#8230; deixa eu parar com a enrolação :).</p>
<p style="text-align:justify;">Os números de ponto flutuante (<img src='http://s0.wp.com/latex.php?latex=%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mathbb{F}' title='&#92;mathbb{F}' class='latex' />) são uma tentativa de representar os números reais (<img src='http://s0.wp.com/latex.php?latex=%5Cmathbb%7BR%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mathbb{R}' title='&#92;mathbb{R}' class='latex' />) nos computadores. Entretanto, dada a finitude inerente aos dispositivos computacionais, há perda de informação — e, portanto, <img src='http://s0.wp.com/latex.php?latex=%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mathbb{F}' title='&#92;mathbb{F}' class='latex' /> é subconjunto próprio de <img src='http://s0.wp.com/latex.php?latex=%5Cmathbb%7BR%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mathbb{R}' title='&#92;mathbb{R}' class='latex' /> — de modo que uma das maiores preocupações matemáticas ao se trabalhar com o sistema de ponto flutuante é a falta de fecho aritmético. Isso corresponde a dizer que, para <img src='http://s0.wp.com/latex.php?latex=%5Cstar+%5Cin+%5C%7B%2B%2C+-%2C+%5Ccdot%2C+%2F%5C%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;star &#92;in &#92;{+, -, &#92;cdot, /&#92;}' title='&#92;star &#92;in &#92;{+, -, &#92;cdot, /&#92;}' class='latex' />, nem sempre é verdade que <img src='http://s0.wp.com/latex.php?latex=x+%5Cstar+y+%5Cin+%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='x &#92;star y &#92;in &#92;mathbb{F}' title='x &#92;star y &#92;in &#92;mathbb{F}' class='latex' />. De fato, isso é um problema. Afinal de contas, se o resultado de uma operação não é representável no conjunto de trabalho, a aritmética perde em robustez tornando-se inconsistente e, para todos os fins práticos, inútil.</p>
<p style="text-align:justify;">Uma solução é redefinir os operadores sobre <img src='http://s0.wp.com/latex.php?latex=%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mathbb{F}' title='&#92;mathbb{F}' class='latex' /> de tal forma a criar o fecho. A idéia é aplicar uma função (arredondamento) aos resultados para fazê-los &#8220;caber&#8221; no conjunto. Formalmente, seja <img src='http://s0.wp.com/latex.php?latex=%5Cbigcirc%3A%5Cmathbb%7BR%7D+%5Crightarrow+%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;bigcirc:&#92;mathbb{R} &#92;rightarrow &#92;mathbb{F}' title='&#92;bigcirc:&#92;mathbb{R} &#92;rightarrow &#92;mathbb{F}' class='latex' />. Dizemos que <img src='http://s0.wp.com/latex.php?latex=%5Cbigcirc&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;bigcirc' title='&#92;bigcirc' class='latex' /> é um arredondamento se obedece às seguintes propriedades:</p>
<ol>
<li><img src='http://s0.wp.com/latex.php?latex=%5Cforall+%5C%3B+x+%5Cin+%5Cmathbb%7BF%7D+%5CRightarrow+%5Cbigcirc%28x%29+%3D+x&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;forall &#92;; x &#92;in &#92;mathbb{F} &#92;Rightarrow &#92;bigcirc(x) = x' title='&#92;forall &#92;; x &#92;in &#92;mathbb{F} &#92;Rightarrow &#92;bigcirc(x) = x' class='latex' /></li>
<li><img src='http://s0.wp.com/latex.php?latex=%5Cforall+%5C%3B+x%2C+y+%5Cin+%5Cmathbb%7BR%7D+%5Ctext%7B+e+%7D+x+%5Cle+y+%5CRightarrow+%5Cbigcirc%28x%29+%5Cle+%5Cbigcirc%28y%29&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;forall &#92;; x, y &#92;in &#92;mathbb{R} &#92;text{ e } x &#92;le y &#92;Rightarrow &#92;bigcirc(x) &#92;le &#92;bigcirc(y)' title='&#92;forall &#92;; x, y &#92;in &#92;mathbb{R} &#92;text{ e } x &#92;le y &#92;Rightarrow &#92;bigcirc(x) &#92;le &#92;bigcirc(y)' class='latex' /></li>
</ol>
<p style="text-align:justify;">Ao contrário do que esse formalismo sugere, o significado de tais propriedades é bastante simples. A primeira delas estabelece que todos os elementos do conjunto dos números de ponto flutuante são fixados pela função de arredondamento. Ou seja, o arredondamento de um número de ponto flutuante é o próprio número. A segunda garante a preservação da relação de ordem (monoticidade), o que era de se esperar. Em conjunto, essas propriedades implicam no resultado mais importante a respeito da natureza do arredondamento: a característica de máxima qualidade. O que se quer dizer com isso é que <img src='http://s0.wp.com/latex.php?latex=%5Cnexists+%5C%3B+y+%5Cin+%5Cmathbb%7BF%7D+%5C%3B+%7C+%5C%3B+y+%5Cin+%28%5Cmin%5C%7B%5Cbigcirc%28x%29%2C+x%5C%7D%2C+%5Cmax%5C%7B%5Cbigcirc%28x%29%2C+x%5C%7D%29&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;nexists &#92;; y &#92;in &#92;mathbb{F} &#92;; | &#92;; y &#92;in (&#92;min&#92;{&#92;bigcirc(x), x&#92;}, &#92;max&#92;{&#92;bigcirc(x), x&#92;})' title='&#92;nexists &#92;; y &#92;in &#92;mathbb{F} &#92;; | &#92;; y &#92;in (&#92;min&#92;{&#92;bigcirc(x), x&#92;}, &#92;max&#92;{&#92;bigcirc(x), x&#92;})' class='latex' />, ou seja, entre um número real e o seu ponto flutuante correspondente não existem intermediários pertencentes a <img src='http://s0.wp.com/latex.php?latex=%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mathbb{F}' title='&#92;mathbb{F}' class='latex' />.</p>
<p style="text-align:justify;">Tudo bem, mas qual é a utilidade disso no estabelecimento de uma aritmética de ponto flutuante útil e robusta? Dado <img src='http://s0.wp.com/latex.php?latex=%5Cstar+%5Cin+%5C%7B%2B%2C+-%2C+%5Ccdot%2C+%2F%5C%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;star &#92;in &#92;{+, -, &#92;cdot, /&#92;}' title='&#92;star &#92;in &#92;{+, -, &#92;cdot, /&#92;}' class='latex' />, seja <img src='http://s0.wp.com/latex.php?latex=%5Cbullet+%5Cin+%5C%7B%5Coplus%2C+%5Cominus%2C+%5Codot%2C+%5Coslash%5C%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;bullet &#92;in &#92;{&#92;oplus, &#92;ominus, &#92;odot, &#92;oslash&#92;}' title='&#92;bullet &#92;in &#92;{&#92;oplus, &#92;ominus, &#92;odot, &#92;oslash&#92;}' class='latex' /> o operador correspondente em <img src='http://s0.wp.com/latex.php?latex=%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mathbb{F}' title='&#92;mathbb{F}' class='latex' />. Nós definimos uma aritmética de ponto flutuante como:</p>
<p style="text-align:center;"><img src='http://s0.wp.com/latex.php?latex=%5Cforall+%5C%3B+x%2C+y+%5Cin+%5Cmathbb%7BF%7D+%5CRightarrow+x+%5Cbullet+y+%3D+%5Cbigcirc%28x+%5Cstar+y%29&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;forall &#92;; x, y &#92;in &#92;mathbb{F} &#92;Rightarrow x &#92;bullet y = &#92;bigcirc(x &#92;star y)' title='&#92;forall &#92;; x, y &#92;in &#92;mathbb{F} &#92;Rightarrow x &#92;bullet y = &#92;bigcirc(x &#92;star y)' class='latex' /></p>
<p style="text-align:justify;">Nesse ponto aparece uma questão de ordem prática bastante relevante. Ora, se eu preciso aplicar a função <img src='http://s0.wp.com/latex.php?latex=%5Cbigcirc&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;bigcirc' title='&#92;bigcirc' class='latex' /> ao resultado da operação <img src='http://s0.wp.com/latex.php?latex=%5Cstar&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;star' title='&#92;star' class='latex' />, então de alguma forma eu precisarei representar este resultado na máquina. Mas, não é precisamente esse problema que estamos tentando resolver?! A circularidade é apenas aparente, entretanto. Com efeito, é possível mostrar que, se <img src='http://s0.wp.com/latex.php?latex=x&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='x' title='x' class='latex' /> e <img src='http://s0.wp.com/latex.php?latex=y&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='y' title='y' class='latex' /> estão armazenados em registradores com <img src='http://s0.wp.com/latex.php?latex=p&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='p' title='p' class='latex' /> dígitos de precisão, o valor exato da operação <img src='http://s0.wp.com/latex.php?latex=x+%5Cstar+y&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='x &#92;star y' title='x &#92;star y' class='latex' /> pode ser armazenado em um intermediário com <img src='http://s0.wp.com/latex.php?latex=p+%2B+3&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='p + 3' title='p + 3' class='latex' /> dígitos &#8211; para detalhes a respeito da técnica e do porquê de seu funcionamento, recomendo <a href="http://docs.sun.com/source/806-3568/ncg_goldberg.html" target="_blank">[1]</a>. Procede-se então o arredondamento adaptando o resultado ao registrador ordinário de <img src='http://s0.wp.com/latex.php?latex=p&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='p' title='p' class='latex' /> dígitos.</p>
<p style="text-align:justify;">Agora que nós definimos uma aritmética de ponto flutuante abstrata, é necessário concretizá-la. No contexto, isto significa que nós precisamos definir o comportamento da função <img src='http://s0.wp.com/latex.php?latex=%5Cbigcirc&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;bigcirc' title='&#92;bigcirc' class='latex' />, o que pode ser feito de 4 formas diferentes como descrito abaixo.</p>
<h3>Round to zero</h3>
<p style="text-align:justify;">Este é o método de arredondamento mais simples que existe. Formalmente, a função <em>round to zero</em> <img src='http://s0.wp.com/latex.php?latex=%5Csquare_z+%3A+%5Cmathbb%7BR%7D+%5Crightarrow+%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;square_z : &#92;mathbb{R} &#92;rightarrow &#92;mathbb{F}' title='&#92;square_z : &#92;mathbb{R} &#92;rightarrow &#92;mathbb{F}' class='latex' /> é definida como</p>
<p style="text-align:center;"><img src='http://s0.wp.com/latex.php?latex=%5Csquare_z%28x%29+%3D+sign%28x%29+%5C%3B+max+%5C%3B+%5Clbrace%7By+%5Cin+%5Cmathbb%7BF%7D+%3A+y+%5Cle+%7Cx%7C%5Crbrace%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;square_z(x) = sign(x) &#92;; max &#92;; &#92;lbrace{y &#92;in &#92;mathbb{F} : y &#92;le |x|&#92;rbrace}' title='&#92;square_z(x) = sign(x) &#92;; max &#92;; &#92;lbrace{y &#92;in &#92;mathbb{F} : y &#92;le |x|&#92;rbrace}' class='latex' /></p>
<p style="text-align:justify;">onde <img src='http://s0.wp.com/latex.php?latex=sign%28x%29&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='sign(x)' title='sign(x)' class='latex' /> é o que o próprio nome diz. Este arredondamento é o mais facilmente implementável. De fato, se <img src='http://s0.wp.com/latex.php?latex=%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mathbb{F}' title='&#92;mathbb{F}' class='latex' /> tem precisão <img src='http://s0.wp.com/latex.php?latex=p&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='p' title='p' class='latex' />, é suficiente descartar os dígitos além da posição <img src='http://s0.wp.com/latex.php?latex=p-1&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='p-1' title='p-1' class='latex' />. Por causa disso, este método também é conhecido como <em>truncagem</em>.</p>
<h3>Round toward minus infinity</h3>
<p style="text-align:justify;">Este é um dos modos de arredondamento pertencentes à classe dos <em>direcionados</em>. Um arredondamento <em>direcionado</em> deve resultar no ponto flutuante imediatamente anterior (ou posterior) ao número real correspondente. Formalmente, ele deve satisfazer uma das seguintes propriedades:</p>
<ol>
<li><img src='http://s0.wp.com/latex.php?latex=x+%5Cin+%5Cmathbb%7BR%7D+%5CRightarrow+%5Cbigcirc%28x%29+%5Cle+x&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='x &#92;in &#92;mathbb{R} &#92;Rightarrow &#92;bigcirc(x) &#92;le x' title='x &#92;in &#92;mathbb{R} &#92;Rightarrow &#92;bigcirc(x) &#92;le x' class='latex' /></li>
<li><img src='http://s0.wp.com/latex.php?latex=x+%5Cin+%5Cmathbb%7BR%7D+%5CRightarrow+%5Cbigcirc%28x%29+%5Cge+x&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='x &#92;in &#92;mathbb{R} &#92;Rightarrow &#92;bigcirc(x) &#92;ge x' title='x &#92;in &#92;mathbb{R} &#92;Rightarrow &#92;bigcirc(x) &#92;ge x' class='latex' /></li>
</ol>
<p style="text-align:justify;">Particularmente, o <em>round toward minus infinity</em> obedece a primeira propriedade e é definido por:</p>
<p style="text-align:center;"><img src='http://s0.wp.com/latex.php?latex=%5Cbigtriangledown%28x%29+%3D+max+%5C%3B+%5Clbrace%7By+%5Cin+%5Cmathbb%7BF%7D+%3A+y+%5Cle+x%5Crbrace%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;bigtriangledown(x) = max &#92;; &#92;lbrace{y &#92;in &#92;mathbb{F} : y &#92;le x&#92;rbrace}' title='&#92;bigtriangledown(x) = max &#92;; &#92;lbrace{y &#92;in &#92;mathbb{F} : y &#92;le x&#92;rbrace}' class='latex' /></p>
<p style="text-align:justify;">Note as semelhanças entre este modo e o <em>round to zero</em>. Apesar de parecerem idênticos, existe uma diferença sutil. Por exemplo, se nós tivermos um sistema de ponto flutuante com 2 dígitos de precisão e tentarmos arredondar -1.234 usando o <em>round to zero</em>, nós obteremos -1.23. Por outro lado, se usarmos o <em>round to minus infinity</em>, o resultado será -1.24. De forma geral, é verdade que <img src='http://s0.wp.com/latex.php?latex=%5Csquare_z%28x%29+%3D+sign%28x%29+%5C%3B+%5Cbigtriangledown%28%7Cx%7C%29&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;square_z(x) = sign(x) &#92;; &#92;bigtriangledown(|x|)' title='&#92;square_z(x) = sign(x) &#92;; &#92;bigtriangledown(|x|)' class='latex' />.</p>
<h3>Round toward plus infinity</h3>
<p style="text-align:justify;">O <em>round toward plus infinity</em> é o análogo simétrico do <em>round toward minus infinity</em>. Portanto, este arredondamento satisfaz a segunda das duas propriedades citadas acima e é definido como:</p>
<p style="text-align:center;"><img src='http://s0.wp.com/latex.php?latex=%5Cbigtriangleup%28x%29+%3D+min+%5C%3B+%5Clbrace%7By+%5Cin+%5Cmathbb%7BF%7D+%3A+y+%5Cge+x%5Crbrace%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;bigtriangleup(x) = min &#92;; &#92;lbrace{y &#92;in &#92;mathbb{F} : y &#92;ge x&#92;rbrace}' title='&#92;bigtriangleup(x) = min &#92;; &#92;lbrace{y &#92;in &#92;mathbb{F} : y &#92;ge x&#92;rbrace}' class='latex' /></p>
<p style="text-align:justify;">Note uma propriedade interessante dos arredondamentos <em>direcionados</em>: do que foi dito, nós podemos concluir que o intervalo <img src='http://s0.wp.com/latex.php?latex=%5B%5Cbigtriangledown%28x%29%2C+%5Cbigtriangleup%28x%29%5D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='[&#92;bigtriangledown(x), &#92;bigtriangleup(x)]' title='[&#92;bigtriangledown(x), &#92;bigtriangleup(x)]' class='latex' /> é o menor cujos extremos são números em <img src='http://s0.wp.com/latex.php?latex=%5Cmathbb%7BF%7D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mathbb{F}' title='&#92;mathbb{F}' class='latex' /> e contém <img src='http://s0.wp.com/latex.php?latex=x&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='x' title='x' class='latex' />. Então, o diâmetro deste intervalo é o erro máximo cometido pela função arredondamento. Esta propriedade é usada na <a title="IntPy" href="http://rafaelbarreto.wordpress.com/intpy/">Aritmética Intervalar de Precisão Máxima</a>.</p>
<h3>Round to nearest</h3>
<p style="text-align:justify;">Uma metodologia mais inteligente de arredondamento é considerar o ponto médio <img src='http://s0.wp.com/latex.php?latex=%5Cmu+%3D+%5Cfrac%7B1%7D%7B2%7D%28%5Cbigtriangledown%28x%29%2B%5Cbigtriangleup%28x%29%29&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;mu = &#92;frac{1}{2}(&#92;bigtriangledown(x)+&#92;bigtriangleup(x))' title='&#92;mu = &#92;frac{1}{2}(&#92;bigtriangledown(x)+&#92;bigtriangleup(x))' class='latex' /> do intervalo <img src='http://s0.wp.com/latex.php?latex=%5B%5Cbigtriangledown%28x%29%2C+%5Cbigtriangleup%28x%29%5D&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='[&#92;bigtriangledown(x), &#92;bigtriangleup(x)]' title='[&#92;bigtriangledown(x), &#92;bigtriangleup(x)]' class='latex' />. Desta forma, se <img src='http://s0.wp.com/latex.php?latex=x+%3C+%5Cmu&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='x &lt; &#92;mu' title='x &lt; &#92;mu' class='latex' />, retorne <img src='http://s0.wp.com/latex.php?latex=%5Cbigtriangledown%28x%29&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;bigtriangledown(x)' title='&#92;bigtriangledown(x)' class='latex' />, caso contrário, se <img src='http://s0.wp.com/latex.php?latex=x+%3E+%5Cmu&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='x &gt; &#92;mu' title='x &gt; &#92;mu' class='latex' />, então retorne <img src='http://s0.wp.com/latex.php?latex=%5Cbigtriangleup%28x%29&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='&#92;bigtriangleup(x)' title='&#92;bigtriangleup(x)' class='latex' />. Se <img src='http://s0.wp.com/latex.php?latex=x+%3D+%5Cmu&amp;bg=ffffff&amp;fg=4e4e4e&amp;s=0' alt='x = &#92;mu' title='x = &#92;mu' class='latex' />, nós temos que decidir o que fazer. Esta decisão cria diferentes variantes do arredondamento. O <em>round to nearest</em> implementa exatamente esse método. Em geral, o erro cometido por este modo é menor que o dos outros.</p>
<p style="text-align:justify;">Bem, por agora é isso :). Desculpe se tudo isso foi maçante. De fato, esta é uma abordagem muito teórica para um problema muito prático, mas eu gosto de alguma teoria antes das questões práticas. Isso ajuda a dar fundamentação a possíveis soluções. Em algum ponto no futuro irei escrever sobre o erro de arredondamento considerando o padrão de ponto flutuante IEEE 754 de um ponto de vista prático. Então, até a próxima&#8230; :)</p>
<br />Posted in Floating-Point Numbers, Scientific Computing Tagged: arithmetic, floating-point <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/21/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=21&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2009/03/14/aritmetica-de-ponto-flutuante/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>
	</item>
		<item>
		<title>Introducing myself&#8230;</title>
		<link>http://rafaelbarreto.com/2009/03/09/introducing_myself/</link>
		<comments>http://rafaelbarreto.com/2009/03/09/introducing_myself/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 05:57:34 +0000</pubDate>
		<dc:creator>Rafael Barreto</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[presentation]]></category>

		<guid isPermaLink="false">http://rafaelbarreto.wordpress.com/?p=263</guid>
		<description><![CDATA[Hi people! My name is Rafael Barreto and I am an undergraduate in Computer Engineering at Federal University of Pernambuco (UFPE) in Brazil. I always wanted to have a blog to share stuff I find interesting, but I guess I do not have the discipline for it :P. Well, this is a try&#8230; let&#8217;s see [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=263&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Hi people!</p>
<p style="text-align:justify;">My name is Rafael Barreto and I am an undergraduate in Computer Engineering at <a title="CIn/UFPE" href="http://www.cin.ufpe.br/" target="_blank">Federal University of Pernambuco</a> (UFPE) in Brazil. I always wanted to have a blog to share stuff I find interesting, but I guess I do not have the discipline for it :P. Well, this is a try&#8230; let&#8217;s see if I can stand with it.</p>
<p style="text-align:justify;">My main focus here is technical stuff, especially related to computing and math. However, I like literature and music a lot. So, it&#8217;s possible these themes appear here eventually.</p>
<p style="text-align:justify;">I will try to keep it in english (despite I cannot guarantee this). Mainly because it makes the blog much more accessible and because I really need to practice my writing :P.</p>
<p style="text-align:justify;">That&#8217;s it&#8230; enough of presentation&#8230; =P</p>
<br />Posted in Uncategorized Tagged: presentation <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rafaelbarreto.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rafaelbarreto.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rafaelbarreto.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rafaelbarreto.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rafaelbarreto.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rafaelbarreto.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rafaelbarreto.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rafaelbarreto.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rafaelbarreto.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rafaelbarreto.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rafaelbarreto.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rafaelbarreto.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rafaelbarreto.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rafaelbarreto.wordpress.com/263/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rafaelbarreto.com&amp;blog=3930771&amp;post=263&amp;subd=rafaelbarreto&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rafaelbarreto.com/2009/03/09/introducing_myself/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/524c7f385506bc9215172cc798d31304?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">rafaelbarreto</media:title>
		</media:content>
	</item>
	</channel>
</rss>
